Backtesting a trading strategy: what it is, how to do it and the mistakes that distort 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.
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?
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.
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.
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.
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.
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
- 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 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| No. | Signal | Entry | Exit | Sessions | Gross | Net |
|---|---|---|---|---|---|---|
| 1 | · 73.23 | · 76.50 | 70 | +4.47% | +4.26% | |
| 2 | · 78.41 | · 80.14 | 54 | +2.21% | +2.00% | |
| 3 | · 81.22 | · 80.22 | 4 | −1.23% | −1.43% | |
| 4 | · 80.47 | · 77.75 | 3 | −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
- 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 pricesThis 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.
- Look at the two averages and the green triangles: each triangle is an entry in the report, the dash is the price paid.
- Click the entry the rule could not have made that day.
- 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.
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.
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.
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.
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.
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.
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 periodsThe 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
- 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
- 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
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.
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?
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.
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%.
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.
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 managementThe 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
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
| 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.
DOMINA’s stock pages, indices and commodities are rebuilt every night. Leave your email: we write to you when the picture changes.
No third-party advertising. Unsubscribe with one click. Go to the platform →With your consent we use Google Analytics cookies to count visits. If you decline, the page works the same and no measurement cookie is set. Cookie policy