Strategies9 min read · 1,971 words

How to Backtest a Trading Strategy (With a Worked Example)

Backtest a trading strategy step by step: write testable rules, add costs, log 50+ trades, read win rate, expectancy and drawdown, then test out-of-sample.

How to Backtest a Trading Strategy (With a Worked Example)

To backtest a trading strategy, write rules precise enough that two people would take the same trades, run them over historical data, charge every trade realistic costs, and judge the result on at least 50-100 trades by expectancy and drawdown, not total profit. Then test the same rules on data you did not use to build them.

This guide walks through that process with one worked example from start to finish. For the definition, the types of backtest and how it compares with forward testing, see what is backtesting.

The backtest in six steps

Step What you do Output
1. Write the rules Entry, stop, exit, size, market, timeframe A rule sheet with no judgment calls
2. Pick the data Instrument, period, bar size; split in-sample and out-of-sample A dataset with a hold-out period
3. Run the trades Manually in a spreadsheet or with bar replay, or in code A trade list: date, entry, stop, exit, result
4. Charge the costs Commission, fees, slippage on entry and exit Net result per trade, in dollars and R
5. Read the numbers Win rate, average win and loss, expectancy, profit factor, max drawdown A verdict for the in-sample period
6. Test out-of-sample Same rules, untouched data Proof the edge was not curve-fitted

Step 1: Write rules a computer could follow

“Buy strong stocks on pullbacks” cannot be backtested, because every pass through the chart will pick different trades. Each rule needs a number. Here is the rule sheet we will test:

  • Market and timeframe: liquid US stocks and ETFs, daily chart, long only.
  • Filter: close is above the 200-day simple moving average.
  • Entry: close makes a new 20-day high; buy at the next day’s open. Using the signal day’s close as the fill would be lookahead bias, because you only know the close once the bar is finished.
  • Stop: 2 × ATR(14) below the entry price.
  • Exit: a target at 2R, or the close of the 10th trading day, whichever comes first.
  • Size: risk 1% of the account on each trade, so the position size comes from the stop distance. The position size calculator does the arithmetic.

If a rule makes you hesitate on a chart (“is this a real breakout?”), it is not finished. Rewrite it until the answer is yes or no.

Step 2: Choose the data and hold some back

Use data that matches how you will trade: daily bars for a daily strategy, minute bars or finer for intraday. Free daily data is fine for a first pass; for intraday work, gaps and bad prints in free data can change the result.

Before you start, split the history in two:

  • In-sample (for example 2018-2023): where you build and adjust the rules.
  • Out-of-sample (for example 2024-2025): you do not look at it until the rules are frozen.

Include different conditions in the in-sample period: a trend, a bear market, a long sideways stretch. A breakout strategy tested only on 2021 will look better than it is.

If you test individual stocks, use a list that includes companies later delisted or acquired. Testing today’s index members over the past decade is survivorship bias: the failures are missing, so the results look better than anyone could have achieved.

Backtest setup: historical data, written rules, costs and risk settings

Step 3: Run the trades

There are three ways to do it. They give the same answer if the rules are precise; they differ in speed.

Method How it works Best for
Manual, in a spreadsheet Scroll the chart bar by bar, log every signal First test of a discretionary idea; you learn how the setup behaves
Bar replay TradingView Bar Replay or a platform simulator hides future bars as you step forward Manual testing without seeing what comes next
Code TradingView Pine Script strategies, MetaTrader 5 Strategy Tester, NinjaTrader Strategy Analyzer, or Python libraries such as backtrader Hundreds of trades, many symbols, parameter checks

For a manual test, log one row per trade:

Date Symbol Entry Stop Exit Exit reason Result ($) Result (R)
2019-03-12 XYZ 50.00 47.00 56.00 Target 2R +600 +2.0R
2019-04-02 ABC 31.20 29.70 29.70 Stop −300 −1.0R
2019-04-18 XYZ 55.00 52.00 56.20 Day 10 close +120 +0.4R

Each row risks $300 (1% of a $30,000 account), so the share count changes with the stop distance. Recording results in R (net result ÷ planned risk) makes trades of different sizes comparable and lets you change the account size later without redoing the test. The trading journal Excel template has these columns and the formulas ready.

Step 4: Charge every trade its costs

A backtest without costs measures an idea, not a strategy. For each trade, subtract:

  • Commissions and exchange or regulatory fees, on entry and exit.
  • Slippage: the gap between the price in your rules and the price you would have got. Assume some on market orders and stop exits; stops in fast markets and at the open fill worse than the stop price.
  • Spread, if your data is mid or last price and you trade through the bid and ask.

Express costs in R so you can see what they do. In our example a typical trade risks $3.00 a share on 100 shares ($300). With $0.03 a share of slippage on each side and $1 of fees, one round trip costs about $7, or 0.02R. A scalper risking $0.10 a share with the same costs pays roughly 0.7R a trade, which is why short-term strategies fail on costs far more often than on signals. In TradingView, the strategy() settings take a commission and a slippage value in ticks; set both before you read a single result.

Step 5: Read the results

Say the in-sample run produced 60 trades: 26 winners averaging +1.9R, 32 losers averaging −1.0R and 2 scratches at 0R, all after costs.

Metric Formula Result
Win rate wins ÷ all closed trades 26 ÷ 60 = 43.3%
Expectancy total R ÷ trades (26 × 1.9 − 32 × 1.0) ÷ 60 = 17.4 ÷ 60 = +0.29R
Profit factor gross wins ÷ gross losses 49.4 ÷ 32 = 1.54
Break-even win rate 1 ÷ (1 + average win ÷ average loss) 1 ÷ 2.9 = 34.5%
Max drawdown largest peak-to-trough fall in R −7R (seven losses in a row)

At 1% risk, +0.29R a trade is about +0.29% of the account per trade on average, and the −7R streak is a drop of about 6.8%. Ask whether you would keep taking trade eight after seven straight losses. If not, the strategy is fine and the size is wrong.

Now the sample-size check. With 60 trades, the 95% range around a 43.3% win rate is roughly ±12.5 points: anywhere from about 31% to 56%. The low end is below the 34.5% break-even rate, so 60 trades do not yet prove an edge. The usual answer is more trades, from more symbols or a longer period, not more parameters. The table in how to calculate win rate shows how the range narrows as the sample grows, and the equity curve simulator shows what losing streaks to expect from a given win rate and R.

Do not judge the test by net profit alone. One outsized winner can carry a weak strategy; check the result with the best trade removed. If expectancy turns negative, you have one lucky trade, not a strategy.

Step 6: Test on data you have not seen

Freeze the rules, then run them once on the out-of-sample years. In our example the next 25 trades returned +0.12R per trade. That is weaker than in-sample, which is normal, and still positive after costs.

Signs of an overfitted backtest:

  • Results collapse when a parameter moves slightly (a 20-day high works, 18 and 22 do not).
  • The rules have many conditions, each added to remove a few losing trades.
  • Out-of-sample expectancy is near zero or negative.
  • You re-ran the out-of-sample test after changing the rules. Once you have looked at it, it is in-sample.

For a stricter check, use walk-forward testing: build on one window, test on the next, roll forward and repeat. It is more work and gives a more honest number.

From backtest to live trading

A passed backtest earns the right to a forward test, not to full size.

  1. Paper trade the rules for at least 30-50 trades. See what is paper trading for the evidence bar before going live.
  2. Go live small, at a fraction of your planned risk.
  3. Compare live results with the backtest on the same metrics: win rate, average win, average loss, expectancy and cost per trade in R. A gap usually comes from one of three places: fills worse than assumed, trades you skipped or took outside the rules, or a market that has changed.

A trading journal makes that comparison routine: tag every live trade with the strategy name, mark whether you followed each rule, and check the numbers against your backtest every 20 trades. The trading plan template has room to write the backtest’s figures next to the rules so you have something to measure against.

Frequently asked questions

What is the best software for backtesting?

The one that matches how your rules are written. TradingView’s Strategy Tester and Bar Replay suit chart-based rules and need little or no code. MetaTrader 5 and NinjaTrader have built-in testers for automated strategies on their platforms. Python libraries such as backtrader give the most control if you can code. A spreadsheet is enough for a first manual test.

How much data do I need?

Enough trades rather than enough years. Aim for at least 50-100 trades per strategy, across more than one kind of market. A daily strategy that trades twice a month needs several years of data to get there; an intraday strategy may get there in months.

Why does my strategy fail live when the backtest was profitable?

The most common causes are missing costs or slippage, lookahead bias in the rules (filling at a price you could not have known), overfitting to the test period, and execution: skipped signals or trades taken outside the rules. Compare your live trades with the backtest one metric at a time to find which it is.

Can I backtest without coding?

Yes. Write the rules down, step through the chart with bar replay so you cannot see future bars, and log every signal in a spreadsheet. It is slower than code but works for any strategy you can describe precisely.

Does a good backtest guarantee future profits?

No. It shows the rules had an edge in the period tested, after costs. Markets change, which is why the out-of-sample test, paper trading and a small live start come before full size.

Start journaling with TradeReview for free. Tag trades by strategy and compare live results with your backtest.

Keep reading

StrategiesHow to Calculate Lot Size in Forex (With Examples)

How to calculate lot size in forex: the formula, pip values for USD, JPY and cross pairs, worked examples, gold, and the mistakes that oversize trades.

8 min read
StrategiesTrailing Drawdown Explained: End-of-Day vs Intraday

How trailing drawdown works in prop challenges: static vs end-of-day vs intraday, when the floor stops, a worked example, and Topstep and Apex rules.

9 min read
StrategiesHow to Pass a Prop Firm Challenge

How to pass a prop firm challenge: size trades from the daily loss limit, stop before the firm's limit, run a five-point pre-session check, review daily.

7 min read

Start the journal you will actually reopen.

Free forever, no card. Web, iOS and Android. What the free plan includes

Create free account →See pricing