Backtesting is a critical process in finance that involves testing the performance of a trading or investment strategy using historical data. It provides valuable insights into how a trading or investment strategy might have performed in the past.

    Trading signals are commonly used in backtesting as an essential part of evaluating the performance of a trading strategy. To learn more about different types of trading signals, check out my post about Financial Indicators.

    Backtesting Process

    Backtesting is a systematic process and involves the following 10 key steps:

    1. Strategy Formulation: Defining the trading or investment strategy, which could include specific rules and criteria for making buy or sell decisions, using technical indicators, fundamental analysis, or a combination of factors to generate trading signals. For instance, a trading signal could be when the stock price rises above the SMA (Simple Moving Average).
    2. Data Collection: Gathering historical data, such as historical price information, trading volumes, and other relevant data points.
    3. Data Preprocessing: Cleaning and preprocessing the historical data to ensure it is consistent and free from errors. The quality and accuracy of historical data are crucial for reliable backtesting.
    4. Backtest Simulation: Applying the trading strategy to the historical data as if it were being executed in real-time.
    5. Portfolio Management: Tracking the hypothetical portfolio’s performance during the backtest. This could include managing position sizes, accounting for transaction costs, and implementing risk management techniques.
    6. Performance Metrics: Calculating various performance metrics to evaluate the strategy’s performance. Common metrics include:
      • Total Return: The cumulative profit or loss over the backtest period.
      • Risk-Adjusted Return: Measures like the Sharpe ratio or Sortino radio.
      • Maximum Drawdown: The largest peak-to-through decline in portfolio value.
      • Win-Loss Ratio: The ratio of winning trades to losing trades.
      • Risk Metrics: Metrics that access risk, such as standard deviation or volatility.
    7. Out-of-Sample Testing: Reserving a portion of the historical data for out-of-sample testing, and is used to validate the strategy’s performance on unseen data.
    8. Analysis and Optimization: Identify strengths and weaknesses, and consider making adjustments or optimization to improve performance.
    9. Forward Testing: If the backtest results are satisfactory, deploy the strategy in a forward-testing environment to assess its performance in real-time conditions.
    10. Continuous Monitoring: After deployment, continue to monitor the strategy’s performance in live trading, and make necessary adjustments as market conditions change.

    Backtesting Strategies in Python

    Example #1: SMA/EMA Signal-Based Strategy

    This Python code implements a backtesting strategy for Google’s stock price. It initiates a long position when the stock price surpasses the 20-day Simple Moving Average (SMA) and the 20-day Exponential Moving Average (EMA), allowing for a comparison between these two moving averages.


    The two line shows how much the beginning capital balance increases over time from a baseline of 100. As seen, instead of applying the SMA, applying the EMA in this strategy improved its profitability based on the historical period backtested. Note that the flat line areas indicate periods when we don’t have any positions, so the trading account balance does not change.

    Example #2: Trend Following Strategies

    This Python code implements a backtesting strategy for Google’s stock price and initiates a long signal when the short-term EMA crosses above the long-term EMA and a short signal when the short-term EMA crosses below the long-term EMA.

    The chart above provides a visual representation to confirm the correct construction of signals. When the signal line reaches a value of 1, it signifies a long-position signal, whereas a value of -1 indicates a short-position signal.

    Python Code Continued…

    As seen in the chart above, this particular trading strategy applied to this stock over the chosen time frame does yield a profit.

    Example #3: Mean Reversion Strategy

    The Python code below implements a mean reversion strategy using the Relative Strength Index (RSI):

    • Short Signal: RSI > 70
      • Suggests the asset is likely overbought and the price may soon reverse.
    • Long Signal: RSI < 30
      • Suggests the asset is likely oversold and the price may soon rally.

    This RSI-based mean reversion strategy tries to take advantage of temporary market imbalances and trades more frequently.

    As seen in the chart above, this RSI-based mean reversion strategy yields a profit. Note that if the RSI value does not indicate an overbought or oversold market condition, no trade is taken, so the profit line is flat.

    Backtesting Results and Performance Summary

    • Signal-Based Strategy
      • 20-Day SMA Signal-Based Strategy: 154.04 🥈
      • 20-Day EMA Signal-Based Strategy: 168.56 🥇
    • Trend Following Strategies:
      • Short-term EMA crosses above the long-term EMA: 138.37
    • Mean Reversion Strategy:
      • Relative Strength Index (RSI): 146.82 🥉

    Based on the summary results provided above, it’s evident that the Signal-Based Strategy utilizing the 20-day EMA delivered the highest profitability. But is the 20-day lockback period the best period? In the section below I will describe strategy optimization and benchmarking.

    Strategy Optimization and Benchmarking

    Strategy Optimization

    Strategy optimization involves experimenting with various input parameter values during backtesting and then comparing the resulting outcomes. For instance, for signal-based strategy, is EMA 20-day, 30-day, or 40-day better?

    The Python code below compares the following three strategies:

    1. Initiates a long position when Google’s stock price surpasses the 20-day Simple Moving Average
    2. Initiates a long position when Google’s stock price surpasses the 30-day Simple Moving Average
    3. Initiates a long position when Google’s stock price surpasses the 50-day Simple Moving Average
    As seen in the chart, based on the backtest results, using the 50-day SMA was the best-performing strategy between 1/1/2020 and 7/31/2023

    Benchmarking

    Benchmarking in backtesting refers to comparing the performance of a trading or investment strategy against a benchmark or a reference point. The benchmark is typically a standard or widely recognized index, asset, or portfolio that represents a relevant market or asset class. By benchmarking a strategy, it is possible to assess how well it performs in comparison.

    For instance, the S&P 500 Index is often used as a benchmark for equities, while the U.S. Treasuries are used for measuring bond risks and returns.

    The Python code below shows the stock price if it was bought on 1/1/2020 and not sold, as a benchmark, and then compared to the three signal-trading strategies above (SMA 10, 30, and 50).

    As seen above, the results suggest that for the Google stock price of the selected time period, the active trading effort would not have paid off.

    Conclusion

    Backtesting, strategy optimization, and benchmarking are essential tools in the realm of investment and trading. They allow investors and traders to rigorously assess the performance of their strategies, refine them for better results, and compare them against established benchmarks.

    Backtesting serves as the foundation of strategy evaluation by simulating historical trading scenarios. It enables traders and investors to understand how their strategies would have performed in the past, providing a historical context for decision-making.

    Strategy optimization is the iterative process of fine-tuning a trading or investment strategy by adjusting its parameters or rules. Optimization aims to enhance a strategy’s risk-adjusted returns and overall effectiveness.

    Benchmarking allows investors and traders to put their strategies into context by comparing them to established benchmarks or reference points. These benchmarks represent the performance of passive investment strategies or market indices.

    In some cases, such as the one above, passive strategies such as investing and holding the stock can outperform active trading strategies.