Quant notes · 04 · interactive

Backtester implementation

This page documents backtest.py in the xau-btc-models repository: 157 lines, five functions. Each function is described and then traced on a six-day example with invented closing prices. The page also states the formulas, computes the summary statistics on the example, shows walk-forward selection, and lists review questions. All numbers are computed by the page's JavaScript from the six closes and can be checked by hand.

Constraints 1 · Signals use only past data. 2 · The one-bar lag, pos = target.shift(1), is never removed. 3 · Every result includes costs.

The six-day example uses invented prices. No market data is used and no performance is reported.

1 · Structure

The file contains five functions. backtest calls realised_vol; stats and yearly take the table that backtest returns; walk_forward calls backtest and stats in a loop. Selecting a box shows the function's signature, docstring, inputs and outputs.

Boxes: the five functions in backtest.py. Dashed arrows: a function call, pointing from the caller to the function called. Solid arrows: data returned or passed on. Select a box for its description. The same diagram with each function's code and output in place is on the structure sheet.

returnsThe daily percentage change in price: today's close divided by yesterday's close, minus one. A move from 102 to 101 is a return of −0.98%. Variable ret, line 51.
volatilityHow much the daily returns vary: their standard deviation, with recent days weighted more than older ones, multiplied by √365 so it is quoted as a yearly figure. Variable vol, line 55.
results tableThe table that backtest returns, lines 75–80. One row per day, and one column for each quantity: price, return, signal, position, turnover, gross profit, cost, carry, net profit, equity. Variable res.
parameter gridThe list of settings that walk_forward tries, for example lookbacks of 63, 126 and 252 days. Each entry is tested on the training window and the best one is applied to the test window. Variable grid.
out-of-sample resultsThe test windows of walk_forward joined end to end. These are the periods that were not used to choose the parameters. Variable oos, line 155.
selection logOne row per window: the dates, the parameters chosen, the Sharpe ratio on the training window and the Sharpe ratio on the test window. Variable log, lines 149–151.

2 · Worked example

Left: the five functions of the file, with docstrings, imports and blank lines removed; line numbers are those of the file. Right: the six-day table. Inputs: six closing prices, a hand-written signal, a cost of 5 bps, no carry and no volatility target, so the else branch on line 59 executes. Each step highlights the lines it describes. Steps within the body of backtest also fill one column of the table and show the formula with the arithmetic for day 3. Selecting a line of code moves to its step. Each column depends only on the columns to its left.

Lab A · Step through backtest.py

computed in the page · six closes
Scenario:

      

Inputs: closes 100, 102, 101, 104, 103, 105; signal 0, +1, +1, −1, −1, +1; cost_bps=5; carry_annual=0; vol_target=None; bars_per_year=365. The mask scenario passes tradable = [True, True, True, False, False, True].

3 · Formulas

One formula per box, in the order the code computes them, each followed by its reading.

volt = ewm_stdspan(r)t · √365

Line 23. The exponentially weighted standard deviation of daily returns up to day t, times √365 to quote it per year. Span 30 corresponds to λ ≈ 0.935; the EWMA note (02) covers this line.

scalet = voltargetvolt

Line 56. The volatility you want each instrument to contribute divided by the volatility the market currently shows. At a 10% target and 20% volatility the scale is 0.5; at 60% volatility it is 0.17.

targett = clip( signalt · scalet, −max_leverage, +max_leverage )

Line 57. The signal (+1, −1 or 0) times the scale, capped at ±2 units of notional. With vol_target=None the scale step is skipped and the signal is only clipped (line 59).

post = targett−1

Line 62. The position held during day t is the target computed at the close of day t−1. The decision is made at one close and executed from the next bar.

turnovert = | post − post−1 |

Line 68. The absolute change in position from one day to the next. A change from +1 to −1 is 2.

costt = turnovert · costbps104

Line 69. Turnover times the charge per unit traded. 5 bps = 5 / 10,000 = 0.0005 of notional.

carryt = | post | · carryannual365

Line 70. The daily share of the annual holding cost, charged on the size of the position, long or short.

grosst = post · rt

Line 72. Position held times the day's return: profit before costs.

nett = grosst − costt − carryt

Line 73. Profit after the trading cost and the holding cost.

equityt = ∏s ≤ t (1 + nets)

Line 79. The running product of (1 + net): the value of $1 invested at the start.

drawdownt = equitytmaxs ≤ t equitys − 1

Line 86. Equity divided by its highest value so far, minus one: how far below its running peak the equity is on day t. Zero at a new high, negative otherwise.

MaxDrawdown = mint drawdownt

Line 95. The lowest value of the drawdown series: the largest fall from a peak to a subsequent trough.

CAGR = equityT 365 / T − 1

Line 88. The final equity raised to the power (bars per year ÷ number of bars), minus one: the constant yearly growth rate that would produce the final equity. On six days the exponent is 365/6, so the figure is extreme; it is shown because the code computes it.

Vol = std(net) · √365

Line 89. The standard deviation of daily net returns, times √365 to quote it per year.

Sharpe = mean(net) · 365Vol

Line 94. The annualised mean of daily net returns divided by the annualised volatility: return per unit of risk. NaN when Vol is zero.

4 · Summary statistics

The eleven values returned by stats, computed from the table in section 2 for the selected scenario. Selecting a value shows its line and its arithmetic.

yearReturnMaxDD

yearly() groups by calendar year. The six example days all fall in one year, so there is one row; on nine years of real data it is the quickest regime check: a rule that worked in two years out of nine is suspect.

5 · Walk-forward selection

Lines 116–157. Parameters are selected on a training window and applied to the following test window only. The windows then advance, and the test windows are concatenated. Select a stage.

Why its Sharpe is usually lower, and which to trust.A full-history Sharpe lets the parameters see the whole sample, including the years they are then scored on; the best parameter on a history is partly the noise of that history, so the number is inflated. The walk-forward Sharpe only ever uses a choice that was made before the period it is scored on, so it is closer to what paper trading will show. Trust the walk-forward number, and watch the log it returns: if train_sharpe is 2.0 and test_sharpe is 0.3 in every window, the rule is fitting noise. The grid the project plans to walk forward is the lookback blend from the momentum note (01).

6 · Review questions

Seven questions from session 3 of the study guide. Under each question, three lines state what a complete answer contains: the claim, the mechanism (the formula or line of code) and the evidence (a number from the repository or from notebook 02). Answer in that order before revealing the model answer.

7 · Terminology

Each entry: the technical definition first, then the same idea in everyday words in the orange strip.

Series / DataFramepandas' one-column and many-column tables, indexed by date here.a column of numbers with dates down the side, and a whole spreadsheet of them.
vectorisedoperating on whole columns at once instead of looping row by row.one line does the sum for every day; no "for each day" loop.
notionalthe money value of a position; a position of 1 = 100% of the account.how big the bet is, measured in multiples of your account.
bpsbasis points, 1 bp = 0.01%.a hundredth of a percent. 5 bps on $10,000 is $5.
turnoverthe absolute change in position; per year, the sum.how much buying and selling the rule does.
carrythe cost of holding a position overnight: funding on a perpetual, financing on a CFD.rent for keeping the position open.
leverageposition size in units of the account; 2 means a position worth twice the account.borrowing to bet bigger than your money; the cap keeps it to 2×.
drawdownequity divided by its running maximum, minus one.how far below your best-ever point you are.
CAGRcompound annual growth rate: the constant yearly rate that would produce the final equity.the average yearly growth, if it had been smooth.
out-of-sampledata not used when the parameters were chosen.the part of history the rule never got to peek at.
warm-upthe bars a lookback signal needs before it has a value.a 252-day rule says nothing for its first 252 days; walk_forward feeds the training history in so the test starts warm.

Sources

CarverR. Carver, Systematic Trading, Harriman House, 2015. Ch. 1–3 (why rules, fitting and overfitting) and ch. 12 (speed and size: turnover, costs as a share of Sharpe). Not in the Literature folder; cited from the reading list.
RiskMetricsJ.P. Morgan / Reuters, RiskMetrics Technical Document, 4th ed., 1996, ch. 5. The exponentially weighted volatility estimator behind realised_vol.
Bailey, Borwein, López de Prado & Zhu"Pseudo-Mathematics and Financial Charlatanism", Notices of the AMS (2014). What a backtest is, in-sample versus out-of-sample, and the five-years / 45-trials rule behind walk_forward.
Bailey & López de Prado"The Deflated Sharpe Ratio" (2014). Why the Sharpe ratio in stats must be read with the number of trials and the shape of the returns.
Harvey & Liu"Backtesting", Journal of Portfolio Management (2015). The haircut on reported Sharpe ratios; costs and trial counts.
López de Prado"The 10 Reasons Most Machine Learning Funds Fail" (2018). Look-ahead, and pitfall 9 on walk-forward testing a single path.
Hurst, Ooi & Pedersen"A Century of Evidence on Trend-Following Investing", Journal of Portfolio Management (2017). Judging a rule decade by decade, the habit yearly() applies at the scale of one model.
Code WalkthroughThe project's Code Walkthrough doc: the six-day worked example, the three study sessions and the seven questions in section 8.
backtest.pyxau-btc-models/src/backtest.py, 157 lines, as read on 30 October 2026. Line numbers on this page refer to that version.

All numbers on this page are computed from the six invented closes inside the page. Part of quant-notes. See also 01 · Time-series momentum, 02 · Volatility estimation by EWMA and 03 · Backtest errors and controls.