Skip to content

A comprehensive automated trading system that leverages Large Language Models (LLMs) for intelligent market analysis and trading signal generation.

Notifications You must be signed in to change notification settings

lenko-d/LLM_Trader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– LLM Trader

A comprehensive automated trading system that leverages Large Language Models (LLMs) for intelligent market analysis and trading signal generation.

πŸ“‹ Overview

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.

πŸ—οΈ System Architecture

πŸ“ 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

πŸ”§ Key Features

πŸ€– LLM Powered Multi-Dimensional Analysis

  • 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

πŸ“Š Advanced Portfolio Management

  • 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

🎯 Intelligent Trading Signals

  • 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

πŸ“ˆ Professional Monitoring

  • 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

πŸ’Ύ Enterprise Data Management

  • 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

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • OpenAI API key (for full functionality)

Installation

  1. Clone and setup:

    git clone <repository-url>
    cd LLM_Trader
  2. Create virtual environment:

    python3 -m venv llm_trader_env
    source llm_trader_env/bin/activate  # On Windows: llm_trader_env\Scripts\activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. 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

Running the System

With LLM features (requires API key):

python src/main.py

Demo mode (no API key required):

python demo.py

βš™οΈ Configuration

The 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
  }
}

πŸ“Š Sample Output

πŸ€– 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

πŸ” How It Works

1. Data Collection

  • Fetches real-time stock data using yfinance
  • Retrieves news articles and social sentiment
  • Gathers fundamental financial metrics

2. Analysis Pipeline

  • 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

3. Signal Generation

  • Weighted combination of sentiment and fundamental scores
  • Confidence-based filtering
  • Risk-adjusted position sizing

4. Trade Execution

  • Portfolio optimization based on signals
  • Transaction cost modeling
  • Real-time position management

5. Performance Tracking

  • Comprehensive P&L reporting
  • Risk metrics calculation
  • Historical data persistence

πŸŽ›οΈ Advanced Features

Risk Management

  • Maximum drawdown limits
  • Position size constraints
  • Diversification requirements

Backtesting

  • Historical simulation with realistic market conditions
  • Performance attribution
  • Strategy optimization

Monitoring & Logging

  • Comprehensive logging system
  • Real-time portfolio tracking
  • Performance dashboards

πŸ”’ Security & Best Practices

  • API keys stored securely (environment variables recommended)
  • Input validation and error handling
  • Transaction logging for audit trails
  • Risk limits to prevent catastrophic losses

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

⚠️ Disclaimer

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.

πŸ“ž Support

For questions or issues:

  • Create an issue on GitHub
  • Check the documentation
  • Review the demo script for examples

About

A comprehensive automated trading system that leverages Large Language Models (LLMs) for intelligent market analysis and trading signal generation.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages