-
Notifications
You must be signed in to change notification settings - Fork 1
/
historical_price.go
268 lines (242 loc) · 5.5 KB
/
historical_price.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package aastocks
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
"strings"
"time"
)
// HistoricalPrice is the historical price of quote.
type HistoricalPrice struct {
Time time.Time
Open float64
High float64
Low float64
Close float64
}
// PriceFrequency is the frequency of historical data to be provided.
type PriceFrequency int
const (
// Hourly price frequency
Hourly PriceFrequency = 23
// Daily price frequency
Daily PriceFrequency = 56
// Weekly price frequency
Weekly PriceFrequency = 67
// Monthly price frequency
Monthly PriceFrequency = 68
)
// HistoricalPrices fetches historical price of the quote from AAStocks.
func (q *Quote) HistoricalPrices(frequency PriceFrequency) ([]HistoricalPrice, error) {
url := fmt.Sprintf(`http://chartdata1.internet.aastocks.com/servlet/iDataServlet/getdaily?id=%s.HK&type=24&market=1&level=1&period=%v&encoding=utf8`, q.Symbol, frequency)
resp, err := q.client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
prices := make([]HistoricalPrice, 0)
r := newPriceScanner(resp.Body)
for r.Scan() {
if r.Blank() {
continue
}
prices = append(prices, r.Price())
}
return prices, r.Err()
}
type priceScanner struct {
scanner *bufio.Scanner
price HistoricalPrice
blank bool
err error
}
func newPriceScanner(r io.Reader) *priceScanner {
s := bufio.NewScanner(r)
s.Split(splitPriceData)
p := &priceScanner{
scanner: s,
}
// First scan is name of quote
p.scanner.Scan()
// Second scan is current price
p.scanner.Scan()
return p
}
const (
monthDayLayout = "01/02"
timeLayout = "15:04:05"
monthDayYearLayout = "01/02/2006"
)
func (s *priceScanner) Scan() bool {
if s.err != nil {
return false
}
if !s.scanner.Scan() {
return false
}
t := s.scanner.Text()
if t == "" {
s.blank = true
return true
}
s.blank = false
p, err := s.parsePrice(t)
if err != nil {
s.err = err
return false
}
s.price = p
return true
}
func (s *priceScanner) Price() HistoricalPrice {
return s.price
}
func (s *priceScanner) Err() error {
return s.err
}
func (s *priceScanner) Blank() bool {
return s.blank
}
func (s *priceScanner) parsePrice(str string) (HistoricalPrice, error) {
parts := strings.Split(str, ";")
if len(parts) != 7 && len(parts) != 8 {
return HistoricalPrice{}, fmt.Errorf("Failed to parse price data: %#v", str)
}
type parseFunc func(parts []string, idx int) (func(p *HistoricalPrice), error)
parseFuncs := []struct {
name string
parseFunc parseFunc
}{
{
name: "Time",
parseFunc: func(parts []string, idx int) (func(p *HistoricalPrice), error) {
var err error
t, err := s.priceTime(parts)
f := func(p *HistoricalPrice) {
p.Time = t
}
return f, err
},
},
{
name: "Open price",
parseFunc: func(parts []string, idx int) (func(p *HistoricalPrice), error) {
var err error
v, err := strconv.ParseFloat(parts[idx], 64)
f := func(p *HistoricalPrice) {
p.Open = v
}
return f, err
},
},
{
name: "High price",
parseFunc: func(parts []string, idx int) (func(p *HistoricalPrice), error) {
var err error
v, err := strconv.ParseFloat(parts[idx], 64)
f := func(p *HistoricalPrice) {
p.High = v
}
return f, err
},
},
{
name: "Low price",
parseFunc: func(parts []string, idx int) (func(p *HistoricalPrice), error) {
var err error
v, err := strconv.ParseFloat(parts[idx], 64)
f := func(p *HistoricalPrice) {
p.Low = v
}
return f, err
},
},
{
name: "Close price",
parseFunc: func(parts []string, idx int) (func(p *HistoricalPrice), error) {
var err error
v, err := strconv.ParseFloat(parts[idx], 64)
f := func(p *HistoricalPrice) {
p.Close = v
}
return f, err
},
},
}
startIdx := 0
if len(parts) == 8 {
startIdx = 1
}
p := HistoricalPrice{}
for i, f := range parseFuncs {
opt, err := f.parseFunc(parts, startIdx+i)
if err != nil {
return HistoricalPrice{}, fmt.Errorf("%s failed to be parsed: %v", f.name, err)
}
opt(&p)
}
return p, nil
}
func (s *priceScanner) priceTime(parts []string) (time.Time, error) {
if len(parts) == 8 {
pd, err := time.Parse(monthDayLayout, parts[0])
if err != nil {
return time.Time{}, err
}
ptt, err := time.Parse(timeLayout, parts[1])
if err != nil {
return time.Time{}, err
}
return time.Date(time.Now().Year(), pd.Month(), pd.Day(), ptt.Hour(), ptt.Minute(), ptt.Second(), ptt.Nanosecond(), time.UTC), nil
}
pt, err := time.Parse(monthDayYearLayout, parts[0])
if err != nil {
return time.Time{}, err
}
return pt, nil
}
func splitPriceData(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
pipe := bytes.IndexByte(data, '|')
exclam := bytes.IndexByte(data, '!')
if pipe >= 0 || exclam >= 0 {
var i int
if pipe >= 0 && exclam >= 0 {
i = min(pipe, exclam)
} else {
i = max(pipe, exclam) // split with one which is not -1
}
return i + 1, dropSeparatorRune(data[0:i]), nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), dropSeparatorRune(data), nil
}
// Request more data.
return 0, nil, nil
}
func dropSeparatorRune(data []byte) []byte {
if len(data) > 0 && data[len(data)-1] == '|' {
return data[0 : len(data)-1]
}
if len(data) > 0 && data[len(data)-1] == '!' {
return data[0 : len(data)-1]
}
return data
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}