Quant notes · 03 · interactive
A backtest applies a trading rule to past prices using, on each day, only information available on that day, and deducts transaction costs. This page builds one on a six-day example, then presents four sources of error (look-ahead, omitted costs, selection among trials, aggregation over regimes), the controls for each, and their implementation in the project backtester. Labs use simulated series.
All series on this page are simulated so the "true" answer is known. Nothing here is market data or a performance claim.
Each column uses only the columns to its left, and each row is one day. Read left to right: price → return → signal → position → turnover → cost → gross → net → equity. Two columns carry all the honesty. Position is yesterday's signal, because you decide at the close and hold from the next day. Cost is charged every time the position changes.
The six prices and the signal are the ones in the project's Code Walkthrough. Change a price, click a signal to cycle it through +1 / −1 / 0, or change the cost, and watch every column to the right recompute. The highlighted column is the one-bar lag.
| Day | Price | Return | Signal | Position | Turnover | Cost | Gross | Net | Equity |
|---|
The one line that makes the backtest honest. The target computed from day t−1's close is the position held during day t. In pandas it is target.shift(1).
Today's profit is the position held times today's return, minus a cost on every change of position, minus a daily slice of the financing or funding for holding it. Equity is the running product of (1 + net).
Look-ahead bias is the most common and the most flattering error. Delete the lag and the position on day t is computed from day t's own close, so the rule is trading on a price it has not seen yet. The lab below runs the same rule twice on a market that has no trend at all, so an honest rule should make nothing.
position == signal.shift(1) on every run.Every change of position pays the spread and slippage, and holding a position overnight pays financing (a CFD on gold) or funding (a bitcoin perpetual). A rule that trades often can be profitable before costs and a steady loser after them. The project's starting assumptions are about 5 bps per trade on bitcoin spot and about 3 bps on gold, plus carry.
This one is subtler because nothing in the code is wrong. Test twenty variations of a rule on the same data and one of them will look good by luck. Report only that one and you have a backtest that is "worthless, regardless of how excellent the reported performance might be" (Bailey and López de Prado 2014). The question an honest report must answer is: how many things did you try?
Each trial is a strategy that flips a coin every day to decide long or short, on a market with no trend. Every one of them has a true Sharpe of zero. The chart shows the Sharpe ratio each trial happened to get over about two years; the orange bar is the best one, the one you would be tempted to report.
The expected best Sharpe among N skill-less trials (Bailey and López de Prado 2014, with γ ≈ 0.5772 the Euler–Mascheroni constant and Z−1 the inverse normal). It grows like √(2 ln N): slowly, but it never stops. σSR is how noisy one Sharpe estimate is on your sample length; over two years of daily data it is about 0.7, so the best of 20 coin tosses is expected to show a Sharpe near 1.3, and the best of 300 near 2.1. The Deflated Sharpe Ratio turns this around: given N, how likely is it that your observed Sharpe beats what luck alone would have produced?
A full-history Sharpe of 0.8 can hide a rule that made everything in 2020–21 and lost in every other year. The defences are cheap: the yearly table (each year's return and worst drawdown), and keeping a period of data the rule never saw while it was designed. The project's walk_forward does the second one mechanically. Click a stage.
The four above plus three that are specific to this project's data. Click each for the check that catches it.
pos = target.shift(1).fillna(0.0), applied once to the whole target, which already contains the signal and the volatility scaling. Costs: turnover = pos.diff().abs() and cost = turnover * cost_bps / 1e4, so a +1 to −1 flip is charged as 2. Carry: pos.abs() * carry_annual / bars_per_year, with 365 bars because the daily table has one row per calendar day. Closed days: pos.where(tradable).ffill() freezes gold's position over the weekend, the fix for the week-1 bug that had the model paying the spread twice a week. Sizing: vol_target / realised_vol, an EWMA with span 30, clipped at a leverage of 2. Multiple tries: walk_forward() picks parameters on a training window and keeps only the forward slice; notes/research_log.md keeps the count. Two of the twenty tests are the ones to remember: buy-and-hold with zero costs must reproduce the asset's return exactly, and the position column must equal the shifted signal on every day.# the whole backtester in nine lines (no vol sizing, no closed-day mask) ret = px.pct_change().fillna(0.0) sig = signal.reindex(px.index).fillna(0.0) # +1, -1, 0 or a fraction pos = sig.shift(1).fillna(0.0) # the lag: held during t = decided at t-1 turnover = pos.diff().abs().fillna(pos.abs()) cost = turnover * cost_bps / 1e4 carry = pos.abs() * carry_annual / 365 net = pos * ret - cost - carry equity = (1 + net).cumprod() sharpe = net.mean() * 365 / (net.std() * 365 ** 0.5) # the two sanity tests that catch most bugs assert (pos == sig.shift(1).fillna(0.0)).all() # no look-ahead # buy-and-hold with cost_bps=0, carry=0: equity.iloc[-1] == px.iloc[-1] / px.iloc[0]
Each entry: the technical definition first, then the same idea in everyday words in the orange strip.
notes/research_log.md in xau-btc-models.All charts on this page are generated from simulated series inside the page; no market data is used. Part of quant-notes. See also 01 · Time-series momentum (the rule being tested) and 02 · Volatility estimation by EWMA (the volatility that sizes it).