Backtesting is the process of applying a set of trading rules to historical data to estimate how the strategy would have performed. It is the main research tool of algorithmic trading, and it is also the easiest place to fool yourself. A careful backtest models data, costs and timing realistically; a careless one produces impressive numbers that disappear the moment real money is involved.
Key takeaways
- A backtest is only as good as its data; survivorship bias and look-ahead bias are the two most damaging errors.
- Model fees, spreads and slippage conservatively, because costs often decide whether a strategy is profitable at all.
- Keep data the strategy has never seen for out-of-sample testing, and use walk-forward analysis for strategies that need periodic re-tuning.
- Judge a strategy by several metrics together: Sharpe, Sortino, maximum drawdown, profit factor and number of trades.
- A good backtest raises confidence; it never guarantees future results.
On this page
How a backtest works
At its simplest, a backtest steps through history bar by bar. At each step it asks what the rules would have done using only the information available at that moment, records simulated orders and fills, and tracks the account's equity.
There are two common designs:
| Design | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Vectorized | Computes signals and returns for the whole series at once with array operations | Very fast, good for early research | Easy to introduce look-ahead bias; hard to model order fills, stops and position limits |
| Event-driven | Processes each bar or tick as an event, as a live system would | Realistic order handling; code can often be reused for live trading | Slower and more work to build |
Many researchers screen ideas with vectorized tests and confirm promising ones in an event-driven simulator.
Data quality
Bad data produces confident but meaningless results. Check at least the following, and see the market data article for more:
- Corporate actions. Stock prices must be adjusted for splits and dividends, or the backtest will see false crashes and miss dividend income.
- Futures rolls. Continuous futures series must be stitched across contract expiries in a consistent way.
- Bad ticks and gaps. Erroneous prints, missing bars and duplicated records create fake signals.
- Time zones and timestamps. Mixing exchange time, local time and UTC can shift signals by hours.
- Bar construction. Daily bars from different vendors may close at different times, especially in forex and crypto, which trade around the clock.
The biases that ruin backtests
Survivorship bias
Survivorship bias happens when the test universe includes only assets that still exist today. Companies that went bankrupt, were delisted or were acquired disappear from many free datasets. A strategy tested only on today's index members is tested on the winners, which inflates returns, especially for strategies that buy beaten-down stocks. The same problem affects crypto: thousands of tokens that collapsed are missing from lists of current coins. The fix is a survivorship-free dataset that includes dead instruments with point-in-time index membership.
Look-ahead bias
Look-ahead bias means using information that would not have been available at the time of the trade. Common examples:
- Using a day's closing price to generate a signal and also assuming you bought at that same close.
- Using financial statement data on the period-end date instead of the date it was actually published.
- Normalizing data with statistics (mean, maximum) computed over the whole sample, including the future.
- Using revised economic data instead of the first-release figures traders actually saw.
A useful habit is to shift every signal forward by one bar so that a signal computed at bar t is traded no earlier than bar t+1.
Other biases
- Selection bias: testing only on markets you already know went up.
- Data snooping: testing many variations and reporting the best one. This is covered in overfitting and data snooping.
- Liquidity bias: assuming you could trade size in thin markets at the quoted price.
Modelling costs and slippage
Every simulated trade should pay realistic costs:
- Commissions and exchange fees, including maker/taker fees on crypto venues.
- The spread. Buying at the ask and selling at the bid costs the full bid-ask spread on each round trip.
- Slippage and market impact. Market orders and stops often fill worse than the last price, especially in fast markets and for larger sizes.
- Financing. Overnight swaps, perpetual funding payments and stock borrow fees for shorts.
A sensible approach is to estimate costs from real fills when possible, then run the backtest again at double those costs. If the strategy only works at optimistic cost levels, it probably does not work.
In-sample, out-of-sample and walk-forward
Split your history before you start. Build and tune the strategy on the in-sample portion, then test it once on the out-of-sample portion. If you keep returning to the out-of-sample data to tweak the rules, it stops being out-of-sample.
Walk-forward analysis repeats this process through time. For example: optimize parameters on 2015 to 2018, test on 2019; optimize on 2016 to 2019, test on 2020; and so on. Joining the test periods gives an out-of-sample equity curve that reflects how the strategy would have been re-tuned in real time. Large differences between in-sample and walk-forward results suggest overfitting.
Performance metrics
No single number captures a strategy. Use several together.
| Metric | Formula | What it tells you |
|---|---|---|
| CAGR | (Ending equity / Starting equity)^(1 / years) − 1 | Compound annual growth rate |
| Sharpe ratio | Mean(R − Rf) / StdDev(R − Rf), annualized by multiplying by √(periods per year) | Return per unit of total volatility |
| Sortino ratio | (Mean(R) − T) / Downside deviation, annualized the same way | Return per unit of downside volatility only |
| Maximum drawdown | Largest peak-to-trough fall in equity, as a percentage of the peak | Worst historical pain |
| Profit factor | Gross profit / Gross loss (absolute value) | Dollars won per dollar lost |
| Win rate and expectancy | Share of winning trades; average profit per trade | How returns are distributed |
Here R is the strategy return per period, Rf the risk-free rate per period, and T a target return (often zero). Downside deviation is the square root of the average of min(0, R − T)² taken over all periods, so periods above the target count as zero. For daily data, multiply the daily ratio by √252, about 15.87. Drawdowns and recovery math are covered in drawdown and risk of ruin, and expectancy in risk/reward and expectancy.
The functions below compute these metrics from a series of returns, an equity curve and a list of trade results.
import numpy as np
def sharpe(returns, rf_per_period=0.0, periods_per_year=252):
excess = np.asarray(returns) - rf_per_period
return np.sqrt(periods_per_year) * excess.mean() / excess.std(ddof=1)
def sortino(returns, target=0.0, periods_per_year=252):
r = np.asarray(returns)
downside = np.minimum(r - target, 0.0)
downside_dev = np.sqrt(np.mean(downside ** 2))
return np.sqrt(periods_per_year) * (r.mean() - target) / downside_dev
def max_drawdown(equity):
equity = np.asarray(equity, dtype=float)
peaks = np.maximum.accumulate(equity)
return ((peaks - equity) / peaks).max()
def profit_factor(trade_pnls):
pnl = np.asarray(trade_pnls, dtype=float)
gross_loss = -pnl[pnl < 0].sum()
return pnl[pnl > 0].sum() / gross_loss if gross_loss > 0 else np.inf
Worked example
A strategy starts with 10,000 dollars and makes ten trades with these results, in dollars: +300, −200, +150, −100, −250, +400, −150, +200, −300, +250.
- Gross profit: 300 + 150 + 400 + 200 + 250 = 1,300.
- Gross loss: 200 + 100 + 250 + 150 + 300 = 1,000.
- Profit factor: 1,300 / 1,000 = 1.30.
- Net profit: 300 dollars, so expectancy is 30 dollars per trade, with a 50% win rate.
- Equity path: 10,300; 10,100; 10,250; 10,150; 9,900; 10,300; 10,150; 10,350; 10,050; 10,300.
- Maximum drawdown: from the 10,300 peak to the 9,900 trough, a fall of 400 / 10,300 ≈ 3.9%.
For the risk-adjusted ratios, suppose a longer test produced a mean daily return of 0.05%, a daily standard deviation of 1.0% and a downside deviation of 0.7%, with a risk-free rate of zero. The annualized Sharpe ratio is 0.05 / 1.0 × 15.87 ≈ 0.79, and the Sortino ratio is 0.05 / 0.7 × 15.87 ≈ 1.13.
Ten trades are far too few to trust any of these numbers. As a rough guide, many researchers want at least a few hundred trades, spread across different market conditions, before treating the statistics as meaningful.
Common mistakes
- Trading on the bar that generated the signal. Signals computed from a closing price cannot also be filled at that closing price.
- Using today's index members. This builds survivorship bias into every result.
- Zero or tiny cost assumptions. High-turnover strategies are especially sensitive.
- Reusing the out-of-sample data. Each peek turns it into in-sample data.
- Too few trades. A handful of large winners can produce a spectacular but meaningless backtest.
- Ignoring capacity. A strategy may work with 1,000 dollars and fail at 100,000 because its orders move the price.
FAQ
What is a good Sharpe ratio in a backtest?
Many practitioners treat an annualized Sharpe above 1 as promising for a single strategy. Very high backtested values, such as above 3 for a daily strategy, more often indicate errors, look-ahead bias or overfitting than a real edge.
How much historical data do I need to backtest?
Enough to include different market regimes, such as rising, falling and sideways markets and at least one period of stress. For daily strategies that often means ten years or more; for intraday strategies, fewer years can be enough if they contain many trades.
What is the difference between backtesting and paper trading?
A backtest replays historical data, while paper trading runs the strategy on live prices without real money. Paper trading catches execution and software problems that a backtest cannot.
Why do live results differ from backtest results?
The usual causes are underestimated costs and slippage, overfitting to historical noise, biases in the data and changes in market behavior. Some gap is normal; a large gap means the backtest was flawed.