FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
sweep.hpp
Go to the documentation of this file.
1#pragma once
2// Parameter sweep (8.4/8.5): a list of points, or the cartesian grid that expands to one, over
3// strategy parameters and backtest settings, run on a std::jthread pool; every worker owns its own
4// data cursor (source_factory) and backend, results come back in the points' order (a grid's
5// first parameter varies slowest).
6//
7// walk_forward() runs the same grid on K consecutive time slices (folds) of the data and scores
8// the in-sample winner of fold i-1 on fold i: an out-of-sample check of the sweep's best row.
10
11#include <cstddef>
12#include <cstdint>
13#include <functional>
14#include <limits>
15#include <memory>
16#include <string>
17#include <string_view>
18#include <utility>
19#include <vector>
20
21namespace fastmm::bt {
22
23using ParamGrid = std::vector<std::pair<std::string, std::vector<std::string>>>;
24// The points of a sweep, in order: a grid expanded (expand_grid) or any list.
25using SweepPoints = std::vector<ParamMap>;
26using SourceFactory = std::function<std::unique_ptr<MdSource>()>; // may return nullptr
27using RunFn = std::function<BacktestResult(const BacktestConfig&, MdSource*)>;
29struct SweepPoint {
30 ParamMap params; // the grid values applied for this point
32};
34// Called with each point's result as it is done (index in the list of points or configurations),
35// one call at a time, before it is kept: a caller that needs less of it (the CLI prints the
36// metrics) can drop the rest there, so a sweep of thousands of points holds no more than that.
37using ResultHook = std::function<void(std::size_t index, BacktestResult& result)>;
38
39// Expands the grid in order: [{k1: v11, k2: v21}, {k1: v11, k2: v22}, ...].
40[[nodiscard]] SweepPoints expand_grid(const ParamGrid& grid);
41
42// The configuration a point runs: `start` (shared_start() of the sweep's base) with each key of
43// `point` set, a key of kSweepSettings as that backtest setting (BacktestConfig::set_setting) and
44// any other as a strategy parameter; no output directory, journal or order rows.
45[[nodiscard]] BacktestConfig point_config(const BacktestConfig& start, const ParamMap& point);
46
47// Generic driver; `run` is called once per point on a worker thread. threads <= 0 uses
48// hardware_concurrency.
49std::vector<SweepPoint> sweep(const BacktestConfig& base,
50 const SweepPoints& points,
51 const SourceFactory& source_factory,
52 const RunFn& run,
53 int threads = 0,
54 const ResultHook& done = {});
55std::vector<SweepPoint> sweep(const BacktestConfig& base,
56 const ParamGrid& grid,
57 const SourceFactory& source_factory,
58 const RunFn& run,
59 int threads = 0,
60 const ResultHook& done = {});
61
62template <StrategyLike S>
63std::vector<SweepPoint> sweep(const BacktestConfig& base,
64 const ParamGrid& grid,
65 const SourceFactory& source_factory = {},
66 int threads = 0) {
67 return sweep(
68 base,
69 grid,
70 source_factory,
71 [](const BacktestConfig& c, MdSource* s) { return run_backtest<S>(c, s); },
72 threads);
73}
74
75// A registered strategy's sweep. Under the queue fill models (l2_queue, l3_queue) the points share
76// their passes over the data (sweep_multiverse(), multiverse.hpp) with the results each gives
77// alone; otherwise, or with `separately`, every point is a backtest of its own.
78std::vector<SweepPoint> sweep_by_name(const BacktestConfig& base,
79 std::string strategy,
80 const SweepPoints& points,
81 const SourceFactory& source_factory = {},
82 int threads = 0,
83 bool separately = false,
84 const ResultHook& done = {});
85std::vector<SweepPoint> sweep_by_name(const BacktestConfig& base,
86 std::string strategy,
87 const ParamGrid& grid,
88 const SourceFactory& source_factory = {},
89 int threads = 0,
90 bool separately = false,
91 const ResultHook& done = {});
92
93// ---- walk-forward ------------------------------------------------------------------------------
94
95// Ranking metric of a run, higher is better. score_metric() names four, "net_pnl",
96// "realized_pnl", "sharpe_bar" and "spread_captured_bps", and throws std::invalid_argument for any
97// other name.
98using ScoreFn = std::function<double(const BacktestResult&)>;
99[[nodiscard]] ScoreFn score_metric(std::string_view name);
101struct WalkForwardFold {
102 std::int64_t start_ts = 0; // [start_ts, end_ts) of event time, ns
103 std::int64_t end_ts = 0;
104 std::vector<SweepPoint> points; // every grid point run on this fold alone, grid order
105 std::vector<double> scores; // the metric of each point (NaN ranks last)
106 std::size_t best = 0; // in-sample best of this fold (lowest grid index on ties)
107 // Folds >= 1: the point chosen on the previous fold, its score there (in-sample), its score
108 // here (out-of-sample) and the best score here (hindsight). NaN on fold 0.
109 std::size_t chosen = 0;
110 double in_sample = std::numeric_limits<double>::quiet_NaN();
111 double out_of_sample = std::numeric_limits<double>::quiet_NaN();
112 double hindsight = std::numeric_limits<double>::quiet_NaN();
114
115struct WalkForwardReport {
116 std::string metric;
117 std::vector<std::string> param_names; // grid order; of a list of points, every key they set
118 std::vector<WalkForwardFold> folds;
119 // Means over folds 1..K-1 (NaN with one fold).
120 double mean_in_sample = std::numeric_limits<double>::quiet_NaN();
121 double mean_out_of_sample = std::numeric_limits<double>::quiet_NaN();
122 double mean_hindsight = std::numeric_limits<double>::quiet_NaN();
123 std::size_t choice_changes = 0; // folds i >= 2 whose chosen point differs from fold i-1's
125 // "k1=v1 k2=v2" of one grid point, in grid order.
126 [[nodiscard]] std::string label(const ParamMap& params) const;
127 // One line per fold plus the summary.
128 [[nodiscard]] std::string table() const;
130
131// The k + 1 edges of `folds` equal slices of the data's event-time range: fold i is
132// [edges[i], edges[i + 1]). Reads one cursor from `source_factory` to the end; an empty factory
133// (or one returning nullptr) reads the synthetic market as a SyntheticSource stream, which needs
134// fill_model l2_queue (std::invalid_argument otherwise, and for data with no events or folds < 2).
135[[nodiscard]] std::vector<Timestamp> fold_edges(const BacktestConfig& base,
136 const SourceFactory& source_factory,
137 int folds);
138
139// The cursor a walk-forward fold reads: `inner` from `t0` to `t1`, owning it. A null `inner` is the
140// synthetic market of `base` as a stream (fill_model l2_queue; std::invalid_argument otherwise).
141[[nodiscard]] std::unique_ptr<MdSource> fold_source(const BacktestConfig& base,
142 std::unique_ptr<MdSource> inner,
143 Timestamp t0,
144 Timestamp t1);
145
146// Scores the points of every fold of `rep` by `score_fn`, or by the metric named `rep.metric` when
147// `score_fn` is empty, and fills in best, chosen, the in-sample / out-of-sample / hindsight scores,
148// the means and the choice changes. With one fold, its start_ts / end_ts are set from its results.
149// walk_forward() ends with it; a caller that ran the points itself (the Python package, for
150// strategies written in Python) or ranks by a score of its own calls it directly. Throws
151// std::invalid_argument for an unknown metric.
152void score_walk_forward(WalkForwardReport& rep, const ScoreFn& score_fn = {});
154// Splits the data's event-time range into `folds` equal slices and runs the whole grid on each
155// one (a fresh backtest per point and fold, all on one pool of `threads` workers). Each fold
156// reads a TimeSliceSource over the worker's cursor, so it starts on the book as of its first
157// instant with a flat engine. folds == 1 is exactly sweep(). The synthetic market
158// (source_factory empty or returning nullptr) is sliced as a SyntheticSource stream, which needs
159// fill_model l2_queue: the coupled matching market cannot be cut and throws
160// std::invalid_argument.
162 const SweepPoints& points,
163 const SourceFactory& source_factory,
164 const RunFn& run,
165 int folds,
166 std::string_view metric = "net_pnl",
167 int threads = 0);
169 const ParamGrid& grid,
170 const SourceFactory& source_factory,
171 const RunFn& run,
172 int folds,
173 std::string_view metric = "net_pnl",
174 int threads = 0);
175
176// walk_forward() of a registered strategy. Under the queue fill models the points of each fold
177// share their passes over the fold's data (sweep_multiverse(), multiverse.hpp), with the same
178// report. `done` sees each result, with index fold * points + point (ResultHook).
180 std::string strategy,
181 const SweepPoints& points,
182 const SourceFactory& source_factory,
183 int folds,
184 std::string_view metric = "net_pnl",
185 int threads = 0,
186 const ResultHook& done = {});
187WalkForwardReport walk_forward_by_name(const BacktestConfig& base,
188 std::string strategy,
189 const ParamGrid& grid,
190 const SourceFactory& source_factory,
191 int folds,
192 std::string_view metric = "net_pnl",
193 int threads = 0,
194 const ResultHook& done = {});
195
196} // namespace fastmm::bt
BacktestRunner (8.4): wires Engine<S, SimClock, SimTransport, InlineFeed> to a SimDriver and collects...
Definition backtest_config.hpp:44
std::vector< SweepPoint > sweep_by_name(const BacktestConfig &base, std::string strategy, const SweepPoints &points, const SourceFactory &source_factory={}, int threads=0, bool separately=false, const ResultHook &done={})
A registered strategy's sweep.
SweepPoints expand_grid(const ParamGrid &grid)
Expands the grid in order: [{k1: v11, k2: v21}, {k1: v11, k2: v22}, ...].
void score_walk_forward(WalkForwardReport &rep, const ScoreFn &score_fn={})
Scores the points of every fold of rep by score_fn, or by the metric named rep.metric when score_fn i...
std::unique_ptr< MdSource > fold_source(const BacktestConfig &base, std::unique_ptr< MdSource > inner, Timestamp t0, Timestamp t1)
The cursor a walk-forward fold reads: inner from t0 to t1, owning it.
std::function< BacktestResult(const BacktestConfig &, MdSource *)> RunFn
Definition sweep.hpp:29
std::function< void(std::size_t index, BacktestResult &result)> ResultHook
Called with each point's result as it is done (index in the list of points or configurations),...
Definition sweep.hpp:39
std::function< std::unique_ptr< MdSource >()> SourceFactory
may return nullptr
Definition sweep.hpp:28
std::vector< Timestamp > fold_edges(const BacktestConfig &base, const SourceFactory &source_factory, int folds)
The k + 1 edges of folds equal slices of the data's event-time range: fold i is [edges[i],...
std::vector< std::pair< std::string, std::vector< std::string > > > ParamGrid
Definition sweep.hpp:25
std::vector< SweepPoint > sweep(const BacktestConfig &base, const SweepPoints &points, const SourceFactory &source_factory, const RunFn &run, int threads=0, const ResultHook &done={})
Generic driver; run is called once per point on a worker thread.
std::function< double(const BacktestResult &)> ScoreFn
Ranking metric of a run, higher is better.
Definition sweep.hpp:99
WalkForwardReport walk_forward_by_name(const BacktestConfig &base, std::string strategy, const SweepPoints &points, const SourceFactory &source_factory, int folds, std::string_view metric="net_pnl", int threads=0, const ResultHook &done={})
walk_forward() of a registered strategy.
WalkForwardReport walk_forward(const BacktestConfig &base, const SweepPoints &points, const SourceFactory &source_factory, const RunFn &run, int folds, std::string_view metric="net_pnl", int threads=0)
Splits the data's event-time range into folds equal slices and runs the whole grid on each one (a fre...
std::vector< ParamMap > SweepPoints
The points of a sweep, in order: a grid expanded (expand_grid) or any list.
Definition sweep.hpp:27
BacktestConfig point_config(const BacktestConfig &start, const ParamMap &point)
The configuration a point runs: start (shared_start() of the sweep's base) with each key of point set...
ScoreFn score_metric(std::string_view name)
std::map< std::string, std::string > ParamMap
Definition params.hpp:119
Definition time.hpp:45
Definition backtest_config.hpp:80
Definition result.hpp:116
Definition sweep.hpp:31
BacktestResult result
Definition sweep.hpp:33
ParamMap params
the grid values applied for this point
Definition sweep.hpp:32
Definition sweep.hpp:102
double in_sample
Definition sweep.hpp:111
std::int64_t start_ts
[start_ts, end_ts) of event time, ns
Definition sweep.hpp:103
std::int64_t end_ts
Definition sweep.hpp:104
std::size_t best
in-sample best of this fold (lowest grid index on ties)
Definition sweep.hpp:107
double hindsight
Definition sweep.hpp:113
std::vector< double > scores
the metric of each point (NaN ranks last)
Definition sweep.hpp:106
std::vector< SweepPoint > points
every grid point run on this fold alone, grid order
Definition sweep.hpp:105
double out_of_sample
Definition sweep.hpp:112
std::size_t chosen
Folds >= 1: the point chosen on the previous fold, its score there (in-sample), its score here (out-o...
Definition sweep.hpp:110
Definition sweep.hpp:116
std::string label(const ParamMap &params) const
"k1=v1 k2=v2" of one grid point, in grid order.
std::vector< std::string > param_names
grid order; of a list of points, every key they set
Definition sweep.hpp:118
double mean_in_sample
Means over folds 1..K-1 (NaN with one fold).
Definition sweep.hpp:121
std::size_t choice_changes
folds i >= 2 whose chosen point differs from fold i-1's
Definition sweep.hpp:124
double mean_hindsight
Definition sweep.hpp:123
std::string table() const
One line per fold plus the summary.
double mean_out_of_sample
Definition sweep.hpp:122
std::string metric
Definition sweep.hpp:117
std::vector< WalkForwardFold > folds
Definition sweep.hpp:119