A comprehensive machine learning-powered trading system with live market data integration, advanced risk management, and real-time monitoring capabilities.
- 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
- 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
- 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
- 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
- Performance Metrics: Comprehensive statistical analysis
- Benchmark Comparison: Compare against market indices
- Trade Analysis: Detailed trade-by-trade breakdown
- Visualization: Interactive charts and performance plots
- 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
- Python 3.8 or higher
- Internet connection for live market data
-
Clone or Download the Project
git clone <repository-url> cd ml-trading-system
-
Install Dependencies
pip install -r requirements.txt
-
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
-
Verify Installation
python test_system.py
python test_system.pyThis will validate all components with live market data.
streamlit run src/nifty50_trading_app.py- 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
- Navigate to "Advanced ML Models"
- Select a ticker symbol (e.g., AAPL, GOOGL, MSFT)
- Choose optimization method (Grid Search or Random Search)
- Select feature selection method
- Click "Train and Optimize Model"
- Review results and feature importance
- Go to "Live Trading" section
- Set initial capital and risk parameters
- Choose between:
- Manual Trading: Place orders manually
- ML-Driven Trading: Automated signals from trained models
- Monitor positions in real-time
- Review performance metrics
- Visit "Trading Simulation"
- Select symbols and date range
- Choose strategy type:
- Simple Moving Average
- ML-Enhanced Strategy
- Momentum Strategy
- Mean Reversion Strategy
- Configure parameters and run simulation
- Analyze results and performance metrics
- Access "Real-Time Dashboard"
- Monitor risk metrics:
- Portfolio VaR and CVaR
- Position concentrations
- Drawdown analysis
- Review risk alerts and recommendations
- Adjust position sizes based on risk limits
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 drawdownAdjust 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- 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)
Simply enter the ticker symbol in any interface - the system will automatically fetch data if available.
python test_system.py# 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()"- This system is designed for paper trading and educational purposes
- No real money transactions are executed
- All trades are simulated using live market data
- 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
- 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
-
Import Errors
# Ensure all dependencies are installed pip install -r requirements.txt -
Data Fetch Failures
- Check internet connection
- Verify ticker symbols are valid
- Some symbols may not be available on Yahoo Finance
-
TA-Lib Installation Issues
- Follow platform-specific installation instructions above
- Some features may work without TA-Lib but with reduced functionality
-
Performance Issues
- Reduce the number of symbols being processed
- Decrease the historical data range
- Close unused browser tabs when running Streamlit
- Check the error messages in the terminal
- Run
python test_system.pyto identify specific issues - Verify all dependencies are correctly installed
- Ensure you have a stable internet connection
- 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
This project is for educational and research purposes. Please ensure compliance with all applicable financial regulations in your jurisdiction.
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.
The project is organized into multiple files for better maintainability:
main.py- Entry point for the ML trading systemdata_loader.py- Functions for loading and preprocessing stock datafeature_engineering.py- Feature selection and correlation analysisensemble_models.py- Custom stacked ensemble model implementationmodel_builder.py- Functions for building and training various ML modelsvisualization.py- Visualization utilities for model performance and feature importancerequirements.txt- Required dependencies
Install the required dependencies:
pip install -r requirements.txtRun the main script to execute the complete ML trading pipeline:
python main.pyThe script will:
- Load historical stock data from Yahoo Finance
- Analyze feature correlations
- Build and train multiple ML models
- Evaluate model performance
- Analyze feature importance
- Make predictions with the best-performing model
- 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
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.