Overview
This Python script is designed to backtest a trading strategy based on the Moving Average Convergence/Divergence (MACD) and the Stochastic Oscillator technical indicators. It connects to the Interactive Brokers (IB) API to fetch historical data, computes the technical indicators, 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 5 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:
- Technical Indicator Calculation:
- MACD (Moving Average Convergence Divergence):
- Calculates the 12-period and 26-period EMAs.
- Computes the MACD line and the 9-period signal line.
- Stochastic Oscillator:
- Calculates the 14-period low and high.
- Computes the %K and %D lines.
- MACD (Moving Average Convergence Divergence):
- Generates buy signals when the MACD line crosses above the signal line, and %K is above 30 and rising.
- Closes position when the MACD line crosses below the signal line.
- 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.
- Technical Indicator Calculation:
- 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.
- For this same strategy that took into account commission fees, click here
- Sample Limitation: The strategy was tested on the top 5 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) 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, this MACD + Stochastic strategy demonstrates promise for certain stocks, but it is essential to remain vigilant about its limitations and continuously seek improvements. By incorporating commission fees, 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!