A comprehensive trading algorithm that combines multiple strategies from academic research papers, implementing both traditional quantitative methods and machine learning approaches with an interactive dashboard.
This project implements and combines 11 different trading strategies from two academic papers:
- Trading Strategies for Equities (Part I) - Traditional quantitative strategies
- Trading Strategies with Machine Learning - ML-based approaches
The algorithm fetches real market data, applies all strategies, and combines their signals using weighted averaging to generate final trading decisions.
- Price Momentum - Trend-following based on historical price performance
- Earnings Momentum - Quarterly performance-based signals
- Low Volatility Anomaly - Risk-adjusted return optimization
- Implied Volatility - Volatility-based trading signals
- Pairs Trading - Statistical arbitrage between correlated assets
- Single Moving Average - Simple trend-following system
- Dual Moving Average - Crossover-based signals
- Triple Moving Average - Multi-timeframe trend confirmation
- KNN Trend Prediction - K-Nearest Neighbors for trend forecasting
- KNN Outlier Detection - Anomaly detection for contrarian signals
- Random Forest Classification - Ensemble learning for buy/sell signals
- Real-time Data Fetching via Yahoo Finance API
- Economic Data Integration via FRED API (optional)
- Interactive Dashboard with Plotly and Dash
- Performance Analytics with comprehensive metrics
- Backtesting Engine with risk-adjusted returns
Recent backtest results (2020-2024):
| Symbol | Total Return | Annualized Return | Sharpe Ratio | Max Drawdown |
|---|---|---|---|---|
| TSLA | 61.68% | 10.11% | 0.1902 | -70.71% |
| GOOGL | 30.83% | 5.54% | 0.2061 | -49.61% |
| AAPL | 10.85% | 2.09% | 0.0783 | -37.99% |
| MSFT | 8.98% | 1.74% | 0.0688 | -52.79% |
| AMZN | -7.68% | -1.59% | -0.0522 | -52.82% |
- Python 3.8+
- pip package manager
-
Clone or download the files:
# Files needed: # - combined_trading_algorithm.py # - run_trading_algo.py # - README.md
-
Install required packages:
pip3 install pandas numpy scikit-learn plotly dash yfinance fredapi matplotlib seaborn ta-lib dash-bootstrap-components
-
Install TA-Lib system dependency (macOS):
brew install ta-lib
For other systems, see TA-Lib installation guide.
python3 run_trading_algo.py- Data Fetching - Downloads 5 years of stock data for AAPL, MSFT, GOOGL, AMZN, TSLA
- Signal Generation - Calculates signals for all 11 strategies
- Performance Analysis - Computes comprehensive performance metrics
- Dashboard Launch - Opens interactive web interface at
http://127.0.0.1:8050
The interactive dashboard includes:
- Price Charts with buy/sell signal overlays
- Signal Timeline showing strategy decisions over time
- Performance Comparison vs Buy-and-Hold benchmark
- Strategy Analysis for individual strategy performance
- Performance Metrics (Sharpe ratio, max drawdown, etc.)
- Risk Analysis with volatility measurements
- Return Attribution by strategy
- Interactive Controls for strategy and symbol selection
Edit the symbols list in run_trading_algo.py:
symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA'] # Add your symbols hereModify the date range:
start_date = '2020-01-01'
end_date = '2024-12-31'Customize strategy weights in combined_trading_algorithm.py:
self.strategy_weights = {
'momentum': 0.15,
'earnings_momentum': 0.10,
'low_volatility': 0.10,
# ... adjust weights as desired
}Get a free FRED API key from FRED API and add it:
fred_api_key = "your_api_key_here"-
CombinedTradingAlgorithm - Main algorithm class
- Data fetching and preprocessing
- Strategy implementation
- Signal generation and combination
- Performance calculation
-
Strategy Methods - Individual strategy implementations
- Each strategy returns signals (-1, 0, 1)
- Signals are combined using weighted averaging
- Final signals trigger buy/sell/hold decisions
-
Dashboard - Interactive web interface
- Built with Plotly Dash
- Real-time chart updates
- Performance analytics
- Strategy comparison tools
Market Data โ Technical Indicators โ Individual Strategies โ Weighted Combination โ Final Signals โ Performance Analysis
- Price Momentum: Buys assets with positive 60-day momentum
- Earnings Momentum: Uses quarterly performance for signals
- Low Volatility: Favors low-volatility stocks (anomaly exploitation)
- Implied Volatility: Trades based on volatility mean reversion
- Moving Averages: Single, dual, and triple MA systems
- Pairs Trading: Statistical arbitrage between correlated assets
- KNN: Uses nearest neighbors for trend prediction and outlier detection
- Random Forest: Ensemble learning for classification-based signals
- Price: SMA, EMA, MACD, Bollinger Bands
- Momentum: RSI, Price Rate of Change
- Volatility: ATR, Historical Volatility
- Volume: Volume SMA, Volume Rate of Change
The algorithm calculates:
- Total Return - Cumulative strategy performance
- Annualized Return - Geometric mean annual return
- Sharpe Ratio - Risk-adjusted return measure
- Sortino Ratio - Downside risk-adjusted return
- Maximum Drawdown - Largest peak-to-trough decline
- Volatility - Annualized standard deviation of returns
- Trend Prediction: Classifies next-day price direction
- Outlier Detection: Identifies unusual market conditions
- Features: Returns, Volume, RSI, MACD
- Signal Classification: Predicts 5-day forward returns
- Feature Importance: Identifies key technical indicators
- Features: SMA, RSI, MACD, Volume, ATR
- Anomaly Detection: Clusters market regimes
- Outlier Identification: Flags unusual market states
- Position Sizing: Equal weight allocation
- Signal Normalization: Prevents extreme positions
- Volatility Adjustment: Risk-adjusted position sizing
- Drawdown Monitoring: Real-time risk metrics
- Real-time P&L: Live performance tracking
- Risk Metrics: Continuous risk assessment
- Strategy Attribution: Performance by strategy component
trading-algorithm/
โ
โโโ combined_trading_algorithm.py # Main algorithm implementation
โโโ run_trading_algo.py # Simple startup script
โโโ README.md # This file
โโโ Trading_Strategies_*.txt # Extracted PDF content (optional)
โโโ requirements.txt # Package dependencies (see installation)
- Real-time trading integration
- Additional ML models (LSTM, Transformer)
- Options and futures strategies
- Portfolio optimization
- Risk parity allocation
- Factor model integration
- Alternative data sources
- Sentiment analysis integration
- High-frequency strategies
- Multi-asset class support
- Advanced risk management
- Fork the repository
- Create a feature branch
- Implement your enhancement
- Add tests and documentation
- Submit a pull request
- New trading strategies
- Performance optimizations
- Additional data sources
- Enhanced visualizations
- Risk management features
This project is open source and available under the MIT License.
Based on academic research from:
- Trading Strategies for Equities (Part I) by Chenjie LI, Maxime LE FLOCH
- Trading Strategies with Machine Learning by Chenjie LI
- TA-Lib Installation: Follow system-specific installation guides
- API Limits: Yahoo Finance has rate limits; reduce frequency if needed
- Memory Usage: Large datasets may require optimization
- Dashboard Performance: Close browser tabs if dashboard is slow
- Check the Issues section for common problems
- Review the installation steps carefully
- Ensure all dependencies are properly installed
This software is for educational and research purposes only. It is not financial advice. Trading involves risk, and past performance does not guarantee future results. Always consult with qualified financial professionals before making investment decisions.
Happy Trading! ๐
Built with โค๏ธ for the quantitative finance community