Overview
This Python script is designed to backtest a simple moving average crossover strategy. It connects to the Interactive Brokers (IB) API to fetch historical data, computes technical indicators (SMA and EMA), executes the trading strategy and evaluates its performance using key financial metrics.
Main Script

- Initialisation:
- Connects to the IB API.
- Starts a thread for the WebSocket connection.
- Data Retrieval:
- Loops through the list of top 10 US companies by market capitalization, requesting historical data for each stock.
- Uses a 1-year period (01/06/2023 – 01/06/2024) with 30-minute bars, requesting trades data during regular trading hours.
- Backtesting:
- Iterates through each stock’s data, computing the EMA (9-period) and SMA (20-period).
- Generates buy/sell signals based on the crossover strategy (EMA9 > SMA20 indicates a buy, EMA9 < SMA20 indicates a sell).
- When crossover is detected, position is changed at the next candle’s opening price.
- Calculates the position, entry price, profit and loss (PnL), and cumulative PnL.
- Computes additional metrics: Sharpe ratio, max drawdown, number of trades, win rate, mean return per trade, mean returns of winning and losing trades.
- Visualisation:
- Plots the cumulative returns of the buy-and-hold strategy against the algorithmic trading strategy.
- Annotates the plot with performance metrics.
Final Thoughts
Key Considerations
- Commission and Slippage: This backtesting strategy did not account for transaction costs such as commissions and slippage. These factors can significantly reduce the overall profitability, especially in strategies with a high number of trades. It is essential to factor in these costs for a more realistic assessment of the strategy’s performance.
- Sample Limitation: The strategy was tested on the top 10 US companies by market capitalization. While this provides insights into its performance on large-cap stocks, it may not be representative of other stocks, including mid-cap and small-cap companies. Broader testing across different stock categories and sectors is recommended for a more comprehensive evaluation.
- Flexibility and Adaptability: The provided code is designed to be flexible and can be easily adapted to test different stocks of your choice. Experimenting with various timeframes and durations can help refine the strategy further. It’s also advisable to test the strategy under different market conditions to gauge its robustness.
Future Research Directions
- Alternative Indicators: Exploring other technical indicators, such as the Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), or Bollinger Bands, could potentially enhance the strategy’s performance.
- Combined Strategies: Combining multiple strategies might offer better results by capturing different market dynamics. For example, integrating momentum-based strategies with mean-reversion approaches can provide a balanced approach.
- Live Testing and Real-Time Adjustments: While backtesting provides valuable historical insights, live testing in real market conditions is crucial for validating the strategy’s effectiveness. Real-time adjustments based on market feedback can further optimise performance.
Conclusion
In conclusion, the EMA9 and SMA20 crossover strategy demonstrates promise for certain stocks, but it is essential to remain vigilant about its limitations and continuously seek improvements. By incorporating transaction costs, broadening the sample, and exploring new strategies, traders can enhance their overall trading framework. Continual learning and adaptation are key to achieving long-term success in trading.
By following these guidelines and using the provided code, traders can tailor the strategy to their needs and adapt it to different market scenarios for better outcomes.
Feel free to use the codes shared for your own tickers!