LoginEnter the platform free
DOMINA › Technical analysis › Risk management › Backtesting

Backtesting a trading strategy: what it is, how to do it and the mistakes that distort it

InteractiveExpose the rigged backtestA report states a rule and breaks it once: click the trade that buys before its signal.Try it →

What is backtesting? A rule tested on PepsiCo, 2016

Backtesting is testing a trading rule on past prices: you write the rule in full, apply it session by session as if the future were unknown, and record every trade it would have made, costs included. You read it as a log, not as a forecast: it tells you what the rule would have done on that data, over that period.

Risk management · testing a rule
Backtesting
PepsiCo: sessions from to · adjusted prices · averages on closes, orders at the next open
70.974.377.781.1average 20average 50Jan 4, 2016Apr 4, 2016Jul 1, 2016Sep 29, 2016Dec 28, 2016the account, from the starting capital$10,000$10,108
trades4sessions in a position131costs paid$83final account$10,108account max drawdown−7.8%

The same 4 trades, three costs. With no costs the account ends at $10,189, with 0.10% per side at $10,108, with 0.25% per side at $9,987. The trades do not change: only what you pay does.

InteractiveClick a session: the page shows where the averages were, whether the rule was in a position and what the account was worth. The buttons change the pair of averages and the cost per side.

How do you backtest a trading strategy?

the signal

1Write the rule in full

  • Entry, exit, how much capital, which stocks: all of it before looking at any result.
  • If a choice is left to judgment, the backtest tests today’s judgment, not the rule.
fixed period

2Choose the data and the period

  • Prices adjusted for dividends and corporate actions.
  • A fixed period, written down, and the list of stocks as it was back then.
todaynot yet

3Simulate session by session

  • Every decision uses only the data available up to that session.
  • The signal comes at the close, the order fills the next session.
grossnetcosts

4Take out costs and slippage

  • Commission, the bid-ask spread, a fill worse than the price you saw.
  • They are paid on the way in and on the way out, on every trade.

5Log every trade

  • Entry and exit date and price, gross and net result.
  • The log can be redone by hand: if it does not add up, the backtest has a bug.
in sampleout of sample

6Measure, then test out of sample

  • Number of trades, account drawdown, average result.
  • The real test is on data that played no part in choosing the rule.

Fig. 1 · Signal at the close, order at the next open

signalnot seen yetorder at the openfast averageslow average
  • The signal is only known once the session closes. The fast average crosses above the slow one with that day’s close.
  • The order goes to the next session. The backtest price is the next day’s open, not the close of the signal day.
  • What lies to the right does not exist yet. A backtest that uses it, even for a single session, is looking into the future.

Fig. 2 · In sample and out of sample

in sampleout of sampleyou search for rule and parametersyou test once
  • In sample you search. You try ideas and parameters, and pick one.
  • Out of sample you test once. If you go back and change the rule after looking, that stretch becomes in sample too.
  • The split is decided first. The dates are written down at the start, not after seeing the results.

The backtest trade log

PepsiCo, 20- and 50-session averages, 0.10% cost per side
PepsiCo: the trades of the backtest at the top, 20- and 50-session averages, 0.10% cost per side (adjusted prices)
No.SignalEntryExitSessionsGrossNet
1 · 73.23 · 76.5070+4.47%+4.26%
2 · 78.41 · 80.1454+2.21%+2.00%
3 · 81.22 · 80.224−1.23%−1.43%
4 · 80.47 · 77.753−3.38%−3.57%

How to read the first row: the averages cross at the close, ; the order fills at the next session’s open, , at 73.23. Net takes out the cost on the way in and on the way out. Compounded, the 4 trades make +1.89% gross and +1.08% net, and the account ends at $10,108. These are the numbers of this rule over this period: they say nothing about the period after.

Fig. 3 · PepsiCo: the same log with three cost levels

$10,000$10,500$11,0000% per side: $10,1890.10% per side: $10,1080.25% per side: $9,987Jan 4, 2016Jul 1, 2016Dec 28, 2016
  • The trades are the same. Only the cost of each fill changes: here there are 8, counting entries and exits.
  • The gap widens with every trade. Costs are always paid, whether the trade wins or loses.
  • The right cost is the real one. Your broker’s commission plus slippage: a backtest without costs describes an account that does not exist.

Interactive exerciseSpot the error in the rigged backtest

Apple, 2022: adjusted prices

This report states the same rule as the chart at the top: 20- and 50-session averages, entry at the open after the cross. Its 4 trades are marked on the chart. One of them breaks the rule: it buys at a price nobody could have known that day.

  1. Look at the two averages and the green triangles: each triangle is an entry in the report, the dash is the price paid.
  2. Click the entry the rule could not have made that day.
  3. The page takes the entry within 4 sessions of your click and checks two things: whether the signal was already there and whether the price was an open.
click an entry

Sessions from to . The green dash on each entry is the price the report claims.

What mistakes make a backtest misleading?

1Overfitting

  • You try many parameters and keep the best: the best on past data also contains luck.
  • The more combinations you try, the more first place can be chance.
today

2Survivorship bias

  • A backtest on today’s stocks forgets the ones that were delisted, went bust or were taken over.
  • The right list is the one of back then, session by session.
grossnet

3Costs and slippage

  • Without costs, a rule that buys and sells often looks better than it is.
  • Slippage is the gap between the price you saw and the price you got.
signal

4Look-ahead bias

  • Data used before it existed: a close, a low, an earnings report published later.
  • It is the mistake in the exercise above.
the sample

5Too small a sample

  • The chart at the top has 4 trades: read them as an example, not as evidence.
  • A single period shows a single kind of market.
all in sample

6No out-of-sample test

  • If all the data went into choosing the rule, none is left to test it.
  • Every tweak made after seeing the result uses up the out-of-sample data.

What is overfitting in backtesting?

Alphabet: thirty pairs of averages, two periods

The same rule as the chart at the top, with thirty pairs of averages: six fast and five slow. For each pair the backtest runs twice, in sample from to and out of sample from to , at 0.1% per side. The figure shows no returns: it shows the ranking, from first to thirtieth.

Fig. 4 · Alphabet: the ranking of the thirty pairs, in and out of sample

In sample, 2015-2018507510015020052827211720102314257915193241342011122221030118301654082629156Out of sample, 2019-2022507510015020052312319104718926152712241422202520151317302830166114021291085rows: fast average · columns: slow average · number: rank
  • The top pair in sample is 30 and 50. Out of sample it ranks 28th.
  • Out of sample the top pair is 5 and 75. In sample it ranked 27th.
  • The stock was chosen because the gap is easy to see. On other stocks the top pair in sample lands higher or lower: the in-sample ranking alone does not tell you where.

Fig. 5 · Walk-forward: the window that moves

in sample: you choosetest: you measure1234time
  • Choose on one stretch, test on the next. Then the window moves forward and you start again.
  • What counts is the sum of the tests. Put end to end, the test stretches make an out-of-sample record almost as long as the whole period.

How much do costs and slippage weigh on a backtest? Calculator

Commission per side
%
Slippage per side
%
Trades per year
Years

Arithmetic only: an account that neither gains nor loses anything before costs. Every trade pays twice, on the way in and on the way out.

trades50in total
taken by costs−13.9%of the capital
to break even+0.30%gross, per trade
left $8,606costs $1,394result before costs: zero
$10,000 × (1 − 0.0015)2×50 = $8,606 left: costs alone take 13.9% of the capital.

In the chart at the top the 8 fills, counting entries and exits, at 0.10% per side cost $83.

How do you read backtest results?

few

1The number of trades

  • With few trades the result hinges on one or two of them.
  • Before the result, look at how many trades make it up.

At the top: 4 trades.

drawdown

2The account’s maximum drawdown

  • The account’s worst fall from its high: it is the drawdown of the rule, not of the stock.
  • Read it with its dates: a different period gives a different number.

At the top: −7.8%.

1R

3The average result in R

  • Each trade divided by the risk taken, that is the distance between entry and stop loss.
  • This way trades of different size can be compared. The rule at the top has no stop: R cannot be computed for it.
in a position

4Time in the market

  • How many sessions the capital is exposed.
  • Out of the market the account neither rises nor falls: read a result together with the time it took.

At the top: 131 sessions out of 250, 52% of the period.

A backtest is the mirror image of a trading journal: the backtest lists the trades a rule would have made on past data, the journal lists the trades actually made, with their reasons and their mistakes. Side by side, they show how far real execution drifts from the written rule.

What a backtest does not tell you: how the rule will behave after the period tested. It describes the past of that rule on that data, with those costs. A take profit or a stop added after seeing the result is also a parameter chosen in sample.

Deeper dives: the trading journal · drawdown · the simple moving average · the stop loss · take profit · random walk and efficient markets · mean reversion.

Where to go from here

Risk management

The other lessons in the Β«Risk managementΒ» section

Stop loss

  • an order that closes the position at a level decided before entering
  • below the last swing low, a support level, a trendline, or two ATRs away
  • pick the entry day on a real chart and count the shares

Take profit

  • a limit order that closes at a gain, at a level decided before entering
  • at a multiple of the risk, below resistance, on a chart pattern or with the ATR
  • click the level on a real chart: at least twice the risk and below resistance

Trailing stop loss

  • a stop loss that rises with the price and never moves down
  • by percentage, by amount, by ATR multiples, under recent lows or on a moving average
  • pick the distance and find on a real chart where you would have exited
1:2

Risk reward ratio

  • the potential reward divided by the risk, both set before entering
  • it comes from the chart levels: the stop below support, the target below resistance
  • place the stop and the target on a real chart: the page grades them and works out the ratio

Frequently asked questions

What is backtesting?

It is testing a trading rule on past prices: you simulate every trade the rule would have made, session by session, with costs. The result describes that rule over that period, not what it will do next.

How do you backtest a trading strategy?

Write the rule in full, pick adjusted prices and a fixed period, simulate using only the data available at each session, take out costs and slippage, log every trade, then test the rule on a stretch that played no part in choosing it.

What is overfitting in backtesting?

It is fitting the rule to the past by trying many parameters and keeping the best. In the figure on this page, on Alphabet, the 30 and 50 pair of averages, first of thirty in sample, ranks 28th out of sample.

Does a positive backtest mean the strategy will work?

No. A backtest tells you what a rule would have done on past data, with the assumed costs. The market afterwards can be different, and a good result can come from luck or from a mistake such as overfitting or look-ahead bias.

Method and sources

The sources of this page: the books are cited, the text is ours
Source
John J. Murphy, Technical Analysis of the Financial Markets: chapter 9, moving averages (the crossover of two averages), and chapter 15, computers and trading systems.
Robert Pardo, The Evaluation and Optimization of Trading Strategies: walk-forward testing.
David Aronson, Evidence-Based Technical Analysis: the risk of mistaking the best of many attempts for a rule (data-mining bias).

The charts use the PepsiCo sessions (from to ), the Apple sessions (from to ) and the Alphabet sessions from our archive, adjusted for dividends and corporate actions and rounded as shown on the page. Each period is preceded by 60 sessions needed by the averages. The backtest is the one in the summary box: simple averages on closes, order at the next session’s open, long only, the whole account in every trade, a position still open closed at the last close of the period. The exercise report is rigged on purpose: one trade buys at the low of the 18 sessions up to its signal. The grid in figure 4 uses 0.1% per side and shows ranks, not returns. The examples are verified at every update. Figures 1, 2, 5 and the thumbnails are diagrams drawn to explain, not prices; the calculator is arithmetic. This guide explains how the tools work: it does not contain investment recommendations and promises no returns. Our method · license · report an error.

Cookie preferences