burger

How to Backtest Trading Strategies


One thing connects all professional traders – they have 100% trust in their trading strategy. If we want to join this elite club of traders, we must know what to expect from our trading strategy. This is quite a complicated task since none of us can see the future, but thanks to the historical data, we can easily see how we would have performed in the past. If we can find out that our trading strategy performed well in the last couple of years, there is a very small chance it won’t work in the future.

What is backtesting

Backtesting is the process of evaluating a trading strategy using historical data to determine how it would have performed in the past. This allows you to assess the viability of your strategy before applying it to live trading.

This can be done over the last few months, but we can also go 10 or 20 years back. It all depends on our appetite and how robust we want our backtest to be. Although backtesting can be very time-consuming, it is relatively easy. All we need is a trading platform with access to the historical data and a simple spreadsheet where we will document all trades.

Two methods to backtest

Algorithmic (automated) testing is highly precise, eliminating any bias or subjective judgement that can occur with manual trading. While it may take some time to program, it allows you to easily optimise rules and run new backtests or a batch of them quickly. If you’d like to learn more about algorithmic testing and trading, you can see the course offered by freeCodeCamp.

Manual backtesting is quite an exhaustive process that can easily consume tens to hundreds of hours. To make the most of your time, it’s advisable to first define your strategy conceptually and then examine around 20 instances on the charts that would have triggered a trading opportunity. This initial exploration helps you understand the key elements to include in your backtesting spreadsheet. On the other hand it offers a significant advantage in that it allows your brain to fully engage with and believe in the strategy. By manually testing, you’re not just running numbers—you’re actively learning to spot visual cues, patterns, and their variations in the market. This hands-on approach deepens your understanding of market behaviour and helps you gain confidence in your strategy. Over time, this process not only reinforces your trading rules but also hones your ability to recognise profitable opportunities in real-time trading.

Variables to Consider for Backtesting

We cover the specifics of optimisation in another lesson, but here are a few examples to consider:

  • Risk to Reward Ratio vs. Win Rate: This involves balancing small, consistent profits against the potential for larger gains by capturing trends that occasionally result in significant returns. However, this must be contrasted with the frequency of winning trades versus losing ones. A higher risk-to-reward ratio might mean fewer winning trades, leading to potentially longer losing streaks. Conversely, a lower risk-to-reward ratio might result in more frequent wins but with smaller profits. Understanding how often you will win and anticipating possible winning and losing streaks is crucial for managing expectations and maintaining psychological resilience during trading.
  • Confirmation Methods and Their Frequency: Experimenting with different types of confirmation signals is essential to determine which are most effective in various market conditions. Additionally, consider testing combinations of multiple confirmation signals to see if they provide stronger or more reliable trade setups.
  • Timing of Market Movements: Analyse the time it takes for the market to move after your trade is triggered. Sometimes, you can expect immediate reactions. However, in other situations, patience may be required. Understanding the typical timing and volatility of market movements can help you set more appropriate stop-loss and take-profit levels.
  • Fixed Risk to Reward Ratio vs. Discretionary Targets: Decide whether to use a fixed risk-to-reward ratio, such as 2:1 for every trade, or apply discretionary targets when you anticipate certain various levels to be reached. Alternatively, you could use techniques like trailing stops to lock in profits.
  • Scaling In and Out: Consider strategies for gradually increasing or reducing your position size to manage risk and maximise returns.

Remember to keep your rules simple to ensure they are easy to execute and replicate over time.

Here’s a step-by-step guide on how to backtest a trading strategy:

How to backtest a trading strategy?

  1. Choose a Backtesting Platform or Tool

    • For Manual Backtesting: You can manually backtest using a spreadsheet like MS Excel or Google Sheets. This involves going through historical data, applying your strategy rules and recording the results.
      • The easiest way is to open your platform, set your charts with all the visualisations and indicators and scroll back in time.
      • Then scroll forward candle by candle, to avoid any bias, to not let your brain convince you about the made up situations.
      • annotating your chart, highlighting situations and taking screenshots.
      • Collect the data to the spreadsheet so you can count the statistics in the end.
    • Automated Backtesting: Use software or trading platforms that allow for automated backtesting, such as MetaTrader and TradingView or advanced trading platforms with specialised backtesting modules like NinjaTrader, Amibroker or Tradestation.
  2. Set a few clear rules for your strategy

    • Timeframe: Specify the timeframe or their combination on which your strategy will be applied (e.g., daily, 4-hour, 15 minute).
    • Entry and Exit Rules: Clearly outline the conditions under which you will enter and exit trades. These rules should be specific and objectively observable, such as “Buy when the whole body of a 30-minute candle closes above a key resistance zone if a market is trending in the uptrend on 1-day time frame and the distance between stop loss level and nearest resistance is in a ratio of at least 2:1.
    • Risk Management: Define how much you will risk per trade, where you will place stop-loss orders, and how you will determine position size.
    • For more information see our lesson on How to create a trading plan and strategy.
  3. Collect Historical Data

    • Select the Market and Timeframe: Choose the currency pairs, stocks, or other instruments you want to test, and ensure you have historical data for the appropriate timeframe.
    • Find and Download Accurate Market Data: You need to obtain high-quality historical price data from a reliable source, considering that CFD brokerages and prop trading firms often have varying conditions in terms of pricing, fees, and spreads. Depending on how far back you need to go and the timeframe you’re interested in, you may need to pay for the data or find it available for free from trading platforms or financial websites.
    • Data sets:
      • In-Sample Data: This is the portion of historical data used to develop, optimise, and fine-tune your trading strategy. During this phase, you adjust parameters and test different variations to improve the strategy’s performance. The risk with in-sample data is overfitting, where the strategy becomes too closely tailored to the historical data and may not perform well in new, unseen data.
      • Out-of-Sample Data: This is a separate set of historical data that was not used during the backtesting and/or optimisation process. It is reserved for testing the strategy after development to ensure that it performs well under different market conditions.
  4. Run the Backtest

    • Manual Backtesting Steps:
      • Start with Historical Data: Use a charting platform to go back in time and simulate trades as close to if you were trading in real-time as possible.
      • Apply Your Strategy: For each trading signal (buy/sell), record the entry price, stop-loss, take-profit levels, and any other relevant details.
      • Track the Outcome: Move forward bar by bar (candle by candle) and record the outcome of each trade (profit/loss).
      • Log Results: Keep a detailed log of each trade individually in a spreadsheet or other tool, noting all important observations.
    • Automated Backtesting Steps:
      • Input Your Strategy: Enter your strategy’s rules into the backtesting software.
      • Run the Backtest: The software will simulate trades based on your strategy over the selected historical period.
      • Analyse Results: The software will generate a report showing the performance metrics of your strategy, including total profit/loss, win rate, drawdowns, and other key statistics.
    • Basic data to collect into your spreadsheet or database:
      • Instrument (for backtests performed on more instruments)
      • Time and date of entry
      • Entry by market or limit order
      • Entry price
      • Exit price
      • Entry pattern and timeframe (if applicable)
      • Exit pattern and timeframe (if applicable)
      • Position size and % risk on your trading account
      • MAE – maximal adverse excursion (measured by pips/ticks, percentually or by Reward-to-Risk Ratio)
      • MFE – maximal favourable excursion (measured by pips/ticks, percentually or by Reward-to-Risk Ratio)
      • Result of the trade measured in Reward-to-Risk ratio or the amount of ticks/pips
      • Notes for the trade – level of conviction, emotional aspects

      If possible, adding the screenshot to all the trades in your backtest is also good. This way, you can easily come back to it later.

  5. Analyse the Backtest Results

    • Win Rate: Calculate the percentage of winning trades versus losing trades.
    • Risk-Reward Ratio: Evaluate the average reward relative to the average risk for each trade.
    • Profitability: Assess whether the strategy is profitable over the long term.
    • Maximal Drawdown: Look at the maximum drawdown, which is the largest peak-to-trough decline in your portfolio during the backtest period.
    • Consistency: Check if the strategy performs consistently over different market conditions or time periods.
    • Monte Carlo Analysis: Use Monte Carlo analysis to simulate various potential trading scenarios by randomising the sequence of trades in your backtest. This helps assess the robustness of your strategy across different sequences of winning and losing trades, allowing you to identify potential weaknesses and enhance the overall resilience of your strategy.
    • Equity Curve Simulator: You can also simulate a variety of possible outcomes using our tool, which will show you potential equity curve scenarios based on your win rate, risk-to-reward ratio, and initial capital.
    • Statistical significance: Some traders might test the first ten trades, and if they see their strategy works, they decide it is just enough and give up on further backtesting. This is definitely not a good approach as we don’t have a robust data sample. To be really sure our trading system is stable and robust, we need a sample size of at least 100-200 trades. This way, we will gain much more confidence in our trading. We will gain much more confidence knowing that our strategy has a positive expectancy over the long run.

Statistics – what to look for

A key component of any trading strategy is understanding probabilities and statistical metrics, such as the expected return of a trade or win/loss ratio. Traders often backtest their strategies using historical data to refine their approach. Based on the collected backtest data, you should review following metrics:

Expected Return

  • The expected return is the average amount of profit or loss a trader can anticipate from a trade, calculated by multiplying the probability of each outcome by its respective return, and then summing them up.
  • This metric helps traders evaluate whether a strategy is likely to be profitable in the long run. Positive expected returns suggest that the strategy is statistically favourable over time, even if individual trades result in losses.

Profit Factor

  • Profit factor is the ratio of the total profits to total losses over a specific period or set of trades. A profit factor greater than 1 indicates that the strategy is profitable overall.
  • This ratio provides insight into the overall efficiency of a trading strategy by comparing how much profit is made for every dollar lost. It’s a simple way to measure profitability.
  • A profit factor of 2 means the strategy makes $2 in profit for every $1 lost.

Average Win/Loss

  • The average win/loss is the average size of winning trades compared to the average size of losing trades.
  • This metric helps traders understand the potential magnitude of wins compared to losses. A strategy with a high average win/loss ratio can remain profitable even if the win rate is relatively low.
  • For instance, an average win/loss ratio of 3 means that, on average, winning trades are three times larger than losing trades.

Sharpe Ratio

  • The Sharpe ratio is a risk-adjusted measure of return, showing how much excess return is received for the additional volatility (risk) taken by the trader. It is one of the most commonly used metrics in finance to compare different strategies.
  • The Sharpe ratio allows traders to evaluate whether a strategy’s returns are due to smart trading or simply taking on too much risk. A higher Sharpe ratio indicates better risk-adjusted returns.
  • A ratio above 1 is generally considered good, while above 2 is excellent.

Average Risk-Reward Ratio (RRR)

  • The average risk-reward ratio (RRR) compares the potential risk of a trade to the potential reward. It’s calculated by dividing the expected profit of a trade by the expected loss.
  • This ratio helps traders assess whether a trade is worth taking. Even with a low win rate, a favourable risk-reward ratio can lead to profitability if the rewards of winning trades significantly outweigh the losses.
  • A risk-reward ratio of 1:2, for example, means the potential reward is twice the potential risk.

Win Rate

  • The win rate is the percentage of winning trades out of the total number of trades executed.
  • While a high win rate can be desirable, it’s not the only factor for profitability. A strategy with a lower win rate but higher average win size (compared to losses) can still be profitable.
  • For example, a win rate of 60% means 60 out of every 100 trades are profitable.

Max Drawdown

  • Max drawdown (MDD) is the largest peak-to-trough decline in the value of a trading portfolio during a specific time period. It measures the maximum percentage loss from a portfolio’s high point (peak) to its lowest point (trough) before recovering. The max drawdown is a critical risk metric used to evaluate the downside risk in a trading strategy.
  • Max drawdown gives traders insight into the worst-case scenario in terms of capital loss during a trading strategy. A large drawdown can indicate higher risk exposure, while a smaller drawdown suggests a more conservative approach. It is particularly useful in risk management, as it helps traders and investors understand the potential loss before a recovery is expected.

Optimising the Strategy

  • Starting Over: It’s important to save your backtests so you can revisit and refine them without starting from scratch. To save time, it’s advisable to first observe the market and estimate which parameter variations would be beneficial to include in the backtest, as starting over can be time-consuming.
  • Parameter Tweaking: Adjust the parameters of your strategy (e.g., different confirmation patterns, stop-loss levels) to see if performance improves. Be cautious of over-optimising by adding too many conditions, which can lead to curve-fitting—a strategy that works well on historical data but poorly in live trading.
  • Multiple Markets: Test your strategy on different currency pairs or assets to ensure it’s robust across various markets or to determine if it’s better suited to a specific one.

Out of Sample and Forward Testing

  • Out-of-Sample Testing: Evaluate the performance on data that wasn’t used during the backtesting process. This helps ensure that your strategy is not overfitted to historical data and can perform well in real market conditions. The process is the same as for backtesting.
  • Paper Trading: After backtesting, consider paper trading (simulated trading with a demo account) to see how the strategy performs in real-time conditions before committing real money.

Review and Refine

  • Ongoing Analysis: Regularly review and refine your strategy as you gain more data and experience. Market conditions change, and a strategy that worked in the past may need adjustments to remain effective.