Skip to content

realBravo/combined-trading-algo

Repository files navigation

๐Ÿš€ Combined Trading Algorithm

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.

๐Ÿ“Š Overview

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.

๐ŸŽฏ Features

Trading Strategies Implemented

Traditional Strategies (from Equities PDF)

  • 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

Machine Learning Strategies (from ML PDF)

  • 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

Technical Features

  • 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

๐Ÿ“ˆ Performance Results

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%

๐Ÿ› ๏ธ Installation

Prerequisites

  • Python 3.8+
  • pip package manager

Quick Setup

  1. Clone or download the files:

    # Files needed:
    # - combined_trading_algorithm.py
    # - run_trading_algo.py
    # - README.md
  2. Install required packages:

    pip3 install pandas numpy scikit-learn plotly dash yfinance fredapi matplotlib seaborn ta-lib dash-bootstrap-components
  3. Install TA-Lib system dependency (macOS):

    brew install ta-lib

    For other systems, see TA-Lib installation guide.

๐Ÿš€ Quick Start

Basic Usage

python3 run_trading_algo.py

What Happens:

  1. Data Fetching - Downloads 5 years of stock data for AAPL, MSFT, GOOGL, AMZN, TSLA
  2. Signal Generation - Calculates signals for all 11 strategies
  3. Performance Analysis - Computes comprehensive performance metrics
  4. Dashboard Launch - Opens interactive web interface at http://127.0.0.1:8050

๐Ÿ“Š Dashboard Features

The interactive dashboard includes:

๐ŸŽจ Visualizations

  • 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

๐Ÿ“ˆ Analytics

  • Performance Metrics (Sharpe ratio, max drawdown, etc.)
  • Risk Analysis with volatility measurements
  • Return Attribution by strategy
  • Interactive Controls for strategy and symbol selection

โš™๏ธ Configuration

Customizing Symbols

Edit the symbols list in run_trading_algo.py:

symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']  # Add your symbols here

Adjusting Date Range

Modify the date range:

start_date = '2020-01-01'
end_date = '2024-12-31'

Strategy Weights

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
}

Adding Economic Data

Get a free FRED API key from FRED API and add it:

fred_api_key = "your_api_key_here"

๐Ÿ—๏ธ Architecture

Core Components

  1. CombinedTradingAlgorithm - Main algorithm class

    • Data fetching and preprocessing
    • Strategy implementation
    • Signal generation and combination
    • Performance calculation
  2. 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
  3. Dashboard - Interactive web interface

    • Built with Plotly Dash
    • Real-time chart updates
    • Performance analytics
    • Strategy comparison tools

Signal Flow

Market Data โ†’ Technical Indicators โ†’ Individual Strategies โ†’ Weighted Combination โ†’ Final Signals โ†’ Performance Analysis

๐Ÿ“š Strategy Details

Momentum Strategies

  • Price Momentum: Buys assets with positive 60-day momentum
  • Earnings Momentum: Uses quarterly performance for signals

Volatility Strategies

  • Low Volatility: Favors low-volatility stocks (anomaly exploitation)
  • Implied Volatility: Trades based on volatility mean reversion

Technical Analysis

  • Moving Averages: Single, dual, and triple MA systems
  • Pairs Trading: Statistical arbitrage between correlated assets

Machine Learning

  • KNN: Uses nearest neighbors for trend prediction and outlier detection
  • Random Forest: Ensemble learning for classification-based signals

๐Ÿ”ง Technical Indicators Used

  • Price: SMA, EMA, MACD, Bollinger Bands
  • Momentum: RSI, Price Rate of Change
  • Volatility: ATR, Historical Volatility
  • Volume: Volume SMA, Volume Rate of Change

๐Ÿ“Š Performance Metrics

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

๐Ÿค– Machine Learning Features

K-Nearest Neighbors (KNN)

  • Trend Prediction: Classifies next-day price direction
  • Outlier Detection: Identifies unusual market conditions
  • Features: Returns, Volume, RSI, MACD

Random Forest

  • Signal Classification: Predicts 5-day forward returns
  • Feature Importance: Identifies key technical indicators
  • Features: SMA, RSI, MACD, Volume, ATR

DBSCAN Clustering

  • Anomaly Detection: Clusters market regimes
  • Outlier Identification: Flags unusual market states

๐Ÿšจ Risk Management

Built-in Risk Controls

  • Position Sizing: Equal weight allocation
  • Signal Normalization: Prevents extreme positions
  • Volatility Adjustment: Risk-adjusted position sizing
  • Drawdown Monitoring: Real-time risk metrics

Performance Monitoring

  • Real-time P&L: Live performance tracking
  • Risk Metrics: Continuous risk assessment
  • Strategy Attribution: Performance by strategy component

๐Ÿ“ File Structure

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)

๐Ÿ”ฎ Future Enhancements

Planned Features

  • Real-time trading integration
  • Additional ML models (LSTM, Transformer)
  • Options and futures strategies
  • Portfolio optimization
  • Risk parity allocation
  • Factor model integration

Potential Improvements

  • Alternative data sources
  • Sentiment analysis integration
  • High-frequency strategies
  • Multi-asset class support
  • Advanced risk management

๐Ÿค Contributing

How to Contribute

  1. Fork the repository
  2. Create a feature branch
  3. Implement your enhancement
  4. Add tests and documentation
  5. Submit a pull request

Areas for Contribution

  • New trading strategies
  • Performance optimizations
  • Additional data sources
  • Enhanced visualizations
  • Risk management features

๐Ÿ“„ License

This project is open source and available under the MIT License.

๐Ÿ™ Acknowledgments

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

๐Ÿ“ž Support

Common Issues

  1. TA-Lib Installation: Follow system-specific installation guides
  2. API Limits: Yahoo Finance has rate limits; reduce frequency if needed
  3. Memory Usage: Large datasets may require optimization
  4. Dashboard Performance: Close browser tabs if dashboard is slow

Getting Help

  • Check the Issues section for common problems
  • Review the installation steps carefully
  • Ensure all dependencies are properly installed

๐ŸŽฏ Disclaimer

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages