algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-backtest-offline.cpp
1// A backtest with no broker, no credentials, and no network.
2//
3// Bars are built in code, so the output is identical every time. That makes this the place to see what
4// a backtest does and, more usefully, what it declines to tell you: the caveats print alongside the
5// figures because a reader who has to remember which assumptions applied to their run eventually will
6// not remember.
7//
8// `MyStrategy` below is the part to replace with your own. It is replayed at daily and at minute
9// granularity, and the engine is told nothing about which it is getting; then once more at no cost, to
10// show what the costs were doing. Neither KIS nor Toss makes intraday history easy, but that is a
11// limitation of those adapters rather than of backtesting.
12//
13// The replays run in every build. Scoring them (`backtest::Report`) needs a linear algebra backend
14// (`ATL_USE_EIGEN=ON`); without one the program prints what each replay filled.
15//
16// Run it as:
17//
18// example-backtest-offline
19
20#include <algotradelib/backtest>
21#include <algotradelib/krx>
22
23#include <chrono>
24#include <cstddef>
25#include <iomanip>
26#include <iostream>
27#include <optional>
28#include <sstream>
29#include <string>
30#include <vector>
31
32namespace {
33
35namespace backtest = algotradelib::backtest;
36namespace math = algotradelib::math;
37
38#if defined(ATL_HAS_EIGEN)
45std::string money_or_absent(const std::optional<algotradelib::Decimal64>& amount) {
46 return amount ? amount->str() : std::string("(absent: see the caveats)");
47}
48#endif
49
60
61InstrumentId samsung() {
62 return InstrumentId{Country::KR, Venue::COMBINED, "005930"};
63}
64
65Instrument samsung_reference() {
66 Instrument reference;
67 reference.id_ = samsung();
68 reference.name_ = "Samsung Electronics";
69 reference.type_ = SecurityType::STOCK;
70 reference.currency_ = Currency{"KRW"};
71 reference.lot_size_ = Decimal64::parse("1");
72 reference.price_rule_ = algotradelib::krx::equity_price_rule();
73 return reference;
74}
75
76// ---------------------------------------------------------------------------------------------
77// Your strategy.
78//
79// A strategy is a plain struct with **template** member functions. It is not templated on a broker,
80// holds no session, and performs no I/O, which is exactly why this same source runs in a dry run and
81// in a live session without being rewritten. The template is load-bearing rather than stylistic: it
82// is what lets one strategy be handed three different runner contexts. `ATL_ASSERT_STRATEGY` below
83// compiles every handler against two stub contexts, so a handler accidentally written against one
84// concrete context, or one the runner's call does not fit, fails here rather than when somebody first
85// runs it live.
86//
87// Emit a **target position**, not an order. A strategy that emits orders has to remember whether it
88// already entered, and after a restart it does not know -- so it either misses an exit or re-enters a
89// position it already holds. Stating the position you want leaves that to reconciliation, which can
90// see the portfolio and the working orders; you cannot.
91// ---------------------------------------------------------------------------------------------
92struct MyStrategy {
94 std::size_t lookback_{5};
96 Decimal64 quantity_{Decimal64::parse("1000")};
97
98 std::vector<Decimal64> history_;
99
100 template <class Ctx>
101 void on_bar(Ctx& ctx, const strategy::BarEvent& bar) {
102 history_.push_back(bar.bar_.close_);
103 if (history_.size() < lookback_) {
104 return;
105 }
106
107 // Kept in `Decimal64` rather than converted to `math::Scalar`, for two reasons worth knowing
108 // before you write the real thing.
109 //
110 // The first is that this strategy then needs no linear-algebra backend, so it compiles and runs in
111 // a build configured with `ATL_USE_EIGEN=OFF`.
112 //
113 // The second is the comparison itself. Rather than divide the sum to get a mean -- which is the
114 // one operation on an exact decimal that has to choose a scale and therefore round -- multiply
115 // the other side. `close * n < sum` is the same question as `close < sum / n`, and it is exact.
116 // Every arithmetic function returns `std::optional` because it checks for overflow, so a
117 // strategy that cannot compute its own signal emits nothing instead of guessing.
118 //
119 // For real indicator work, cross into `math::Scalar` through `analytics::to_scalar` and come
120 // back through `PriceRule::round_to_tick`. That gate is not decoration: it is what stops an
121 // indicator's value reaching the wire as an off-tick limit price.
122 std::optional<Decimal64> sum = Decimal64::parse("0");
123 for (std::size_t at = history_.size() - lookback_; sum && at < history_.size(); ++at) {
124 sum = algotradelib::decimal_add(*sum, history_[at]);
125 }
126 const auto scaled = algotradelib::decimal_multiply(history_.back(), Decimal64::parse(std::to_string(lookback_)));
127 if (!sum || !scaled) {
128 return;
129 }
130
131 // Buy what has fallen below its own recent average, hold nothing otherwise. It is a toy: the
132 // point of the runs below is what a replay reports, not this signal.
133 const bool cheap = algotradelib::decimal_less(*scaled, *sum);
134
135 strategy::TargetPosition target;
136 target.instrument_ = bar.instrument_;
137 target.target_quantity_ = cheap ? quantity_ : Decimal64::parse("0");
138 ctx.submit(target);
139 }
140};
141
143const std::vector<int>& closes() {
144 static const std::vector<int> path = {
145 60000,
146 60500,
147 61200,
148 61000,
149 62000,
150 63000,
151 64500,
152 65000,
153 66200,
154 67000,
155 68500,
156 69000,
157 70200,
158 71000,
159 72500,
160 73000,
161 72800,
162 72000,
163 71000,
164 69500,
165 68000,
166 66500,
167 65000,
168 63500,
169 62000,
170 61000,
171 60000,
172 59000,
173 58500,
174 58000,
175 58500,
176 59500,
177 61000,
178 62500,
179 64000,
180 65500,
181 67000,
182 68500,
183 70000,
184 71500,
185 };
186 return path;
187}
188
190backtest::NextBarFillModel realistic_costs() {
191 return backtest::NextBarFillModel(
192 backtest::CommissionModel::of(Decimal64::parse("0.00015"), Decimal64::parse("100")),
193 backtest::SlippageModel::of_ticks(1)
194 );
195}
196
197backtest::ReplayConfig config_for() {
198 backtest::ReplayConfig config;
199 config.cash_ = Decimal64::parse("100000000");
200 config.instruments_ = {samsung_reference()};
201 config.series_capacity_ = 64;
202 // Any phase, so a minute replay's pre-open and post-close bars are not refused while the point here
203 // is the strategy rather than the operator's limits.
204 config.limits_.permitted_phases_ = std::nullopt;
205 return config;
206}
207
209template <typename Strategy>
210backtest::Backtester<Strategy> replay(
211 Strategy instance, BarInterval interval, const backtest::NextBarFillModel& fills = realistic_costs()
212) {
213 backtest::Backtester<Strategy> engine(std::move(instance), config_for(), fills);
214 const auto start = std::chrono::system_clock::time_point{} + std::chrono::hours(24 * 20000);
215 for (std::size_t at = 0; at < closes().size(); ++at) {
216 const auto step = interval == BarInterval::ONE_MINUTE ?
217 std::chrono::minutes(static_cast<int>(at)) :
218 std::chrono::duration_cast<std::chrono::minutes>(std::chrono::hours(24 * static_cast<int>(at)));
219 Bar bar;
220 bar.timestamp_ = start + step;
221 bar.open_ = Decimal64::parse(std::to_string(closes()[at]));
222 bar.high_ = *bar.open_;
223 bar.low_ = *bar.open_;
224 bar.close_ = *bar.open_;
225 bar.volume_ = Decimal64::parse("1200000");
226 engine.feed(strategy::make_bar_event(samsung(), interval, BarStamp::CLOSE, bar));
227 }
228 engine.finish();
229 return engine;
230}
231
232#if defined(ATL_HAS_EIGEN)
234std::string percent(math::Scalar value) {
235 if (!math::observed(value)) {
236 return math::is_undefined(value) ? "undefined" : " --";
237 }
238 std::ostringstream text;
239 text << std::fixed << std::setprecision(2) << std::setw(7) << value * 100.0 << " %";
240 return text.str();
241}
242
244std::string plain(math::Scalar value) {
245 if (!math::observed(value)) {
246 return math::is_undefined(value) ? "undefined" : " --";
247 }
248 std::ostringstream text;
249 text << std::fixed << std::setprecision(3) << std::setw(9) << value;
250 return text.str();
251}
252
254void print(const std::string& title, const backtest::Report& report) {
255 std::cout
256 << title << "\n"
257 << " bars " << report.bars_ << "\n"
258 << " executions " << report.executions_ << "\n"
259 << " total return " << percent(report.total_return_) << "\n"
260 << " Sharpe " << plain(report.sharpe_) << " (per bar)\n"
261 << " annualized " << plain(report.annualized_sharpe_) << "\n"
262 << " Sortino " << plain(report.sortino_) << "\n"
263 << " max drawdown " << percent(report.max_drawdown_) << "\n"
264 << " turnover " << percent(report.total_turnover_) << "\n"
265 << " commission " << money_or_absent(report.commission_paid_) << " KRW\n"
266 << " slippage " << money_or_absent(report.slippage_paid_) << " KRW\n";
267 std::cout
268 << " assumed limit fills " << backtest::limit_fill_price_name(report.caveats_.limit_fill_) << ", slippage "
269 << report.caveats_.slippage_ticks_ << " tick\n";
270 // The rates that actually charged something, rather than one number: a run spanning a rate change
271 // or costing by venue charges more than one, and printing the first would name an accident.
272 for (const auto& applied : report.caveats_.applied_rates_) {
273 std::cout
274 << " commission rate " << applied.rate_.str() << " with a " << applied.minimum_.str() << " floor, "
275 << commission_origin_name(applied.origin_) << ", charged " << applied.executions_ << " execution(s)\n";
276 }
277 if (report.caveats_.cost_totals_incomplete_) {
278 // The third reason a total can be absent, and the one a reader must not miss: it is not that
279 // the run spanned currencies or traded nothing, it is that an addition did not fit and the
280 // figures below it are short by an amount nobody can name.
281 std::cout
282 << " cost totals INCOMPLETE -- an exact sum did not fit; slippage is understated"
283 << " and the fee totals are withheld\n";
284 }
285 if (report.caveats_.inclusive_commission_executions_ > 0) {
286 std::cout
287 << " commission is inclusive of any institution charge on "
288 << report.caveats_.inclusive_commission_executions_ << " execution(s)\n";
289 }
290 std::cout << " not modelled volume, queue position, market impact, borrow\n";
291 if (report.caveats_.gaps_ > 0) {
292 std::cout << " gaps " << report.caveats_.gaps_ << " (not interpolated across)\n";
293 }
294 if (report.caveats_.unfilled_ > 0) {
295 std::cout << " unfilled " << report.caveats_.unfilled_ << " (no next bar to fill against)\n";
296 }
297 if (report.caveats_.expired_day_orders_ > 0) {
298 std::cout
299 << " expired " << report.caveats_.expired_day_orders_
300 << " DAY order(s) unfilled at their session's close, as at a broker\n";
301 }
302 if (report.caveats_.multiple_instruments_) {
303 std::cout
304 << " CAVEAT more than one instrument: this result may carry survivorship\n"
305 << " bias, because reference data lists what exists now\n";
306 }
307 std::cout << "\n";
308}
309#endif
310
311} // namespace
312
313// Compiles every handler against a stub with no capability and one with every capability, so both
314// branches of each capability gate are checked. Each runner checks it again with its own context.
317
318int main() {
319 std::cout << "005930, " << closes().size() << " bars built in code -- no credentials, no network\n\n";
320
321 // The same strategy over the same path: daily, then as minute bars, then daily at no cost at all.
322 const auto daily = replay(MyStrategy{}, BarInterval::ONE_DAY);
323 const auto minutes = replay(MyStrategy{}, BarInterval::ONE_MINUTE);
324 const auto costless = replay(MyStrategy{}, BarInterval::ONE_DAY, backtest::NextBarFillModel{});
325
326#if defined(ATL_HAS_EIGEN)
327 const auto daily_periods = backtest::periods_per_year(BarInterval::ONE_DAY, strategy::SessionWindow::krx(), 245.0);
328 const auto minute_periods =
329 backtest::periods_per_year(BarInterval::ONE_MINUTE, strategy::SessionWindow::krx(), 245.0);
330 std::cout
331 << "periods per year: " << *daily_periods << " daily, " << *minute_periods
332 << " minute -- which is why annualizing takes the count rather than assuming it\n\n";
333
334 print("MyStrategy(5), daily", backtest::summarize(daily.result(), daily.fills(), *daily_periods));
335
336 // The engine is told nothing about which granularity it is getting; only the annualizing constant
337 // differs, and it differs because the caller says so rather than because the engine guessed.
338 print(
339 "MyStrategy(5), minute bars -- identical decisions, different annualizing",
340 backtest::summarize(minutes.result(), minutes.fills(), *minute_periods)
341 );
342 std::cout
343 << " ^ Note the annualized Sharpe against the daily run above. The per-bar figure is\n"
344 << " identical -- the decisions were identical -- and only the constant differs, because\n"
345 << " sqrt(95550) is about twenty times sqrt(245). The larger number is arithmetically\n"
346 << " right and practically meaningless here: this path moves like daily data, so calling\n"
347 << " its bars minutes claims a frequency the returns do not have. Two lessons. Mislabel\n"
348 << " your bar frequency and the annualized figure is wrong by the square root of the\n"
349 << " ratio. And annualizing assumes returns are serially uncorrelated, which a trading\n"
350 << " rule can violate by construction.\n\n";
351
352 print(
353 "MyStrategy(5), daily, at zero cost -- the difference is what costs cost",
354 backtest::summarize(costless.result(), costless.fills(), *daily_periods)
355 );
356
357 std::cout
358 << "Read the caveats, not only the figures. A backtest is the easiest place to produce a\n"
359 << "confident wrong number, and the ones above assume every fill was available in full at\n"
360 << "the price shown, which no bar can actually tell us.\n";
361#else
362 const auto filled = [](const char* title, const auto& engine) {
363 std::cout
364 << title << ": replayed " << engine.result().bars_ << " bars and filled " << engine.result().executions_.size()
365 << " orders\n";
366 };
367 filled("MyStrategy(5), daily", daily);
368 filled("MyStrategy(5), minute bars", minutes);
369 filled("MyStrategy(5), daily, at zero cost", costless);
370 std::cout
371 << "\nScoring those fills needs a linear algebra backend and this build has none.\n"
372 << "Configure with -DATL_USE_EIGEN=ON for the report and its caveats.\n";
373#endif
374
375 return 0;
376}
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
#define ATL_ASSERT_STRATEGY(S, Ctx)
Asserts at compile time that S is a strategy a runner with context Ctx can drive.
Definition concept.hpp:866
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
Definition bootstrap.hpp:16
PriceRule equity_price_rule()
Returns the KRX stock tick table (January 2023 revision).
Definition krx.hpp:12
The numeric vocabulary: Scalar, missing(), and the matrix and vector types.
Definition eigen.hpp:10
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
Definition concept.hpp:240
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
Definition event.hpp:380
ProbeContextT< NoCaps > MinimalContext
A probe context whose broker implements nothing optional.
Definition concept.hpp:802
ProbeContextT< AllCaps > FullContext
A probe context whose broker implements everything optional.
Definition concept.hpp:805
BarStamp
Which edge of its period a bar's timestamp marks.
SecurityType
What kind of security an instrument is.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
constexpr std::string_view commission_origin_name(CommissionOrigin origin) noexcept
Returns a lowercase name for an origin, such as "caller_stated", for reports.
Definition types.hpp:1709
Country
A country (market) the library supports.
Definition types.hpp:32
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
BarInterval
The period one bar covers.
One bar: the prices and volume of one period, as exact decimals.
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
Reference data for one instrument.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
Definition event.hpp:136
InstrumentId instrument_
The instrument.
Definition intent.hpp:453
Decimal64 target_quantity_
The position to hold, signed: negative is short, and zero means flat.
Definition intent.hpp:455