Howwise RSS
Trading Software10 min read

Backtest vs Live Trading Results Difference: Debug Runbook

Short answer

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.

Key takeaways
  • 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.

ObservationLayerLikely causesNext step
Replay of recorded live data gives different signals than liveData or logicPartial bar used live, adjusted vs raw prices, timezone or label shift, state lost on restart, warm-upDiff the data snapshots, then the indicator values
Signals match, entry or exit prices differFillsSame-bar close fills, mid-price fills, touch-fills on limits, latency, stale quotesMeasure shortfall against decision price
Signals match, some orders never filledOrder lifecycleRejections, 429s, min lot, tick-size rounding, margin, unfilled limitsAudit order states and error logs
Everything matches but net PnL is lower by a steady amountCostsCommission tiers, spread, borrow or funding, market impactRebuild the cost model from fills
Everything matches within costs, results still differVariance or overfitShort live window, selection bias in backtestBootstrap 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.

  1. 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.
  2. Pin the code: log the git commit hash and config file hash at startup, and run the replay on that same commit.
  3. 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.
  4. Write signals (symbol, bar timestamp, target position, decision price) from both runs to the same schema.
  5. 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.
Tip: Log a hash of the exact bar window (for example the last N rows) used at each decision. When a signal differs, a hash mismatch says it is data, and a hash match says it is code or state.

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.

BucketHow it is computedExample gap
Signal differencesBacktest PnL of missing_in_live rows minus live PnL of extra_in_live rows1,150
Fill price / slippage(fill price - decision price) x signed qty on matched rows1,900
Fees and commissionsSum of fee column minus backtest fee assumption600
Missed or rejected ordersBacktest PnL of rows with status rejected, canceled or expired450
Partial fills(requested qty - filled qty) x backtest per-unit PnL250
Funding / borrowActual carry charges minus modelled carry300
Unexplained residualGap minus sum of buckets0
Tip: A residual larger than about 10 percent of the gap means the logs are missing something, usually a corporate action, a manual trade or a position that drifted. Find it before drawing conclusions from the other buckets.

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.

AreaBacktest assumptionLive realityFix
FillsFill at the signal bar close, or at midOrder is sent after the bar closes; you cross the spreadFill at next bar open; buy at ask, sell at bid
Limit ordersFilled when price touches the limitQueue position means a touch often does not fillRequire trade-through (price trades beyond the limit) or a fill probability below 100 percent
DataAdjusted prices, final bars, cleaned historyRaw prices, a partial live bar, bad ticks, single-venue feedRecord live data and backtest on it; use the same adjustment and consolidated or venue feed
TimeBar label equals bar close; one timezoneVendor labels bars by open; exchange-local vs UTC; DST shifts; clock driftConvert everything to UTC at ingestion; assert label convention; sync NTP and log skew
Order lifecycleInstant acceptance, any sizeRejections, partial fills, lot and tick rounding, margin limits, HTTP 429 dropsModel rounding and min lot; retry with backoff and a client order id so retries are idempotent
UniverseToday's constituentsDelisted names existed thenPoint-in-time universe including delisted symbols
StateContinuous run, full historyRestarts lose state; indicators re-warm on fewer barsPersist positions and indicator state, or warm up on the same lookback and compare to the backtest value
SizingEquity from the simulated accountLive equity, cash and margin differLog equity_at_decision and size from the live number in replay
Warning: Retry logic can double-send orders if the first request actually reached the broker. Always attach a client order id so a retry after a timeout or a 429 cannot create a second position.

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 variance
Warning: Sample size limits every conclusion. The standard error of an annualised Sharpe ratio is roughly sqrt((1 + 0.5 x SR^2) / years), so one year of data around SR 1 has an error of about 1.2, wide enough to hide a real gap. Under about 30 trades the bootstrap is nearly uninformative, and a few hundred trades or more is needed to detect modest degradation.

What 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.

  1. Same code path: confirm live and backtest import the same strategy module and commit hash, with identical config.
  2. Same data: replay recorded live data; compare bar hashes, adjustment mode, feed and missing bars.
  3. Same timestamps: assert UTC everywhere, bar label convention, completed bars only, and check DST days and clock skew.
  4. Same signals: run the matched / missing / extra diff and resolve every non-matched row.
  5. Same fills: compare fill prices to decision price, review order types, rejections, partial fills, rounding and rate-limit errors.
  6. Same costs: rebuild fees, spread, impact, borrow and funding from actual statements.
  7. Statistics: bootstrap the live window against cost-adjusted backtest returns and count trades before judging.
  8. 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.
Warning: Do not tune backtest parameters or fudge slippage until the curves match. That hides the cause and fits noise. Change the model only for a mechanism you measured in the live logs.

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.

Related topics:backtestinglive tradingreconciliationslippagepython