2022-05-19 10:23:12 +00:00
|
|
|
package optimizer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2022-05-19 12:31:25 +00:00
|
|
|
"strings"
|
2022-05-19 10:23:12 +00:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"gopkg.in/yaml.v3"
|
2022-05-19 12:31:25 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/backtest"
|
2022-05-19 10:23:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var log = logrus.WithField("component", "optimizer")
|
|
|
|
|
|
|
|
type Executor interface {
|
2022-05-19 12:31:25 +00:00
|
|
|
Execute(configJson []byte) (*backtest.SummaryReport, error)
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type LocalProcessExecutor struct {
|
2022-05-19 12:31:25 +00:00
|
|
|
Bin string
|
|
|
|
WorkDir string
|
|
|
|
ConfigDir string
|
|
|
|
OutputDir string
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 12:31:25 +00:00
|
|
|
func (e *LocalProcessExecutor) Execute(configJson []byte) (*backtest.SummaryReport, error) {
|
2022-05-19 10:23:12 +00:00
|
|
|
var o map[string]interface{}
|
|
|
|
if err := json.Unmarshal(configJson, &o); err != nil {
|
2022-05-19 12:31:25 +00:00
|
|
|
return nil, err
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
yamlConfig, err := yaml.Marshal(o)
|
|
|
|
if err != nil {
|
2022-05-19 12:31:25 +00:00
|
|
|
return nil, err
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
tf, err := os.CreateTemp(e.ConfigDir, "bbgo-*.yaml")
|
|
|
|
if err != nil {
|
2022-05-19 12:31:25 +00:00
|
|
|
return nil, err
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err = tf.Write(yamlConfig); err != nil {
|
2022-05-19 12:31:25 +00:00
|
|
|
return nil, err
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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 10:23:12 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 12:31:25 +00:00
|
|
|
return summaryReport, nil
|
2022-05-19 10:23:12 +00:00
|
|
|
}
|