Backtest vs Live Trading Results Difference: Debug Runbook
The backtest vs live trading results difference comes from three places: different signals (a data or logic bug), different fills (execution, costs, latency), or plain variance. Replay live data through the backtester, diff signals first, then attribute PnL.
- Run the backtester on the data the live system actually recorded; if signals still differ it is a data or logic problem, if they match and PnL differs it is execution.
- Join backtest and live trades on strategy, symbol and bar timestamp, and label every row matched, missing in live, extra in live, or different price or size.
- Split the PnL gap into signals, slippage, fees, rejected orders, partial fills and carry costs, and the unexplained residual should be near zero.
- Bootstrap the backtest trade returns to build a distribution for a live window of the same length before calling a gap a bug.
- Never tune backtest parameters until they match live PnL; fix the specific mechanism you found instead.
Why does a backtest vs live trading results difference appear?
A backtest is a model of the market plus a model of your broker. Live trading replaces both models with the real thing, so any divergence has to come from one of three layers: the signals (inputs or logic changed), the fills (the execution model was too kind), or chance (the live sample is too short or the backtest was overfit).
The cheapest way to keep these layers apart is to test them in order. Signals can be compared exactly, so do that first. Fills and costs can be measured and attributed in money terms. Only after both are clean does a statistical argument make sense.
This is the decision tree the rest of the page follows.
| Observation | Layer | Likely causes | Next step |
|---|---|---|---|
| Replay of recorded live data gives different signals than live | Data or logic | Partial bar used live, adjusted vs raw prices, timezone or label shift, state lost on restart, warm-up | Diff the data snapshots, then the indicator values |
| Signals match, entry or exit prices differ | Fills | Same-bar close fills, mid-price fills, touch-fills on limits, latency, stale quotes | Measure shortfall against decision price |
| Signals match, some orders never filled | Order lifecycle | Rejections, 429s, min lot, tick-size rounding, margin, unfilled limits | Audit order states and error logs |
| Everything matches but net PnL is lower by a steady amount | Costs | Commission tiers, spread, borrow or funding, market impact | Rebuild the cost model from fills |
| Everything matches within costs, results still differ | Variance or overfit | Short live window, selection bias in backtest | Bootstrap test, then count trades |
How do I replay live data through the backtester?
Replay (feeding recorded live market data back through the backtest engine, offline, with no orders sent) removes the data and the market from the equation. You record exactly what the live process saw, feed those same bytes through the backtest engine, and compare the signals it produces to the signals live produced.
Do not confuse this with shadow mode, which runs the live system in parallel on live data without sending orders. Replay is offline and repeatable, so you can rerun it as often as you need.
Compare signals, not PnL. A signal is deterministic given the data and the code, so any difference is a defect you can localise, while PnL is polluted by fills.
- Persist every raw message the live process consumes (quotes, trades, bars as delivered, including partial bar updates) with an exchange timestamp and a local receive timestamp.
- Pin the code: log the git commit hash and config file hash at startup, and run the replay on that same commit.
- Feed the recorded stream through the same strategy class the live runner uses. A separate backtest implementation of the same idea is the single most common source of silent divergence.
- Write signals (symbol, bar timestamp, target position, decision price) from both runs to the same schema.
- Diff them. If they match, move to fills. If not, bisect: compare the input bars, then each indicator column, then the first bar where the signal flips.
What should I log, and how do I diff trades row by row?
Reconciliation is only possible if live logs the decision, not just the fill. Without the decision price and signal time you cannot separate slippage from latency from a changed signal.
Use one row per order event with these fields: strategy, symbol, signal_ts (bar timestamp in UTC), decision_price (the price the model assumed), order_id and client_order_id, order_type, side, requested_qty, limit_price, submit_ts, ack_ts, first_fill_ts, last_fill_ts, filled_qty, avg_fill_price, fee, fee_currency, status, reject_reason, position_before, equity_at_decision, data_hash and code_hash.
Then join the backtest and live tables and classify each row. Strategy, symbol and bar timestamp form the key, because order ids do not exist in the backtest.
import numpy as np, pandas as pd
key = ["strategy", "symbol", "signal_ts"]
bt = pd.read_parquet("bt_trades.parquet")
lv = pd.read_parquet("live_trades.parquet")
for d in (bt, lv):
d["signal_ts"] = pd.to_datetime(d["signal_ts"], utc=True)
m = bt.merge(lv, on=key, how="outer", suffixes=("_bt", "_lv"), indicator=True)
qty_diff = (m.qty_bt - m.filled_qty_lv).abs() > 1e-9
px_diff = (m.price_bt - m.avg_fill_price_lv).abs() / m.price_bt > 0.0005
m["class"] = np.select(
[m._merge == "left_only", m._merge == "right_only", qty_diff | px_diff],
["missing_in_live", "extra_in_live", "different_price_or_size"],
default="matched",
)
print(m["class"].value_counts())
# Measure latency and stale quotes: attach the last quote before each fill
fills = lv.sort_values("first_fill_ts")
quotes = pd.read_parquet("quotes.parquet").sort_values("quote_ts")
j = pd.merge_asof(fills, quotes, left_on="first_fill_ts", right_on="quote_ts",
by="symbol", direction="backward",
tolerance=pd.Timedelta("2s"))
j["ack_ms"] = (j.ack_ts - j.submit_ts).dt.total_seconds() * 1000 How do I attribute the PnL gap to specific causes?
Implementation shortfall splits the difference between paper PnL (decision prices, zero costs) and realised PnL into buckets. Compute each bucket from the joined table, in this order, so they do not double count: signal differences first, then price, then quantity, then costs.
Worked example for one month: backtest PnL 12,000, live PnL 7,350, gap 4,650.
| Bucket | How it is computed | Example gap |
|---|---|---|
| Signal differences | Backtest PnL of missing_in_live rows minus live PnL of extra_in_live rows | 1,150 |
| Fill price / slippage | (fill price - decision price) x signed qty on matched rows | 1,900 |
| Fees and commissions | Sum of fee column minus backtest fee assumption | 600 |
| Missed or rejected orders | Backtest PnL of rows with status rejected, canceled or expired | 450 |
| Partial fills | (requested qty - filled qty) x backtest per-unit PnL | 250 |
| Funding / borrow | Actual carry charges minus modelled carry | 300 |
| Unexplained residual | Gap minus sum of buckets | 0 |
Which backtest assumptions most often cause the gap?
Once signals match, the remaining differences nearly always trace to an optimistic execution or data assumption. The table lists the usual ones with the fix.
The look-ahead bias, next-bar-open fill, survivorship bias and resampling articles on this site cover the deep mechanics; here the point is how each one shows up in a live diff.
| Area | Backtest assumption | Live reality | Fix |
|---|---|---|---|
| Fills | Fill at the signal bar close, or at mid | Order is sent after the bar closes; you cross the spread | Fill at next bar open; buy at ask, sell at bid |
| Limit orders | Filled when price touches the limit | Queue position means a touch often does not fill | Require trade-through (price trades beyond the limit) or a fill probability below 100 percent |
| Data | Adjusted prices, final bars, cleaned history | Raw prices, a partial live bar, bad ticks, single-venue feed | Record live data and backtest on it; use the same adjustment and consolidated or venue feed |
| Time | Bar label equals bar close; one timezone | Vendor labels bars by open; exchange-local vs UTC; DST shifts; clock drift | Convert everything to UTC at ingestion; assert label convention; sync NTP and log skew |
| Order lifecycle | Instant acceptance, any size | Rejections, partial fills, lot and tick rounding, margin limits, HTTP 429 drops | Model rounding and min lot; retry with backoff and a client order id so retries are idempotent |
| Universe | Today's constituents | Delisted names existed then | Point-in-time universe including delisted symbols |
| State | Continuous run, full history | Restarts lose state; indicators re-warm on fewer bars | Persist positions and indicator state, or warm up on the same lookback and compare to the backtest value |
| Sizing | Equity from the simulated account | Live equity, cash and margin differ | Log equity_at_decision and size from the live number in replay |
How do I model slippage and costs realistically?
Measure live slippage as signed shortfall in basis points against the decision price, then fit a model to it. Signed means positive is always a cost: for a buy, (fill - decision) / decision, and for a sell the opposite.
A useful starting model has a spread term and a volume-participation term. Half the spread is paid on every marketable order, and impact grows roughly with the square root of your size relative to volume. The coefficient is not universal, so fit it to your own fills by regression instead of trusting a default.
Also model fee tiers (volume-based commission changes mid-month), exchange and regulatory fees, borrow rates for shorts, and perpetual futures funding, which is charged on a schedule such as every 8 hours on many venues.
def slippage_bps(spread_bps, qty, adv, daily_vol_bps, k_spread=0.5, y=0.7):
"""Expected cost in bps: half-spread plus square-root impact.
y is fitted by regressing realised shortfall on sqrt(qty/adv)."""
participation = qty / adv
return k_spread * spread_bps + y * daily_vol_bps * participation ** 0.5
# Example: 4 bps spread, 0.5% of ADV, 150 bps daily vol
# 0.5*4 + 0.7*150*sqrt(0.005) = 2 + 7.4 = 9.4 bps per side Is the gap a bug or just variance?
If signals match, costs are modelled and the live result is still lower, ask whether the live window is plausibly a draw from the backtest distribution. Resample the backtest trades into windows with the same number of trades as the live sample and see where the live result lands.
Use a block bootstrap if trade returns are autocorrelated, otherwise you understate the spread of outcomes. Use the cost-adjusted backtest returns, not the raw ones, so you are not comparing a net result to a gross one.
import numpy as np
def live_percentile(bt_returns, live_returns, block=5, n=10000, seed=0):
rng = np.random.default_rng(seed)
r = np.asarray(bt_returns); L = len(live_returns)
starts = rng.integers(0, len(r) - block, size=(n, -(-L // block)))
sims = np.stack([np.concatenate([r[s:s+block] for s in row])[:L].sum()
for row in starts])
live = np.sum(live_returns)
return (sims < live).mean(), np.percentile(sims, [2.5, 50, 97.5])
# pct < 0.025 -> live is unusually bad: look for a bug or overfit
# pct around 0.2 -> ordinary varianceWhat is the ordered checklist, cheapest checks first?
Work down this list and stop at the first layer that explains the gap. Each step is cheaper and more decisive than the one after it.
- Same code path: confirm live and backtest import the same strategy module and commit hash, with identical config.
- Same data: replay recorded live data; compare bar hashes, adjustment mode, feed and missing bars.
- Same timestamps: assert UTC everywhere, bar label convention, completed bars only, and check DST days and clock skew.
- Same signals: run the matched / missing / extra diff and resolve every non-matched row.
- Same fills: compare fill prices to decision price, review order types, rejections, partial fills, rounding and rate-limit errors.
- Same costs: rebuild fees, spread, impact, borrow and funding from actual statements.
- Statistics: bootstrap the live window against cost-adjusted backtest returns and count trades before judging.
- Then ask whether the backtest itself was overfit: many parameter trials and picking the best one inflates backtest performance, so deflate it for the number of variants tested.
Common questions
Why do paper trading and backtest results differ?
Paper trading usually runs on live data but fills from a simulator that may use last price or mid, ignores queue position and has no real rejections. The backtest also differs in data (final vs partial bars) and timing. Compare paper to a replay of its own recorded data first to separate the two.
How many live trades do I need before judging the strategy?
Treat fewer than about 30 trades as uninformative, and expect to need hundreds to detect moderate degradation in per-trade expectancy. The right number depends on return variance, so bootstrap the backtest to see how wide the outcomes for your trade count really are.
How do I measure live slippage against backtest slippage?
Record the decision price at signal time and compute signed shortfall in bps for each fill, then group by symbol, order type, size bucket and time of day. Compare that distribution to the assumption in the backtest, and split the gap into delay (arrival price versus decision) and execution (fill versus arrival).
Can a restart change live results?
Yes. If positions, open orders or indicator state are not persisted, the strategy can re-enter, duplicate orders, compute indicators on a shorter warm-up or miss exits. Persist four things: open positions, open orders, indicator state, and the last processed bar timestamp so no bar is skipped or processed twice. To check a restart reproduces the backtest signals, restart the process mid-session, replay the same recorded data through the backtester, and diff the signals for the bars after the restart; indicator values and target positions should match the backtest for the same bars.
Is it a bug if live is better than the backtest?
It deserves the same investigation. Better-than-expected live results can come from extra trades, a cost model that was too harsh, or a sizing difference, and they usually reveal a signal mismatch too. Run the same diff and attribution.