23#include <algotradelib/backtest>
24#include <algotradelib/kis>
25#include <algotradelib/tossinvest>
27#include <boost/asio/ssl/context.hpp>
42namespace ssl = boost::asio::ssl;
46namespace strategy = algotradelib::strategy;
47namespace backtest = algotradelib::backtest;
48namespace math = algotradelib::math;
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)");
63using algotradelib::BarQuery;
64using algotradelib::BarSeries;
65using algotradelib::BlockingSession;
67using algotradelib::Currency;
68using algotradelib::Decimal64;
69using algotradelib::Instrument;
70using algotradelib::InstrumentId;
74struct FetchedHistory {
75 Instrument reference_;
85template <
typename Session>
86std::optional<FetchedHistory> read_history(Session& session,
const InstrumentId& instrument, std::size_t count) {
87 auto reference = session.instrument(instrument);
89 std::cerr <<
"could not read reference data: " << reference.error().message_ <<
'\n';
94 query.instrument_ = instrument;
95 query.interval_ = BarInterval::ONE_DAY;
99 query.adjusted_ =
true;
101 auto bars = session.bars(query);
103 std::cerr <<
"could not read bars: " <<
bars.error().message_ <<
'\n';
106 if (
bars.value().bars_.size() < 2) {
107 std::cerr <<
"the broker returned too few bars to replay\n";
111 FetchedHistory history;
112 history.reference_ = std::move(reference.value());
113 history.bars_ = std::move(
bars.value());
127 void on_bar(Ctx& ctx,
const strategy::BarEvent& bar) {
128 strategy::TargetPosition target;
141struct MovingAverageCross {
143 std::size_t fast_{20};
145 std::size_t slow_{50};
149 std::vector<Decimal64> closes_;
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_) {
157 const auto fast_sum = sum_of_last(fast_);
158 const auto slow_sum = sum_of_last(slow_);
159 if (!fast_sum || !slow_sum) {
164 if (!left || !right) {
167 strategy::TargetPosition target;
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) {
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;
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)
203 for (
const auto& bar : history.bars_.bars_) {
211 const auto report = backtest::summarize(engine.result(), engine.fills(), periods);
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" :
"--");
220 << std::fixed << std::setprecision(as_percent ? 2 : 3) << (as_percent ? value * 100.0 : value)
221 << (as_percent ?
" %" :
"");
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)
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_) {
242 <<
" cost totals INCOMPLETE -- an exact sum did not fit; slippage is understated"
243 <<
" and the fee totals are withheld\n";
250template <
typename Session>
251int backtest_with(Session& session,
const std::string& symbol) {
252 const InstrumentId instrument{Country::KR, Venue::COMBINED, symbol};
254 const auto history = read_history(session, instrument, 400);
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";
264#if defined(ATL_HAS_EIGEN)
266 "HoldsShares -- the benchmark every strategy is measured against", HoldsShares{Decimal64::parse(
"100")}, *history
269 MovingAverageCross crossing;
270 crossing.quantity_ = Decimal64::parse(
"100");
271 replay_and_report(
"MovingAverageCross(20, 50)", crossing, *history);
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";
278 std::cout <<
"The report needs a linear algebra backend; configure with -DATL_USE_EIGEN=ON.\n";
283int backtest_kis(ssl::context& tls,
const std::string& symbol) {
284 namespace kis = algotradelib::kis;
286 kis::KisConfig config;
288 kis::KisAccount account;
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);
296int backtest_tossinvest(ssl::context& tls,
const std::string& symbol,
const char* sequence) {
297 namespace toss = algotradelib::tossinvest;
299 toss::TossConfig config;
301 auto client = std::make_shared<toss::TossBlockingClient>(tls, std::move(config));
303 std::int64_t selected = 0;
304 if (sequence !=
nullptr) {
305 selected = std::strtoll(sequence,
nullptr, 10);
308 if (!accounts || accounts.value().empty()) {
309 std::cerr <<
"could not discover a Toss account\n";
312 selected = accounts.value().front().selector_;
315 BlockingSession<toss::TossBlockingClient> session(std::move(client), selected);
316 return backtest_with(session, symbol);
321int main(
int argc,
char** argv) {
322 const std::string broker = argc > 1 ? argv[1] :
"";
323 if (broker !=
"kis" && broker !=
"tossinvest") {
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";
329 const std::string symbol = argc > 2 ? argv[2] :
"005930";
332 ssl::context tls(ssl::context::tls_client);
333 tls.set_default_verify_paths();
334 tls.set_verify_mode(ssl::verify_peer);
336 if (broker ==
"kis") {
337 return backtest_kis(tls, symbol);
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';
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.
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
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.
Country
A country (market) the library supports.
Venue
A trading venue: an exchange, or the combined view across exchanges.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
BarInterval
The period one bar covers.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
InstrumentId instrument_
The instrument.
Decimal64 target_quantity_
The position to hold, signed: negative is short, and zero means flat.