FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
ab_test.hpp
Go to the documentation of this file.
1#pragma once
2// A/B tests of strategy parameters ([ab], docs/how-to/strategies/ab-test.md).
3//
4// AbPlan says which arm each instrument is in at any time. It is a function of the [ab] table, the
5// instrument table and the time only, so fastmm-live, a backtest and fastmm-data ab (which
6// rebuilds it from a journal's configuration) agree on it.
7//
8// instrument each instrument stays in one arm. The instruments, heaviest first, are cut into
9// strata of as many instruments as there are arms, and each stratum gives every arm
10// one instrument, in an order drawn from the seed; or [ab.assign] names each
11// instrument's arm, and those it does not name stay out of the test.
12// time every instrument is in the same arm. Time is cut into blocks of block_s from the
13// Unix epoch (plus block_offset_s), and each run of as many blocks as there are arms
14// gives every arm one block, in an order drawn from the seed.
15// crossover both: an instrument's arm is its stratum slot plus the block's draw, modulo the
16// number of arms, so each block splits the instruments and each run of blocks puts
17// every instrument in every arm once.
18// branch a backtest runs once per arm over the same data and seed, every instrument in that
19// run's arm (set_branch) from the test's start, the start of trading when it names
20// none (set_default_start); fastmm-live refuses it. The runs share the market and the
21// draws until their order flows differ, so each instrument is paired with itself.
22//
23// AbController keeps a session's instruments in the plan's arms. When an instrument's arm changes
24// it publishes the arm's parameters (the configured values with the arm's on top) as one
25// ParamUpdate, Origin::Experiment with the arm in ParamUpdateMsg::arm. The engine applies it like
26// any update, the journal records it, and the orders sent after it carry the arm (Order::arm).
27// Off the engine thread: it allocates.
30#include "fastmm/core/time.hpp"
32
33#include <cstddef>
34#include <cstdint>
35#include <optional>
36#include <span>
37#include <string>
38#include <string_view>
39#include <vector>
40
41namespace fastmm {
42
43inline constexpr std::size_t kMaxAbArms = 16;
44
45enum class AbAssignment : std::uint8_t { Instrument, Time, Crossover, Branch };
46[[nodiscard]] constexpr std::string_view to_string(AbAssignment a) noexcept {
47 switch (a) {
49 return "instrument";
51 return "time";
53 return "crossover";
55 return "branch";
56 }
57 return "?";
58}
59
60// "YYYY-MM-DD", "YYYY-MM-DD HH:MM" or "YYYY-MM-DD HH:MM:SS", with a T for the space and a trailing
61// Z allowed, UTC, as ns since the epoch.
62[[nodiscard]] std::optional<std::int64_t> parse_utc_time(std::string_view s);
63// "YYYY-MM-DD HH:MM:SS UTC".
64[[nodiscard]] std::string format_utc_time(std::int64_t ns);
65
66class AbPlan {
67 public:
68 static constexpr int kNoArm = -1;
69
70 // `venue_names` name the venue ids of `instruments` (Config::venues order), for [ab.weights]
71 // keys written "venue:symbol". Throws ConfigError for a weight naming no instrument or an
72 // instrument with no weight (when there are weights), and for an instrument or crossover split
73 // over fewer instruments than arms.
76 std::span<const std::string> venue_names);
77
78 [[nodiscard]] const AbSection& section() const noexcept { return s_; }
79 [[nodiscard]] AbAssignment assignment() const noexcept { return kind_; }
80 [[nodiscard]] std::size_t arms() const noexcept { return s_.arms.size(); }
81 [[nodiscard]] std::size_t instruments() const noexcept { return slot_.size(); }
82 [[nodiscard]] const std::string& arm_name(int arm) const {
83 return s_.arms.at(static_cast<std::size_t>(arm)).name;
84 }
85 // The instrument's name in the configuration's terms: "venue:symbol".
86 [[nodiscard]] const std::string& instrument_name(std::size_t inst) const {
87 return names_.at(inst);
88 }
89 [[nodiscard]] std::int64_t start_ns() const noexcept { return start_ns_; } // INT64_MIN: none
90 [[nodiscard]] std::int64_t end_ns() const noexcept { return end_ns_; } // INT64_MAX: none
91 [[nodiscard]] std::int64_t block_ns() const noexcept { return block_ns_; } // 0: no blocks
92 // When block `k` ends (time, crossover).
93 [[nodiscard]] std::int64_t block_end(std::int64_t k) const noexcept {
94 return (k + 1) * block_ns_ + offset_ns_;
95 }
96 // The instrument is in the test: [ab.assign] names it, or there is none.
97 [[nodiscard]] bool in_test(std::size_t inst) const noexcept {
98 return inst < slot_.size() && slot_[inst] != kOut;
99 }
100 // branch: the arm of this run, and the start when [ab] start names none.
101 void set_branch(int arm) noexcept { branch_ = arm; }
102 [[nodiscard]] int branch() const noexcept { return branch_; }
103 void set_default_start(std::int64_t ns) noexcept {
104 if (s_.start.empty()) start_ns_ = ns;
106
107 // The arm instrument `inst` is in at `t` (ns since the epoch): kNoArm before start and from end.
108 [[nodiscard]] int arm_at(std::size_t inst, std::int64_t t) const noexcept;
109 // The first time after `t` at which arm_at() may change, INT64_MAX when it never does.
110 [[nodiscard]] std::int64_t next_change(std::int64_t t) const noexcept;
111 // The block `t` falls in (time, crossover), 0 with instrument.
112 [[nodiscard]] std::int64_t block_of(std::int64_t t) const noexcept;
113 // The run of arms() blocks `t` falls in, each arm once in it (time, crossover); 0 with
114 // instrument.
115 [[nodiscard]] std::int64_t round_of(std::int64_t t) const noexcept;
116 // The instrument's stratum (instrument, crossover; 0 with time) and its slot in it.
117 [[nodiscard]] std::size_t stratum(std::size_t inst) const noexcept { return stratum_[inst]; }
118 [[nodiscard]] std::size_t slot(std::size_t inst) const noexcept { return slot_[inst]; }
119 // Every arm names the same parameters with the same values: an A/A test.
120 [[nodiscard]] bool identical_arms() const noexcept;
121
122 private:
123 [[nodiscard]] std::size_t block_draw(std::int64_t block) const noexcept;
124
125 AbSection s_;
127 std::int64_t start_ns_;
128 std::int64_t end_ns_;
129 static constexpr std::uint8_t kOut = 0xFF; // slot_ of an instrument [ab.assign] leaves out
130 std::int64_t block_ns_ = 0;
131 std::int64_t offset_ns_ = 0;
132 int branch_ = 0;
133 std::vector<std::uint8_t> slot_;
134 std::vector<std::size_t> stratum_;
135 std::vector<std::string> names_;
136};
137
138class AbController {
139 public:
141 enum class State : std::uint8_t { Waiting, Running, Ended };
143 // `publisher`'s values now are the configured parameters each arm starts from; it must outlive
144 // the controller. Throws std::invalid_argument when an arm names a parameter the strategy does
145 // not have or a value its schema or validate() refuses, or when the plan splits the
146 // instruments and the strategy keeps one parameter set (ParamScope::Shared).
147 AbController(AbPlan plan, ParamPublisher& publisher);
148
149 [[nodiscard]] const AbPlan& plan() const noexcept { return plan_; }
150 // Publishes the parameters of each instrument whose arm differs at `now` from the one it was
151 // last put in, one update for every instrument when they all move to the same arm. False when
152 // the sink refused one: the instruments not yet moved are moved by the next call.
153 bool poll(Timestamp now);
154 // The next time poll() has something to do after `now`; Timestamp::max() once ended.
155 [[nodiscard]] Timestamp next_change(Timestamp now) const noexcept;
156 // Ends the test at the next poll(): every instrument leaves its arm and gets the configured
157 // parameters, or with `promote` the parameters of that arm. Later polls do nothing.
158 void stop(int promote = AbPlan::kNoArm) noexcept;
159 [[nodiscard]] State state(Timestamp now) const noexcept;
160 [[nodiscard]] int promoted() const noexcept { return promote_; }
161 // The arm's index by name, kNoArm when none has it.
162 [[nodiscard]] int arm(std::string_view name) const noexcept;
163 // A parameter some arm names: the test sets it while it runs.
164 [[nodiscard]] bool owns(std::string_view param) const noexcept;
165 // The values an arm's update carries (kNoArm: the configured ones), in name order.
166 [[nodiscard]] const std::vector<ParamValue>& values(int arm) const;
167 // The arm the instrument was last put in, kNoArm when none.
168 [[nodiscard]] int current(std::size_t inst) const noexcept { return current_[inst]; }
169 // Updates the publisher refused when they were published (a validate() that no longer holds
170 // for an instrument's parameters), and the last reason.
171 [[nodiscard]] std::uint64_t refused() const noexcept { return refused_; }
172 [[nodiscard]] const std::string& last_error() const noexcept { return last_error_; }
173 // fastmm-ctl ab: the test on the first line, then one line per topic: its arms, the block and
174 // end, and each instrument's arm.
175 [[nodiscard]] std::string status(Timestamp now) const;
176
177 private:
178 bool publish(InstrumentId inst, int values, std::uint8_t arm);
179
180 AbPlan plan_;
181 ParamPublisher* pub_;
182 std::vector<ParamValue> base_;
183 std::vector<std::vector<ParamValue>> arm_values_;
184 std::vector<int> current_;
185 std::string source_;
186 bool stopping_ = false;
187 bool ended_ = false;
188 int promote_ = AbPlan::kNoArm;
189 std::uint64_t refused_ = 0;
190 std::string last_error_;
191};
192
193[[nodiscard]] constexpr std::string_view to_string(AbController::State s) noexcept {
194 switch (s) {
196 return "waiting";
198 return "running";
200 return "ended";
201 }
202 return "?";
203}
204
205} // namespace fastmm
Definition ab_test.hpp:140
ParamPublisher::ParamValue ParamValue
Definition ab_test.hpp:142
State
Definition ab_test.hpp:143
Definition ab_test.hpp:68
void set_default_start(std::int64_t ns) noexcept
Definition ab_test.hpp:105
const std::string & instrument_name(std::size_t inst) const
The instrument's name in the configuration's terms: "venue:symbol".
Definition ab_test.hpp:88
std::size_t slot(std::size_t inst) const noexcept
Definition ab_test.hpp:120
void set_branch(int arm) noexcept
branch: the arm of this run, and the start when [ab] start names none.
Definition ab_test.hpp:103
bool identical_arms() const noexcept
Every arm names the same parameters with the same values: an A/A test.
std::size_t stratum(std::size_t inst) const noexcept
The instrument's stratum (instrument, crossover; 0 with time) and its slot in it.
Definition ab_test.hpp:119
const std::string & arm_name(int arm) const
Definition ab_test.hpp:84
std::size_t instruments() const noexcept
Definition ab_test.hpp:83
bool in_test(std::size_t inst) const noexcept
The instrument is in the test: [ab.assign] names it, or there is none.
Definition ab_test.hpp:99
static constexpr int kNoArm
Definition ab_test.hpp:70
std::int64_t end_ns() const noexcept
INT64_MAX: none.
Definition ab_test.hpp:92
int branch() const noexcept
Definition ab_test.hpp:104
std::int64_t block_end(std::int64_t k) const noexcept
When block k ends (time, crossover).
Definition ab_test.hpp:95
std::size_t arms() const noexcept
Definition ab_test.hpp:82
int arm_at(std::size_t inst, std::int64_t t) const noexcept
The arm instrument inst is in at t (ns since the epoch): kNoArm before start and from end.
std::int64_t block_of(std::int64_t t) const noexcept
The block t falls in (time, crossover), 0 with instrument.
const AbSection & section() const noexcept
Definition ab_test.hpp:80
AbAssignment assignment() const noexcept
Definition ab_test.hpp:81
std::int64_t start_ns() const noexcept
INT64_MIN: none.
Definition ab_test.hpp:91
std::int64_t block_ns() const noexcept
0: no blocks
Definition ab_test.hpp:93
std::int64_t round_of(std::int64_t t) const noexcept
The run of arms() blocks t falls in, each arm once in it (time, crossover); 0 with instrument.
std::int64_t next_change(std::int64_t t) const noexcept
The first time after t at which arm_at() may change, INT64_MAX when it never does.
Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by (venue,...
Definition instrument.hpp:147
Definition param_publisher.hpp:61
std::pair< std::string, std::string > ParamValue
name, value as ParamDesc::parse takes
Definition param_publisher.hpp:63
Typed configuration (8.7).
Instrument: the single definition of a tradable contract (5.3 / 5.15).
Definition strategy.hpp:23
std::optional< std::int64_t > parse_utc_time(std::string_view s)
"YYYY-MM-DD", "YYYY-MM-DD HH:MM" or "YYYY-MM-DD HH:MM:SS", with a T for the space and a trailing Z al...
AbAssignment
Definition ab_test.hpp:47
constexpr std::size_t kMaxAbArms
Definition ab_test.hpp:45
std::string format_utc_time(std::int64_t ns)
"YYYY-MM-DD HH:MM:SS UTC".
constexpr std::string_view to_string(ParamType t) noexcept
Definition params.hpp:63
ParamPublisher: builds ParamUpdate messages for a running engine, off the engine thread (ADR-0013).
Definition config.hpp:329
std::string start
UTC; empty: from the start of the session.
Definition config.hpp:334
std::vector< AbArmSection > arms
Definition config.hpp:344
Definition instrument.hpp:29
Definition time.hpp:45
Time primitives.