-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stocks.go
52 lines (46 loc) · 1.29 KB
/
stocks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Package stocks is defining a Go package named "stocks" that contains functions for retrieving and
// processing stock data from Yahoo Finance API.
package stocks
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
// GetFullDetails retrieves full details of a stock using its ticker symbol from Yahoo Finance API and
// returns the result.
func GetFullDetails(ticker string) *Result {
res, err := http.Get(fmt.Sprintf(yahooURL, ticker))
if err != nil {
println(err)
return nil
}
var out tLR
d := json.NewDecoder(res.Body)
err = d.Decode(&out)
if err != nil || len(out.QuoteResponse.Result) == 0 {
if err != nil {
println(err)
}
return nil
}
return &out.QuoteResponse.Result[0]
}
// GetPriceAndPercentage returns the price, percentage change, and direction of a given stock ticker.
func GetPriceAndPercentage(ticker string) (string, string, string) {
det := GetFullDetails(ticker)
if det == nil {
return "", "", ""
}
trimmedPrice := strconv.FormatFloat(det.RegularMarketPrice, 'f', 2, 64)
trimmedPercent := strconv.FormatFloat(det.RegularMarketChangePercent, 'f', 2, 64)
var direction string
if det.RegularMarketChangePercent < 0 {
//We are down
direction = "↓"
} else {
//We are up
direction = "↑"
}
return "$" trimmedPrice, trimmedPercent "%", direction
}