algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-backtest-broker.cpp
1// Backtest a strategy on bars fetched from a real broker.
2//
3// Two phases, deliberately separated: **read, then replay**. The session is used once, to fetch bars
4// and reference data, and then closed out of the picture — the replay itself touches nothing. That
5// separation is the point. A backtest that held a session open could accidentally reach for data
6// mid-replay, which is how a backtest ends up using information the strategy could not have had.
7//
8// It places no orders. There is no code path here that could: the engine's executor queues fills and
9// has no session at all.
10//
11// Run it as:
12//
13// example-backtest-broker kis 005930
14// example-backtest-broker tossinvest 005930 [account-sequence]
15//
16// Credentials come from the same environment variables the other examples document. What you can fetch
17// bounds what you can test: KIS returns 100 daily bars a request and one `bars()` call pages up to
18// 50 requests (about 5,000 bars, roughly twenty years of KRX trading days), but serves minute bars
19// one trading day at a time.
20
21#include "kis_credentials.hpp"
22
23#include <algotradelib/backtest>
24#include <algotradelib/kis>
25#include <algotradelib/tossinvest>
26
27#include <boost/asio/ssl/context.hpp>
28
29#include <cstddef>
30#include <cstdint>
31#include <cstdlib>
32#include <exception>
33#include <iomanip>
34#include <iostream>
35#include <memory>
36#include <optional>
37#include <sstream>
38#include <string>
39#include <utility>
40#include <vector>
41
42namespace ssl = boost::asio::ssl;
43
44namespace {
45
46namespace strategy = algotradelib::strategy;
47namespace backtest = algotradelib::backtest;
48namespace math = algotradelib::math;
49
50#if defined(ATL_HAS_EIGEN)
57std::string money_or_absent(const std::optional<algotradelib::Decimal64>& amount) {
58 return amount ? amount->str() : std::string("(absent: see the caveats)");
59}
60#endif
61
63using algotradelib::BarQuery;
64using algotradelib::BarSeries;
65using algotradelib::BlockingSession;
67using algotradelib::Currency;
68using algotradelib::Decimal64;
69using algotradelib::Instrument;
70using algotradelib::InstrumentId;
72
74struct FetchedHistory {
75 Instrument reference_;
76 BarSeries bars_;
77};
78
85template <typename Session>
86std::optional<FetchedHistory> read_history(Session& session, const InstrumentId& instrument, std::size_t count) {
87 auto reference = session.instrument(instrument);
88 if (!reference) {
89 std::cerr << "could not read reference data: " << reference.error().message_ << '\n';
90 return std::nullopt;
91 }
92
93 BarQuery query;
94 query.instrument_ = instrument;
95 query.interval_ = BarInterval::ONE_DAY;
96 query.count_ = count;
97 // Adjusted, and this matters more than it looks: unadjusted prices invent a signal at every split
98 // and every dividend, so a backtest on them measures corporate actions rather than a strategy.
99 query.adjusted_ = true;
100
101 auto bars = session.bars(query);
102 if (!bars) {
103 std::cerr << "could not read bars: " << bars.error().message_ << '\n';
104 return std::nullopt;
105 }
106 if (bars.value().bars_.size() < 2) {
107 std::cerr << "the broker returned too few bars to replay\n";
108 return std::nullopt;
109 }
110
111 FetchedHistory history;
112 history.reference_ = std::move(reference.value());
113 history.bars_ = std::move(bars.value());
114 return history;
115}
116
117// ---------------------------------------------------------------------------------------------
118// Two strategies, written here as you would write your own.
119// ---------------------------------------------------------------------------------------------
120
122struct HoldsShares {
124 Decimal64 quantity_;
125
126 template <class Ctx>
127 void on_bar(Ctx& ctx, const strategy::BarEvent& bar) {
128 strategy::TargetPosition target;
129 target.instrument_ = bar.instrument_;
130 target.target_quantity_ = quantity_;
131 ctx.submit(target);
132 }
133};
134
141struct MovingAverageCross {
143 std::size_t fast_{20};
145 std::size_t slow_{50};
147 Decimal64 quantity_;
149 std::vector<Decimal64> closes_;
150
151 template <class Ctx>
152 void on_bar(Ctx& ctx, const strategy::BarEvent& bar) {
153 closes_.push_back(bar.bar_.close_);
154 if (fast_ == 0 || slow_ <= fast_ || closes_.size() < slow_) {
155 return;
156 }
157 const auto fast_sum = sum_of_last(fast_);
158 const auto slow_sum = sum_of_last(slow_);
159 if (!fast_sum || !slow_sum) {
160 return;
161 }
162 const auto left = algotradelib::decimal_multiply(*fast_sum, Decimal64(static_cast<std::int64_t>(slow_), 0));
163 const auto right = algotradelib::decimal_multiply(*slow_sum, Decimal64(static_cast<std::int64_t>(fast_), 0));
164 if (!left || !right) {
165 return;
166 }
167 strategy::TargetPosition target;
168 target.instrument_ = bar.instrument_;
169 target.target_quantity_ = algotradelib::decimal_less(*right, *left) ? quantity_ : Decimal64::parse("0");
170 ctx.submit(target);
171 }
172
173private:
174 // The sum of the last `count` closes, or nothing if an addition overflowed.
175 std::optional<Decimal64> sum_of_last(std::size_t count) const {
176 std::optional<Decimal64> sum = Decimal64::parse("0");
177 for (std::size_t at = closes_.size() - count; sum && at < closes_.size(); ++at) {
178 sum = algotradelib::decimal_add(*sum, closes_[at]);
179 }
180 return sum;
181 }
182};
183
184#if defined(ATL_HAS_EIGEN)
186template <typename Strategy>
187void replay_and_report(const char* title, Strategy instance, const FetchedHistory& history) {
188 backtest::ReplayConfig config;
189 config.cash_ = Decimal64::parse("100000000");
190 config.instruments_ = {history.reference_};
191 config.currency_ = history.bars_.currency_;
192 config.series_capacity_ = 512;
193 config.limits_.permitted_phases_ = std::nullopt;
194
195 backtest::Backtester<Strategy> engine(
196 std::move(instance), std::move(config),
197 backtest::NextBarFillModel(
198 backtest::CommissionModel::of(Decimal64::parse("0.00015"), Decimal64::parse("100")),
199 backtest::SlippageModel::of_ticks(1)
200 )
201 );
202
203 for (const auto& bar : history.bars_.bars_) {
204 engine.feed(
205 strategy::make_bar_event(history.bars_.instrument_, history.bars_.interval_, history.bars_.stamp_, bar)
206 );
207 }
208 engine.finish();
209
210 const auto periods = backtest::periods_per_year(history.bars_.interval_, strategy::SessionWindow::krx(), 245.0);
211 const auto report = backtest::summarize(engine.result(), engine.fills(), periods);
212
213 const auto show = [](math::Scalar value, bool as_percent) {
214 std::ostringstream text;
215 if (!math::observed(value)) {
216 text << (math::is_undefined(value) ? "undefined" : "--");
217 return text.str();
218 }
219 text
220 << std::fixed << std::setprecision(as_percent ? 2 : 3) << (as_percent ? value * 100.0 : value)
221 << (as_percent ? " %" : "");
222 return text.str();
223 };
224
225 std::cout
226 << title << "\n"
227 << " bars " << report.bars_ << "\n"
228 << " executions " << report.executions_ << "\n"
229 << " total return " << show(report.total_return_, true) << "\n"
230 << " Sharpe " << show(report.sharpe_, false) << " per bar, " << show(report.annualized_sharpe_, false)
231 << " annualized\n"
232 << " Sortino " << show(report.sortino_, false) << "\n"
233 << " max drawdown " << show(report.max_drawdown_, true) << "\n"
234 << " turnover " << show(report.total_turnover_, true) << "\n"
235 << " commission " << money_or_absent(report.commission_paid_) << "\n"
236 << " slippage " << money_or_absent(report.slippage_paid_) << "\n"
237 << " not modelled volume, queue position, market impact, borrow\n";
238 if (report.caveats_.cost_totals_incomplete_) {
239 // The reason a total can be absent that is not "no trades" and not "two currencies": an exact
240 // sum was refused, so the figures above are short by an amount nobody can name.
241 std::cout
242 << " cost totals INCOMPLETE -- an exact sum did not fit; slippage is understated"
243 << " and the fee totals are withheld\n";
244 }
245 std::cout << "\n";
246}
247#endif
248
250template <typename Session>
251int backtest_with(Session& session, const std::string& symbol) {
252 const InstrumentId instrument{Country::KR, Venue::COMBINED, symbol};
253
254 const auto history = read_history(session, instrument, 400);
255 if (!history) {
256 return 1;
257 }
258
259 std::cout
260 << "broker: " << Session::BrokerTag::name << " instrument: " << symbol << " bars: "
261 << history->bars_.bars_.size() << (history->bars_.adjusted_ ? " adjusted" : " UNADJUSTED") << "\n"
262 << "the session is now finished with: nothing below reads it\n\n";
263
264#if defined(ATL_HAS_EIGEN)
265 replay_and_report(
266 "HoldsShares -- the benchmark every strategy is measured against", HoldsShares{Decimal64::parse("100")}, *history
267 );
268
269 MovingAverageCross crossing;
270 crossing.quantity_ = Decimal64::parse("100");
271 replay_and_report("MovingAverageCross(20, 50)", crossing, *history);
272
273 std::cout
274 << "These are real prices and a simulated fill model. Every figure assumes the whole order was\n"
275 << "available at the price shown, which no bar can tell us -- so treat a small edge here as\n"
276 << "noise rather than as a result.\n";
277#else
278 std::cout << "The report needs a linear algebra backend; configure with -DATL_USE_EIGEN=ON.\n";
279#endif
280 return 0;
281}
282
283int backtest_kis(ssl::context& tls, const std::string& symbol) {
284 namespace kis = algotradelib::kis;
285
286 kis::KisConfig config;
287 config.from_env();
288 kis::KisAccount account;
289 account.from_env();
290
291 auto client = std::make_shared<kis::KisBlockingClient>(tls, std::move(config), kis_credentials::paced_options());
292 BlockingSession<kis::KisBlockingClient> session(std::move(client), std::move(account));
293 return backtest_with(session, symbol);
294}
295
296int backtest_tossinvest(ssl::context& tls, const std::string& symbol, const char* sequence) {
297 namespace toss = algotradelib::tossinvest;
298
299 toss::TossConfig config;
300 config.from_env();
301 auto client = std::make_shared<toss::TossBlockingClient>(tls, std::move(config));
302
303 std::int64_t selected = 0;
304 if (sequence != nullptr) {
305 selected = std::strtoll(sequence, nullptr, 10);
306 } else {
307 auto accounts = algotradelib::list_accounts(*client);
308 if (!accounts || accounts.value().empty()) {
309 std::cerr << "could not discover a Toss account\n";
310 return 1;
311 }
312 selected = accounts.value().front().selector_;
313 }
314
315 BlockingSession<toss::TossBlockingClient> session(std::move(client), selected);
316 return backtest_with(session, symbol);
317}
318
319} // namespace
320
321int main(int argc, char** argv) {
322 const std::string broker = argc > 1 ? argv[1] : "";
323 if (broker != "kis" && broker != "tossinvest") {
324 std::cerr
325 << "usage: example-backtest-broker <kis|tossinvest> [symbol] [account-sequence]\n\n"
326 << "Fetches history and replays it. Places no order: the engine has no session to send to.\n";
327 return 2;
328 }
329 const std::string symbol = argc > 2 ? argv[2] : "005930";
330
331 try {
332 ssl::context tls(ssl::context::tls_client);
333 tls.set_default_verify_paths();
334 tls.set_verify_mode(ssl::verify_peer);
335
336 if (broker == "kis") {
337 return backtest_kis(tls, symbol);
338 }
339 return backtest_tossinvest(tls, symbol, argc > 3 ? argv[3] : nullptr);
340 } catch (const std::exception& exception) {
341 std::cerr << "example failed: " << exception.what() << '\n';
342 return 1;
343 }
344}
The examples' KIS credentials: one JSON file per account, or the environment.
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
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
Definition concept.hpp:309
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
Result< std::vector< AccountInfo< Client > > > list_accounts(Client &client)
Lists a broker's accounts with a blocking client, before a session exists; requires BrokerCaps<Client...
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
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.
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