algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
algotradelib::backtest::Backtester< Strategy, CapsType > Class Template Reference

Replays bars (and quotes) through one strategy, with a ledger and a fill model. More...

#include <algotradelib/src/backtest/engine.hpp>

Public Types

using Tag = BacktestTag
 The order-reference tag.
using Executor = QueueingExecutor<Tag>
 The executor type.
using Runner = runner::Runner<Strategy, CapsType, Tag, Executor>
 The runner::Runner the replay drives, the same type a live session uses.

Public Member Functions

 Backtester (Strategy strategy={}, ReplayConfig config={}, NextBarFillModel fills=NextBarFillModel{})
 Constructs a replay.
const Strategy & strategy () const noexcept
 Returns the strategy, to read the state it kept.
const ReplayLedger & ledger () const noexcept
 Returns the ledger: positions, cash and realized profit.
const NextBarFillModel & fills () const noexcept
 Returns the fill model, for summarize.
const ReplayResult & result () const noexcept
 Returns what the replay has produced so far.
std::optional< Money > run_cash () const
 Returns the run's cash, with RiskLimits::run_budget_ set (runner::Runner::run_cash).
std::optional< Decimal64 > run_holding (const InstrumentId &instrument) const
 Returns the run's own shares of an instrument, with RiskLimits::run_budget_ set.
void feed (const strategy::BarEvent &event, std::optional< bool > trading_day=true)
 Replays one bar.
void finish_history ()
 Ends history now (ReplayConfig::trade_from_): delivers a pending history period to on_bars, after which every history handler has run and no traded one has. An event before trade_from_ is refused afterwards. Optional, and idempotent: without it the first traded event delivers that period.
void feed (const strategy::QuoteEvent &event, std::optional< bool > trading_day=true)
 Replays one quote: moves the price and the clock to it, re-derives the phase (calling on_phase on a change), calls on_quote, and publishes order updates.
template<typename T>
void feed (const strategy::DataEvent< T > &event, std::optional< bool > trading_day=true)
 Replays one record: moves the clock to when it became known, re-derives the phase (calling on_phase on a change), calls on_data, and publishes order updates.
void finish ()
 Ends the replay: calls on_stop (with the current portfolio, including orders from the last bar), settles what it asked for, and counts the orders still queued.

Detailed Description

template<typename Strategy, typename CapsType = strategy::NoCaps>
class algotradelib::backtest::Backtester< Strategy, CapsType >

Replays bars (and quotes) through one strategy, with a ledger and a fill model.

Feed bars with feed, in timestamp order across instruments, then call finish and summarize the result().

backtest::Backtester<MyStrategy> replay(MyStrategy{}, config);
for (const auto& bar : bars) {
replay.feed(strategy::make_bar_event(id, BarInterval::ONE_DAY, BarStamp::CLOSE, bar));
}
replay.finish();
const auto report = backtest::summarize(replay.result(), replay.fills());
Replays bars (and quotes) through one strategy, with a ledger and a fill model.
Definition engine.hpp:843
void finish()
Ends the replay: calls on_stop (with the current portfolio, including orders from the last bar),...
Definition engine.hpp:1327
Report summarize(const ReplayResult &result, const NextBarFillModel &fills, std::optional< math::Scalar > periods_per_year=std::nullopt, math::Scalar risk_free=math::Scalar{0})
Summarizes a replay into a Report.
Definition report.hpp:560
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
@ CLOSE
The timestamp is the instant the period ended.

Two replays, each with its own strategy, configuration and fill model, may run at once on two threads: a replay writes only to its own objects. What they share (bars, records, instruments, price rules) must not change meanwhile, and code of yours they call (a market-price rule, the strategy's own) must be safe on two threads.

Template Parameters
StrategyThe strategy type.
CapsTypeThe broker capabilities the strategy sees as Ctx::caps.

Definition at line 843 of file engine.hpp.

Member Typedef Documentation

◆ Executor

template<typename Strategy, typename CapsType = strategy::NoCaps>
using algotradelib::backtest::Backtester< Strategy, CapsType >::Executor = QueueingExecutor<Tag>

The executor type.

Definition at line 848 of file engine.hpp.

◆ Runner

template<typename Strategy, typename CapsType = strategy::NoCaps>
using algotradelib::backtest::Backtester< Strategy, CapsType >::Runner = runner::Runner<Strategy, CapsType, Tag, Executor>

The runner::Runner the replay drives, the same type a live session uses.

Definition at line 850 of file engine.hpp.

◆ Tag

template<typename Strategy, typename CapsType = strategy::NoCaps>
using algotradelib::backtest::Backtester< Strategy, CapsType >::Tag = BacktestTag

The order-reference tag.

Definition at line 846 of file engine.hpp.

Constructor & Destructor Documentation

◆ Backtester()

template<typename Strategy, typename CapsType = strategy::NoCaps>
algotradelib::backtest::Backtester< Strategy, CapsType >::Backtester ( Strategy strategy = {},
ReplayConfig config = {},
NextBarFillModel fills = NextBarFillModel{} )
inline

Constructs a replay.

Parameters
strategyThe strategy.
configThe settings.
fillsThe fill model (commission, slippage, limit pricing, sale tax).

Definition at line 858 of file engine.hpp.

Member Function Documentation

◆ feed() [1/3]

template<typename Strategy, typename CapsType = strategy::NoCaps>
void algotradelib::backtest::Backtester< Strategy, CapsType >::feed ( const strategy::BarEvent & event,
std::optional< bool > trading_day = true )
inline

Replays one bar.

In order: on the replay's first event, call on_start (Runner::start; its orders are eligible on this bar), record the previous period's equity point if this bar begins another period (EquityCurve::PER_PERIOD), fill orders resting from earlier bars against this bar (and call on_fill), mark positions at the close (recording this bar's point under EquityCurve::PER_BAR), advance the clock to the bar's period end (calling on_phase on a change), then call on_bar, whose orders wait for a later bar. After a halt it does nothing.

For a strategy declaring on_bars, the bar is cached instead and held with the rest of its period; the period goes to on_bars (one call per interval) when the first later bar arrives, before that bar settles, or at a quote at or after it, or at finish. Its orders wait for a later period's bar, as on_bar's do. Such a strategy is fed every bar of a period before anything later.

A bar before ReplayConfig::trade_from_ is history: it is priced and goes to on_bar (or its period to on_bars), whose orders are discarded, and none of the other steps runs.

Parameters
eventThe bar; feed bars in timestamp order across instruments. Within one instrument and interval each bar's timestamp must be later than the last.
trading_dayWhether the bar's date trades, for the phase; empty gives UNKNOWN.
Exceptions
std::invalid_argument(with a linear algebra backend) if series_capacity_ is zero, or the bar is not later than the previous bar of its instrument and interval. The exception propagates after the bar was counted and settled; it does not set ReplayResult::halted_.
std::invalid_argument(for a strategy declaring on_bars, with or without a linear algebra backend) if the bar's period was already delivered, it is earlier than bars already fed, or its instrument and interval already have a bar for that period; thrown before anything changes.
std::invalid_argumentif the bar is history and history has ended (finish_history, or a traded event), before anything changes.

Definition at line 960 of file engine.hpp.

◆ feed() [2/3]

template<typename Strategy, typename CapsType = strategy::NoCaps>
template<typename T>
void algotradelib::backtest::Backtester< Strategy, CapsType >::feed ( const strategy::DataEvent< T > & event,
std::optional< bool > trading_day = true )
inline

Replays one record: moves the clock to when it became known, re-derives the phase (calling on_phase on a change), calls on_data, and publishes order updates.

Only for a strategy declaring on_data, with a record of its data_type. Feed records in time order with the bars, and a record before the bars of its instant, so that a bar's handler sees what was known by the bar's end. With on_bars, a buffered period that ended before the record is delivered first; one that ends at the record's instant stays buffered, so its slice sees the record.

An order placed from on_data is dated at known_at_: it fills against a bar whose period began at or after the record, never at an earlier bar's open. Where a bar's start is not derivable (a close-stamped weekly, monthly or yearly bar) the fill is allowed and counted in ReplayResult::unchecked_fill_causality_, as for a quote. A record does not price an instrument, mark the ledger, record an equity point or fill anything. On the replay's first event, on_start is called first, dated at the record.

A record before ReplayConfig::trade_from_ is history: it goes to on_data, whose orders are discarded, without moving the clock; on_start's orders are then undated.

Template Parameters
TThe record type.
Parameters
eventThe record.
trading_dayWhether the record's date trades; empty gives UNKNOWN.
Exceptions
std::invalid_argumentif the record is earlier than a record or a bar already fed, or, for a strategy declaring on_bars, than a period already delivered, or is history after history ended.

Definition at line 1251 of file engine.hpp.

◆ feed() [3/3]

template<typename Strategy, typename CapsType = strategy::NoCaps>
void algotradelib::backtest::Backtester< Strategy, CapsType >::feed ( const strategy::QuoteEvent & event,
std::optional< bool > trading_day = true )
inline

Replays one quote: moves the price and the clock to it, re-derives the phase (calling on_phase on a change), calls on_quote, and publishes order updates.

On the replay's first event, on_start is called first, after the quote's instant is taken as the decision instant: its orders cannot fill against a bar whose period began before the quote.

A quote does not mark the ledger, record an equity point or fill anything. An order placed from on_quote fills against a later bar, not the quote (see ReportCaveats::quotes_). Compared with a live loop, on_phase fires before on_quote here (live, after the iteration's polls), and order updates are published here after every quote (live, only when the working-order poll runs) to a strategy that declares on_order_update. A quote before the first bar is fine; its orders wait for a bar.

Parameters
eventThe quote; feed it in timestamp order with the bars, since the clock follows whatever instant it is given, even backwards.
trading_dayWhether the quote's date trades; empty gives UNKNOWN.
Exceptions
std::invalid_argumentfor a strategy declaring on_bars, if the quote is earlier than bars already fed; a quote at or after a pending period first delivers that period to on_bars.
std::invalid_argumentif the quote is before ReplayConfig::trade_from_.

Definition at line 1149 of file engine.hpp.

◆ fills()

template<typename Strategy, typename CapsType = strategy::NoCaps>
const NextBarFillModel & algotradelib::backtest::Backtester< Strategy, CapsType >::fills ( ) const
inlinenoexcept

Returns the fill model, for summarize.

Returns
The fill model.

Definition at line 899 of file engine.hpp.

◆ finish()

template<typename Strategy, typename CapsType = strategy::NoCaps>
void algotradelib::backtest::Backtester< Strategy, CapsType >::finish ( )
inline

Ends the replay: calls on_stop (with the current portfolio, including orders from the last bar), settles what it asked for, and counts the orders still queued.

For a strategy declaring on_bars, the last period's bars are delivered first. A replay given no event calls on_start before on_stop.

After a halt it does nothing; on_stop is not called.

Definition at line 1327 of file engine.hpp.

◆ finish_history()

template<typename Strategy, typename CapsType = strategy::NoCaps>
void algotradelib::backtest::Backtester< Strategy, CapsType >::finish_history ( )
inline

Ends history now (ReplayConfig::trade_from_): delivers a pending history period to on_bars, after which every history handler has run and no traded one has. An event before trade_from_ is refused afterwards. Optional, and idempotent: without it the first traded event delivers that period.

Definition at line 1116 of file engine.hpp.

◆ ledger()

template<typename Strategy, typename CapsType = strategy::NoCaps>
const ReplayLedger & algotradelib::backtest::Backtester< Strategy, CapsType >::ledger ( ) const
inlinenoexcept

Returns the ledger: positions, cash and realized profit.

It keeps no executions (ExecutionHistory::NONE): they are in result().executions_, once.

Returns
The ledger.

Definition at line 891 of file engine.hpp.

◆ result()

template<typename Strategy, typename CapsType = strategy::NoCaps>
const ReplayResult & algotradelib::backtest::Backtester< Strategy, CapsType >::result ( ) const
inlinenoexcept

Returns what the replay has produced so far.

Returns
The result.

Definition at line 907 of file engine.hpp.

◆ run_cash()

template<typename Strategy, typename CapsType = strategy::NoCaps>
std::optional< Money > algotradelib::backtest::Backtester< Strategy, CapsType >::run_cash ( ) const
inline

Returns the run's cash, with RiskLimits::run_budget_ set (runner::Runner::run_cash).

Returns
The budget less what the replay's fills spent, plus what they returned, less their costs; or std::nullopt without a budget.

Definition at line 916 of file engine.hpp.

◆ run_holding()

template<typename Strategy, typename CapsType = strategy::NoCaps>
std::optional< Decimal64 > algotradelib::backtest::Backtester< Strategy, CapsType >::run_holding ( const InstrumentId & instrument) const
inline

Returns the run's own shares of an instrument, with RiskLimits::run_budget_ set.

Parameters
instrumentThe instrument.
Returns
The shares, or std::nullopt without a budget.

Definition at line 925 of file engine.hpp.

◆ strategy()

template<typename Strategy, typename CapsType = strategy::NoCaps>
const Strategy & algotradelib::backtest::Backtester< Strategy, CapsType >::strategy ( ) const
inlinenoexcept

Returns the strategy, to read the state it kept.

Returns
The strategy.

Definition at line 880 of file engine.hpp.


The documentation for this class was generated from the following file: