forked from aktau/gofinance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlc.go
464 lines (394 loc) · 11.3 KB
/
sqlc.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
package sqlitecache
import (
"database/sql"
"fmt"
"github.com/aktau/gofinance/fquery"
"github.com/aktau/gofinance/util"
"github.com/coopernurse/gorp"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"strings"
"sync"
"time"
)
/* a version of the fquery.HistEntry struct with a symbol appended,
* so we can query it easier. */
type dbHistEntry struct {
Symbol string
Date time.Time
Open float64
Close float64
AdjClose float64
High float64
Low float64
Volume int64
}
type dbHistMeta struct {
Symbol string
Amount int64
MinDate int64
MaxDate int64
/* processed versions of MinDate/MaxDate */
rMinDate time.Time
rMaxDate time.Time
}
var (
VERBOSITY = 0
)
type SqliteCache struct {
fquery.Source
gorp *gorp.DbMap
quoteExpiry time.Duration
}
func New(path string, src fquery.Source) (*SqliteCache, error) {
db, err := sql.Open("sqlite3", path)
if err != nil {
return nil, err
}
db.Exec("PRAGMA synchronous=NORMAL")
db.Exec("PRAGMA journal_mode=WAL")
db.Exec("PRAGMA temp_store=MEMORY")
db.Exec("PRAGMA cache_size=4096")
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
if VERBOSITY >= 2 {
dbmap.TraceOn("", log.New(os.Stdout, "dbmap: ", log.Lmicroseconds))
}
c := &SqliteCache{src, dbmap, 30 * time.Second}
c.gorp.AddTableWithName(fquery.Quote{}, "quotes").SetKeys(false, "Symbol")
c.gorp.AddTableWithName(dbHistEntry{}, "histquotes").SetKeys(false, "Symbol", "Date")
err = c.gorp.CreateTablesIfNotExists()
if err != nil {
c.Close()
return nil, err
}
/* support date range queries over all symbols */
_, err = c.gorp.Exec(`CREATE INDEX IF NOT EXISTS hq_date_idx ON histquotes (Date)`)
if err != nil {
c.Close()
return nil, err
}
return c, nil
}
func (c *SqliteCache) SetQuoteExpiry(dur time.Duration) {
c.quoteExpiry = dur
}
func (c *SqliteCache) HasQuote(symbol string) bool {
return false
}
func (c *SqliteCache) HasHist(symbol string, start *time.Time, end *time.Time) bool {
return false
}
func (c *SqliteCache) Close() error {
return c.gorp.Db.Close()
}
/* TODO: escape your strings, symbols could be user input */
func (c *SqliteCache) Quote(symbols []string) ([]fquery.Quote, error) {
/* fetch all the quotes we have */
quotedSymbols := quoteSymbols(symbols)
var results []fquery.Quote
cutoff := time.Now().Add(-c.quoteExpiry)
_, err := c.gorp.Select(&results,
fmt.Sprintf(
"SELECT * FROM quotes WHERE Symbol IN (%v) AND Updated >= datetime(%v, 'unixepoch')",
strings.Join(quotedSymbols, ","), cutoff.Unix()))
if err != nil {
/* if an error occured, just patch through to the source */
vprintln("sqlitecache: error while fetching quotes, ", err, ", will use underlying source")
return c.Source.Quote(symbols)
}
/* in case no error occured, check which ones were not in the cache,
* they need to be added to the list of quotes to fetch from the src */
quoteMap := fquery.QuotesToMap(results)
toFetch := make([]string, 0, len(symbols))
for _, symbol := range symbols {
if _, ok := quoteMap[symbol]; !ok {
toFetch = append(toFetch, symbol)
vprintln(symbol, "was NOT fetched from cache!")
} else {
vprintln(symbol, "was fetched from cache!")
}
}
/* fetch all missing items, store in cache and add to the results we
* already got from the cache */
fetched, err := c.Source.Quote(toFetch)
if err != nil {
vprintf("sqlitecache: error while fetching either of %v: %v\n", toFetch, err)
return results, nil
}
err = c.mergeQuotes(fetched...)
if err != nil {
vprintf("sqlitecache: error, could not merge quotes of %v into cache, %v\n", toFetch, err)
}
results = append(results, fetched...)
return results, nil
}
/* I consider this to be an extremely dirty function, it should be split up
* and possibly (hopefully) simplified*/
func (c *SqliteCache) Hist(symbols []string) (map[string]fquery.Hist, error) {
/* fetch all the historical results we have in the cache */
symbolSet := sliceToSet(symbols)
/* find out how many entries we have per symbol (we do this so we can
* process the cached symbols and fetch the missing ones in parallel */
sqliteCastToUnix := func(selector string) string {
return `strftime('%s',` + selector + `)`
}
var meta []*dbHistMeta
_, err := c.gorp.Select(&meta,
fmt.Sprintf(
`SELECT Symbol, count(Symbol) AS Amount,
%v AS MinDate,
%v AS MaxDate
FROM histquotes
WHERE Symbol IN (%v)
GROUP BY Symbol`,
sqliteCastToUnix("min(Date)"),
sqliteCastToUnix("max(Date)"),
strings.Join(quoteSymbols(symbols), ",")))
if err != nil {
/* if an error occured, just patch through to the source */
vprintln("sqlitecache: error while fetching history metadata, ", err, ", will use underlying source")
return c.Source.Hist(symbols)
}
/* convert the timestamps from UNIX timestamps to time.Time */
for _, m := range meta {
m.rMinDate = time.Unix(m.MinDate, 0)
m.rMaxDate = time.Unix(m.MaxDate, 0)
}
/* convert the meta list to a map, for easier searching */
metaMap := make(map[string]*dbHistMeta, len(meta))
for _, m := range meta {
metaMap[m.Symbol] = m
}
yesterday := Yesterday()
missing := make([]string, 0, len(symbols))
for _, s := range symbols {
m, found := metaMap[s]
if !found {
vprintln(s, "was NOT fetched from cache!")
missing = append(missing, s)
} else {
if m.rMaxDate.Before(yesterday) {
vprintln(s, "was NOT fetched from cache! (historical prices "+
"not recent enough), last available date was",
m.rMaxDate.Format("02/01/2006"))
missing = append(missing, s)
delete(symbolSet, s)
} else {
vprintln(s, "was fetched from cache!")
}
}
}
hist := make(map[string]fquery.Hist, len(symbols))
var (
histmutex sync.Mutex
wg sync.WaitGroup
)
if len(symbolSet) > 0 {
adjSymbols := setToSlice(symbolSet)
vprintln("fetching", adjSymbols, "from the SQLite db")
/* now query the actual entries */
var results []dbHistEntry
_, err = c.gorp.Select(&results,
fmt.Sprintf(
`SELECT * FROM histquotes WHERE Symbol IN (%v) ORDER BY Symbol, Date`,
strings.Join(quoteSymbols(adjSymbols), ",")))
if err != nil {
/* if an error occured, just patch through to the source */
vprintln("sqlitecache: error while fetching historical quotes, ", err, ", will use underlying source")
return c.Source.Hist(symbols)
}
/* process the dbHistEntries into fquery.Hist structures */
wg.Add(1)
go func() {
defer wg.Done()
var (
cursymb string
curhist fquery.Hist
)
for _, e := range results {
/* detect transitions between symbols */
if cursymb != e.Symbol {
/* if this is not the first iteration, finish up the hist
* entry we've been working on */
if len(cursymb) != 0 {
histmutex.Lock()
hist[cursymb] = curhist
histmutex.Unlock()
}
/* move to the following symbol */
info := metaMap[e.Symbol]
cursymb = e.Symbol
curhist = fquery.Hist{
Symbol: e.Symbol,
From: info.rMinDate,
To: info.rMaxDate,
Entries: make([]fquery.HistEntry, 0, info.Amount),
}
}
curhist.Entries = append(curhist.Entries, normalizeHistEntry(&e))
}
/* add the last one too */
histmutex.Lock()
hist[cursymb] = curhist
histmutex.Unlock()
}()
}
/* fetch the missing entries from the original source */
if len(missing) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
/* fetch the missing symbols */
missingMap, err := c.Source.Hist(missing)
if err != nil {
vprintln("sqlitecache: error occured while fetching missing", missing, "hist. quotes,", err)
} else {
missinglist := make([]fquery.Hist, 0, len(missingMap))
for symbol, history := range missingMap {
histmutex.Lock()
hist[symbol] = history
histmutex.Unlock()
missinglist = append(missinglist, history)
}
/* add the previously missing items to the cache, so we don't have to
* request them again */
c.mergeHistory(missinglist...)
}
}()
}
wg.Wait()
return hist, nil
}
/*
func (c *SqliteCache) HistLimit(symbol []string, start time.Time, end time.Time) (map[string]fquery.Hist, error) {
return nil, fmt.Errorf("not supported")
}
func (c *SqliteCache) DividendHist(symbol []string) (map[string]fquery.DividendHist, error) {
return nil, fmt.Errorf("not supported")
}
func (c *SqliteCache) DividendHistLimit(symbol []string, start time.Time, end time.Time) (map[string]fquery.DividendHist, error) {
return nil, fmt.Errorf("not supported")
}
*/
func (c *SqliteCache) String() string {
return "SQLite cache, backed by: " + c.String()
}
func (c *SqliteCache) mergeQuotes(quotes ...fquery.Quote) error {
if len(quotes) == 0 {
return nil
}
tx, err := c.gorp.Begin()
if err != nil {
return err
}
for _, quote := range quotes {
vprintln("merging quote: ", quote.Symbol)
count, err := tx.Update("e)
if err == nil && count == 1 {
continue
}
vprintln("sqlitecache: error while UPDATE'ing symbol", quote.Symbol,
"err:", err, ", count:", count)
/* update didn't work, so try insert */
err = tx.Insert("e)
if err != nil {
vprintln("sqlitecache: error while INSERTing", err)
}
}
return tx.Commit()
}
func (c *SqliteCache) mergeHistory(hists ...fquery.Hist) error {
if len(hists) == 0 {
return nil
}
tx, err := c.gorp.Begin()
if err != nil {
return err
}
for _, hist := range hists {
/* delete values we're going to override anyway */
vprintln("deleting potentially already stored history for symbol",
hist.Symbol, "from", hist.From, "to", hist.To)
delquery := `DELETE
FROM histquotes
WHERE Symbol = '%v'
AND Date BETWEEN datetime(%v, 'unixepoch')
AND datetime(%v, 'unixepoch')`
delquery = fmt.Sprintf(delquery, hist.Symbol, hist.From.Unix(), hist.To.Unix())
_, err := tx.Exec(delquery)
if err != nil {
vprintln("sqlitecache: mergeHistory: error while deleting, query:",
delquery, "error:", err)
}
vprintln("merging history:", hist.Symbol)
for _, entry := range hist.Entries {
/* insert */
err := tx.Insert(newDbHistEntry(hist.Symbol, &entry))
if err != nil {
vprintln("sqlitecache: mergeHistory: error while INSERTing", err)
}
}
}
return tx.Commit()
}
func vprintln(a ...interface{}) (int, error) {
if VERBOSITY > 0 {
return fmt.Println(a...)
}
return 0, nil
}
func vprintf(format string, a ...interface{}) (int, error) {
if VERBOSITY > 0 {
return fmt.Printf(format, a...)
}
return 0, nil
}
func quoteSymbols(symbols []string) []string {
return util.MapStr(func(s string) string {
return `'` + s + `'`
}, symbols)
}
func normalizeHistEntry(e *dbHistEntry) fquery.HistEntry {
return fquery.HistEntry{
Date: util.YearMonthDay(e.Date),
Open: e.Open,
Close: e.Close,
AdjClose: e.AdjClose,
Low: e.Low,
High: e.High,
Volume: e.Volume,
}
}
func newDbHistEntry(symbol string, e *fquery.HistEntry) *dbHistEntry {
return &dbHistEntry{
Symbol: symbol,
Date: time.Time(e.Date),
Open: e.Open,
Close: e.Close,
AdjClose: e.AdjClose,
Low: e.Low,
High: e.High,
Volume: e.Volume,
}
}
func Yesterday() time.Time {
const day = 24 * time.Hour
return time.Now().Add(-1 * day)
}
func sliceToSet(xs []string) map[string]bool {
m := make(map[string]bool, len(xs))
for _, x := range xs {
m[x] = true
}
return m
}
func setToSlice(m map[string]bool) []string {
xs := make([]string, len(m))
idx := 0
for str := range m {
xs[idx] = str
idx++
}
return xs
}