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