A comprehensive automated trading system that leverages Large Language Models (LLMs) for intelligent market analysis and trading signal generation.
LLM Trader combines sentiment analysis, fundamental analysis, and portfolio management to create an automated trading system. The system uses OpenAI's GPT models to interpret market data and generate trading signals, making it a powerful tool for algorithmic trading.
π LLM Trader/
βββ src/
β βββ main.py # Main orchestrator & entry point
β βββ sentiment/
β β βββ sentiment_analyzer.py # News & social sentiment analysis
β βββ fundamental/
β β βββ fundamental_analyzer.py # Financial metrics & ratios
β βββ technical/
β β βββ technical_analyzer.py # Technical indicators & patterns
β βββ social/
β β βββ social_sentiment.py # Twitter/Reddit/News sentiment
β βββ ml/
β β βββ prediction_models.py # ML price prediction models
β βββ rl/
β β βββ strategy_optimizer.py # RL strategy optimization
β βββ api/
β β βββ api_gateway.py # REST API for integrations
β βββ options/
β β βββ options_trader.py # Options trading & Greeks
β βββ futures/
β β βββ futures_trader.py # Futures trading & leverage
β βββ crypto/
β β βββ crypto_trader.py # Cryptocurrency trading & DeFi
β βββ forex/
β β βββ forex_trader.py # Forex trading & pip calculations
β βββ hft/
β β βββ high_freq_trader.py # High-frequency trading & microstructure
β βββ altdata/
β β βββ alternative_data.py # Alternative data & web scraping
β βββ neural/
β β βββ neural_networks.py # Neural networks & deep learning
β βββ advanced_orders/
β β βββ advanced_order_manager.py # Advanced order types & execution
β βββ factor_investing/
β β βββ factor_models.py # Multi-factor models & smart beta strategies
β βββ market_microstructure/
β β βββ market_microstructure_analyzer.py # Order flow & liquidity analysis
β βββ regime/
β β βββ market_regime.py # Market regime detection
β βββ volatility/
β β βββ volatility_forecaster.py # Advanced volatility forecasting models
β βββ economic_indicators/
β β βββ economic_analyzer.py # Economic data integration & impact analysis
β βββ news_sentiment/
β β βββ news_sentiment_analyzer.py # Real-time news sentiment analysis
β βββ earnings_analysis/
β β βββ earnings_analyzer.py # Automated earnings report analysis
β βββ sec_filing_analysis/
β β βββ sec_filing_analyzer.py # SEC filing analysis (10-K, 10-Q, 8-K)
β βββ insider_trading/
β β βββ insider_analyzer.py # Insider trading pattern analysis
β βββ dark_pool/
β β βββ dark_pool_analyzer.py # Dark pool trading activity analysis
β βββ yield_curve/
β β βββ yield_curve_analyzer.py # Yield curve analysis and forecasting
β βββ compliance/
β β βββ audit_system.py # Compliance & audit trails
β βββ strategy/
β β βββ strategy_engine.py # Signal generation & strategy logic
β βββ agent/
β β βββ trading_agent.py # Trade execution & portfolio management
β βββ simulation/
β β βββ market_simulator.py # Market simulation & backtesting
β βββ alerts/
β β βββ alert_system.py # Notification & alert system
β βββ optimization/
β β βββ portfolio_optimizer.py # MPT & risk parity optimization
β βββ streaming/
β β βββ data_streamer.py # Real-time market data streaming
β βββ analytics/
β β βββ performance_analyzer.py # Advanced performance analytics
β βββ multiasset/
β β βββ asset_manager.py # Multi-asset class support
β βββ data/
β βββ persistence.py # Data storage & retrieval
βββ dashboard.py # Interactive web dashboard
βββ demo.py # Demo script (no API key required)
βββ config.json # System configuration
βββ requirements.txt # Python dependencies
βββ README.md # This documentation
- Sentiment Analysis: Processes news articles, social media, and earnings calls using GPT
- Fundamental Analysis: Analyzes P/E ratios, EPS, revenue growth, debt-to-equity using LLM interpretation
- Technical Analysis: 8+ indicators (RSI, MACD, Bollinger Bands) with pattern recognition
- Strategy Generation: Combines multiple data sources for intelligent signal generation
- Risk Management: Configurable risk tolerance and position limits
- Portfolio Optimization: MPT, risk parity, and efficient frontier analysis
- Position Sizing: Dynamic allocation based on signal strength and confidence
- Rebalancing: Automatic portfolio rebalancing with threshold controls
- Transaction Costs: Realistic commission and spread modeling
- Multi-Source Integration: Combines sentiment, fundamentals, and technical factors
- Confidence Scoring: Each signal includes confidence levels and reasoning
- Signal Types: BUY, SELL, HOLD with strength indicators (WEAK/MODERATE/STRONG)
- Alert System: Email, SMS, and platform notifications for high-confidence signals
- Interactive Dashboard: Real-time web interface with Streamlit
- Performance Analytics: Comprehensive P&L reporting and risk metrics
- Backtesting Engine: Historical strategy testing with realistic market simulation
- Market Simulation: GBM-based price movements with event simulation
- Trade History: Complete audit trail of all transactions
- Portfolio Tracking: Real-time portfolio valuation and P&L
- Signal Storage: Historical signal data for analysis and optimization
- Alert Logging: Comprehensive notification and system event tracking
- Python 3.8+
- OpenAI API key (for full functionality)
-
Clone and setup:
git clone <repository-url> cd LLM_Trader
-
Create virtual environment:
python3 -m venv llm_trader_env source llm_trader_env/bin/activate # On Windows: llm_trader_env\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Configure API key:
# Option 1: Environment variable export OPENAI_API_KEY='your-api-key-here' # Option 2: Edit config.json # Add your API key to the "openai_api_key" field
With LLM features (requires API key):
python src/main.pyDemo mode (no API key required):
python demo.pyThe system is highly configurable via config.json:
{
"openai_api_key": "your-api-key",
"risk_tolerance": 0.1,
"initial_capital": 100000,
"max_positions": 10,
"trading_universe": ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"],
"sentiment_sources": ["news", "social_media", "earnings_calls"],
"fundamental_metrics": ["pe_ratio", "eps", "revenue_growth", "debt_to_equity"],
"logging": {
"level": "INFO",
"file": "logs/llm_trader.log"
},
"simulation": {
"days": 30,
"volatility": 0.02,
"trend": 0.0001
},
"trading": {
"min_trade_size": 1000,
"max_position_size": 0.1,
"commission_rate": 0.001,
"spread_cost": 0.0005
}
}π€ LLM Trader Demo - Running without LLM features
============================================================
π Mock Sentiment Analysis Results:
AAPL: Sentiment = 0.30, Confidence = 0.80
MSFT: Sentiment = 0.60, Confidence = 0.90
π Mock Fundamental Analysis Results:
AAPL: Score = 0.40, Recommendation = BUY
P/E Ratio: 28.5, EPS: 6.42
MSFT: Score = 0.70, Recommendation = BUY
P/E Ratio: 32.1, EPS: 11.8
π― Mock Trading Signals:
AAPL: BUY (MODERATE) - Confidence: 0.75
MSFT: BUY (STRONG) - Confidence: 0.85
π° Portfolio Simulation:
Initial Capital: $100,000.00
Final Portfolio Value: $90,393.20
Trades Executed: 2
- Fetches real-time stock data using yfinance
- Retrieves news articles and social sentiment
- Gathers fundamental financial metrics
- Sentiment Analyzer: Uses GPT to analyze text sentiment from multiple sources
- Fundamental Analyzer: Calculates key ratios and uses LLM for interpretation
- Strategy Engine: Combines analyses with configurable weights
- Weighted combination of sentiment and fundamental scores
- Confidence-based filtering
- Risk-adjusted position sizing
- Portfolio optimization based on signals
- Transaction cost modeling
- Real-time position management
- Comprehensive P&L reporting
- Risk metrics calculation
- Historical data persistence
- Maximum drawdown limits
- Position size constraints
- Diversification requirements
- Historical simulation with realistic market conditions
- Performance attribution
- Strategy optimization
- Comprehensive logging system
- Real-time portfolio tracking
- Performance dashboards
- API keys stored securely (environment variables recommended)
- Input validation and error handling
- Transaction logging for audit trails
- Risk limits to prevent catastrophic losses
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
This software is for educational and research purposes only. It should not be used for actual trading without thorough testing and professional consultation. Past performance does not guarantee future results. Always consult with a financial advisor before making investment decisions.
For questions or issues:
- Create an issue on GitHub
- Check the documentation
- Review the demo script for examples