AI trading system with real-time data processing, machine learning models, risk management, and automated execution capabilities.
- Real-time Data Ingestion: Multi-source market data collection (Yahoo Finance, Alpaca, News APIs)
- Advanced ML Models: LSTM, Transformer, and ensemble models for price prediction
- Risk Management: VaR calculation, stress testing, portfolio diversification
- Portfolio Management: Automated position sizing, trade execution, performance tracking
- Backtesting Framework: Historical strategy validation with realistic conditions
- REST API: Complete API for system integration and monitoring
- Monitoring & Logging: Comprehensive system monitoring with Prometheus metrics
- β Multi-asset trading (stocks, ETFs, indices)
- β Real-time signal generation and execution
- β Advanced risk controls and position management
- β Comprehensive backtesting with transaction costs
- β Production-ready monitoring and alerting
- β Scalable architecture for high-frequency trading
ai_trading_system/
βββ main.py # Main entry point
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ ai_trading_system_design.md # Detailed system design
βββ TODO.md # Development tasks
βββ core/ # Core trading engine
β βββ engine.py # Main trading orchestrator
β βββ __init__.py
βββ data/ # Data ingestion layer
β βββ manager.py # Market data collection
β βββ __init__.py
βββ models/ # ML prediction models
β βββ predictor.py # Price prediction models
β βββ __init__.py
βββ risk_management/ # Risk assessment
β βββ manager.py # VaR and risk controls
β βββ __init__.py
βββ portfolio/ # Portfolio management
β βββ manager.py # Position and execution
β βββ __init__.py
βββ backtesting/ # Strategy validation
β βββ engine.py # Backtesting framework
β βββ __init__.py
βββ api/ # REST API layer
β βββ app.py # FastAPI application
β βββ __init__.py
βββ utils/ # Utilities
β βββ logging_config.py # Structured logging
β βββ monitoring.py # System monitoring
β βββ __init__.py
βββ config/ # Configuration
β βββ settings.toml # System settings
β βββ __init__.py
βββ tests/ # Test suite
βββ __init__.py
- Python 3.8+
- Git
- Redis (optional, for caching)
- Alpaca/Polygon account (for live trading)
-
Clone the repository
git clone <repository-url> cd ai_trading_system
-
Create virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\\Scripts\\activate
-
Install dependencies
pip install -r requirements.txt
-
Configure settings
# Copy and edit configuration cp ai_trading_system/config/settings.toml.example ai_trading_system/config/settings.toml # Edit with your API keys and preferences
-
Set environment variables (optional)
export ALPACA_API_KEY="your-api-key" export ALPACA_API_SECRET="your-api-secret" export DATABASE_URL="your-database-url"
python -m ai_trading_system.main --mode api --port 8000The API will be available at http://localhost:8000 with:
- Interactive Docs:
http://localhost:8000/docs - Health Check:
http://localhost:8000/health - Portfolio:
http://localhost:8000/portfolio - Trading Signals:
http://localhost:8000/signals
python -m ai_trading_system.main --mode tradingpython -m ai_trading_system.main --mode api --reloadcurl http://localhost:8000/statuscurl -X POST "http://localhost:8000/trade" \
-H "Content-Type: application/json" \
-d '{
"symbol": "AAPL",
"action": "buy",
"quantity": 100,
"price_target": 150.0
}'curl -X POST "http://localhost:8000/backtest" \
-H "Content-Type: application/json" \
-d '{
"symbols": ["AAPL", "MSFT", "GOOGL"],
"start_date": "2023-01-01T00:00:00",
"end_date": "2023-12-31T23:59:59",
"strategy_name": "momentum",
"initial_capital": 100000
}'curl http://localhost:8000/portfolio[system]
name = "AI Trading System"
environment = "development" # development, staging, production
log_level = "INFO"
[trading]
max_positions = 50
max_position_size = 0.05 # 5% of portfolio
min_trade_size = 1000 # $1000 minimum
[risk]
max_var = 0.02 # 2% daily VaR limit
stop_loss_pct = 0.05 # 5% stop loss
take_profit_pct = 0.15 # 15% take profit
[models]
prediction_horizon = 24 # hours
retrain_interval = 168 # hours (1 week)
[api]
host = "0.0.0.0"
port = 8000
workers = 4
[alpaca]
api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"
base_url = "https://paper-api.alpaca.markets" # Paper trading- Prometheus Metrics: Available at
http://localhost:8000/metrics - Health Checks:
http://localhost:8000/health - Structured Logging: All events logged with context
- Performance Tracking: Response times, throughput, error rates
- Portfolio value and performance
- Trading signal accuracy
- System resource usage
- API response times
- Error rates and alerts
- Momentum: Buy when price > moving average
- Mean Reversion: Buy when RSI < 30, sell when RSI > 70
import requests
response = requests.post("http://localhost:8000/backtest", json={
"symbols": ["AAPL", "MSFT"],
"start_date": "2023-01-01T00:00:00",
"end_date": "2023-12-31T23:59:59",
"strategy_name": "momentum",
"initial_capital": 100000
})
results = response.json()
print(f"Total Return: {results['total_return']:.2%}")- Value at Risk (VaR): 2% daily limit
- Position Limits: Maximum 5% per position
- Stop Losses: Automatic 5% stop loss
- Diversification: Sector and asset class limits
- Stress Testing: Market crash scenario analysis
- Sharpe ratio optimization
- Maximum drawdown tracking
- Portfolio correlation analysis
- Real-time risk monitoring
- LSTM Networks: Time series price prediction
- Transformers: Multi-horizon forecasting
- XGBoost: Ensemble price movement prediction
- Random Forest: Feature importance analysis
# Train models via API
requests.post("http://localhost:8000/models/train", json={
"symbols": ["AAPL", "MSFT", "GOOGL"]
})| Method | Endpoint | Description |
|---|---|---|
| GET | / |
API information |
| GET | /health |
Health check |
| GET | /status |
System status |
| GET | /portfolio |
Portfolio information |
| POST | /trade |
Execute trade |
| POST | /backtest |
Run backtest |
| GET | /signals |
Current signals |
| GET | /market-data |
Market data |
| POST | /models/train |
Train models |
| GET | /performance |
Performance metrics |
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "-m", "ai_trading_system.main", "--mode", "api"]# Production environment variables
export ENVIRONMENT=production
export LOG_LEVEL=WARNING
export ALPACA_API_KEY=prod-key
export DATABASE_URL=postgresql://...- Configure Sentry for error tracking
- Set up Prometheus/Grafana for metrics
- Configure log aggregation (ELK stack)
- Set up alerting for critical metrics
# Install test dependencies
pip install pytest pytest-asyncio
# Run tests
pytest tests/
# Run with coverage
pytest --cov=ai_trading_system tests/# Format code
black ai_trading_system/
isort ai_trading_system/
# Lint code
flake8 ai_trading_system/-
Import Errors
# Ensure you're in the project root cd /path/to/ai_trading_system export PYTHONPATH=$PWD:$PYTHONPATH
-
API Connection Issues
- Check Alpaca API credentials
- Verify network connectivity
- Check API rate limits
-
Model Training Issues
- Ensure sufficient historical data
- Check memory availability for large models
- Verify data quality and completeness
-
Performance Issues
- Monitor system resource usage
- Check log files for errors
- Review Prometheus metrics
# Enable debug logging
export LOG_LEVEL=DEBUG
# Run with detailed output
python -m ai_trading_system.main --mode api --reloadThis project is licensed under the MIT License - see the LICENSE file for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
For support and questions:
- Create an issue in the repository
- Check the troubleshooting guide above
- Review the API documentation at
/docs