-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
local.go
204 lines (167 loc) · 4.63 KB
/
local.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
package optimizer
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"github.com/cheggaaa/pb/v3"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/c9s/bbgo/pkg/backtest"
)
var log = logrus.WithField("component", "optimizer")
type BacktestTask struct {
ConfigJson []byte
Params []interface{}
Labels []string
Report *backtest.SummaryReport
Error error
}
type Executor interface {
Execute(configJson []byte) (*backtest.SummaryReport, error)
Run(ctx context.Context, taskC chan BacktestTask, bar *pb.ProgressBar) (chan BacktestTask, error)
}
type AsyncHandle struct {
Error error
Report *backtest.SummaryReport
Done chan struct{}
}
type LocalProcessExecutor struct {
Config *LocalExecutorConfig
Bin string
WorkDir string
ConfigDir string
OutputDir string
}
func (e *LocalProcessExecutor) ExecuteAsync(configJson []byte) *AsyncHandle {
handle := &AsyncHandle{
Done: make(chan struct{}),
}
go func() {
defer close(handle.Done)
report, err := e.Execute(configJson)
handle.Error = err
handle.Report = report
}()
return handle
}
func (e *LocalProcessExecutor) readReport(reportPath string) (*backtest.SummaryReport, error) {
summaryReportFilepath := strings.TrimSpace(reportPath)
_, err := os.Stat(summaryReportFilepath)
if os.IsNotExist(err) {
return nil, err
}
summaryReport, err := backtest.ReadSummaryReport(summaryReportFilepath)
if err != nil {
return nil, err
}
return summaryReport, nil
}
// Prepare prepares the environment for the following back tests
// this is a blocking operation
func (e *LocalProcessExecutor) Prepare(configJson []byte) error {
log.Debugln("syncing backtest data before starting backtests...")
tf, err := jsonToYamlConfig(e.ConfigDir, configJson)
if err != nil {
return err
}
c := exec.Command(e.Bin, "backtest", "--sync", "--sync-only", "--config", tf.Name())
output, err := c.Output()
if err != nil {
return errors.Wrapf(err, "failed to sync backtest data: %s", string(output))
}
return nil
}
func (e *LocalProcessExecutor) Run(ctx context.Context, taskC chan BacktestTask, bar *pb.ProgressBar) (chan BacktestTask, error) {
var maxNumOfProcess = e.Config.MaxNumberOfProcesses
var resultsC = make(chan BacktestTask, maxNumOfProcess*2)
wg := sync.WaitGroup{}
wg.Add(maxNumOfProcess)
go func() {
wg.Wait()
close(resultsC)
}()
for i := 0; i < maxNumOfProcess; i++ {
// fork workers
go func(id int, taskC chan BacktestTask) {
taskCnt := 0
bar.Set("log", fmt.Sprintf("starting local worker #%d", id))
bar.Write()
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case task, ok := <-taskC:
if !ok {
return
}
taskCnt++
bar.Set("log", fmt.Sprintf("local worker #%d received param task: %v", id, task.Params))
bar.Write()
report, err := e.Execute(task.ConfigJson)
if err != nil {
if err2, ok := err.(*exec.ExitError); ok {
log.WithError(err).Errorf("execute error: %s", err2.Stderr)
} else {
log.WithError(err).Errorf("execute error")
}
}
task.Error = err
task.Report = report
resultsC <- task
}
}
}(i+1, taskC)
}
return resultsC, nil
}
// Execute runs the config json and returns the summary report. This is a blocking operation.
func (e *LocalProcessExecutor) Execute(configJson []byte) (*backtest.SummaryReport, error) {
tf, err := jsonToYamlConfig(e.ConfigDir, configJson)
if err != nil {
return nil, err
}
c := exec.Command(e.Bin, "backtest", "--config", tf.Name(), "--output", e.OutputDir, "--subdir")
output, err := c.Output()
if err != nil {
log.WithError(err).WithField("command", []string{e.Bin, "backtest", "--config", tf.Name(), "--output", e.OutputDir, "--subdir"}).Errorf("failed to execute backtest")
return nil, err
}
// the last line is the report path
scanner := bufio.NewScanner(bytes.NewBuffer(output))
var reportFilePath string
for scanner.Scan() {
reportFilePath = scanner.Text()
}
return e.readReport(reportFilePath)
}
// jsonToYamlConfig translate json format config into a YAML format config file
// The generated file is a temp file
func jsonToYamlConfig(dir string, configJson []byte) (*os.File, error) {
var o map[string]interface{}
if err := json.Unmarshal(configJson, &o); err != nil {
return nil, err
}
yamlConfig, err := yaml.Marshal(o)
if err != nil {
return nil, err
}
tf, err := os.CreateTemp(dir, "bbgo-*.yaml")
if err != nil {
return nil, err
}
if _, err = tf.Write(yamlConfig); err != nil {
return nil, err
}
if err := tf.Close(); err != nil {
return nil, err
}
return tf, nil
}