# How to Backtest a Trading Strategy

> How to backtest a trading strategy step by step: write testable rules, split your data, log every trade in R, then check the result for overfitting before you trust it.

Canonical: https://www.journalx.io/guides/how-to-backtest-a-trading-strategy

To backtest a trading strategy, write rules precise enough that two people would take the same trades, then apply them to historical data you have split into a tuning period and an untouched test period. Log every trade in R with costs included, collect at least 100 trades, and check the result on the test period before trusting it.

Learning how to backtest a trading strategy is mostly learning what not to trust. Running rules over old charts is easy. The hard part is getting a result that still holds on data you haven't seen, because a backtest will happily show you an edge that only exists in the past. This guide walks through the process in order, from writing the rules to reading the numbers, and spends the most time on the steps that keep a backtest honest.

It is written for traders who already have a setup in mind and want to find out whether it has an [expectancy](/glossary/expectancy) worth trading, before risking money on it.

## Step 1: Write rules a stranger could follow

A backtest tests rules, so the rules have to exist before the test starts. If you decide what counts as a valid entry while looking at the chart, you are testing your hindsight, not a strategy.

Write down each of these before you open a single historical chart:

- **Market and timeframe.** Which symbols, which chart, which session hours.
- **Setup conditions.** What has to be true before a trade is even possible (trend filter, level, pattern, time of day).
- **Entry trigger.** The exact event that puts you in, and the order type.
- **[Stop-loss](/glossary/stop-loss).** Where it goes, measured from something you can see on the chart. This defines 1R for every trade.
- **Exit.** A fixed [take-profit](/glossary/take-profit), a trailing rule, a time stop, or a mix. Ambiguous exits are where most manual backtests drift.
- **Size.** Risk the same fraction of the account on every trade (for example 1R = 1%), so results stay comparable.
- **What disqualifies a trade.** News events, gaps, a second setup while one trade is still open.

The test for whether the rules are ready: hand them to another trader and see if they mark the same trades you would. If they can't, the rules are too vague to backtest, and they will be too vague to follow live. Our guide to [creating a trading plan](/guides/how-to-create-a-trading-plan) covers how to turn loose ideas into rules you can check.

## Step 2: Choose manual or software backtesting

There are two ways to run the test, and they fail in different ways.

|              | Manual backtesting                                                                           | Software (coded) backtesting                                         |
| ------------ | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| How it works | Step through historical charts bar by bar and record each trade by hand                      | Write the rules as code and let a platform run them over the data    |
| Best for     | Discretionary setups, patterns that are hard to code, learning a setup                       | Fully mechanical rules, many markets, long histories                 |
| Speed        | Slow: every trade is stepped through and logged by hand                                      | Thousands of trades in seconds                                       |
| Main risk    | Hindsight: seeing the right side of the chart, or skipping trades you "would not have taken" | Overfitting: testing hundreds of variations because each one is free |
| Costs        | You add them yourself                                                                        | Defaults are often zero, so you have to set them                     |

For manual backtesting, use a replay tool that hides the future, such as [TradingView's Bar Replay](https://www.tradingview.com/support/solutions/43000712747/), and advance one bar at a time. Scrolling back over a finished chart and spotting setups is not a backtest, because your eye finds the ones that worked.

Many traders do both: a manual pass to learn how the setup behaves and to write precise rules, then a coded test once the rules are mechanical enough to program.

## Step 3: Split your data before you start

This is the step most backtests skip, and it is the one that decides whether the result means anything.

Before testing, divide your history into two parts. The **in-sample** period is where you build and tune the rules. The **out-of-sample** period, usually the most recent 20 to 30 percent, stays untouched until the rules are final. You run the finished strategy on it once and record what happens. If you go back and tweak the rules after seeing the out-of-sample result, it becomes in-sample data and you no longer have an honest test.

![A single split uses five years to build and tune the rules and holds back the last two years for one out-of-sample test. A walk-forward test repeats this in rounds, tuning on a rolling three-year window and testing on the following year.](https://assets.journalx.io/marketing/guides/how-to-backtest-a-trading-strategy/in-sample-out-of-sample-split.avif)

A stricter version is a [walk-forward test](https://en.wikipedia.org/wiki/Walk_forward_optimization): tune on one window, test on the next, slide both forward, and repeat. Stitch the test windows together and you get a track record built entirely from data the rules never saw.

Three more checks on the data itself:

- **Cover different conditions.** A test that only spans one trending year tells you how the strategy did in one trending year. Include quiet and volatile periods, and rising and falling markets.
- **Watch for [survivorship bias](https://en.wikipedia.org/wiki/Survivorship_bias).** A stock list built from today's index members leaves out the companies that went bankrupt or were delisted, which flatters most long strategies.
- **Use only information available at the time.** Indicators that repaint, or a daily close used to trigger an entry earlier that same day, leak the future into the test (look-ahead bias).

## Step 4: Set your sample size in advance

Decide how many trades the backtest needs before you start, and don't judge the strategy until you reach that number.

The rough rule is **trades needed ≈ (2 × standard deviation ÷ expectancy)²**, with both numbers measured in [R-multiples](/glossary/r-multiple). For typical setups that lands between 100 and 400 trades. A thin edge needs more, because halving the expectancy quadruples the trades you need. [How many trades you need to judge a strategy](/blog/how-many-trades-to-evaluate-a-strategy) works through the numbers for different win rates and payoffs.

If your setup only fires twice a month on one market, that sample can take years of history. Add more markets that behave in a similar way, or accept that the result will carry a wide margin of error and size it that way.

## Step 5: Log every backtest trade like a live trade

Record each backtest trade with the same fields you use for live trades. That makes the backtest easy to analyze, and later lets you compare backtest and live results line by line. [What to track in a trading journal](/blog/what-to-track-in-a-trading-journal) covers the full list. At minimum:

| Field                            | Why it matters                                   |
| -------------------------------- | ------------------------------------------------ |
| Date and time, symbol, direction | Lets you slice by session, market and side later |
| Planned entry, stop and target   | Fixes 1R before the outcome is known             |
| Actual exit and exit reason      | Shows which exit rule did the work               |
| Net result in R, after costs     | The number every statistic is built from         |
| Market condition tag             | Trend, range, high or low volatility             |
| Rule notes and a screenshot      | Lets you audit the trade later                   |

Three habits keep the log honest:

- **Include costs on every trade.** Add commissions, and assume some [slippage](/glossary/slippage) on market orders and stops. A 0.1R edge is cut in half once a 0.05R round-trip cost comes out of every trade.
- **Log every valid setup.** If the rules say take it, it goes in, including the ones that look ugly. Skipping "trades I wouldn't have taken" is how hindsight gets back into a manual backtest.
- **Mark ambiguous trades instead of deciding them.** When a setup could be read either way, tag it. If the ambiguous trades perform differently from the clear ones, your rules need tightening.

## Step 6: Read the results in the right order

Once you hit your sample size, read the results in this order, on the in-sample period first:

1. **Expectancy in R.** The average result per trade. If it isn't clearly positive after costs, nothing below matters. Our guide on [how to calculate expectancy](/guides/how-to-calculate-expectancy) shows the arithmetic and how to put an error band on it.
2. **[Win rate](/glossary/win-rate) next to [average win](/glossary/average-win) and [average loss](/glossary/average-loss).** These explain why the expectancy is what it is, and tell you what the strategy will feel like to trade.
3. **[Profit factor](/glossary/profit-factor).** Gross profit divided by gross loss. A profit factor only slightly above 1 after costs leaves little room, because a bit of extra slippage can wipe it out.
4. **[Maximum drawdown](/glossary/drawdown) and the longest losing streak.** These decide whether you can sit through the strategy in practice. Then check what [risk per trade](/glossary/risk-per-trade) keeps that drawdown survivable.
5. **The [equity curve](/glossary/equity-curve).** A steady curve and a curve that made all its money in one month can have the same expectancy. The second one is a bet on that month repeating.

Only after that, look at slices: by session, market, or condition tag. Each slice is a smaller sample, so treat a great-looking slice as a question for the next test, not an answer.

## Step 7: Check for overfitting before you trust it

Overfitting means tuning rules until they fit the noise in your data. It is the main way backtests mislead people, and it happens through ordinary-looking work: trying a tighter stop, then a different moving average, then a session filter, and keeping whatever scored best.

The chart below shows why that is dangerous. It is a simulation of 20 variations of a strategy, every one of them with zero edge (40 percent winners at +1.5R, 60 percent losers at −1R). The best of the 20 over the first 200 trades finished at +32.5R. Over the next 100 trades, on data that played no part in picking it, it made nothing.

![Twenty simulated strategy variations with zero true edge. The best one over the first 200 trades reaches +32.5R in-sample, then makes +0R over the next 100 out-of-sample trades.](https://assets.journalx.io/marketing/guides/how-to-backtest-a-trading-strategy/best-of-20-backtests.avif)

That isn't a lucky draw. Across 2,000 repeats of the same simulation, the best-of-20 variation averaged about +0.16R per trade in-sample and close to zero afterwards. If none of 20 variations has an edge, the chance that at least one still passes a standard 95 percent significance test is about 64 percent ([the multiple comparisons problem](https://en.wikipedia.org/wiki/Multiple_comparisons_problem)). Researchers found the same effect in strategy backtests: [Bailey, Borwein, López de Prado and Zhu](https://scholarworks.wmich.edu/math_pubs/40/) show that trying just 7 independent configurations on two years of daily data is enough to expect one with an annualized [Sharpe ratio](/glossary/sharpe-ratio) of 1 in-sample and zero out-of-sample.

Four checks catch most overfitting:

- **Count your variations.** Write down every version you tried, not just the winner. The more you tried, the more skeptical the result deserves.
- **Run the out-of-sample test once.** Compare its expectancy to the in-sample number. Some decay is normal. A collapse to zero means the in-sample edge was mostly fit.
- **Check that neighbors also work.** If a 20-period filter works and 18 and 22 don't, you found noise. A real effect usually holds across a range of nearby settings.
- **Prefer fewer rules.** Every added filter is another dial to fit the past with. A setup with three rules that holds up is worth more than one with nine that looks better.

A backtest result means little without the number of variations behind it. "+0.3R per trade over 250 trades, best of 4 versions, held at +0.2R out-of-sample" is a result you can act on. "+0.6R per trade" on its own is not.

## Step 8: Forward test at small size

A backtest that survives its out-of-sample test has earned a live trial, not full size. Trade it with real orders at small risk, or on a simulator, and log the trades with the same fields as the backtest.

Then compare the two side by side every few weeks as part of [your weekly trade review](/guides/the-weekly-trade-review-process). Live results usually come in somewhat below the backtest. What you are looking for is where the gap comes from:

- **Costs and fills.** If live slippage is larger than you assumed, rerun the backtest with the real figure.
- **Execution.** Missed setups, late entries and early exits show up as live trades that don't match the backtest log. That is a discipline problem, not a strategy problem.
- **Edge decay.** If you followed the rules, costs are in line, and the results still trail by a wide margin over a large sample, the edge may have been fit or may have faded.

Scale up only once the live sample is large enough to judge on its own, using the same sample-size target as Step 4.

## Putting it together

Backtesting a trading strategy comes down to three disciplines. Fix the rules before you look at the data. Keep part of the data away from yourself until the end. Log enough trades, with costs, to tell an edge from noise. The steps that feel slow, splitting the data, counting variations, logging the ugly trades, are the ones that make the result worth trusting. Everything else is software and patience.

Keep backtest trades in their own JournalX account, entered by hand or imported from CSV, next to your live account. Both get the same expectancy, win rate and drawdown stats per setup, so you can tell whether a gap comes from the strategy or from execution.
