![]() |
algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
|
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report. More...
Classes | |
| struct | AppliedRate |
| The commission rate that charged an execution, as the backtest report lists it. More... | |
| class | Backtester |
| Replays bars (and quotes) through one strategy, with a ledger and a fill model. More... | |
| struct | BacktestTag |
| The broker tag of a replay's order references (they reach no broker). More... | |
| struct | CommissionCharge |
| What one execution was charged: the broker's commission and the institution fee. More... | |
| struct | CommissionModel |
| A flat commission: a rate on traded value, with an optional per-execution minimum. More... | |
| class | CommissionPolicy |
| How a backtest charges commission: one stated model, or a schedule resolved per execution. More... | |
| struct | Differences |
| Chains the drawn changes (Paparoditis and Politis): the path's previous close plus value - from. More... | |
| struct | EquityPoint |
| One point on a replay's equity curve: per period end, or per bar (EquityCurve). More... | |
| struct | Execution |
| One execution a backtest produced, and what it cost. More... | |
| struct | Expanding |
| Training on every position from the end of the first history to each test range. More... | |
| struct | FillDecision |
| What NextBarFillModel::decide concluded about one order and one bar. More... | |
| struct | Fold |
| One fold: its training and test ranges, and where each one's history starts. More... | |
| struct | FoldLengths |
| The lengths of a fold, in positions. More... | |
| struct | IndexRange |
| A half-open range of positions, [begin_, end_). More... | |
| struct | is_price_join |
| Whether Join can join drawn blocks: true when a const Join has a member join(double, double, double) returning something convertible to double. More... | |
| struct | is_price_join< Join, std::enable_if_t< std::is_convertible_v< decltype(std::declval< const Join & >().join(double{}, double{}, double{})), double > > > |
| A join with the member join that resample_closes and resample_bars call. More... | |
| struct | is_window_scheme |
| Whether Scheme can choose a fold's training range: true when a const Scheme has a member train(std::size_t, const FoldLengths&) returning something convertible to IndexRange. More... | |
| struct | is_window_scheme< Scheme, std::enable_if_t< std::is_convertible_v< decltype(std::declval< const Scheme & >().train(std::size_t{}, std::declval< const FoldLengths & >())), IndexRange > > > |
| A scheme with the member train that folds calls. More... | |
| struct | Levels |
| Joins the drawn prices as they are (Künsch; Politis and Romano): for a stationary series, not trending prices, where each block boundary is a jump. More... | |
| struct | MarketPriceInput |
| What a market-price rule is given (see NextBarFillModel::with_market_price). More... | |
| struct | MeasureInput |
| What a measure of a finished replay reads: the replay, its report, and its equity curve's levels and returns as the columns analytics::sharpe, analytics::sortino and analytics::max_drawdown take. More... | |
| class | NextBarFillModel |
| The fill model: market orders at the next bar's open, limit orders when the next bar's range reaches them, stop-limit orders once released. More... | |
| struct | QueuedOrder |
| One order a replay accepted and has not yet filled or withdrawn. More... | |
| class | QueueingExecutor |
| The replay's executor: accepts orders and holds them until they fill or are withdrawn. More... | |
| class | ReplayClock |
| A backtest's clock: the current instant and market phase, moved by the replayed events. More... | |
| struct | ReplayConfig |
| A replay's settings, besides the strategy and the bars. More... | |
| class | ReplayLedger |
| Positions, cash and realized profit, updated by each execution of a replay. More... | |
| struct | ReplayResult |
| Everything a replay produced; summarize turns it into a Report. More... | |
| struct | Report |
| The summary of a replay; read halted_ and caveats_ before the figures. More... | |
| struct | ReportCaveats |
| What a replay's figures assumed and did not account for. More... | |
| struct | Returns |
| Chains the drawn returns: a path price is the path's previous close times value / from. More... | |
| struct | Rolling |
| Training on the train_ positions just before each test range. More... | |
| struct | SellTax |
| A tax on sales, stated by the caller; see NextBarFillModel::with_sell_tax. More... | |
| struct | SlippageModel |
| Slippage: how far a fill price moves against the order (a buy pays more, a sell gets less). More... | |
Typedefs | |
| using | MarketPriceFunction = std::function<std::optional<Decimal64>(const MarketPriceInput&)> |
| A market-price rule: the price a market order trades at against next_, before slippage, or nothing when it does not trade against that bar. | |
Enumerations | |
| enum class | LimitFillPrice { AT_LIMIT , AT_OPEN_IF_BETTER } |
| Which price a backtest credits a limit order that fills. More... | |
| enum class | EquityCurve { PER_PERIOD , PER_BAR , NONE } |
| Which points a replay records on its equity curve (ReplayResult::equity_); see ReplayConfig::equity_curve_. More... | |
| enum class | MarketPrice { NEXT_OPEN , DECISION_CLOSE , NEXT_CLOSE } |
| A market-price rule the library ships; see NextBarFillModel::with_market_price(MarketPrice). More... | |
| enum class | ExecutionHistory { KEEP , NONE } |
| Whether a ReplayLedger keeps the executions it applies. More... | |
Functions | |
| template<typename Join = Returns> | |
| std::vector< Decimal64 > | resample_closes (const std::vector< Decimal64 > &closes, const PriceRule &rule, const std::vector< std::size_t > &indices, const Join &join=Join{}) |
| Rebuilds one instrument's closes along a bootstrap path (analytics::bootstrap_indices), joining the drawn blocks by Join, and rounds each to its nearest grid price, a tie going up. | |
| template<typename Join = Returns> | |
| std::vector< Bar > | resample_bars (const std::vector< Bar > &bars, const PriceRule &rule, const std::vector< std::size_t > &indices, const Join &join=Join{}) |
| Rebuilds one instrument's bars along a bootstrap path (analytics::bootstrap_indices): each drawn day's prices joined to the path's previous close and rounded to their nearest grid prices, a tie going up. | |
| std::optional< std::chrono::seconds > | interval_duration (BarInterval interval) |
| Returns the fixed duration of an interval (bar_interval_length). | |
| std::optional< math::Scalar > | periods_per_year (BarInterval interval, const strategy::SessionWindow &session, math::Scalar trading_days) |
| Returns how many bars of an interval a year contains, for analytics::annualize_ratio. | |
| Result< CommissionModel > | commission_model_from (const CommissionSchedule &schedule, Country country, const Date &date) |
| Builds a flat commission model from a schedule's rate for a market on a date. | |
| constexpr std::string_view | limit_fill_price_name (LimitFillPrice choice) noexcept |
| Returns a lowercase name for a choice, such as "at_limit", for reports. | |
| template<typename Scheme = Rolling> | |
| std::vector< Fold > | folds (std::size_t count, const FoldLengths &lengths, const Scheme &scheme=Scheme{}) |
| Lists the folds over a time index of count positions. | |
| 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. | |
| MeasureInput | measure_input (const ReplayResult &result, const NextBarFillModel &fills, std::optional< math::Scalar > periods_per_year=std::nullopt) |
| Builds the input a measure reads from a finished replay, calling summarize once. | |
| MeasureInput | measure_input (const ReplayResult &&, const NextBarFillModel &, std::optional< math::Scalar >=std::nullopt)=delete |
| Refused: the input would refer to a temporary result that is gone before the input is read. | |
| ReplayResult | chain_results (const std::vector< const ReplayResult * > &results) |
| Chains test replays into one result, so summarize and measure_input give the chain's figures. | |
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
| using algotradelib::backtest::MarketPriceFunction = std::function<std::optional<Decimal64>(const MarketPriceInput&)> |
A market-price rule: the price a market order trades at against next_, before slippage, or nothing when it does not trade against that bar.
Nothing checks the price against next_'s range: a rule may name any price (the decision bar's close lies outside the next bar's range after a gap). The report names the rule and counts the fills it priced.
|
strong |
Which points a replay records on its equity curve (ReplayResult::equity_); see ReplayConfig::equity_curve_.
| Enumerator | |
|---|---|
| PER_PERIOD | One point per period end, after the last bar of that period: one a day for daily bars, however many instruments trade. A ratio over the curve (summarize) is then per period. Precisely, one point for each run of consecutive bars sharing a period end, after the run's last bar: a replay fed in period-end order (every on_bars replay, and an on_bar replay of one interval and one stamp convention) gets one per period; bars whose period ends interleave (mixed intervals, or open- and close-stamped bars) get a point at each change, so none is lost. The last period's point is recorded by finish. |
| PER_BAR | One point per bar fed. A replay of many instruments records one per instrument per period, all at the same instant, and a ratio over them is per bar, not per period. |
| NONE | No points, for a run that does not read the curve; summarize then reports no ratio. |
Definition at line 637 of file engine.hpp.
|
strong |
Whether a ReplayLedger keeps the executions it applies.
| Enumerator | |
|---|---|
| KEEP | Keep every execution, readable through ReplayLedger::executions(). |
| NONE | Keep none, for an owner that records them itself (a Backtester, in ReplayResult::executions_). Positions, cash, realized profit and equity are the same as with KEEP. |
Definition at line 63 of file ledger.hpp.
|
strong |
Which price a backtest credits a limit order that fills.
| Enumerator | |
|---|---|
| AT_LIMIT | The default: fill at the limit, or at the bar's worst traded price when the whole bar was better than the limit. A bar that gaps through a resting limit is not credited its open. A limit marketable through the whole bar (a buy above the high) is credited the high (a sell below the low, the low), which is better than the limit; ReportCaveats::limit_fills_bounded_ counts those fills. |
| AT_OPEN_IF_BETTER | Fill at the bar's open when it opened through the limit (assumes the order was resting before the open). |
|
strong |
A market-price rule the library ships; see NextBarFillModel::with_market_price(MarketPrice).
| Enumerator | |
|---|---|
| NEXT_OPEN | The default: a market order fills at the next bar's open (its close if it has no open). |
| DECISION_CLOSE | A market order fills at the price it was decided on, named decision-close in the report. The price is the instrument's last price when the strategy decided the order (MarketPriceInput::decision_price_): the close of the bar it decided on, the open of an open point, or the quote it decided on. That price is the instrument's own last one, so it can be days old after a gap in that instrument's data; an order placed in on_fill gets the price before the fill bar. With no price known yet (the first bar's fill of an order placed in on_start) the order fills at the fill bar's open, and with neither it does not trade against that bar. This is the textbook convention of backtests that trade on close; it is optimistic. The strategy trades at a price it has already seen, which a market cannot give: a real closing-auction order is sent before the final price is known. |
| NEXT_CLOSE | A market order fills at the close of the bar it fills against, named next-close in the report. The bar is the next eligible one under the engine's existing causality rules, as for any rule: the same instrument's next bar whose period starts at or after the decision, so an order decided on a quote inside a bar's period waits for a later bar; where the decision's instant is nominal, the engine admits the bar and counts it (ReplayResult::unchecked_fill_causality_). This is the price basis of backtests that trade on the next bar's close; it is a price convention, not a closing-order simulation. The fill keeps the model's timing: it is stamped at the bar's period end, charged on the bar's trading date (its open's date when known), and a DAY order expires with the session of the bar it was queued for. That holds for intraday bars inside one session and for daily trading-date bars; a daily bar stamped at its close from a date alone is taken at its literal instant, and a bar crossing the session's close or local midnight is not detected. On a weekly, monthly or yearly bar the close's date and session are not known, so an order this rule would price there is not priced: a costing error (code next_close_bar_too_long) halts the replay. |
|
inline |
Chains test replays into one result, so summarize and measure_input give the chain's figures.
The chain is a synthetic account reset to the previous fold's close at each boundary, not a continuously held portfolio. Each later fold's curve is scaled so its first point is the close so far, each point a decimal of fifteen significant digits (a relative error near 1e-15 at each boundary, compounding over the folds) where a decimal's 255 places hold them; a level nearer the 255th place keeps fewer digits and can be far less accurate, but a nonzero level is never rounded to zero. Returns are kept as recorded, and a fold's first point carries none. Executions, rejections and refusals are concatenated and counts summed; each first_* instant and the market-price rule come from the first fold that has one, and lowest_cash_ is the lowest over the folds, each in its own capital. summarize measures turnover against fold 0's opening equity. The folds should share one fill model and one ReplayConfig but for trade_from_; this is not checked.
| results | The test replays, in order. |
| std::invalid_argument | if results is empty or holds a null pointer, a halted result, one with no curve point or one in another currency; if a fold does not start after the previous one ends, its first equity or the close it follows is not positive, or a scaled equity does not fit a decimal (too large, or nonzero and zero once rounded to 255 places). |
Definition at line 650 of file report.hpp.
Referenced by chain_results().
|
inline |
Builds a flat commission model from a schedule's rate for a market on a date.
The model has no minimum (none is published) and no tax; it charges that one rate for the whole replay, even if the schedule changes rate later. For per-date rates use CommissionPolicy::scheduled.
| schedule | The schedule, published by a broker or stated by the caller. |
| country | The market. |
| date | The date whose rate to use. |
Definition at line 96 of file cost.hpp.
Referenced by commission_model_from().
| std::vector< Fold > algotradelib::backtest::folds | ( | std::size_t | count, |
| const FoldLengths & | lengths, | ||
| const Scheme & | scheme = Scheme{} ) |
Lists the folds over a time index of count positions.
Fold k tests [t_k, t_k + test_) with t_k = warmup_ + train_ + k * step_, for every k whose test range fits; a shorter last test range is dropped, so every fold tests the same length. The training range is scheme.train(t_k, lengths). Chaining the test ranges into one curve needs step_ == test_; any positive step is allowed.
| Scheme | The training scheme: Rolling, Expanding, or one of your own with the member IndexRange train(std::size_t test_begin, const FoldLengths& lengths) const. |
| count | The number of positions in the time index. |
| lengths | The fold lengths. |
| scheme | The training scheme. |
| std::invalid_argument | if train_ or step_ is zero, warmup_ + train_ + test_ exceeds count, or the scheme returns a range that starts before warmup_, is empty, or ends after the test range starts. |
Definition at line 114 of file folds.hpp.
Referenced by folds().
|
inline |
Returns the fixed duration of an interval (bar_interval_length).
| interval | The interval. |
Definition at line 30 of file clock.hpp.
Referenced by algotradelib::backtest::ReplayClock::contiguous(), interval_duration(), and periods_per_year().
|
inlineconstexprnoexcept |
Returns a lowercase name for a choice, such as "at_limit", for reports.
| choice | The choice. |
Definition at line 587 of file cost.hpp.
Referenced by limit_fill_price_name().
|
delete |
Refused: the input would refer to a temporary result that is gone before the input is read.
|
inline |
Builds the input a measure reads from a finished replay, calling summarize once.
Does not throw for an empty curve or a halted replay: the levels and returns are then empty or end at the halt, as the report's figures do. A measure computing its own ratio applies the report's rule for equity at or below zero by reading math::is_undefined(report_.sharpe_).
| result | The replay's result; it must outlive the input (see MeasureInput). |
| fills | The fill model the replay used. |
| periods_per_year | Periods in a year, as for summarize. |
| std::invalid_argument | if periods_per_year is given, not positive, and the equity curve is not empty. |
Definition at line 610 of file report.hpp.
Referenced by measure_input(), and measure_input().
|
inline |
Returns how many bars of an interval a year contains, for analytics::annualize_ratio.
Daily bars: trading_days. Intraday bars: the bars a session holds, times trading_days. A session that is not a whole number of bars ends with a shorter one, which counts: KRX's 390-minute session holds 390 one-minute bars (95,550 a year over 245 days) and 7 hourly ones, the last of them 30 minutes.
| interval | The bar interval. |
| session | The session window (used for intraday bars). |
| trading_days | Trading days per year, such as about 245 for KRX or 252 for US markets. |
Definition at line 47 of file clock.hpp.
Referenced by measure_input(), periods_per_year(), and summarize().
| std::vector< Bar > algotradelib::backtest::resample_bars | ( | const std::vector< Bar > & | bars, |
| const PriceRule & | rule, | ||
| const std::vector< std::size_t > & | indices, | ||
| const Join & | join = Join{} ) |
Rebuilds one instrument's bars along a bootstrap path (analytics::bootstrap_indices): each drawn day's prices joined to the path's previous close and rounded to their nearest grid prices, a tie going up.
Call it with the same indices for every instrument of a path. The identity draw (0, 1, ..., n - 2) returns bars as they are. Otherwise bar 0 is the first bar with its prices rounded. Bar k draws day j + 1 with j = indices[k - 1]: each of its prices value (open, high, low, close) becomes join.join(level, bars[j].close_, value), level the path's close k - 1 unrounded, so the closes are those of resample_closes when the scale is the same (here it is read over every price). Bar k takes bars[k]'s timestamp and the drawn day's volume; an empty open stays empty. Bar 0 keeps its own traded_value_; a drawn bar (k >= 1) has none.
An ordered bar (low at most open and close, high at least both) stays ordered, since every built-in join and the rounding are non-decreasing in the price; the input's order is not checked. With Differences or Levels a price can be at or below zero; whether a replay may trade at it is the caller's choice.
| Join | Returns, Differences, Levels, or one of your own with the member double join(double level, double from, double value) const, non-decreasing in value. A join without static constexpr bool any_sign = true takes and returns positive prices only. |
| bars | The bars, in order, one per instant. |
| rule | The price grid, as resample_closes. |
| indices | The drawn returns, each below bars.size() - 1. |
| join | The join. |
| std::invalid_argument | for what resample_closes refuses, read over every price of every bar (an empty open is skipped). |
Definition at line 331 of file bootstrap.hpp.
Referenced by resample_bars().
| std::vector< Decimal64 > algotradelib::backtest::resample_closes | ( | const std::vector< Decimal64 > & | closes, |
| const PriceRule & | rule, | ||
| const std::vector< std::size_t > & | indices, | ||
| const Join & | join = Join{} ) |
Rebuilds one instrument's closes along a bootstrap path (analytics::bootstrap_indices), joining the drawn blocks by Join, and rounds each to its nearest grid price, a tie going up.
Call it with the same indices for every instrument of a path, so they move on the same drawn days. The identity draw (0, 1, ..., n - 2) returns closes as they are. Otherwise close 0 is the first close, and close k is join.join(level, closes[j], closes[j + 1]) with j = indices[k - 1] and level close k - 1, accumulated unrounded and rounded once each; with Returns, close k - 1 times closes[j + 1] / closes[j]. The arithmetic is in grid units (10^-s, s the largest scale among the closes and the rule's band starts and ticks): converting a price to units is exact below 2^53, and Differences and Levels stay in whole units. Returns divides and multiplies in rounded binary64 doubles in a fixed order, with no multiply-add to fuse, so its result is the same wherever doubles are IEEE binary64 rounding to nearest (not x87 extended precision).
Levels keeps close 0 and draws closes 1 to n - 1, so a circular block wraps from close n - 1 to close 1. With Differences or Levels a close can be at or below zero; whether a replay may trade at it is the caller's choice.
| Join | Returns, Differences, Levels, or one of your own with the member double join(double level, double from, double value) const. A join without static constexpr bool any_sign = true takes and returns positive closes only. |
| closes | The closes, in order. |
| rule | The price grid: UNCONSTRAINED rounds to one unit, from zero (at every sign with any_sign); a stated grid must be aligned (each band's start a multiple of its own tick and of the previous band's). |
| indices | The drawn returns, each below closes.size() - 1. |
| join | The join. |
| std::invalid_argument | for fewer than two closes, too many indices or one out of range, a close at or below zero (without any_sign), an UNKNOWN or unaligned rule, or a band or tick at or beyond 2^53 units at the rule's own scale (the identity draw included); for a drawn path, a close, band, tick, level or grid neighbour at or beyond 2^53 units in magnitude, a level below a stated grid's first band (or below zero without any_sign), a close rounded to zero (without any_sign), or what join throws. |
Definition at line 269 of file bootstrap.hpp.
Referenced by resample_closes().
|
inline |
Summarizes a replay into a Report.
| result | The replay's result. |
| fills | The fill model the replay used, so the report states its costs and assumptions. |
| periods_per_year | Periods in a year, for the annualized Sharpe ratio (see backtest::periods_per_year); absent leaves it missing(). |
| risk_free | The risk-free rate per period, in the units of the returns. |
| std::invalid_argument | if periods_per_year is given, not positive, and the equity curve is not empty. |
Definition at line 560 of file report.hpp.
Referenced by summarize().