-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock.go
89 lines (76 loc) · 2.33 KB
/
stock.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Package stock allows to use yahoo finance api to get historical quotes data
It uses YQL pointing to yahoo.finance.historicaldata to get the necessary info
*/
package yahoofinance
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
)
const (
YQL_HISTORICAL_DATA = "select Date, Close from yahoo.finance.historicaldata where symbol=\"%s\" and startDate=\"%s\" and endDate=\"%s\""
YQL_WEB_SERVICE_URL = "http://query.yahooapis.com/v1/public/yql?format=json&diagnostics=false&callback=&%s"
)
// Aux struct to unmarshal API Response
type rootResult struct {
Query queryInfo
}
// Aux struct to unmarshal API Response
type queryInfo struct {
Results resultsInfo
}
// Aux struct to unmarshal API Response
type resultsInfo struct {
Quote []quoteInfo
}
// Aux struct to unmarshal API Response
type quoteInfo struct {
Close string
Date string
}
type Quote struct {
Close float64
Date time.Time
Avg float64
Top float64
Bottom float64
}
// Set the correct data types to allow to work with quotes and reverse order
func normalize(quotesOriginal []quoteInfo) (quotes []Quote) {
var length = len(quotesOriginal)
quotes = make([]Quote, length)
for i, q := range quotesOriginal {
close, err := strconv.ParseFloat(q.Close, 64)
perror(err)
date, err := time.Parse("2006-01-02", q.Date)
perror(err)
quotes[length - i - 1] = Quote{Close: close, Date: date}
}
return
}
func perror(err error) {
if err != nil {
panic(err)
}
}
func HistoricalPrices(symbol string, start, end time.Time) []Quote {
yql := fmt.Sprintf(YQL_HISTORICAL_DATA, symbol, start.Format("2006-01-02"), end.Format("2006-01-02")) // Replace dynamic info for q Param
v := url.Values{} //I use v to hack reserved symbols to be encoded before API call
v.Set("q", yql)
v.Add("env", "store://datatables.org/alltableswithkeys")
yqlUrl := fmt.Sprintf(YQL_WEB_SERVICE_URL, v.Encode())
resp, err := http.Get(yqlUrl) //Call to Yahoo API
perror(err)
defer resp.Body.Close() //Automatic close resp after use it
body, err := ioutil.ReadAll(resp.Body) //Get reponse
perror(err)
var data rootResult
err = json.Unmarshal(body, &data) //Fill aux struct with API response
perror(err)
return normalize(data.Query.Results.Quote) //Return quotes
}