A comprehensive, modular algorithmic trading system with machine learning integration, advanced technical analysis, and robust risk management capabilities.
This repository contains a progressive evolution of algorithmic trading systems, from simple implementations to a fully-featured trading bot with ML capabilities, live trading support, and comprehensive backtesting.
- Version 1: Basic trading logic without API integration
- Version 2: API integration (Alpaca)
- Version 3: Enhanced features with error handling
- Version 4: Modular architecture with dependencies
- Version 4WD: Production-ready system with full functionality ✨ (Current)
- 🎯 Multiple Trading Strategies: Momentum breakout, mean reversion, trend following, and breakout strategies
- 🤖 Machine Learning Integration: Gradient boosting for price direction prediction
- 📊 Advanced Technical Analysis: 25+ indicators with TA-Lib support
- 💰 Live Trading: Alpaca API integration with paper and live trading modes
- 📈 Backtesting Engine: Historical strategy validation with detailed analytics
- 🔄 Simulation Mode: Risk-free testing with real market data
- 📉 Dynamic Position Sizing: Kelly Criterion and volatility-based sizing
- 🛡️ Stop Loss Protection: ATR-based and percentage-based stops
- 📊 Portfolio Heat Monitoring: Drawdown protection and exposure limits
⚠️ Daily Loss Limits: Automatic trading suspension on excessive losses- 🎲 Correlation Management: Avoid overconcentration in correlated assets
- 🏗️ Modular Architecture: Clean separation of concerns
- 📝 Comprehensive Logging: Detailed trade and performance logging
- 📊 Performance Reporting: Real-time metrics and exportable reports
- 🔧 Configurable Settings: Easy customization via config files
- 🐛 Error Handling: Robust fallbacks and graceful degradation
# Python 3.8 or higher
python --version
# Clone or download this repository
git clone https://github.com/The-Align-Project/Trading-Algorithm.git
cd "Algorithmic Trading"# Navigate to the working version
cd "Version 4WD (Working Dependencies)"
# Install required dependencies
pip install pandas numpy
# Install optional dependencies for full features
pip install yfinance scikit-learn scipy alpaca-trade-api
# Install TA-Lib (optional, for advanced indicators)
# macOS:
brew install ta-lib && pip install TA-Lib
# Windows: Download from https://www.lfd.uci.edu/~gohlke/pythonlibs/
# Linux:
sudo apt-get install libta-lib-dev && pip install TA-Lib# Start the trading system
python main.py
# Run demo mode
python main.py --demo
# Show help
python main.py --helpAlgorithmic Trading/
├── Version 1 (No API)/ # Initial implementation
├── Version 2 (API)/ # API integration
├── Version 2E (Error API)/ # Error handling improvements
├── Version 2FW (Fully Working API)/ # Stable API version
├── Version 3E (Error API)/ # Enhanced features
├── Version 4 (Dependencies)/ # Modular architecture
└── Version 4WD (Working Dependencies)/ ⭐ CURRENT VERSION
├── main.py # Main entry point
├── config.py # Configuration and settings
├── trading_engine.py # Core trading logic
├── strategies.py # Trading strategies
├── indicators.py # Technical indicators
├── ml_predictor.py # ML prediction model
├── risk_manager.py # Risk management
├── portfolio_manager.py # Portfolio tracking
├── data_fetcher.py # Market data retrieval
├── backtester.py # Backtesting engine
├── requirements.txt # Python dependencies
├── README.md # Detailed documentation
├── QUICK_START.md # Quick start guide
├── BUG_FIX_REPORT.md # Recent fixes
├── logs/ # Log files
└── results/ # Trading results
├── backtest/ # Backtest results
├── live/ # Live trading results
└── simulations/ # Simulation results
python main.py
# Select: 2 (Simulation Mode)
# Choose watchlist: 1 (Tech Stocks)- Uses real market data
- Simulated order execution
- No API credentials required
- Perfect for learning and testing
python main.py
# Select: 1 (Live Trading)
# Enter Alpaca API credentials- Connects to Alpaca API
- Paper trading or live trading
- Real-time market data
- Actual order execution
python main.py
# Select: 3 (Backtest Mode)- Historical strategy testing
- Performance analytics
- Strategy optimization
- Export detailed reports
- Identifies strong trending moves with volume confirmation
- Uses RSI, MACD, and moving average alignment
- ML prediction integration for directional confidence
- Dynamic stop loss (2x ATR) and take profit (3x ATR)
- Trades oversold/overbought conditions
- RSI + Bollinger Band signals
- Works best in ranging markets
- Targets return to mean prices
- Follows established market trends
- Multiple timeframe confirmation
- Pullback entries for better risk/reward
- Trend strength filtering
- Bollinger Band expansion breakouts
- Volume spike confirmation
- Volatility expansion filter
- Quick profit-taking on momentum
- Combines signals from all strategies
- Weighted by confidence scores
- Reduces false signals
- Improved risk-adjusted returns
- Algorithm: Gradient Boosting Classifier
- Features: 20+ technical indicators and price patterns
- Target: Next-day price direction (up/down)
- Retraining: Automatic on new data
- Technical indicator values (RSI, MACD, BB)
- Price ratios and momentum
- Volume patterns and volatility
- Lagged price and volume data
# In config.py - TradingConfig class
MAX_POSITION_SIZE = 0.1 # Max 10% per position
MAX_DAILY_LOSS = 0.02 # Max 2% daily loss
MAX_DRAWDOWN = 0.15 # Max 15% drawdown
MIN_CONFIDENCE = 0.6 # Minimum signal confidence (60%)
MAX_EXECUTIONS_PER_ITERATION = 5 # Limit trades per cyclePre-configured symbol lists in config.py:
- Tech: AAPL, MSFT, GOOGL, TSLA, NVDA
- Blue Chips: AAPL, MSFT, JNJ, PG, KO
- Growth: TSLA, NVDA, AMD, CRM, NFLX
- Check Interval: 300 seconds (5 minutes) default
- Initial Capital: $100,000 default
- Commission: $0 default (configurable)
- Total Return: Portfolio appreciation percentage
- Win Rate: Percentage of profitable trades
- Profit Factor: Gross profits ÷ gross losses
- Sharpe Ratio: Risk-adjusted returns
- Maximum Drawdown: Largest peak-to-trough decline
- Average Trade: Mean profit/loss per trade
- Real-time console output
- Timestamped performance reports
- Trade-by-trade logging
- Strategy performance breakdown
- Exportable CSV and text reports
Edit strategies.py to add your own trading logic:
def my_custom_strategy(self, data: pd.DataFrame) -> TradeSignal:
# Your strategy logic here
if buy_condition:
return TradeSignal(
symbol=symbol,
action="BUY",
confidence=0.8,
price=current_price,
quantity=0
)
return TradeSignal(symbol, "HOLD", 0.0, current_price, 0)Edit indicators.py to create new technical indicators:
@staticmethod
def my_indicator(data: pd.Series, window: int = 14):
# Your indicator calculation
return resultpython main.py
# Select: 3 (Backtest Mode)
# Configure symbols and date range
# Review results in results/backtest/- Sign up at Alpaca Markets
- Get Paper Trading API credentials
- Run in Live Trading mode with paper credentials
- Monitor performance in real-time
- Past performance does not guarantee future results
- All trading involves risk of loss
- You may lose some or all of your invested capital
- No strategy works in all market conditions
- ✅ Start with paper trading
- ✅ Test strategies thoroughly via backtesting
- ✅ Begin with small position sizes
- ✅ Monitor the system regularly
- ✅ Never risk more than you can afford to lose
- ✅ Understand the strategies you're using
- ✅ Comply with all applicable regulations
- System failures can impact trading
- Network connectivity issues may occur
- API rate limits may apply
- Data feed interruptions are possible
Import Errors
pip install -r requirements.txtNo Data Available
- Check internet connection
- Verify symbol names are correct
- Try different date ranges or symbols
Alpaca API Issues
- Verify API credentials
- Check if market is open
- Ensure sufficient buying power
TA-Lib Installation
- Windows: Download pre-built wheel
- macOS: Install via Homebrew first
- Linux: Install libta-lib-dev package
Enable detailed logging in config.py:
logging.basicConfig(level=logging.DEBUG)pandas- Data manipulationnumpy- Numerical computations
yfinance- Real market datascikit-learn- Machine learningscipy- Statistical functionsTA-Lib- Advanced technical indicatorsalpaca-trade-api- Live trading
The system automatically detects available packages and adapts accordingly.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Update documentation
- Submit a pull request
- Follow existing code style
- Add docstrings to functions
- Include error handling
- Update README for new features
This project is licensed under the MIT License - see the LICENSE file for details.
Important: This software is for educational purposes only. Users are responsible for:
- Compliance with financial regulations
- Understanding trading risks
- Proper testing before live trading
- Their own financial decisions
- Built with Python and open-source libraries
- Alpaca Markets for trading API
- TA-Lib for technical indicators
- scikit-learn for machine learning
- 📖 Read the detailed documentation
- 🚀 Check the Quick Start Guide
- 🐛 Review Bug Fix Reports
- 💬 Submit issues via GitHub
- Additional trading strategies
- Enhanced ML models (LSTM, Transformer)
- Multi-asset support (crypto, forex)
- Web dashboard for monitoring
- Advanced portfolio optimization
- Sentiment analysis integration
- Options trading support
⚡ Current Version: 4WD (Working Dependencies)
📅 Last Updated: October 2025
👨💻 Maintained by: The Align Project
Happy Trading! 🚀📈
Remember: The best strategy is the one you understand completely and can execute consistently with proper risk management.