/
main.go
203 lines (185 loc) · 5.94 KB
/
main.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
// Copyright 2022 Stock Parfait
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
"runtime/pprof"
"sort"
"github.com/stockparfait/errors"
"github.com/stockparfait/experiments"
"github.com/stockparfait/experiments/autocorr"
"github.com/stockparfait/experiments/beta"
"github.com/stockparfait/experiments/config"
"github.com/stockparfait/experiments/distribution"
"github.com/stockparfait/experiments/hold"
"github.com/stockparfait/experiments/portfolio"
"github.com/stockparfait/experiments/powerdist"
"github.com/stockparfait/experiments/simulator"
"github.com/stockparfait/experiments/trading"
"github.com/stockparfait/logging"
"github.com/stockparfait/stockparfait/plot"
)
type Flags struct {
DBDir string // default: ~/.stockparfait/sharadar
Config string // required
LogLevel logging.Level
DataJsPath string // write data.js to this path
DataJSONPath string // write data.json to this path
CPUProf string // write CPU profiling data to this file
}
func parseFlags(args []string) (*Flags, error) {
var flags Flags
fs := flag.NewFlagSet("experiments", flag.ExitOnError)
fs.StringVar(&flags.DBDir, "cache",
filepath.Join(os.Getenv("HOME"), ".stockparfait", "sharadar"),
"database path")
fs.StringVar(&flags.Config, "conf", "", "configuration file (required)")
flags.LogLevel = logging.Info
fs.Var(&flags.LogLevel, "log-level", "Log level: debug, info, warning, error")
fs.StringVar(&flags.DataJsPath, "js", "", "file to write 'data.js' plots")
fs.StringVar(&flags.DataJSONPath, "json", "", "file to write 'data.json' plots")
fs.StringVar(&flags.CPUProf, "cpuprof", "",
"file to write CPU profile data in pprof format. Note: adds performance cost.")
err := fs.Parse(args)
if err != nil {
return nil, err
}
if flags.Config == "" {
return nil, errors.Reason("missing required -conf")
}
return &flags, err
}
func runExperiment(ctx context.Context, ec config.ExperimentConfig) error {
var e experiments.Experiment
switch ec.(type) {
case *config.TestExperimentConfig:
e = &experiments.TestExperiment{}
case *config.Hold:
e = &hold.Hold{}
case *config.Distribution:
e = &distribution.Distribution{}
case *config.PowerDist:
e = &powerdist.PowerDist{}
case *config.Portfolio:
e = &portfolio.Portfolio{}
case *config.AutoCorrelation:
e = &autocorr.AutoCorrelation{}
case *config.Beta:
e = &beta.Beta{}
case *config.Trading:
e = &trading.Trading{}
case *config.Simulator:
e = &simulator.Simulator{}
default:
return errors.Reason("unsupported experiment '%s'", ec.Name())
}
if err := e.Run(ctx, ec); err != nil {
return errors.Annotate(err, "failed experiment '%s'", ec.Name())
}
return nil
}
func printValues(ctx context.Context) error {
keys := []string{}
values := experiments.GetValues(ctx)
if values == nil {
return errors.Reason("no values in context")
}
for k := range values {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
for _, k := range keys {
fmt.Printf("%s: %s\n", k, values[k])
}
return nil
}
func writePlots(ctx context.Context, flags *Flags) error {
if flags.DataJsPath != "" {
f, err := os.OpenFile(flags.DataJsPath,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return errors.Annotate(err, "cannot open file for writing :'%s'",
flags.DataJsPath)
}
defer f.Close()
if err := plot.WriteJS(ctx, f); err != nil {
return errors.Annotate(err, "failed to write '%s'", flags.DataJsPath)
}
}
if flags.DataJSONPath != "" {
f, err := os.OpenFile(flags.DataJSONPath,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return errors.Annotate(err, "cannot open file for writing :'%s'",
flags.DataJSONPath)
}
defer f.Close()
if err := plot.WriteJSON(ctx, f); err != nil {
return errors.Annotate(err, "failed to write '%s'", flags.DataJSONPath)
}
}
return nil
}
func run(ctx context.Context, flags *Flags) error {
if flags.CPUProf != "" {
f, err := os.OpenFile(flags.CPUProf, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return errors.Annotate(err, "cannot open file for writing :'%s'",
flags.CPUProf)
}
defer f.Close()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
cfg, err := config.Load(flags.Config)
if err != nil {
return errors.Annotate(err, "failed to load config")
}
if err := plot.ConfigureGroups(ctx, cfg.Groups); err != nil {
return errors.Annotate(err, "failed to add groups")
}
for _, e := range cfg.Experiments {
if err := runExperiment(ctx, e.Config); err != nil {
return errors.Annotate(err, "failed to run experiment '%s'",
e.Config.Name())
}
}
if err := printValues(ctx); err != nil {
return errors.Annotate(err, "failed to print values")
}
if err := writePlots(ctx, flags); err != nil {
return errors.Annotate(err, "failed to write plots")
}
return nil
}
// main should remain minimal, as it is not unit-tested due to os.Exit.
func main() {
ctx := context.Background()
flags, err := parseFlags(os.Args[1:])
if err != nil {
ctx = logging.Use(ctx, logging.DefaultGoLogger(logging.Info))
logging.Errorf(ctx, "failed to parse flags:\n%s", err.Error())
os.Exit(1)
}
ctx = logging.Use(ctx, logging.DefaultGoLogger(flags.LogLevel))
canvas := plot.NewCanvas()
values := make(experiments.Values)
ctx = plot.Use(ctx, canvas)
ctx = experiments.UseValues(ctx, values)
if err := run(ctx, flags); err != nil {
logging.Errorf(ctx, err.Error())
os.Exit(1)
}
}