VALYNOX
VALYNOXSTRATEGY RESEARCH TECHNOLOGY
VALYNOXMultiAlphasMultiAlphas
ACADEMY / Backtesting and validation

What is backtesting in trading? Rules replayed on old prices, costs in

Backtesting is replaying fixed trading rules on historical prices, bar by bar, with costs included, and recording every trade the rules would have made. A result is only worth reading when costs and trade count are in it: commission alone turned one ES rule from a profit into a loss, and a profit factor near 5 on gold came from 15 trades.

By · Published · updated · Editorial policy

Contents
  1. What is backtesting in trading?
  2. What does backtesting mean?
  3. How do you backtest a trading strategy?
  4. What is lookahead bias?
  5. How many trades does a backtest need?
  6. Which numbers in a backtest report matter most?
  7. Why do backtests fail in live trading?
  8. Can you backtest for free?
  9. What should you check after a backtest looks good?
  10. Frequently asked questions
  11. References

What is backtesting in trading?

Backtesting is replaying a fixed set of trading rules on historical prices, bar by bar, with costs included. Read the cost line and the trade count before any other number, because they decide whether the rest means anything: commission alone turned an ES 60-minute RSI rule from $32,475 to −$3,705, and a profit factor of 4.839 on gold came from 15 trades.

Both numbers come from runs of this site's hosted backtest on 2026-10-31, shown in full further down. The ES rule (ES is the E-mini S&P 500 future) took 540 trades on 60-minute bars from September 2018 to October 2026 and paid $36,180 in commission at $67 a round trip. The gold rule (GC is the COMEX gold future) took 15 trades on daily bars over the same years, during a long rise in gold. Neither run forecasts anything. The ES rule earns less per trade than a trade costs, so it fails on the cost line. The gold rule's summary number rests on a trade list too short to tell the rule from the market, so it fails on the trade count. A report that fails either check goes back to the workbench, whatever the rest of it says.

What does backtesting mean?

A backtest is a simulation that applies a complete set of trading rules to past prices, one bar at a time, and records every trade the rules would have made. A bar is one row of price data for a fixed time span, with its open, high, low and close. The simulation reads one bar, asks whether any rule fires, places the order, moves to the next bar, and repeats until the data ends.

Three things go in and three things come out.

PartInput (what you supply)Output (what you get)
1Historical bar data: for futures, a continuous series that joins one contract month to the nextA trade list: entry time and price, exit time and price, result of each trade after costs
2Complete rules: entry, exit, stop and position size, each written so a computer can follow itAn equity curve: the account value after every closed trade, plotted over time
3Cost and fill assumptions: commission, fees, slippage and when an order is filledSummary numbers: trades, net profit, average trade, maximum drawdown, profit factor, win rate
A backtest takes three inputs (bar data, complete rules, cost and fill assumptions), replays them bar by bar, and produces three outputs (trade list, equity curve, summary numbers) Inputs decide the output Three in, one replay, three out Bar data Rules Costs & fills Replay bar by bar Trade list Equity curve Summary Leave costs out: unreadable report. So: fill every input before you run.
A backtest is a machine with defined inputs and outputs. What goes in decides what comes out; a weak input such as missing costs produces a report that cannot be read.

Two of the summary numbers appear often in this article, so here is what they are. The profit factor is the sum of all winning trades divided by the sum of all losing trades; a value of 1.0 means the wins exactly paid for the losses. The win rate is the share of trades that closed with a gain. Neither number says anything on its own about how many trades produced it, which is why the trade count is always read next to them.

How do you backtest a trading strategy?

A futures backtest is only as realistic as five settings fixed before the first run: the data, the rules, the costs, the session and the execution timing. Fix them in this order, because each one depends on the one before it.

  1. Prepare clean continuous data. A futures contract expires, so a test over several years needs a continuous series, which is one price history built by joining one contract month to the next. The join is called a roll. Check how the rolls were handled (a price jump at each roll will show up as a fake trade result), whether the timestamps use the exchange's time zone, and whether there are gaps or bad ticks. Choose a bar size that fits the rule: if a stop and a target can both be hit inside one long bar, that bar cannot tell you which came first. The guide to backtest data quality lists the checks for gaps, bad ticks, time zones and rolls.
  2. Write the rules completely. Every entry, exit, stop and position size must be a rule a computer can follow with no judgment. "Buy when the trend looks strong" is not a rule. "Buy when the close is above the 50-bar moving average" is. If a rule needs you to look at the chart, the backtest cannot run it, and neither can you at three in the morning.
  3. Add round-trip costs. Include commission, exchange fees, tax where it applies, and slippage. Slippage is the difference between the price the backtest assumed and the price you would really get. Model costs per round trip (entry plus exit) in the same units as the result. The guide to trading costs in backtests: commission, slippage and the average trade shows how to estimate each part.
  4. Set the trading session. Decide which hours the strategy trades and which bars it may use. Day-only bars and full-session bars give different indicator values and different results on the same contract.
  5. Use next-bar execution. Next-bar execution means the backtest acts on a signal at the following bar, not at the close of the bar that produced the signal.
Five settings of a futures backtest (data, rules, costs, session and next-bar fill) all feed into one backtest report, so each one changes the result Five inputs shape the report Every arrow feeds one result 1 Data 2 Rules 3 Costs 4 Session 5 Next-bar fill Report Each setting changes the report. So: set all five before you run.
The five settings of a futures backtest, in order. Each one changes the report, so all five are fixed before the first run.

Sessions matter more in futures than many traders expect. On TAIEX futures (台指期, code TX), the regular session runs from 08:45 to 13:45 Taiwan time, and the after-hours session runs from 15:00 to 05:00 the next day. A 60-minute rule tested on regular-session bars only sees five bars a day; the same rule on full-session bars sees nearly four times as many and trades a very different market at night. Exchanges can change session hours, contract values and fees, so confirm them on the exchange's contract page before you test. The free futures market hours tool shows trading hours by exchange and session in your own time zone.

Once the five settings are fixed, run the rules once and read the trade list before the summary numbers. Open ten trades at random and check that each entry and exit happened where the rule says it should, at a price that existed on the next bar. A longer walkthrough with free tools and the usual mistakes is in the guide on how to backtest a trading strategy. Keep the five settings identical across every variant you test, or the comparison between variants means nothing. MultiAlphas (Valynox) takes fees, slippage, the trading session and next-bar execution as backtesting settings and evaluates many strategies with the same ones.

What is lookahead bias?

Lookahead bias is any rule that uses information not yet available at the moment of the decision. The most common case is a fill at the same bar close that produced the signal: the rule computes an indicator from the close, decides to buy, and the backtest buys at that very close. In real trading the close is only known when the bar is over, and the next tradeable price is on the following bar. Next-bar execution removes this case by design.

The same four price bars twice: with lookahead the signal and the fill both sit on the close of bar 2, which is wrong; with next-bar execution the signal is on the close of bar 2 and the fill on the open of bar 3, which is right Fill on the next bar Arrow = signal, dot = fill Lookahead Next bar No Yes The signal close can't be traded. So: always fill on the next bar.
A signal computed on a bar's close cannot be filled at that same close. The honest fill is the next bar.

Same-bar fills are not the only leak. Each of the common ones leaves a sign in the report and has a plain fix.

LeakHow it gets inFix
Same-bar fillSignal and fill on the same closeFill at the next bar's open or later
Today's high or low in an intraday ruleA rule on 15-minute bars reads the daily high before the day has endedUse only the high or low of bars already closed
Whole-history scalingAn indicator normalized by the maximum or minimum of the entire data setScale with a rolling window that ends at the current bar
Stop and target in one barThe backtest assumes the target was hit firstAssume the stop was hit first, or test on smaller bars
Revised dataA continuous series rebuilt later with roll rules that were not known at the timeRecord the roll rule with the data and keep it fixed

The one-bar shift check catches most of these in a minute. Delay every signal by one extra bar and rerun. A real edge weakens a little, because fills come later. A result that collapses was leaning on information it would not have had. The guide to look-ahead bias walks through the check and the leaks it exposes in more detail.

How many trades does a backtest need?

A few hundred, spread across rising, falling and flat years; with far fewer you cannot tell what the rule did from what the market did. The measured gold run below shows how good that can look anyway.

Source: MultiAlphas hosted backtest (ap_backtest connector), run 2026-10-31

Measure (GC daily, 2018-09 to 2026-10)Result
Closed trades15
Net profit$225,618
Profit factor4.839
Win rate40%

A profit factor near 5 on 15 trades, during a long rise in gold. Too few trades to tell the rule from the market.

The rule is as plain as they come: buy one contract when the 20-day exponential moving average crosses above the 50-day, sell when it crosses back below, long only (see the moving averages page for how the EMA is built). A win rate of 40% next to a profit factor near 5 means the few winners were far larger than the losers, which is what a trend-following rule does when the market it follows keeps rising. What the run cannot show is whether the rule had anything to do with it. Gold rose for most of these years; a rule that is long during the rising stretches collects that rise whatever its logic. Fifteen trades cannot separate the two explanations, so the number to read in this report is 15, not $225,618.

Illustration over the same years 2018 to 2026: on the left, 15 trades with profit factor 4.839 sit on a steadily rising gold price, so rule and market cannot be told apart; on the right, hundreds of trades spread across rising, falling and flat stretches test the rule itself 15 trades: rule or market? Illustration, same years 2018–2026 15 trades PF 4.839 Hundreds Up, down, flat 15 trades can't split rule from market. So: aim for hundreds across years.
A result from 15 trades can be the market or luck; a result from hundreds of trades across up, down and flat years is evidence about the rule.

No single count fits every rule. These guides set it:

  • A few dozen trades is a weak sample; a few hundred says much more. With 15 trades, moving one trade from the loss column to the win column changes the win rate by several points and the expectancy with it. Put the win rate, average win and average loss from your own report into the free expectancy calculator and change one trade's result; if the expectancy swings widely, the sample is still too small to read.
  • Trades must be spread across years and conditions. Three hundred trades packed into one rising year test the rule in one weather pattern only. The yearly results table in the report shows whether the trades cover rising, falling and flat periods.
  • More parameters need more trades. A rule with six tunable settings has far more ways to fit noise than a rule with one. Bailey, Borwein, López de Prado and Zhu (2014) show that the more configurations a researcher tries, the longer the backtest must be before the best result among them means anything.
  • Long histories are the classical answer. Brock, Lakonishok and LeBaron (1992) tested simple moving-average and trading-range breakout rules on about ninety years of Dow Jones index prices and compared the results with simulated price series. The length of the record, covering many decades of different market conditions, is what made their findings worth discussing, and the authors themselves pointed out that trading costs would have to be considered before anyone traded the rules.

Which numbers in a backtest report matter most?

Costs and trade count first, then average trade, maximum drawdown and yearly spread; net profit on its own tells you the least. The measured ES run shows why costs go first.

Source: MultiAlphas hosted backtest (ap_backtest connector), run 2026-10-31

Measure (ES 60-min, 2018-09 to 2026-10)Result
Closed trades540
Net profit after costs−$3,705
Commission alone, $67 a round trip$36,180
Net profit with commission added back$32,475
Profit factor0.993
The same ES 60-min rule before and after commission. One contract.
The same ES 60-min rule before and after commission. One contract. ES · 60-minute · 2018-09-02 to 2026-10-14 · MultiAlphas backtest

The rule buys one contract when the 14-period RSI crosses up through 30, sells when it crosses up through 60, and uses a 30-point stop, long only, on 60-minute bars. Over eight years it closed 540 trades. With commission added back the result is $32,475. The commission on 540 round trips at $67 each is $36,180, more than the whole result, so the net profit after costs is −$3,705 and the profit factor is 0.993: the wins did not even cover the losses. The run cannot say whether RSI has any value on ES. It can say that this rule's move per trade was smaller than the cost of taking the trade, and a report that showed only the pre-commission figure would have hidden that.

With costs settled, read the rest of the report in this order.

OutputWhat it tells youWhat to look for
Number of tradesHow much evidence the result rests onToo few, and every row below it is unreliable.
Average trade (after costs)The edge per tradeIt should be several times the round-trip cost, so a small rise in slippage does not erase it.
Maximum drawdownThe deepest loss from a peakAsk whether you could keep trading through it, in money and in nerves.
Drawdown durationHow long equity stayed below its last peakLong flat periods are hard to sit through live.
Yearly resultsWhether the result depends on one periodOne great year and several flat ones is fragile.
Long vs. short resultsWhether one side carries everythingKnow which side earns the result and why.

Maximum drawdown is the largest drop in the equity curve from a peak to a later low. The free drawdown calculator computes maximum drawdown and recovery from any equity series, including one exported from a backtest. The ratios that often head a report, such as Sharpe and Sortino, are explained in the guide on how to read a backtest report; each of them also rests on the trade count beneath it.

The average trade comes from one simple formula:

Average trade = net profit ÷ number of trades

Here "net profit" is the total result after all costs. "Number of trades" counts each completed round trip once. The result is what one trade earned or lost on average, in points or money, and it is the number to hold against the round-trip cost.

Hypothetical example

A rule set on TAIEX futures day-session bars is tested over five years. The report shows 250 trades and a net result of 2,500 index points after an assumed cost of 3 points per round trip. Average trade: 2,500 ÷ 250 = 10 points. Maximum drawdown: 700 points.

Stress test: raise the assumed cost from 3 to 5 points. The net result falls by 2 × 250 = 500 points, to 2,000 points, and the average trade falls to 8 points. The edge survives the higher cost.

A second rule set shows 40 trades and an average trade of 4 points. One extra point of slippage removes a quarter of its edge, and 40 trades are too few to separate skill from luck. The first report is worth testing further; the second is not.

Hypothetical example, average trade equals net profit divided by trades: when the assumed cost rises from 3 to 5 points, each average trade after costs loses 2 points; the 10-point rule keeps 8 and survives, the 4-point rule keeps 2 and loses half its edge Edge per trade vs cost Net avg trade, cost from 3 to 5 pts Example 10 → 8 4 → 2 Survives Halved 2 more points halve a 4-pt edge. So: edge several times the cost.
The average trade after costs is the edge per trade. Raising the cost from 3 to 5 points takes 2 points from each: the 10-point rule keeps 8, the hypothetical 4-point rule keeps 2. The edge must be several times the round-trip cost to survive a rise in slippage.

Read these numbers side by side, not one at a time: equity next to drawdown, the trade list next to periodic performance, the long side next to the short. Set against the curve that produced them, the 540 trades and −$3,705 of the ES run show which stretches gave the money back. The Performance Report page shows those views together.

Why do backtests fail in live trading?

The main cause is overfitting; the next is a cost line or a trade count that was already weak in the report. Overfitting is when rules or parameters fit random wiggles in historical data that will not happen the same way again. It is what happens when the same data is used both to choose the rules and to grade them.

Think of a student who memorizes last year's exam answers. The score on last year's exam is perfect. The score on this year's exam shows what the student really learned. A backtest tuned on the same data it reports is the memorized exam.

Hypothetical equity curve of an overfitted strategy: it rises smoothly on the in-sample data used to choose the rules, then stays flat with small ups and downs on out-of-sample data it never saw The fit stops on new data Hypothetical equity curve In-sample Out-of-sample The tuned fit did not carry over. So: judge it on unseen data.
Hypothetical illustration: an overfitted strategy looks smooth on the data used to build it and loses its edge on data it never saw.

Overfitting grows with the number of variants you try. Test enough combinations of rules and parameters and one will look excellent by chance alone. Bailey, Borwein, López de Prado and Zhu (2014) call this backtest overfitting and show that the best in-sample result from many trials often performs poorly on new data; they also show that selecting the best of many variants without reporting how many were tried amounts to presenting luck as skill. Harvey and Liu (2015) make the related point that a reported backtest result should be discounted for the number of tests behind it, because the more strategies a researcher examines, the higher the bar a surviving result must clear. Testing a hundred variants and reporting the best one is like a lottery winner describing a method.

Other causes are more practical, and each one leaves a sign you can check in the report itself.

Sign to checkWhy it matters
A very smooth equity curve with many parametersMany settings give the search more ways to fit noise.
Results change sharply when a parameter moves one stepA real edge rarely sits on a single exact value.
Small average trade, many tradesReal slippage can be larger than the assumed cost; the ES run above is the pattern.
Fills at the same bar's close that gave the signalThis uses a price you could not have traded at.
Big jumps in equity at contract rollsThe continuous data may contain roll errors.
Most profit from one short periodThat market condition may not return; the gold run above is the pattern.
Night-session or thin-market trades at full sizeThe backtest assumed liquidity that the live order book may not have.

Can you backtest for free?

Yes. A charting platform's strategy tester, free backtesting software and a spreadsheet each run a first backtest at no cost, and the same checks apply to all three: costs in, next-bar fills, and a trade count large enough to mean something.

  1. A charting platform's strategy tester. Charting platforms with a script language let you write the rules, set commission and slippage, and read a trade list and equity curve on the chart. The guide to the TradingView strategy tester walks through its settings and what to check first, including the order fill timing and the continuous contract the chart uses.
  2. Free backtesting software. Several programs and libraries run rules on data you supply, which gives you full control of the continuous series and the roll rule. The page on free backtesting software compares what each route asks you to set up yourself.
  3. A spreadsheet. For a rule on daily bars with one entry and one exit, a spreadsheet works: one row per bar, a column for the indicator, a column for the signal, a column for the position taken on the next row, and a column for the result after cost. It is slow and it teaches the most, because every leak and every cost is a cell you typed.

The three routes differ in how much of the five settings they let you control and how much they ask you to check by hand.

SettingCharting platform strategy testerFree backtesting softwareSpreadsheet
Continuous data and rollsPartly (the platform builds the series)Set by youManual
Complete rulesSet by you (script)Set by youManual
Costs and slippageSet by youSet by youManual
Session choicePartly (chart session)Set by youManual
Next-bar executionPartly (a fill setting)Set by youManual
Many variants at oncePartlyPartlyManual
Six backtest settings across three free routes: a charting platform tester lets you set rules and costs and only partly controls data, session, fills and variants; free software lets you set all of them, variants partly; a spreadsheet makes every setting manual Free routes: what you set Six settings, three free tools Charting Software Sheet Data & rolls Rules Costs Session Next-bar fill Many variants Partly You set Manual You set You set Manual You set You set Manual Partly You set Manual Partly You set Manual Partly Partly Manual
Three free ways to run a first backtest, and how much of each setting you control or must check by hand.

Whichever route you take, the report deserves the same two questions before anything else: what did the costs line say, and how many trades produced the number? A free tool that lets you set commission to zero will happily show you the $32,475 version of the ES rule. The −$3,705 version is the one you would have traded.

What should you check after a backtest looks good?

Test the strategy on data it never saw, and test the way you built it, before any live trade. In-sample data is the data used to choose the rules and parameters. Out-of-sample data is data that played no part in those choices. A good backtest is the start of this checklist, not the end of it.

  1. Hold out data. Keep the most recent part of the history aside, for example the last 20 to 30 percent. Build on the rest, then run the finished rules once on the held-out part without changes. A result that keeps most of its edge per trade there has passed its first real test.
  2. Run a walk-forward analysis. Walk-forward analysis is a repeated cycle of optimizing on one window of data and testing the chosen settings on the next window, then moving forward. It shows whether your re-tuning process holds up across many periods, not one. The guide to walk-forward analysis covers window lengths and how to read the joined out-of-sample curve. Set your pass thresholds before you see the result, and stop at the first failed check. MultiAlphas's strategy validation works the same way: Basic, Standard and Extensive validation, walk-forward analysis, thresholds you set, and the later checks stop when a strategy fails one.
  3. Double the slippage and rerun. A strategy that fails here depended on cheap execution. The ES run above would not survive this step; the first hypothetical TAIEX rule would.
  4. Move each parameter one or two steps. Results that stay similar point to a broad edge; results that collapse point to a lucky value. Write down the range of each parameter where the result holds, because that range is what you will trade, not the single best number.
  5. Read the yearly results and the long and short sides. Look for profit spread across years and market conditions, not packed into one, and know which side of the market earns it.
Five checks in order after a backtest looks good: hold out 20 to 30 percent of data, walk-forward analysis, double the slippage, shift parameters, read yearly results and long and short sides; a fail at any step sends the rules back for rework, passing all five leads to small live size and checking live fills Five checks, in order Pass each before any live trade 1. Hold out 20–30% 2. Walk-forward 3. Double slippage 4. Shift parameters 5. Years and sides Fail Rework the rules All pass: trade small, check fills
Five checks in order after a backtest looks good. A fail at any step sends the rules back to the workbench; a pass at all five leads to small live size, not full size.

A strategy that passes these checks has stronger evidence behind it. It is still evidence about the past, so size the first live trades small and compare every live fill with the price the backtest assumed. The difference between the two, averaged over the first few dozen live trades, is the slippage number to put back into the next backtest.

Frequently asked questions

What is backtesting in trading, in simple words?

Backtesting means running a fixed set of trading rules over past prices, bar by bar, to see what trades they would have made and what those trades would have earned or lost after costs. It is a measurement of the past, not a prediction. Its usefulness depends on realistic costs, honest fill timing and enough trades.

What does 回測 mean?

回測 is the Chinese term for backtesting. 回 means back and 測 means test, so it is a test run backwards in time: historical data, fixed rules, recorded trades. The method and its limits are the same in every language.

How much data does a backtest need?

Enough to produce a few hundred trades spread across rising, falling and flat periods. For a daily-bar rule that trades a few times a year, this can mean decades; for an intraday rule, a few years may be enough. The trade count and its spread across years matter more than the calendar length on its own.

Is a good backtest proof that a strategy works?

No. A good backtest shows that the rules fit the past data, which can happen by luck, by overfitting or because the market rose while the rule was long. The gold run in this article shows a profit factor near 5 from 15 trades in a rising market. Out-of-sample tests, walk-forward analysis and cost stress tests separate a fitted result from a repeatable one.

What is the difference between backtesting and paper trading?

Backtesting runs rules over past data in seconds or minutes and covers years of history. Paper trading runs rules forward in real time without real money, so it is slow but uses prices the strategy has never seen. Many traders backtest first, validate on out-of-sample data, then paper trade or trade small to compare real fills with the backtest's assumptions.

References

  • Bailey, D. H., Borwein, J., López de Prado, M., & Zhu, Q. J. (2014). Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance. Notices of the American Mathematical Society, 61(5), 458–471.
  • Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple Technical Trading Rules and the Stochastic Properties of Stock Returns. The Journal of Finance, 47(5), 1731–1764.
  • Harvey, C. R., & Liu, Y. (2015). Backtesting. The Journal of Portfolio Management, 42(1), 13–28.