📌  相关文章
📜  nokia stock - Go 编程语言 - Go 编程语言(1)

📅  最后修改于: 2023-12-03 14:44:45.067000             🧑  作者: Mango

Nokia Stock in Go Programming Language

Introduction

This is a program written in Go Programming Language that fetches real-time stock data for Nokia Corporation from Yahoo Finance API and displays it in a command-line interface.

Dependencies

This program has the following dependencies:

You can install them using the following commands:

go get github.com/go-resty/resty/v2
go get github.com/olekukonko/tablewriter
Usage

To run the program, navigate to the directory where the program is saved and run the following command:

go run nokia_stock.go

You will be presented with a table displaying real-time stock data for Nokia Corporation, including the current stock price, change percentage, and trading volume.

Code Explanation

The program starts by importing the required dependencies:

import (
    "fmt"
    "net/url"
    "strconv"
    "strings"

    "github.com/go-resty/resty/v2"
    "github.com/olekukonko/tablewriter"
)

It then defines a struct NokiaStock to hold the stock data:

type NokiaStock struct {
    Price    float64
    Change   float64
    Volume   int
}

The fetchData function uses the RESTful API provided by Yahoo Finance to fetch the real-time stock data for Nokia Corporation:

func fetchData() (*NokiaStock, error) {
    u := url.QueryEscape("select * from yahoo.finance.quotes where symbol in ('NOK')")
    url := fmt.Sprintf("https://query.yahooapis.com/v1/public/yql?q=%s&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", u)
    client := resty.New()
    resp, err := client.R().Get(url)
    if err != nil {
        return nil, err
    }
    result := resp.String()
    pos1 := strings.Index(result, "\"LastTradePriceOnly\"")
    pos2 := strings.Index(result, "\"ChangePercentChange\"")
    pos3 := strings.Index(result, "\"Volume\"")
    price, _ := strconv.ParseFloat(result[pos1+21:pos1+28], 64)
    change, _ := strconv.ParseFloat(result[pos2+23:pos2+29], 64)
    volume, _ := strconv.Atoi(result[pos3+9 : pos3+18])
    return &NokiaStock{Price: price, Change: change, Volume: volume}, nil
}

The main main function uses the tablewriter package to display the stock data in a table:

func main() {
    data, err := fetchData()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    table := tablewriter.NewWriter(os.Stdout)
    table.SetHeader([]string{"Price", "Change (%)", "Volume"})
    table.SetAlignment(tablewriter.ALIGN_CENTER)
    table.Append([]string{fmt.Sprintf("%.2f", data.Price), fmt.Sprintf("%.2f", data.Change), fmt.Sprintf("%d", data.Volume)})
    table.Render()
}
Conclusion

This program demonstrates how to fetch real-time stock data from an API and display it in a command-line interface using the Go Programming Language.