bbgo_origin/pkg/optimizer/local.go

71 lines
1.3 KiB
Go
Raw Normal View History

package optimizer
import (
"encoding/json"
"os"
"os/exec"
2022-05-19 12:31:25 +00:00
"strings"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
2022-05-19 12:31:25 +00:00
"github.com/c9s/bbgo/pkg/backtest"
)
var log = logrus.WithField("component", "optimizer")
type Executor interface {
2022-05-19 12:31:25 +00:00
Execute(configJson []byte) (*backtest.SummaryReport, error)
}
type LocalProcessExecutor struct {
2022-05-19 12:31:25 +00:00
Bin string
WorkDir string
ConfigDir string
OutputDir string
}
2022-05-19 12:31:25 +00:00
func (e *LocalProcessExecutor) Execute(configJson []byte) (*backtest.SummaryReport, error) {
var o map[string]interface{}
if err := json.Unmarshal(configJson, &o); err != nil {
2022-05-19 12:31:25 +00:00
return nil, err
}
yamlConfig, err := yaml.Marshal(o)
if err != nil {
2022-05-19 12:31:25 +00:00
return nil, err
}
tf, err := os.CreateTemp(e.ConfigDir, "bbgo-*.yaml")
if err != nil {
2022-05-19 12:31:25 +00:00
return nil, err
}
if _, err = tf.Write(yamlConfig); err != nil {
2022-05-19 12:31:25 +00:00
return nil, err
}
2022-06-20 03:07:48 +00:00
if err := tf.Close(); err != nil {
return nil, err
}
c := exec.Command(e.Bin, "backtest", "--config", tf.Name(), "--output", e.OutputDir, "--subdir")
2022-05-19 12:31:25 +00:00
output, err := c.Output()
if err != nil {
return nil, err
}
summaryReportFilepath := strings.TrimSpace(string(output))
_, err = os.Stat(summaryReportFilepath)
if os.IsNotExist(err) {
return nil, err
}
summaryReport, err := backtest.ReadSummaryReport(summaryReportFilepath)
if err != nil {
return nil, err
}
2022-05-19 12:31:25 +00:00
return summaryReport, nil
}