-
Notifications
You must be signed in to change notification settings - Fork 82
/
quote.go
1578 lines (1351 loc) · 43.1 KB
/
quote.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Package quote is free quote downloader library and cli
Downloads daily/weekly/monthly historical price quotes from Yahoo
and daily/intraday data from Tiingo
Copyright 2024 Mark Chenoweth
Licensed under terms of MIT license (see LICENSE)
*/
package quote
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/textproto"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
)
// Quote - stucture for historical price data
type Quote struct {
Symbol string `json:"symbol"`
Precision int64 `json:"-"`
Date []time.Time `json:"date"`
Open []float64 `json:"open"`
High []float64 `json:"high"`
Low []float64 `json:"low"`
Close []float64 `json:"close"`
Volume []float64 `json:"volume"`
}
// Quotes - an array of historical price data
type Quotes []Quote
// Period - for quote history
type Period string
// ClientTimeout - connect/read timeout for client requests
const ClientTimeout = 10 * time.Second
const (
// Min1 - 1 Minute time period
Min1 Period = "60"
// Min3 - 3 Minute time period
Min3 Period = "3m"
// Min5 - 5 Minute time period
Min5 Period = "300"
// Min15 - 15 Minute time period
Min15 Period = "900"
// Min30 - 30 Minute time period
Min30 Period = "1800"
// Min60 - 60 Minute time period
Min60 Period = "3600"
// Hour2 - 2 hour time period
Hour2 Period = "2h"
// Hour4 - 4 hour time period
Hour4 Period = "4h"
// Hour6 - 6 hour time period
Hour6 Period = "6h"
// Hour8 - 8 hour time period
Hour8 Period = "8h"
// Hour12 - 12 hour time period
Hour12 Period = "12h"
// Daily time period
Daily Period = "d"
// Day3 - 3 day time period
Day3 Period = "3d"
// Weekly time period
Weekly Period = "w"
// Monthly time period
Monthly Period = "m"
)
// Log - standard logger, disabled by default
var Log *log.Logger
// Delay - time delay in milliseconds between quote requests (default=100)
// Be nice, don't get blocked
var Delay time.Duration
func init() {
Log = log.New(io.Discard, "quote: ", log.Ldate|log.Ltime|log.Lshortfile)
Delay = 100
}
// NewQuote - new empty Quote struct
func NewQuote(symbol string, bars int) Quote {
return Quote{
Symbol: symbol,
Date: make([]time.Time, bars),
Open: make([]float64, bars),
High: make([]float64, bars),
Low: make([]float64, bars),
Close: make([]float64, bars),
Volume: make([]float64, bars),
}
}
// ParseDateString - parse a potentially partial date string to Time
func ParseDateString(dt string) time.Time {
if dt == "" {
return time.Now()
}
t, _ := time.Parse("2006-01-02 15:04", dt+"0000-01-01 00:00"[len(dt):])
return t
}
func getPrecision(symbol string) int {
var precision int
precision = 2
if strings.Contains(strings.ToUpper(symbol), "BTC") ||
strings.Contains(strings.ToUpper(symbol), "ETH") ||
strings.Contains(strings.ToUpper(symbol), "USD") {
precision = 8
}
return precision
}
// CSV - convert Quote structure to csv string
func (q Quote) CSV() string {
precision := getPrecision(q.Symbol)
var buffer bytes.Buffer
buffer.WriteString("datetime,open,high,low,close,volume\n")
for bar := range q.Close {
str := fmt.Sprintf("%s,%.*f,%.*f,%.*f,%.*f,%.*f\n", q.Date[bar].Format("2006-01-02 15:04"),
precision, q.Open[bar], precision, q.High[bar], precision, q.Low[bar], precision, q.Close[bar], precision, q.Volume[bar])
buffer.WriteString(str)
}
return buffer.String()
}
// Highstock - convert Quote structure to Highstock json format
func (q Quote) Highstock() string {
precision := getPrecision(q.Symbol)
var buffer bytes.Buffer
buffer.WriteString("[\n")
for bar := range q.Close {
comma := ","
if bar == len(q.Close)-1 {
comma = ""
}
str := fmt.Sprintf("[%d,%.*f,%.*f,%.*f,%.*f,%.*f]%s\n",
q.Date[bar].UnixNano()/1000000, precision, q.Open[bar], precision, q.High[bar], precision, q.Low[bar], precision, q.Close[bar], precision, q.Volume[bar], comma)
buffer.WriteString(str)
}
buffer.WriteString("]\n")
return buffer.String()
}
// Amibroker - convert Quote structure to csv string
func (q Quote) Amibroker() string {
precision := getPrecision(q.Symbol)
var buffer bytes.Buffer
buffer.WriteString("date,time,open,high,low,close,volume\n")
for bar := range q.Close {
str := fmt.Sprintf("%s,%s,%.*f,%.*f,%.*f,%.*f,%.*f\n", q.Date[bar].Format("2006-01-02"), q.Date[bar].Format("15:04"),
precision, q.Open[bar], precision, q.High[bar], precision, q.Low[bar], precision, q.Close[bar], precision, q.Volume[bar])
buffer.WriteString(str)
}
return buffer.String()
}
// WriteCSV - write Quote struct to csv file
func (q Quote) WriteCSV(filename string) error {
if filename == "" {
if q.Symbol != "" {
filename = q.Symbol + ".csv"
} else {
filename = "quote.csv"
}
}
csv := q.CSV()
return os.WriteFile(filename, []byte(csv), 0644)
}
// WriteAmibroker - write Quote struct to csv file
func (q Quote) WriteAmibroker(filename string) error {
if filename == "" {
if q.Symbol != "" {
filename = q.Symbol + ".csv"
} else {
filename = "quote.csv"
}
}
csv := q.Amibroker()
return os.WriteFile(filename, []byte(csv), 0644)
}
// WriteHighstock - write Quote struct to Highstock json format
func (q Quote) WriteHighstock(filename string) error {
if filename == "" {
if q.Symbol != "" {
filename = q.Symbol + ".json"
} else {
filename = "quote.json"
}
}
csv := q.Highstock()
return os.WriteFile(filename, []byte(csv), 0644)
}
// NewQuoteFromCSV - parse csv quote string into Quote structure
func NewQuoteFromCSV(symbol, csv string) (Quote, error) {
tmp := strings.Split(csv, "\n")
numrows := len(tmp)
q := NewQuote(symbol, numrows-1)
for row, bar := 1, 0; row < numrows; row, bar = row+1, bar+1 {
line := strings.Split(tmp[row], ",")
if len(line) != 6 {
break
}
q.Date[bar], _ = time.Parse("2006-01-02 15:04", line[0])
q.Open[bar], _ = strconv.ParseFloat(line[1], 64)
q.High[bar], _ = strconv.ParseFloat(line[2], 64)
q.Low[bar], _ = strconv.ParseFloat(line[3], 64)
q.Close[bar], _ = strconv.ParseFloat(line[4], 64)
q.Volume[bar], _ = strconv.ParseFloat(line[5], 64)
}
return q, nil
}
// NewQuoteFromCSVDateFormat - parse csv quote string into Quote structure
// with specified DateTime format
func NewQuoteFromCSVDateFormat(symbol, csv string, format string) (Quote, error) {
tmp := strings.Split(csv, "\n")
numrows := len(tmp)
q := NewQuote("", numrows-1)
if len(strings.TrimSpace(format)) == 0 {
format = "2006-01-02 15:04"
}
for row, bar := 1, 0; row < numrows; row, bar = row+1, bar+1 {
line := strings.Split(tmp[row], ",")
q.Date[bar], _ = time.Parse(format, line[0])
q.Open[bar], _ = strconv.ParseFloat(line[1], 64)
q.High[bar], _ = strconv.ParseFloat(line[2], 64)
q.Low[bar], _ = strconv.ParseFloat(line[3], 64)
q.Close[bar], _ = strconv.ParseFloat(line[4], 64)
q.Volume[bar], _ = strconv.ParseFloat(line[5], 64)
}
return q, nil
}
// NewQuoteFromCSVFile - parse csv quote file into Quote structure
func NewQuoteFromCSVFile(symbol, filename string) (Quote, error) {
csv, err := os.ReadFile(filename)
if err != nil {
return NewQuote("", 0), err
}
return NewQuoteFromCSV(symbol, string(csv))
}
// NewQuoteFromCSVFileDateFormat - parse csv quote file into Quote structure
// with specified DateTime format
func NewQuoteFromCSVFileDateFormat(symbol, filename string, format string) (Quote, error) {
csv, err := os.ReadFile(filename)
if err != nil {
return NewQuote("", 0), err
}
return NewQuoteFromCSVDateFormat(symbol, string(csv), format)
}
// JSON - convert Quote struct to json string
func (q Quote) JSON(indent bool) string {
var j []byte
if indent {
j, _ = json.MarshalIndent(q, "", " ")
} else {
j, _ = json.Marshal(q)
}
return string(j)
}
// WriteJSON - write Quote struct to json file
func (q Quote) WriteJSON(filename string, indent bool) error {
if filename == "" {
filename = q.Symbol + ".json"
}
json := q.JSON(indent)
return os.WriteFile(filename, []byte(json), 0644)
}
// NewQuoteFromJSON - parse json quote string into Quote structure
func NewQuoteFromJSON(jsn string) (Quote, error) {
q := Quote{}
err := json.Unmarshal([]byte(jsn), &q)
if err != nil {
return q, err
}
return q, nil
}
// NewQuoteFromJSONFile - parse json quote string into Quote structure
func NewQuoteFromJSONFile(filename string) (Quote, error) {
jsn, err := os.ReadFile(filename)
if err != nil {
return NewQuote("", 0), err
}
return NewQuoteFromJSON(string(jsn))
}
// CSV - convert Quotes structure to csv string
func (q Quotes) CSV() string {
var buffer bytes.Buffer
buffer.WriteString("symbol,datetime,open,high,low,close,volume\n")
for sym := 0; sym < len(q); sym++ {
quote := q[sym]
precision := getPrecision(quote.Symbol)
for bar := range quote.Close {
str := fmt.Sprintf("%s,%s,%.*f,%.*f,%.*f,%.*f,%.*f\n",
quote.Symbol, quote.Date[bar].Format("2006-01-02 15:04"), precision, quote.Open[bar], precision, quote.High[bar], precision, quote.Low[bar], precision, quote.Close[bar], precision, quote.Volume[bar])
buffer.WriteString(str)
}
}
return buffer.String()
}
// Highstock - convert Quotes structure to Highstock json format
func (q Quotes) Highstock() string {
var buffer bytes.Buffer
buffer.WriteString("{")
for sym := 0; sym < len(q); sym++ {
quote := q[sym]
precision := getPrecision(quote.Symbol)
for bar := range quote.Close {
comma := ","
if bar == len(quote.Close)-1 {
comma = ""
}
if bar == 0 {
buffer.WriteString(fmt.Sprintf("\"%s\":[\n", quote.Symbol))
}
str := fmt.Sprintf("[%d,%.*f,%.*f,%.*f,%.*f,%.*f]%s\n",
quote.Date[bar].UnixNano()/1000000, precision, quote.Open[bar], precision, quote.High[bar], precision, quote.Low[bar], precision, quote.Close[bar], precision, quote.Volume[bar], comma)
buffer.WriteString(str)
}
if sym < len(q)-1 {
buffer.WriteString("],\n")
} else {
buffer.WriteString("]\n")
}
}
buffer.WriteString("}")
return buffer.String()
}
// Amibroker - convert Quotes structure to csv string
func (q Quotes) Amibroker() string {
var buffer bytes.Buffer
buffer.WriteString("symbol,date,time,open,high,low,close,volume\n")
for sym := 0; sym < len(q); sym++ {
quote := q[sym]
precision := getPrecision(quote.Symbol)
for bar := range quote.Close {
str := fmt.Sprintf("%s,%s,%s,%.*f,%.*f,%.*f,%.*f,%.*f\n",
quote.Symbol, quote.Date[bar].Format("2006-01-02"), quote.Date[bar].Format("15:04"), precision, quote.Open[bar], precision, quote.High[bar], precision, quote.Low[bar], precision, quote.Close[bar], precision, quote.Volume[bar])
buffer.WriteString(str)
}
}
return buffer.String()
}
// WriteCSV - write Quotes structure to file
func (q Quotes) WriteCSV(filename string) error {
if filename == "" {
filename = "quotes.csv"
}
csv := q.CSV()
ba := []byte(csv)
return os.WriteFile(filename, ba, 0644)
}
// WriteAmibroker - write Quotes structure to file
func (q Quotes) WriteAmibroker(filename string) error {
if filename == "" {
filename = "quotes.csv"
}
csv := q.Amibroker()
ba := []byte(csv)
return os.WriteFile(filename, ba, 0644)
}
// NewQuotesFromCSV - parse csv quote string into Quotes array
func NewQuotesFromCSV(csv string) (Quotes, error) {
quotes := Quotes{}
tmp := strings.Split(csv, "\n")
numrows := len(tmp)
var index = make(map[string]int)
for idx := 1; idx < numrows; idx++ {
sym := strings.Split(tmp[idx], ",")[0]
index[sym]++
}
row := 1
for sym, len := range index {
q := NewQuote(sym, len)
for bar := 0; bar < len; bar++ {
line := strings.Split(tmp[row], ",")
q.Date[bar], _ = time.Parse("2006-01-02 15:04", line[1])
q.Open[bar], _ = strconv.ParseFloat(line[2], 64)
q.High[bar], _ = strconv.ParseFloat(line[3], 64)
q.Low[bar], _ = strconv.ParseFloat(line[4], 64)
q.Close[bar], _ = strconv.ParseFloat(line[5], 64)
q.Volume[bar], _ = strconv.ParseFloat(line[6], 64)
row++
}
quotes = append(quotes, q)
}
return quotes, nil
}
// NewQuotesFromCSVFile - parse csv quote file into Quotes array
func NewQuotesFromCSVFile(filename string) (Quotes, error) {
csv, err := os.ReadFile(filename)
if err != nil {
return Quotes{}, err
}
return NewQuotesFromCSV(string(csv))
}
// JSON - convert Quotes struct to json string
func (q Quotes) JSON(indent bool) string {
var j []byte
if indent {
j, _ = json.MarshalIndent(q, "", " ")
} else {
j, _ = json.Marshal(q)
}
return string(j)
}
// WriteJSON - write Quote struct to json file
func (q Quotes) WriteJSON(filename string, indent bool) error {
if filename == "" {
filename = "quotes.json"
}
jsn := q.JSON(indent)
return os.WriteFile(filename, []byte(jsn), 0644)
}
// WriteHighstock - write Quote struct to json file in Highstock format
func (q Quotes) WriteHighstock(filename string) error {
if filename == "" {
filename = "quotes.json"
}
hc := q.Highstock()
return os.WriteFile(filename, []byte(hc), 0644)
}
// NewQuotesFromJSON - parse json quote string into Quote structure
func NewQuotesFromJSON(jsn string) (Quotes, error) {
quotes := Quotes{}
err := json.Unmarshal([]byte(jsn), "es)
if err != nil {
return quotes, err
}
return quotes, nil
}
// NewQuotesFromJSONFile - parse json quote string into Quote structure
func NewQuotesFromJSONFile(filename string) (Quotes, error) {
jsn, err := os.ReadFile(filename)
if err != nil {
return Quotes{}, err
}
return NewQuotesFromJSON(string(jsn))
}
// NewQuoteFromYahoo - Yahoo historical prices for a symbol
func NewQuoteFromYahoo(symbol, startDate, endDate string, period Period, adjustQuote bool) (Quote, error) {
var resp *http.Response
if period != Daily {
Log.Printf("Yahoo intraday data no longer supported\n")
return NewQuote("", 0), errors.New("yahoo intraday data no longer supported")
}
from := ParseDateString(startDate)
to := ParseDateString(endDate)
client := &http.Client{
Timeout: ClientTimeout,
}
initReq, err := http.NewRequest("GET", "https://finance.yahoo.com", nil)
if err != nil {
return NewQuote("", 0), err
}
initReq.Header.Set("User-Agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11")
client.Do(initReq)
url := fmt.Sprintf(
"https://query2.finance.yahoo.com/v8/finance/chart/%s?period1=%d&period2=%d&interval=1d&events=history&corsDomain=finance.yahoo.com",
symbol,
from.Unix(),
to.Unix())
resp, err = client.Get(url)
// Error getting response from the client.
if err != nil {
Log.Printf("Error: symbol '%s' not found\n", symbol)
return NewQuote("", 0), err
}
defer resp.Body.Close()
// Read all bytes of the response body.
respBody, err := io.ReadAll(resp.Body)
if err != nil {
Log.Printf("Error: bad data for symbol '%s'\n", symbol)
return NewQuote("", 0), err
}
// Unmarshal the bytes into a dynamic JSON object.
var jsonResponse map[string]interface{}
err = json.Unmarshal(respBody, &jsonResponse)
if err != nil {
Log.Printf("Error: bad data for symbol '%s'\n", symbol)
return NewQuote("", 0), err
}
// Dynamically parse the tree of JSON to get the data we need.
chart, ok := jsonResponse["chart"].(map[string]interface{})
if !ok {
Log.Printf("Error: Invalid chart structure within JSON response")
return NewQuote("", 0), err
}
result, ok := chart["result"].([]interface{})
if !ok || len(result) == 0 {
log.Fatal("Error: Invalid result structure within JSON response")
return NewQuote("", 0), err
}
firstResult, ok := result[0].(map[string]interface{})
if !ok {
log.Fatal("Error: Invalid result[0] structure within JSON response")
return NewQuote("", 0), err
}
timestamps, ok := firstResult["timestamp"].([]interface{})
if !ok {
log.Fatal("Error: Invalid timestamp structure within JSON response")
return NewQuote("", 0), err
}
indicators, ok := firstResult["indicators"].(map[string]interface{})
if !ok {
log.Fatal("Error: Invalid indicators structure within JSON response")
return NewQuote("", 0), err
}
quote, ok := indicators["quote"].([]interface{})
if !ok || len(quote) == 0 {
log.Fatal("Error: Invalid quote structure within JSON response")
return NewQuote("", 0), err
}
firstQuote, ok := quote[0].(map[string]interface{})
if !ok {
log.Fatal("Error: Invalid quote[0] structure within JSON response")
return NewQuote("", 0), err
}
high, ok := firstQuote["high"].([]interface{})
if !ok {
log.Fatal("Error: Invalid high structure within JSON response")
return NewQuote("", 0), err
}
low, ok := firstQuote["low"].([]interface{})
if !ok {
log.Fatal("Error: Invalid low structure within JSON response")
return NewQuote("", 0), err
}
open, ok := firstQuote["open"].([]interface{})
if !ok {
log.Fatal("Error: Invalid open structure within JSON response")
return NewQuote("", 0), err
}
volume, ok := firstQuote["volume"].([]interface{})
if !ok {
log.Fatal("Error: Invalid volume structure within JSON response")
return NewQuote("", 0), err
}
close, ok := firstQuote["close"].([]interface{})
if !ok {
log.Fatal("Error: Invalid close structure within JSON response")
return NewQuote("", 0), err
}
adjCloseObj, ok := indicators["adjclose"].([]interface{})
if !ok || len(quote) == 0 {
log.Fatal("Error: Invalid adjclose structure within JSON response")
return NewQuote("", 0), err
}
firstAdjClose, ok := adjCloseObj[0].(map[string]interface{})
if !ok {
log.Fatal("Error: Invalid adjclose[0] structure within JSON response")
return NewQuote("", 0), err
}
adjClose, ok := firstAdjClose["adjclose"].([]interface{})
if !ok {
log.Fatal("Error: Invalid adjclose inner structure within JSON response")
return NewQuote("", 0), err
}
quoteObj := NewQuote(symbol, len(timestamps))
for row := 0; row < len(timestamps); row++ {
o := open[row].(float64)
h := high[row].(float64)
l := low[row].(float64)
c := close[row].(float64)
a := adjClose[row].(float64)
v := volume[row].(float64)
quoteObj.Date[row] = time.Unix(int64(timestamps[row].(float64)), 0)
// Adjustment ratio
if adjustQuote {
quoteObj.Open[row] = o
quoteObj.High[row] = h
quoteObj.Low[row] = l
quoteObj.Close[row] = a
} else {
ratio := c / a
quoteObj.Open[row] = o * ratio
quoteObj.High[row] = h * ratio
quoteObj.Low[row] = l * ratio
quoteObj.Close[row] = c
}
quoteObj.Volume[row] = v
}
return quoteObj, nil
}
/*
func NewQuoteFromYahoo(symbol, startDate, endDate string, period Period, adjustQuote bool) (Quote, error) {
from := ParseDateString(startDate)
to := ParseDateString(endDate)
url := fmt.Sprintf(
"http://ichart.yahoo.com/table.csv?s=%s&a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&g=%s&ignore=.csv",
symbol,
from.Month()-1, from.Day(), from.Year(),
to.Month()-1, to.Day(), to.Year(),
period)
resp, err := http.Get(url)
if err != nil {
Log.Printf("symbol '%s' not found\n", symbol)
return NewQuote("", 0), err
}
defer resp.Body.Close()
var csvdata [][]string
reader := csv.NewReader(resp.Body)
csvdata, err = reader.ReadAll()
if err != nil {
Log.Printf("bad data for symbol '%s'\n", symbol)
return NewQuote("", 0), err
}
numrows := len(csvdata) - 1
quote := NewQuote(symbol, numrows)
for row := 1; row < len(csvdata); row++ {
// Parse row of data
d, _ := time.Parse("2006-01-02", csvdata[row][0])
o, _ := strconv.ParseFloat(csvdata[row][1], 64)
h, _ := strconv.ParseFloat(csvdata[row][2], 64)
l, _ := strconv.ParseFloat(csvdata[row][3], 64)
c, _ := strconv.ParseFloat(csvdata[row][4], 64)
v, _ := strconv.ParseFloat(csvdata[row][5], 64)
a, _ := strconv.ParseFloat(csvdata[row][6], 64)
// Adjustment factor
factor := 1.0
if adjustQuote {
factor = a / c
}
// Append to quote
bar := numrows - row // reverse the order
quote.Date[bar] = d
quote.Open[bar] = o * factor
quote.High[bar] = h * factor
quote.Low[bar] = l * factor
quote.Close[bar] = c * factor
quote.Volume[bar] = v
}
return quote, nil
}
*/
// NewQuotesFromYahoo - create a list of prices from symbols in file
func NewQuotesFromYahoo(filename, startDate, endDate string, period Period, adjustQuote bool) (Quotes, error) {
quotes := Quotes{}
inFile, err := os.Open(filename)
if err != nil {
return quotes, err
}
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
sym := scanner.Text()
quote, err := NewQuoteFromYahoo(sym, startDate, endDate, period, adjustQuote)
if err == nil {
quotes = append(quotes, quote)
}
time.Sleep(Delay * time.Millisecond)
}
return quotes, nil
}
// NewQuotesFromYahooSyms - create a list of prices from symbols in string array
func NewQuotesFromYahooSyms(symbols []string, startDate, endDate string, period Period, adjustQuote bool) (Quotes, error) {
quotes := Quotes{}
for _, symbol := range symbols {
quote, err := NewQuoteFromYahoo(symbol, startDate, endDate, period, adjustQuote)
if err == nil {
quotes = append(quotes, quote)
}
time.Sleep(Delay * time.Millisecond)
}
return quotes, nil
}
func tiingoDaily(symbol string, from, to time.Time, token string) (Quote, error) {
type tquote struct {
AdjClose float64 `json:"adjClose"`
AdjHigh float64 `json:"adjHigh"`
AdjLow float64 `json:"adjLow"`
AdjOpen float64 `json:"adjOpen"`
AdjVolume float64 `json:"adjVolume"`
Close float64 `json:"close"`
Date string `json:"date"`
DivCash float64 `json:"divCash"`
High float64 `json:"high"`
Low float64 `json:"low"`
Open float64 `json:"open"`
SplitFactor float64 `json:"splitFactor"`
Volume float64 `json:"volume"`
}
var tiingo []tquote
url := fmt.Sprintf(
"https://api.tiingo.com/tiingo/daily/%s/prices?startDate=%s&endDate=%s",
symbol,
url.QueryEscape(from.Format("2006-1-2")),
url.QueryEscape(to.Format("2006-1-2")))
client := &http.Client{Timeout: ClientTimeout}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", fmt.Sprintf("Token %s", token))
resp, err := client.Do(req)
if err != nil {
Log.Printf("tiingo error: %v\n", err)
return NewQuote("", 0), err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
contents, _ := io.ReadAll(resp.Body)
err = json.Unmarshal(contents, &tiingo)
if err != nil {
Log.Printf("tiingo error: %v\n", err)
return NewQuote("", 0), err
}
} else if resp.StatusCode == http.StatusNotFound {
Log.Printf("symbol '%s' not found\n", symbol)
return NewQuote("", 0), err
}
numrows := len(tiingo)
quote := NewQuote(symbol, numrows)
for bar := 0; bar < numrows; bar++ {
quote.Date[bar], _ = time.Parse("2006-01-02", tiingo[bar].Date[0:10])
quote.Open[bar] = tiingo[bar].AdjOpen
quote.High[bar] = tiingo[bar].AdjHigh
quote.Low[bar] = tiingo[bar].AdjLow
quote.Close[bar] = tiingo[bar].AdjClose
quote.Volume[bar] = float64(tiingo[bar].Volume)
}
return quote, nil
}
func tiingoCrypto(symbol string, from, to time.Time, period Period, token string) (Quote, error) {
resampleFreq := "1day"
switch period {
case Min1:
resampleFreq = "1min"
case Min3:
resampleFreq = "3min"
case Min5:
resampleFreq = "5min"
case Min15:
resampleFreq = "15min"
case Min30:
resampleFreq = "30min"
case Min60:
resampleFreq = "1hour"
case Hour2:
resampleFreq = "2hour"
case Hour4:
resampleFreq = "4hour"
case Hour6:
resampleFreq = "6hour"
case Hour8:
resampleFreq = "8hour"
case Hour12:
resampleFreq = "12hour"
case Daily:
resampleFreq = "1day"
}
type priceData struct {
TradesDone float64 `json:"tradesDone"`
Close float64 `json:"close"`
VolumeNotional float64 `json:"volumeNotional"`
Low float64 `json:"low"`
Open float64 `json:"open"`
Date string `json:"date"` // "2017-12-19T00:00:00Z"
High float64 `json:"high"`
Volume float64 `json:"volume"`
}
type cryptoData struct {
Ticker string `json:"ticker"`
BaseCurrency string `json:"baseCurrency"`
QuoteCurrency string `json:"quoteCurrency"`
PriceData []priceData `json:"priceData"`
}
var crypto []cryptoData
url := fmt.Sprintf(
"https://api.tiingo.com/tiingo/crypto/prices?tickers=%s&startDate=%s&endDate=%s&resampleFreq=%s",
symbol,
url.QueryEscape(from.Format("2006-1-2")),
url.QueryEscape(to.Format("2006-1-2")),
resampleFreq)
client := &http.Client{Timeout: ClientTimeout}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", fmt.Sprintf("Token %s", token))
resp, err := client.Do(req)
if err != nil {
Log.Printf("symbol '%s' not found\n", symbol)
return NewQuote("", 0), err
}
defer resp.Body.Close()
contents, _ := io.ReadAll(resp.Body)
err = json.Unmarshal(contents, &crypto)
if err != nil {
Log.Printf("tiingo crypto symbol '%s' error: %v\n", symbol, err)
return NewQuote("", 0), err
}
if len(crypto) < 1 {
Log.Printf("tiingo crypto symbol '%s' No data returned", symbol)
return NewQuote("", 0), err
}
numrows := len(crypto[0].PriceData)
quote := NewQuote(symbol, numrows)
for bar := 0; bar < numrows; bar++ {
quote.Date[bar], _ = time.Parse(time.RFC3339, crypto[0].PriceData[bar].Date)
quote.Open[bar] = crypto[0].PriceData[bar].Open
quote.High[bar] = crypto[0].PriceData[bar].High
quote.Low[bar] = crypto[0].PriceData[bar].Low
quote.Close[bar] = crypto[0].PriceData[bar].Close
quote.Volume[bar] = float64(crypto[0].PriceData[bar].Volume)
}
return quote, nil
}
// NewQuoteFromTiingo - Tiingo daily historical prices for a symbol
func NewQuoteFromTiingo(symbol, startDate, endDate string, token string) (Quote, error) {
from := ParseDateString(startDate)
to := ParseDateString(endDate)
return tiingoDaily(symbol, from, to, token)
}
// NewQuoteFromTiingoCrypto - Tiingo crypto historical prices for a symbol
func NewQuoteFromTiingoCrypto(symbol, startDate, endDate string, period Period, token string) (Quote, error) {
from := ParseDateString(startDate)
to := ParseDateString(endDate)
return tiingoCrypto(symbol, from, to, period, token)
}
// NewQuotesFromTiingoSyms - create a list of prices from symbols in string array
func NewQuotesFromTiingoSyms(symbols []string, startDate, endDate string, token string) (Quotes, error) {
quotes := Quotes{}
for _, symbol := range symbols {
quote, err := NewQuoteFromTiingo(symbol, startDate, endDate, token)
if err == nil {
quotes = append(quotes, quote)
} else {
Log.Println("error downloading " + symbol)
}
time.Sleep(Delay * time.Millisecond)
}
return quotes, nil
}
// NewQuotesFromTiingoCryptoSyms - create a list of prices from symbols in string array
func NewQuotesFromTiingoCryptoSyms(symbols []string, startDate, endDate string, period Period, token string) (Quotes, error) {
quotes := Quotes{}
for _, symbol := range symbols {
quote, err := NewQuoteFromTiingoCrypto(symbol, startDate, endDate, period, token)
if err == nil {
quotes = append(quotes, quote)
} else {
Log.Println("error downloading " + symbol)
}
time.Sleep(Delay * time.Millisecond)
}
return quotes, nil
}
// NewQuoteFromCoinbase - Coinbase Pro historical prices for a symbol
func NewQuoteFromCoinbase(symbol, startDate, endDate string, period Period) (Quote, error) {
start := ParseDateString(startDate) //.In(time.Now().Location())
end := ParseDateString(endDate) //.In(time.Now().Location())
var granularity int // seconds
switch period {
case Min1:
granularity = 60
case Min5:
granularity = 5 * 60
case Min15:
granularity = 15 * 60
case Min30:
granularity = 30 * 60
case Min60:
granularity = 60 * 60
case Daily:
granularity = 24 * 60 * 60
case Weekly:
granularity = 7 * 24 * 60 * 60
default:
granularity = 24 * 60 * 60
}
var quote Quote