Quant notes · 04 · interactive
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.
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.
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.
ret, line 51.vol, line 55.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.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.walk_forward joined end to end. These are the periods that were not used to choose the parameters. Variable oos, line 155.log, lines 149–151.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.
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].
One formula per box, in the order the code computes them, each followed by its reading.
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.
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.
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).
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.
Line 68. The absolute change in position from one day to the next. A change from +1 to −1 is 2.
Line 69. Turnover times the charge per unit traded. 5 bps = 5 / 10,000 = 0.0005 of notional.
Line 70. The daily share of the annual holding cost, charged on the size of the position, long or short.
Line 72. Position held times the day's return: profit before costs.
Line 73. Profit after the trading cost and the holding cost.
Line 79. The running product of (1 + net): the value of $1 invested at the start.
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.
Line 95. The lowest value of the drawdown series: the largest fall from a peak to a subsequent trough.
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.
Line 89. The standard deviation of daily net returns, times √365 to quote it per year.
Line 94. The annualised mean of daily net returns divided by the annualised volatility: return per unit of risk. NaN when Vol is zero.
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.
| year | Return | MaxDD |
|---|
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.
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.
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).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.
Each entry: the technical definition first, then the same idea in everyday words in the orange strip.
xau-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.