20#include <algotradelib/backtest>
21#include <algotradelib/krx>
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)");
61InstrumentId samsung() {
62 return InstrumentId{Country::KR, Venue::COMBINED,
"005930"};
65Instrument samsung_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");
94 std::size_t lookback_{5};
96 Decimal64 quantity_{Decimal64::parse(
"1000")};
98 std::vector<Decimal64> history_;
101 void on_bar(Ctx& ctx,
const strategy::BarEvent& bar) {
102 history_.push_back(
bar.bar_.close_);
103 if (history_.size() < lookback_) {
122 std::optional<Decimal64> sum = Decimal64::parse(
"0");
123 for (std::size_t at = history_.size() - lookback_; sum && at < history_.size(); ++at) {
127 if (!sum || !scaled) {
135 strategy::TargetPosition target;
143const std::vector<int>& closes() {
144 static const std::vector<int> path = {
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)
197backtest::ReplayConfig config_for() {
198 backtest::ReplayConfig config;
199 config.cash_ = Decimal64::parse(
"100000000");
200 config.instruments_ = {samsung_reference()};
201 config.series_capacity_ = 64;
204 config.limits_.permitted_phases_ = std::nullopt;
209template <
typename Strategy>
210backtest::Backtester<Strategy> replay(
211 Strategy instance, BarInterval interval,
const backtest::NextBarFillModel& fills = realistic_costs()
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)));
221 bar.open_ = Decimal64::parse(std::to_string(closes()[at]));
225 bar.volume_ = Decimal64::parse(
"1200000");
232#if defined(ATL_HAS_EIGEN)
234std::string percent(math::Scalar value) {
235 if (!math::observed(value)) {
236 return math::is_undefined(value) ?
"undefined" :
" --";
238 std::ostringstream text;
239 text << std::fixed << std::setprecision(2) << std::setw(7) << value * 100.0 <<
" %";
244std::string plain(math::Scalar value) {
245 if (!math::observed(value)) {
246 return math::is_undefined(value) ?
"undefined" :
" --";
248 std::ostringstream text;
249 text << std::fixed << std::setprecision(3) << std::setw(9) << value;
254void print(
const std::string& title,
const backtest::Report& report) {
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";
268 <<
" assumed limit fills " << backtest::limit_fill_price_name(report.caveats_.limit_fill_) <<
", slippage "
269 << report.caveats_.slippage_ticks_ <<
" tick\n";
272 for (
const auto& applied : report.caveats_.applied_rates_) {
274 <<
" commission rate " << applied.rate_.str() <<
" with a " << applied.minimum_.str() <<
" floor, "
277 if (report.caveats_.cost_totals_incomplete_) {
282 <<
" cost totals INCOMPLETE -- an exact sum did not fit; slippage is understated"
283 <<
" and the fee totals are withheld\n";
285 if (report.caveats_.inclusive_commission_executions_ > 0) {
287 <<
" commission is inclusive of any institution charge on "
288 << report.caveats_.inclusive_commission_executions_ <<
" execution(s)\n";
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";
294 if (report.caveats_.unfilled_ > 0) {
295 std::cout <<
" unfilled " << report.caveats_.unfilled_ <<
" (no next bar to fill against)\n";
297 if (report.caveats_.expired_day_orders_ > 0) {
299 <<
" expired " << report.caveats_.expired_day_orders_
300 <<
" DAY order(s) unfilled at their session's close, as at a broker\n";
302 if (report.caveats_.multiple_instruments_) {
304 <<
" CAVEAT more than one instrument: this result may carry survivorship\n"
305 <<
" bias, because reference data lists what exists now\n";
319 std::cout <<
"005930, " << closes().size() <<
" bars built in code -- no credentials, no network\n\n";
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{});
326#if defined(ATL_HAS_EIGEN)
328 const auto minute_periods =
331 <<
"periods per year: " << *daily_periods <<
" daily, " << *minute_periods
332 <<
" minute -- which is why annualizing takes the count rather than assuming it\n\n";
334 print(
"MyStrategy(5), daily", backtest::summarize(daily.result(), daily.fills(), *daily_periods));
339 "MyStrategy(5), minute bars -- identical decisions, different annualizing",
340 backtest::summarize(minutes.result(), minutes.fills(), *minute_periods)
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";
353 "MyStrategy(5), daily, at zero cost -- the difference is what costs cost",
354 backtest::summarize(costless.result(), costless.fills(), *daily_periods)
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";
362 const auto filled = [](
const char* title,
const auto& engine) {
364 << title <<
": replayed " << engine.result().bars_ <<
" bars and filled " << engine.result().executions_.size()
367 filled(
"MyStrategy(5), daily", daily);
368 filled(
"MyStrategy(5), minute bars", minutes);
369 filled(
"MyStrategy(5), daily, at zero cost", costless);
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";
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
#define ATL_ASSERT_STRATEGY(S, Ctx)
Asserts at compile time that S is a strategy a runner with context Ctx can drive.
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
PriceRule equity_price_rule()
Returns the KRX stock tick table (January 2023 revision).
The numeric vocabulary: Scalar, missing(), and the matrix and vector types.
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
ProbeContextT< NoCaps > MinimalContext
A probe context whose broker implements nothing optional.
ProbeContextT< AllCaps > FullContext
A probe context whose broker implements everything optional.
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.
constexpr std::string_view commission_origin_name(CommissionOrigin origin) noexcept
Returns a lowercase name for an origin, such as "caller_stated", for reports.
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.
One bar: the prices and volume of one period, as exact decimals.
Identifies an instrument: its country, venue and symbol.
Reference data for one instrument.
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.