-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbtengine.go
103 lines (91 loc) · 2.5 KB
/
btengine.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
package malgova
import (
"log"
"reflect"
"sync"
"time"
"github.com/sivamgr/kstreamdb"
)
// BacktestEngine struct
type BacktestEngine struct {
algos []reflect.Type
orders []orderEntry
scores []AlgoScore
}
// RegisterAlgo BacktestEngine
func (bt *BacktestEngine) RegisterAlgo(a interface{}) {
if bt.algos == nil {
bt.algos = make([]reflect.Type, 0)
}
bt.algos = append(bt.algos, reflect.TypeOf(a))
}
// RunAlgoBetweenDate method
func (bt *BacktestEngine) RunAlgoBetweenDate(feed *kstreamdb.DB, oms OrderManager, algoName string, startDate time.Time, endDate time.Time) {
selectedAlgo := make([]reflect.Type, 0)
for _, a := range bt.algos {
if a.Name() == algoName {
selectedAlgo = append(selectedAlgo, a)
break
}
}
if len(selectedAlgo) == 0 {
return
}
dates, _ := feed.GetDates()
dayRunner := btDayRunner{}
dayRunner.setup(selectedAlgo)
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
var wg sync.WaitGroup
for _, dt := range dates {
if dt.Format("20060102") < startDate.Format("20060102") || dt.Format("20060102") > endDate.Format("20060102") {
continue
}
log.Printf("[%s] Loading data", dt.Format("2006/01/02"))
data, _ := feed.LoadDataForDate(dt)
log.Printf("[%s] %d ticks loaded", dt.Format("2006/01/02"), len(data))
wg.Wait()
wg.Add(1)
go func(d time.Time) {
dayRunner.run(d, data)
wg.Done()
log.Printf("[%s] Completed", d.Format("2006/01/02"))
}(dt)
}
wg.Wait()
dayRunner.exit()
//pull the orders from the run
bt.orders = dayRunner.popOrders()
// analyze the orders and generate scores for algo
bt.scores = calculateAlgoScores(bt.orders)
}
// Run BacktestEngine
func (bt *BacktestEngine) Run(feed *kstreamdb.DB, oms OrderManager) {
// Load All Data into memory
dates, _ := feed.GetDates()
dayRunner := btDayRunner{}
dayRunner.setup(bt.algos)
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
var wg sync.WaitGroup
for _, dt := range dates {
log.Printf("[%s] Loading data", dt.Format("2006/01/02"))
data, _ := feed.LoadDataForDate(dt)
log.Printf("[%s] %d ticks loaded", dt.Format("2006/01/02"), len(data))
wg.Wait()
wg.Add(1)
go func(d time.Time) {
dayRunner.run(d, data)
wg.Done()
log.Printf("[%s] Completed", d.Format("2006/01/02"))
}(dt)
}
wg.Wait()
dayRunner.exit()
//pull the orders from the run
bt.orders = dayRunner.popOrders()
// analyze the orders and generate scores for algo
bt.scores = calculateAlgoScores(bt.orders)
}
// Scores returns the scores calculated
func (bt *BacktestEngine) Scores() []AlgoScore {
return bt.scores
}