Skip to content

jsjgdh/ml-trading

Repository files navigation

๐Ÿš€ Advanced ML Trading System

A comprehensive machine learning-powered trading system with live market data integration, advanced risk management, and real-time monitoring capabilities.

๐ŸŒŸ Features

๐Ÿค– Advanced ML Optimization

  • Hyperparameter Tuning: Grid Search and Randomized Search optimization
  • Feature Selection: Univariate and Recursive Feature Elimination (RFE)
  • Ensemble Models: Voting and Stacking classifiers with multiple algorithms
  • Model Types: Random Forest, XGBoost, LightGBM, Gradient Boosting, Ridge, ElasticNet, SVR, MLP

๐Ÿ’ฐ Live Trading Engine

  • Paper Trading: Risk-free testing with real market data
  • Live Market Data: Real-time price feeds via Yahoo Finance
  • Order Management: Market and limit order simulation
  • Portfolio Tracking: Real-time position and P&L monitoring
  • Database Integration: SQLite for trade and portfolio history

๐Ÿ›ก๏ธ Risk Management

  • Position Sizing: Kelly Criterion, Volatility Targeting, Risk Parity
  • Risk Metrics: VaR, CVaR, Sharpe Ratio, Sortino Ratio, Maximum Drawdown
  • Volatility Estimation: EWMA, GARCH, Realized Volatility
  • Risk Alerts: Real-time monitoring and limit checking

๐Ÿ“ˆ Enhanced Trading Strategies

  • ML-Enhanced Signals: Machine learning-driven trade signals
  • Technical Indicators: 15+ technical analysis indicators
  • Multi-Strategy Aggregation: Combine multiple strategy signals
  • Momentum & Mean Reversion: Classic trading strategies with ML enhancement

๐Ÿ“Š Advanced Backtesting

  • Performance Metrics: Comprehensive statistical analysis
  • Benchmark Comparison: Compare against market indices
  • Trade Analysis: Detailed trade-by-trade breakdown
  • Visualization: Interactive charts and performance plots

๐ŸŽฏ Real-Time Dashboard

  • Live Monitoring: Real-time portfolio and market data
  • Performance Charts: Interactive Plotly visualizations
  • Risk Analytics: Live risk metrics and alerts
  • Trade Management: Manual and automated trading controls

๐Ÿ› ๏ธ Installation

Prerequisites

  • Python 3.8 or higher
  • Internet connection for live market data

Setup Instructions

  1. Clone or Download the Project

    git clone <repository-url>
    cd ml-trading-system
  2. Install Dependencies

    pip install -r requirements.txt
  3. Install TA-Lib (Optional but Recommended)

    Windows:

    # Download TA-Lib wheel from: https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib
    pip install TA_Lib-0.4.24-cp39-cp39-win_amd64.whl  # Adjust for your Python version

    macOS:

    brew install ta-lib
    pip install TA-Lib

    Linux:

    sudo apt-get install libta-lib-dev
    pip install TA-Lib
  4. Verify Installation

    python test_system.py

๐Ÿš€ Quick Start

1. Run System Tests

python test_system.py

This will validate all components with live market data.

2. Launch the Application

streamlit run src/nifty50_trading_app.py

3. Navigate the Interface

  • Home: Overview and system status
  • Advanced ML Models: Train and optimize ML models
  • Live Trading: Paper trading with real market data
  • Trading Simulation: Backtest strategies
  • Performance Dashboard: Analyze results
  • Real-Time Dashboard: Monitor live trading

๐Ÿ“‹ Usage Guide

Training ML Models

  1. Navigate to "Advanced ML Models"
  2. Select a ticker symbol (e.g., AAPL, GOOGL, MSFT)
  3. Choose optimization method (Grid Search or Random Search)
  4. Select feature selection method
  5. Click "Train and Optimize Model"
  6. Review results and feature importance

Paper Trading

  1. Go to "Live Trading" section
  2. Set initial capital and risk parameters
  3. Choose between:
    • Manual Trading: Place orders manually
    • ML-Driven Trading: Automated signals from trained models
  4. Monitor positions in real-time
  5. Review performance metrics

Backtesting Strategies

  1. Visit "Trading Simulation"
  2. Select symbols and date range
  3. Choose strategy type:
    • Simple Moving Average
    • ML-Enhanced Strategy
    • Momentum Strategy
    • Mean Reversion Strategy
  4. Configure parameters and run simulation
  5. Analyze results and performance metrics

Risk Management

  1. Access "Real-Time Dashboard"
  2. Monitor risk metrics:
    • Portfolio VaR and CVaR
    • Position concentrations
    • Drawdown analysis
  3. Review risk alerts and recommendations
  4. Adjust position sizes based on risk limits

๐Ÿ”ง Configuration

Risk Parameters

Edit risk settings in the dashboard or modify default values in src/risk_management.py:

# Default risk limits
MAX_POSITION_SIZE = 0.1  # 10% of portfolio
MAX_PORTFOLIO_VAR = 0.05  # 5% daily VaR
MAX_DRAWDOWN = 0.2  # 20% maximum drawdown

Trading Parameters

Adjust trading settings in src/live_trading_engine.py:

# Default trading parameters
DEFAULT_COMMISSION = 0.001  # 0.1% commission
DEFAULT_SLIPPAGE = 0.0005   # 0.05% slippage
MIN_ORDER_SIZE = 100        # Minimum order value

๐Ÿ“Š Supported Assets

Current Support

  • US Stocks: All stocks available on Yahoo Finance
  • Major Indices: S&P 500, NASDAQ, Dow Jones
  • ETFs: Most major ETFs
  • Crypto: Bitcoin, Ethereum (via Yahoo Finance)

Adding New Assets

Simply enter the ticker symbol in any interface - the system will automatically fetch data if available.

๐Ÿงช Testing

Comprehensive System Test

python test_system.py

Individual Component Tests

# Test ML optimization
python -c "from test_system import SystemTester; SystemTester().test_ml_optimization()"

# Test live trading
python -c "from test_system import SystemTester; SystemTester().test_live_trading_engine()"

# Test risk management
python -c "from test_system import SystemTester; SystemTester().test_risk_management()"

๐Ÿšจ Important Notes

Paper Trading Only

  • This system is designed for paper trading and educational purposes
  • No real money transactions are executed
  • All trades are simulated using live market data

Data Limitations

  • Market data is sourced from Yahoo Finance (free tier)
  • Real-time data may have 15-20 minute delays
  • For production trading, consider premium data providers

Risk Disclaimer

  • Past performance does not guarantee future results
  • All trading involves risk of loss
  • This software is for educational and research purposes only
  • Always consult with financial professionals before making investment decisions

๐Ÿ› ๏ธ Troubleshooting

Common Issues

  1. Import Errors

    # Ensure all dependencies are installed
    pip install -r requirements.txt
  2. Data Fetch Failures

    • Check internet connection
    • Verify ticker symbols are valid
    • Some symbols may not be available on Yahoo Finance
  3. TA-Lib Installation Issues

    • Follow platform-specific installation instructions above
    • Some features may work without TA-Lib but with reduced functionality
  4. Performance Issues

    • Reduce the number of symbols being processed
    • Decrease the historical data range
    • Close unused browser tabs when running Streamlit

Getting Help

  1. Check the error messages in the terminal
  2. Run python test_system.py to identify specific issues
  3. Verify all dependencies are correctly installed
  4. Ensure you have a stable internet connection

๐Ÿ”ฎ Future Enhancements

  • Real Broker Integration: Connect to real trading APIs
  • Advanced ML Models: Deep learning and reinforcement learning
  • Alternative Data: News sentiment, social media analysis
  • Multi-Asset Support: Forex, commodities, bonds
  • Cloud Deployment: AWS/GCP deployment options
  • Mobile App: React Native mobile interface

๐Ÿ“„ License

This project is for educational and research purposes. Please ensure compliance with all applicable financial regulations in your jurisdiction.

๐Ÿค Contributing

Contributions are welcome! Please ensure all new features include appropriate tests and documentation.


Happy Trading! ๐Ÿ“ˆ๐Ÿš€

Remember: This is a paper trading system for educational purposes. Always practice proper risk management and never invest more than you can afford to lose.

Project Structure

The project is organized into multiple files for better maintainability:

  • main.py - Entry point for the ML trading system
  • data_loader.py - Functions for loading and preprocessing stock data
  • feature_engineering.py - Feature selection and correlation analysis
  • ensemble_models.py - Custom stacked ensemble model implementation
  • model_builder.py - Functions for building and training various ML models
  • visualization.py - Visualization utilities for model performance and feature importance
  • requirements.txt - Required dependencies

Installation

Install the required dependencies:

pip install -r requirements.txt

Usage

Run the main script to execute the complete ML trading pipeline:

python main.py

The script will:

  1. Load historical stock data from Yahoo Finance
  2. Analyze feature correlations
  3. Build and train multiple ML models
  4. Evaluate model performance
  5. Analyze feature importance
  6. Make predictions with the best-performing model

Features

  • Data Loading: Fetches real-time stock data with economic indicators
  • Feature Engineering: Calculates technical indicators and selects the most important features
  • Model Training: Implements multiple ML models including:
    • Linear models (Linear Regression, Ridge, Elastic Net)
    • Tree-based models (Random Forest, Gradient Boosting, XGBoost, LightGBM)
    • Neural Networks
    • Time Series models (ARIMA)
    • Custom Stacked Ensemble
  • Visualization: Provides visualizations for model performance and feature importance

Customization

You can customize the stock ticker and time period when running the script. The default is set to TCS.NS (Tata Consultancy Services) with 8 years of historical data.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages