How to Backtest a Trading Strategy

By

GTE Education

By

GTE Education

Published:

Published

Reading time:

~12 mintues

Reading time

~12 mintues

Key Takeaways

Backtesting a trading strategy takes seven steps: write the rules so they can be applied without judgment, choose the market and period, check the data, set realistic costs, run the test, read the results, and validate on a stretch of history the rules were never tuned on.

The number of trades a backtest produces matters more than the number of years it covers. A strategy that triggers twice a month needs several years of history before the results mean much, while an intraday strategy can reach the same number of trades in a few weeks.

Backtesting a trade idea or strategy only gives accurate results if it accounts for trading costs like platform fees and slippage. Leave them out and the backtest overstates the returns the idea would really have earned.

Backtesting a perpetual futures strategy carries a cost that equity and forex testing does not: a recurring funding payment between traders that has historically sat near a baseline of about 0.01% every eight hours even in quiet markets, which works out to roughly 11% a year on a position held throughout.

A backtest is better at ruling a strategy out than proving one works. A strategy that fails when tested against historical price action, or that turns unprofitable once costs are included, should be excluded or refined. Strategies that hold up are good candidates for a forward test on live prices.

How do you backtest a trading strategy?

Backtesting a trading strategy runs its rules through historical market data to measure how it would have performed. What a backtest is made of, how it helps a trader, and the pitfalls to avoid are all covered in what backtesting is.

Running a backtest is a seven-step procedure: define the idea as a set of testable rules, choose the market and period, check the data, set realistic costs, run the test, read the results, and validate them on history the rules never saw. Most of these can be done in any order, but the first and the last cannot. If you set the rules after seeing the results, or reuse the history you held back for the final check, the backtest loses its integrity, leaving the results skewed and unreliable.

Step 1: Define the strategy's rules so nothing is left to judgment

A strategy can only be tested if every decision inside it can be carried out the same way twice.

"Buy when the trend looks strong" is not testable, because two people reading it would trade differently. "Buy a stock when its 50-day average price crosses above its 200-day average, sell when it crosses back below, and risk no more than 1% of the account on each position" is testable, because it specifies what triggers an entry, what triggers an exit, and how much rides on each trade.

Writing this down first does more than make the simulation possible. It settles what you are testing in advance, so the results cannot tempt you into bending the rules to fit them. That same precision also makes a strategy automatable: a trading bot follows the logic it is handed and adds no judgment of its own.

Step 2: Choose the market, the history, and the period

Choosing what to test on comes down to three decisions: the market and venue, how much history to use, and which period that history should cover. Each one changes how much the result is worth.

When backtesting, it is important to test on the same instrument and venue you actually plan to trade, because a strategy can behave very differently on a different venue, depending on factors like fees, liquidity, and slippage. For example, a strategy that trades a small-cap token many times a day can turn a profit on a deep, low-fee venue and a loss on a thin, high-fee one, purely from the difference in costs.

In a backtest, history is the amount of past data the strategy runs over, whether that is one year or ten, and how much you need depends on how many versions of the idea you try before settling on one. A single idea, like buying when price breaks above its recent high, still has adjustable settings: how many days count as recent, how far past the high the entry sits, and where the stop goes. Testing a range of these and keeping the best is normal practice, but it carries a catch: try enough versions and one is bound to look strong on your slice of history by luck alone, just as flipping a coin enough times is bound to turn up ten heads in a row. The best-looking version is often just the luckiest.

In the Notices of the American Mathematical Society, Bailey, Borwein, López de Prado and Zhu measured how many versions it takes for luck to produce a false winner. With five years of daily data, trying more than about forty-five versions is, on average, enough to turn up one that looks like a clear winner in the test yet shows no real edge on price action from outside that data set. With only two years, it takes just seven, because a shorter history is easier to fit by luck. So the more versions you try, the more history you need before a winning result means anything, and a long history is no safeguard if you spent it testing version after version.

History is how much data you use; the period is which stretch of it you pick, and what the market was doing during that stretch. Its length matters less than two things: how many trades it produces, and how varied the conditions inside it are. A strategy that triggers twice a month generates around fifty trades in two years, a thin basis for any conclusion, while a strategy trading bitcoin on hourly bars can produce that many in a few weeks and still cover only one kind of market. A good test period puts the strategy through more than one set of conditions, such as a strong trend and a sharp selloff, so its results show how it handles each rather than how well a single stretch happened to suit it.

Step 3: Check the data before you trust it

Historical data is rarely as clean as it looks, and a backtest runs on whatever it is given without complaint, so bad data quietly becomes a result that looks trustworthy and is not. A few quick checks catch most of the trouble before the test relies on it.

Most price history comes as bars, one for each time period, each recording the open, high, low, and close. The errors worth checking for fall into a few kinds:

  • Corrupted bars: a bar whose high sits below its open or close, or whose low sits above them, describes a price that never traded, and the strategy will react to it anyway.

  • Duplicate timestamps: the same moment recorded twice inflates volume and every measure built on it.

  • Unexplained gaps: every missing stretch should have a reason, whether the asset had not launched yet, the venue was down, or nothing traded at all. A gap with no reason is the dangerous one, because missing data looks exactly like a calm market: a strategy that trades more when volatility falls will read a blackout as quiet and size up into it.

  • Unadjusted prices: in stocks, prices not adjusted for splits or dividends show sharp drops no holder actually felt, and a rule watching for sharp declines will trade every one.

Step 4: Charge every trade what it would really cost

A backtest that does not charge for trading overstates any strategy that trades often, and the more often it trades the wider the gap.

Four costs apply to most strategies: the fee to place the order, the worse price a real order gets both going in and coming out, the effect of your own order on the price when the market is thin, and, for a position held on borrowed money or in a perpetual contract, a recurring financing charge for as long as it stays open.

Then multiply by turnover. A cost of 0.2% to enter a position and exit it again is nearly irrelevant to a strategy that holds crude oil futures for three months and fatal to one that trades them daily, which is why two strategies reporting the same simulated return can differ completely once costs are applied. Underestimating costs is one of the classic ways a backtest misleads, and the error favours the strategy.

Step 5: Run the test in sequence

Running the test means walking the rules through the history one period at a time, acting only on the information available at each point and never on what came later.

How you do that can be as simple or as involved as the strategy calls for:

  • By hand: replaying the chart one bar at a time with later bars hidden suits a visual strategy, and it forces you to face every signal, including the ones you would have talked yourself out of.

  • In a spreadsheet: a trade log and its arithmetic handle a straightforward rule-based strategy.

  • With software: most rule-based strategies can be tested without writing any code, and coding your own becomes necessary only when the strategy or the volume of data outgrows the ready-made tools.

By hand is the slowest by far, which is why hand-tested strategies often stop at too few trades to prove much; software trades that away for speed, at the cost of needing every rule specified in advance. Whichever method you use, record every trade the rules produce, not just the ones that look representative.

Step 6: Read the results

The overall profit or loss a strategy shows is ultimately the number that matters most, but on its own it means little, because it says nothing about the risk taken to earn it or how much evidence stands behind it. Three other figures give it that context:

  • Maximum drawdown: the deepest fall from a previous high, and how long the strategy stayed underwater. A high return earned through a drop no trader could sit through is not one you could have kept.

  • Win/loss balance: whether the winners outweighed the losers by enough to matter. A strategy can win nine trades in ten and still lose money, if the tenth loss is bigger than the nine gains combined, so a high win rate alone tells you little.

  • Number of trades: the sample the whole result rests on. A strong return built on a dozen trades is barely evidence at all.

Even a clean set of figures can flatter a result. Sorting the trades by size shows how much of the return came from the largest few, and a strategy that leans on two or three exceptional trades falls apart whenever those are absent. Comparing the return with a plain buy-and-hold keeps it honest: a simulated 40% gain in a market that rose 150% over the same period left the trader worse off than doing nothing.

Step 7: Test on history the rules never saw, then decide

Everything up to this point was measured on the data the strategy was built from, so even a strong result could be a close fit to that history rather than a real edge. The last step is the one that catches it: a test on history the strategy was never shown.

The simplest version is to hold data back. Before any tuning, set aside a stretch of history and leave it untouched. Build and refine the strategy on everything else, then run it once against the stretch you reserved. If the strategy only fit the quirks of the data it was built on, it tends to fall apart on the reserved stretch; if it holds up, it has passed a test it could not have been tuned to beat.

A more thorough version repeats that test as it moves through the record, tuning the strategy on one window of history, testing it on the window just after, then shifting both forward and doing it again, so the strategy is only ever judged on data it had not seen when it was tuned.

A stretch of history can only be used to validate a strategy once. Once you see how the strategy did on it and then change anything, that stretch has joined the data the strategy was tuned on, and testing honestly again means using a fresh stretch it has never seen.

Any one of three failures ends the exercise: the results fall apart on the reserved stretch, the edge disappears once real costs are charged, or the sample is too small to tell skill from luck. A strategy that survives all three has earned a forward test on live prices, not real capital.

What changes when you backtest a crypto trading strategy?

Backtesting guidance is mostly written for markets that close at a fixed hour and publish one official closing price. Crypto has neither, and that changes several things about how a strategy is tested.

A daily candle is a convention, not an event. Nothing closes, so whoever built the dataset picked a boundary, and midnight UTC is a common choice rather than a market fact. Providers also differ on whether a bar is stamped with its start or its end. Alexander and Dakos documented in Quantitative Finance how a mismatch of exactly this kind put a widely used free data series out of step with the exchanges it was meant to describe, an error that propagated into a published crypto index and the research built on it. The practical consequence is that a rule keyed to a daily close behaves differently depending on who supplied the bars.

Because the boundary is arbitrary, it is worth testing: shift the day boundary by a few hours and run the strategy again. If the results move substantially, the strategy is fitted to an arbitrary cutoff rather than to anything the market does. It also means any rule borrowed from a market that closes, whether an opening-range breakout, a gap fill, or an end-of-day exit, is measuring an arbitrary hour once it is ported across.

Perpetual contracts charge rent. A perpetual futures position pays or receives a recurring funding payment for as long as it stays open, commonly every eight hours, though some venues settle hourly and some adjust the interval under stress. Research on bitcoin perpetuals by Christin, Routledge, Soska and Zetlin-Jones found the median funding rate sat at 0.01% per eight-hour period, about 11% a year, and that this is the rate venues apply when the contract is tracking spot normally. When the rate turns negative the position receives the payment instead, so the charge runs both ways, but it is charged on the position's full size rather than the money put up for it, which makes it heavier on a leveraged position than it first appears. A trend strategy holding winners for weeks pays it throughout.

Funding history is published separately from price history, so it has to be fetched deliberately rather than arriving with the prices. And if the results do not show a funding charge on every position held through a settlement, that cost is missing rather than zero.

There is no single official price. Every venue runs its own order book, and the odd prints on one are simply absent from another. On 21 October 2021 bitcoin printed $8,200 on Binance.US, a drop of roughly 87% that lasted under a minute and was later attributed to a bug in one client's trading software. The same minute on Bitstamp showed a fall of about 2.3%, and on Coinbase there was no crash at all. Test a strategy carrying a 10% trailing stop on the first of those histories and every position gets closed out in a panic that traders elsewhere never saw; test a strategy that buys sharp falls on it and the report shows a purchase at $8,200 that no real order could have filled at size. Test on data from the venue where the order would actually go, and check any dramatic result against a second venue before believing it.

A crypto asset list also turns over faster than an equity index. Tokens are delisted, migrate to new contracts, or stop trading entirely, and a universe assembled from what trades today has quietly dropped them.

Thin books can make the chart price a poor guide. A price is a record of a trade that already happened, usually a small one, and it says nothing about how much could have traded there. Behind it sits a queue of resting orders, and an order larger than the front of that queue finishes at a worse average price. For bitcoin on a deep venue in a calm hour the difference is a fraction of a percent. For a smaller token it can be several: one crypto-market data firm measured a $100,000 sale of one mid-sized token returning about $93,600. The queue is thinnest exactly when a strategy most wants to sell, so size orders against the depth actually available rather than against the closing price.

What a backtest cannot settle

A rigorous backtest is one of the best ways to put a trading idea to the test. But markets are unpredictable and always changing, so even a strategy that backtests well should be treated as unproven until it holds up in live markets.

A backtest informs the decision but never makes it. It can show that an idea has merit and what trading it would have demanded, but it cannot tell you whether that merit is worth real capital. That call, and the risk behind it, stays with the trader.

The stakes rise when the strategy is going to run without a person watching each trade. Agentic trading is a human-directed workflow in which an AI agent researches markets and places or stages trades within limits a trader sets, and an agent will follow a flawed rule as faithfully as a sound one. The procedure explained here separates a strategy that has genuinely been tested from one that merely looks tested. Find out which one you have before handing it to an agent.

Frequently Asked Questions

How much historical data do you need to backtest a trading strategy?

How much history a backtest needs depends on more than the number of years. The period has to produce enough trades to mean anything, which for a strategy that trades rarely can take years, and it should cover more than one kind of market condition, such as a rising trend and a sharp selloff, so it is not secretly just a bull-market strategy. It also has to be long enough for the number of variations tried: research published in the Notices of the American Mathematical Society found five years of daily data supports around forty-five genuinely different versions before the search reliably produces a strategy that looks strong in the test but has no edge afterwards.

How many trades does a backtest need before the results mean anything?

No minimum number of trades holds across strategies, and the round numbers in circulation are not backed by anything specific. What determines whether a sample is large enough is how consistent the strategy's results are and how large an edge it claims: a strategy with a small average gain per trade needs far more trades to distinguish that gain from chance than one with a large edge. A useful working test is whether removing the best few trades changes the conclusion.

How long does it take to backtest a trading strategy?

Backtesting time depends almost entirely on the method rather than the strategy. Software applies rules to years of history in seconds once the rules are written, so the work is in specifying and checking them. Replaying charts by hand runs at a few trades per minute at best, which puts a sample of several hundred trades into many hours of work, and that constraint is the usual reason hand-tested strategies stop at samples too small to support a conclusion.

What is walk-forward analysis, and how do you run one?

Walk-forward analysis is a way of validating a trading strategy that tests it repeatedly on history it has not seen, rather than testing it that way once. You tune the strategy on an early window of history, test it on the window immediately after, then slide both windows forward and repeat, collecting the results from every test window. Because the strategy is only ever graded on data it had not seen when it was tuned, the collected results are a harder and more realistic measure than a single test on one held-back period.

Should you backtest a trading strategy manually or with software?

Manual and automated testing answer different questions, so the choice follows the strategy. Replaying charts by hand suits a visual strategy, rehearses the actual decisions, and needs no tools beyond a chart, but it is slow enough that reaching a large sample is impractical. Software reaches large samples, tests many variations, and applies costs consistently, at the price of needing every rule specified in advance. Many traders use both, testing at scale with software and replaying a subset by hand.

How often should you re-test a trading strategy that is already running?

A live strategy is worth re-examining on a schedule and whenever specific things change: the market it trades behaves differently than in the tested period, its costs rise, or its live results fall outside what the backtest suggested was normal, particularly a decline deeper than the worst in the test. Re-testing too often carries its own hazard, since repeatedly adjusting a strategy against recent data is how a tested strategy turns into a tuned one.

Which metrics matter most when reading a backtest result?

The most useful reading order starts with survivability rather than return: the deepest decline from a previous high and how long the strategy spent recovering, because a strategy nobody could hold is untradable regardless of its total. After that comes the relationship between average wins and average losses, then the number of trades the result rests on. Win rate belongs near the bottom of the list, since a high one can coexist with losing money.

How do you backtest a crypto trading strategy?

Backtesting a crypto strategy follows the same procedure as any other market, with four additions. Because crypto never closes, where a trading day starts and ends is an arbitrary choice, so results should survive shifting that boundary by a few hours; funding costs on perpetual contracts have to be fetched and charged separately; price history should come from the venue where the orders will go, because unusual prints exist on some venues and not others; and the worse price a real order receives should be estimated against the orders actually resting in smaller tokens rather than against the price on the chart.

Do you need to include funding costs when backtesting perpetual futures?

Funding is not optional in a perpetual futures backtest, because it applies for as long as a position is open and is charged on the position's full size. Research on bitcoin perpetuals found the median rate sat at 0.01% per eight-hour period, roughly 11% a year, which is small on a trade held for hours and substantial on one held for weeks. Rates also turn negative, in which case the position receives the payment, so leaving funding out distorts the result in both directions rather than only one.

Disclaimer

Disclaimer

This article is for educational purposes only and does not constitute financial, investment, or trading advice. Trading involves significant risk, including the potential loss of capital, and automated or AI-driven tools do not reduce that risk. No technology can predict markets or guarantee returns. Readers should conduct their own research and consider consulting a licensed financial professional before making any trading decision.