Edwin Salguero commited on
Commit ·
46590b0
1
Parent(s): 9fb1755
feat: Add comprehensive Alpaca integration with FinRL
Browse files- Add Alpaca broker module for real trading capabilities
- Integrate Alpaca with FinRL reinforcement learning agent
- Update execution agent to support real broker integration
- Enhance data ingestion with Alpaca market data support
- Add environment configuration for API credentials
- Update demo script to showcase Alpaca integration
- Comprehensive documentation updates
- Support for paper and live trading modes
Files changed (9)
- README.md+266-382
- agentic_ai_system/alpaca_broker.pyAdded+406
- agentic_ai_system/data_ingestion.py+231-88
- agentic_ai_system/execution_agent.py+110-24
- agentic_ai_system/finrl_agent.py+283-212
- config.yaml+14-1
- demo.py+283-102
- env.exampleAdded+28
- requirements.txt+4
24 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472481 unmodified line25025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453524 unmodified linespaperswithcode_id: null---# Algorithmic Trading SystemA comprehensive algorithmic trading system with synthetic data generation, comprehensive logging, extensive testing capabilities, FinRL reinforcement learning integration, and full Docker support.## Features### Core Trading System- **Agent-based Architecture**: Modular design with separate strategy and execution agents- **Technical Analysis**: Built-in technical indicators (SMA, RSI, Bollinger Bands, MACD)- **Risk Management**: Position sizing and drawdown limits- **Order Execution**: Simulated broker integration with realistic execution delays### FinRL Reinforcement Learning- **Multiple RL Algorithms**: Support for PPO, A2C, DDPG, and TD3- **Custom Trading Environment**: Gymnasium-compatible environment for RL training- **Technical Indicators Integration**: Automatic calculation and inclusion of technical indicators- **Portfolio Management**: Realistic portfolio simulation with transaction costs- **Model Persistence**: Save and load trained models for inference- **TensorBoard Integration**: Training progress visualization and monitoring- **Comprehensive Evaluation**: Performance metrics including Sharpe ratio and total returns### Docker Integration- **Multi-Environment Support**: Development, production, and testing environments- **Container Orchestration**: Docker Compose for easy service management- **Monitoring Stack**: Prometheus and Grafana for system monitoring- **Development Tools**: Jupyter Lab integration for interactive development- **Automated Testing**: Containerized test execution with coverage reporting- **Resource Management**: CPU and memory limits for production deployment- **Health Checks**: Built-in health monitoring for all services- **Backup Services**: Automated backup and data persistence### Synthetic Data Generation- **Realistic Market Data**: Generate OHLCV data using geometric Brownian motion- **Multiple Frequencies**: Support for 1min, 5min, 1H, and 1D data- **Market Scenarios**: Normal, volatile, trending, and crash market conditions- **Tick Data**: High-frequency tick data generation for testing- **Configurable Parameters**: Volatility, trend, noise levels, and base prices### Comprehensive Logging- **Multi-level Logging**: Console and file-based logging- **Rotating Log Files**: Automatic log rotation with size limits- **Specialized Loggers**: Separate loggers for trading, performance, and errors- **Structured Logging**: Detailed log messages with timestamps and context### Testing Framework- **Unit Tests**: Comprehensive tests for all components- **Integration Tests**: End-to-end workflow testing- **Test Coverage**: Code coverage reporting with HTML and XML outputs- **Mock Testing**: Isolated testing with mocked dependencies## Installation### Option 1: Docker (Recommended)1. Clone the repository:```bashgit clone https://huggingface.co/ParallelLLC/algorithmic_tradingcd algorithmic_trading```2. Build and run with Docker:```bash# Build the imagedocker build -t algorithmic-trading .# Run the trading systemdocker run -p 8000:8000 algorithmic-trading```### Option 2: Local Installation1. Clone the repository:```bashgit clone https://huggingface.co/esalguero/algorithmic_tradingcd algorithmic_trading```2. Install dependencies:```bashpip install -r requirements.txt```## Docker Usage### Quick Start```bash# Build and start development environment./scripts/docker-build.sh dev# Build and start production environment./scripts/docker-build.sh prod# Run tests in Docker./scripts/docker-build.sh test# Stop all containers./scripts/docker-build.sh stop```### Development Environment```bash# Start development environment with Jupyter Labdocker-compose -f docker-compose.dev.yml up -d# Access services:# - Jupyter Lab: http://localhost:8888# - Trading System: http://localhost:8000# - TensorBoard: http://localhost:6006```### Production Environment```bash# Start production environment with monitoringdocker-compose -f docker-compose.prod.yml up -d# Access services:# - Trading System: http://localhost:8000# - Grafana: http://localhost:3000 (admin/admin)# - Prometheus: http://localhost:9090```### Custom Commands```bash# Run a specific command in the container./scripts/docker-build.sh run 'python demo.py'# Run FinRL training./scripts/docker-build.sh run 'python finrl_demo.py'# Run backtesting./scripts/docker-build.sh run 'python -m agentic_ai_system.main --mode backtest'# Show logs./scripts/docker-build.sh logs trading-system```### Docker Compose Services#### Development (`docker-compose.dev.yml`)- **trading-dev**: Jupyter Lab environment with hot reload- **finrl-training-dev**: FinRL training with TensorBoard- **testing**: Automated test execution- **linting**: Code quality checks#### Production (`docker-compose.prod.yml`)- **trading-system**: Main trading system with resource limits- **monitoring**: Prometheus metrics collection- **grafana**: Data visualization dashboard- **backup**: Automated backup service#### Standard (`docker-compose.yml`)- **trading-system**: Basic trading system- **finrl-training**: FinRL training service- **backtesting**: Backtesting service- **development**: Development environment### Docker Features#### Health ChecksAll services include health checks to ensure system reliability:```yamlhealthcheck:test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]interval: 30stimeout: 10sretries: 3start_period: 40s```#### Resource ManagementProduction services include resource limits:```yamldeploy:resources:limits:memory: 2Gcpus: '1.0'reservations:memory: 512Mcpus: '0.5'```#### Volume ManagementPersistent data storage with named volumes:- `trading_data`: Market data and configuration- `trading_logs`: System logs- `trading_models`: Trained models- `prometheus_data`: Monitoring metrics- `grafana_data`: Dashboard configurations#### LoggingStructured logging with rotation:```yamllogging:driver: "json-file"options:max-size: "10m"max-file: "3"```## ConfigurationThe system is configured via `config.yaml`:```yaml# Data source configurationdata_source:type: 'synthetic' # or 'csv'path: 'data/market_data.csv'# Trading parameterstrading:symbol: 'AAPL'timeframe: '1min'capital: 100000# Risk management1 unmodified linemax_position: 100max_drawdown: 0.05# Order executionexecution:broker_api: 'paper'order_size: 10delay_ms: 100success_rate: 0.95# Synthetic data generationsynthetic_data:base_price: 150.0volatility: 0.02trend: 0.001noise_level: 0.005generate_data: truedata_path: 'data/synthetic_market_data.csv'# Logging configurationlogging:log_level: 'INFO'log_dir: 'logs'enable_console: trueenable_file: truemax_file_size_mb: 10backup_count: 5# FinRL configurationfinrl:algorithm: 'PPO'learning_rate: 0.0003batch_size: 64buffer_size: 1000000gamma: 0.99tensorboard_log: 'logs/finrl_tensorboard'training:total_timesteps: 100000eval_freq: 10000save_best_model: truemodel_save_path: 'models/finrl_best/'inference:use_trained_model: falsemodel_path: 'models/finrl_best/best_model'```## Usage### Standard Trading Mode```bashpython -m agentic_ai_system.main```### Backtest Mode```bashpython -m agentic_ai_system.main --mode backtest --start-date 2024-01-01 --end-date 2024-12-31```### Live Trading Mode```bashpython -m agentic_ai_system.main --mode live --duration 60```### Custom Configuration```bashpython -m agentic_ai_system.main --config custom_config.yaml```## Running Tests### All Tests```bashpytest```### Unit Tests Only```bashpytest -m unit```### Integration Tests Only```bashpytest -m integration```### With Coverage Report```bashpytest --cov=agentic_ai_system --cov-report=html```### Specific Test File```bashpytest tests/test_synthetic_data_generator.py```### Docker Testing```bash# Run all tests in Docker./scripts/docker-build.sh test# Run tests with coveragedocker run --rm -v $(pwd):/app algorithmic-trading:latest pytest --cov=agentic_ai_system --cov-report=html```## System Architecture### Components1. **SyntheticDataGenerator**: Generates realistic market data for testing2. **DataIngestion**: Loads and validates market data from various sources3. **StrategyAgent**: Analyzes market data and generates trading signals4. **ExecutionAgent**: Executes trading orders with broker simulation5. **Orchestrator**: Coordinates the entire trading workflow6. **LoggerConfig**: Manages comprehensive logging throughout the system7. **FinRLAgent**: Reinforcement learning agent for advanced trading strategies### Data Flow```Synthetic Data Generator → Data Ingestion → Strategy Agent → Execution Agent↓Logging System↓FinRL Agent (Optional)```### Docker Architecture```┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Development │ │ Production │ │ Monitoring ││ Environment │ │ Environment │ │ Stack │├─────────────────┤ ├─────────────────┤ ├─────────────────┤│ • Jupyter Lab │ │ • Trading Sys │ │ • Prometheus ││ • Hot Reload │ │ • Resource Mgmt │ │ • Grafana ││ • TensorBoard │ │ • Health Checks │ │ • Metrics ││ • Testing │ │ • Logging │ │ • Dashboards │└─────────────────┘ └─────────────────┘ └─────────────────┘```## Monitoring and Observability### Prometheus Metrics- Trading performance metrics- System resource usage- Error rates and response times- Custom business metrics### Grafana Dashboards- Real-time trading performance- System health monitoring- Historical data analysis- Alert management### Health Checks- Service availability monitoring- Dependency health verification- Automatic restart on failure- Performance degradation detection## Deployment### Local Development```bash# Start development environment./scripts/docker-build.sh dev# Access Jupyter Labopen http://localhost:8888```### Production Deployment```bash# Deploy to production./scripts/docker-build.sh prod# Monitor system healthopen http://localhost:3000 # Grafanaopen http://localhost:9090 # Prometheus```### Cloud DeploymentThe Docker setup is compatible with:- **AWS ECS/Fargate**: For serverless container deployment- **Google Cloud Run**: For scalable containerized applications- **Azure Container Instances**: For managed container deployment- **Kubernetes**: For orchestrated container management### Environment Variables```bash# DevelopmentLOG_LEVEL=DEBUGPYTHONDONTWRITEBYTECODE=1# ProductionLOG_LEVEL=INFOPYTHONUNBUFFERED=1```## Troubleshooting### Common Docker Issues#### Build Failures```bash# Clean build cachedocker system prune -a# Rebuild without cachedocker build --no-cache -t algorithmic-trading .```#### Container Startup Issues```bash# Check container logsdocker logs algorithmic-trading# Check container statusdocker ps -a```#### Volume Mount Issues```bash# Check volume permissionsdocker run --rm -v $(pwd):/app algorithmic-trading:latest ls -la /app# Fix volume permissionschmod -R 755 data logs models```### Performance Optimization#### Resource Tuning```yaml# Adjust resource limits in docker-compose.prod.ymldeploy:resources:limits:memory: 4G # Increase for heavy workloadscpus: '2.0' # Increase for CPU-intensive tasks```#### Logging Optimization```yaml# Reduce log verbosity in productionlogging:driver: "json-file"options:max-size: "5m" # Smaller log filesmax-file: "2" # Fewer log files```## Contributing1. Fork the repository2. Create a feature branch3. Add tests for new functionality4. Ensure all tests pass (including Docker tests)5. Submit a pull request### Development Workflow```bash# Start development environment./scripts/docker-build.sh dev# Make changes and test./scripts/docker-build.sh test# Run lintingdocker-compose -f docker-compose.dev.yml run linting# Commit and pushgit add .git commit -m "Add new feature"git push origin feature-branch```## LicenseThis project is licensed under the Apache License, Version 2.0 - see the LICENSE file for details.## AboutA comprehensive, production-ready algorithmic trading system with real-time market data streaming, multi-symbol trading, advanced technical analysis, robust risk management capabilities, and full Docker containerization support.[Medium Article](https://medium.com/@edwinsalguero/data-pipeline-design-in-an-algorithmic-trading-system-ac0d8109c4b9)24 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841924 unmodified linespaperswithcode_id: null---# Algorithmic Trading System with FinRL and Alpaca IntegrationA sophisticated algorithmic trading system that combines reinforcement learning (FinRL) with real-time market data and order execution through Alpaca Markets. This system supports both paper trading and live trading with advanced risk management and technical analysis.## 🚀 Features### Core Trading System- **Multi-source Data Ingestion**: CSV files, Alpaca Markets API, and synthetic data generation- **Technical Analysis**: 20+ technical indicators including RSI, MACD, Bollinger Bands, and more- **Risk Management**: Position sizing, drawdown limits, and portfolio protection- **Real-time Execution**: Live order placement and portfolio monitoring### FinRL Reinforcement Learning- **Multiple Algorithms**: PPO, A2C, DDPG, and TD3 support- **Custom Trading Environment**: Gymnasium-compatible environment for RL training- **Real-time Integration**: Can execute real trades during training and inference- **Model Persistence**: Save and load trained models for consistent performance### Alpaca Broker Integration- **Paper Trading**: Risk-free testing with virtual money- **Live Trading**: Real market execution (use with caution!)- **Market Data**: Real-time and historical data from Alpaca- **Account Management**: Portfolio monitoring and position tracking- **Order Types**: Market orders, limit orders, and order cancellation### Advanced Features- **Docker Support**: Containerized deployment for consistency- **Comprehensive Logging**: Detailed logs for debugging and performance analysis- **Backtesting Engine**: Historical performance evaluation- **Live Trading Simulation**: Real-time trading with configurable duration- **Performance Metrics**: Returns, Sharpe ratio, drawdown analysis## 📋 Prerequisites- Python 3.8+- Alpaca Markets account (free paper trading available)- Docker (optional, for containerized deployment)## 🛠️ Installation### 1. Clone the Repository```bashgit clone <repository-url>cd algorithmic_trading```### 2. Install Dependencies```bashpip install -r requirements.txt```### 3. Set Up Alpaca API CredentialsCreate a `.env` file in the project root:```bashcp env.example .env```Edit `.env` with your Alpaca credentials:```env# Get these from https://app.alpaca.markets/paper/dashboard/overviewALPACA_API_KEY=your_paper_api_key_hereALPACA_SECRET_KEY=your_paper_secret_key_here# For live trading (use with caution!)# ALPACA_API_KEY=your_live_api_key_here# ALPACA_SECRET_KEY=your_live_secret_key_here```### 4. Configure Trading ParametersEdit `config.yaml` to customize your trading strategy:```yaml# Data source configurationdata_source:type: 'alpaca' # Options: 'alpaca', 'csv', 'synthetic'# Trading parameterstrading:symbol: 'AAPL'timeframe: '1m'capital: 100000# Risk management1 unmodified linemax_position: 100max_drawdown: 0.05# Execution settingsexecution:broker_api: 'alpaca_paper' # Options: 'paper', 'alpaca_paper', 'alpaca_live'order_size: 10# FinRL configurationfinrl:algorithm: 'PPO'learning_rate: 0.0003training:total_timesteps: 100000save_best_model: true```## 🚀 Quick Start### 1. Run the Demo```bashpython demo.py```This will:- Test data ingestion from Alpaca- Demonstrate FinRL training- Show trading workflow execution- Run backtesting on historical data### 2. Start Paper Trading```bashpython -m agentic_ai_system.main --mode live --duration 60```### 3. Run Backtesting```bashpython -m agentic_ai_system.main --mode backtest --start-date 2024-01-01 --end-date 2024-01-31```## 📊 Usage Examples### Basic Trading Workflow```pythonfrom agentic_ai_system.main import load_configfrom agentic_ai_system.orchestrator import run# Load configurationconfig = load_config()# Run single trading cycleresult = run(config)print(f"Trading result: {result}")```### FinRL Training```pythonfrom agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfigfrom agentic_ai_system.data_ingestion import load_data# Load data and configurationconfig = load_config()data = load_data(config)# Initialize FinRL agentfinrl_config = FinRLConfig(algorithm='PPO', learning_rate=0.0003)agent = FinRLAgent(finrl_config)# Train the agentresult = agent.train(data=data,config=config,total_timesteps=100000,use_real_broker=False # Use simulation for training)print(f"Training completed: {result}")```### Alpaca Integration```pythonfrom agentic_ai_system.alpaca_broker import AlpacaBroker# Initialize Alpaca brokerconfig = load_config()broker = AlpacaBroker(config)# Get account informationaccount_info = broker.get_account_info()print(f"Account balance: ${account_info['buying_power']:,.2f}")# Place a market orderresult = broker.place_market_order(symbol='AAPL',quantity=10,side='buy')print(f"Order result: {result}")```### Real-time Trading with FinRL```pythonfrom agentic_ai_system.finrl_agent import FinRLAgent# Load trained modelagent = FinRLAgent(FinRLConfig())agent.model = agent._load_model('models/finrl_best/best_model', config)# Make predictions with real executionresult = agent.predict(data=recent_data,config=config,use_real_broker=True # Execute real trades!)```## 🏗️ Architecture### System Components```┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Data Sources │ │ Strategy Agent │ │ Execution Agent ││ │ │ │ │ ││ • Alpaca API │───▶│ • Technical │───▶│ • Alpaca Broker ││ • CSV Files │ │ Indicators │ │ • Order Mgmt ││ • Synthetic │ │ • Signal Gen │ │ • Risk Control │└─────────────────┘ └─────────────────┘ └─────────────────┘│ │ │▼ ▼ ▼┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Data Ingestion │ │ FinRL Agent │ │ Portfolio ││ │ │ │ │ Management ││ • Validation │ │ • PPO/A2C/DDPG │ │ • Positions ││ • Indicators │ │ • Training │ │ • P&L Tracking ││ • Preprocessing │ │ • Prediction │ │ • Risk Metrics │└─────────────────┘ └─────────────────┘ └─────────────────┘```### Data Flow1. **Data Ingestion**: Market data from Alpaca, CSV, or synthetic sources2. **Preprocessing**: Technical indicators, data validation, and feature engineering3. **Strategy Generation**: Traditional technical analysis or FinRL predictions4. **Risk Management**: Position sizing and portfolio protection5. **Order Execution**: Real-time order placement through Alpaca6. **Performance Tracking**: Continuous monitoring and logging## 🔧 Configuration### Alpaca Settings```yamlalpaca:api_key: '' # Set via environment variablesecret_key: '' # Set via environment variablepaper_trading: truebase_url: 'https://paper-api.alpaca.markets'live_url: 'https://api.alpaca.markets'data_url: 'https://data.alpaca.markets'account_type: 'paper' # 'paper' or 'live'```### FinRL Settings```yamlfinrl:algorithm: 'PPO' # PPO, A2C, DDPG, TD3learning_rate: 0.0003batch_size: 64buffer_size: 1000000training:total_timesteps: 100000eval_freq: 10000save_best_model: truemodel_save_path: 'models/finrl_best/'inference:use_trained_model: falsemodel_path: 'models/finrl_best/best_model'```### Risk Management```yamlrisk:max_position: 100max_drawdown: 0.05stop_loss: 0.02take_profit: 0.05```## 📈 Performance Monitoring### LoggingThe system provides comprehensive logging:- `logs/trading_system.log`: Main system logs- `logs/trading.log`: Trading-specific events- `logs/performance.log`: Performance metrics- `logs/finrl_tensorboard/`: FinRL training logs### Metrics Tracked- Portfolio value and returns- Trade execution statistics- Risk metrics (Sharpe ratio, drawdown)- FinRL training progress- Alpaca account status### Real-time Monitoring```python# Get account informationaccount_info = broker.get_account_info()print(f"Portfolio Value: ${account_info['portfolio_value']:,.2f}")# Get current positionspositions = broker.get_positions()for pos in positions:print(f"{pos['symbol']}: {pos['quantity']} shares")# Check market statusmarket_open = broker.is_market_open()print(f"Market: {'OPEN' if market_open else 'CLOSED'}")```## 🐳 Docker Deployment### Build and Run```bash# Build the imagedocker build -t algorithmic-trading .# Run with environment variablesdocker run -it --env-file .env algorithmic-trading# Run with Jupyter Lab for developmentdocker-compose -f docker-compose.dev.yml up```### Production Deployment```bash# Use production compose filedocker-compose -f docker-compose.prod.yml up -d# Monitor logsdocker-compose -f docker-compose.prod.yml logs -f```## 🧪 Testing### Run All Tests```bashpytest tests/ -v```### Test Specific Components```bash# Test Alpaca integrationpytest tests/test_alpaca_integration.py -v# Test FinRL agentpytest tests/test_finrl_agent.py -v# Test trading workflowpytest tests/test_integration.py -v```## ⚠️ Important Notes### Paper Trading vs Live Trading- **Paper Trading**: Uses virtual money, safe for testing- **Live Trading**: Uses real money, use with extreme caution- Always test strategies thoroughly in paper trading before going live### Risk Management- Set appropriate position limits and drawdown thresholds- Monitor your portfolio regularly- Use stop-loss orders to limit potential losses- Never risk more than you can afford to lose### API Rate Limits- Alpaca has rate limits on API calls- The system includes built-in delays to respect these limits- Monitor your API usage in the Alpaca dashboard## 🤝 Contributing1. Fork the repository2. Create a feature branch3. Make your changes4. Add tests for new functionality5. Submit a pull request## 📄 LicenseThis project is licensed under the MIT License - see the LICENSE file for details.## 🆘 Support- **Documentation**: Check the logs and configuration files- **Issues**: Report bugs and feature requests on GitHub- **Alpaca Support**: Contact Alpaca for API-related issues- **Community**: Join our Discord/Telegram for discussions## 🔗 Useful Links- [Alpaca Markets Documentation](https://alpaca.markets/docs/)- [FinRL Documentation](https://finrl.readthedocs.io/)- [Stable Baselines3 Documentation](https://stable-baselines3.readthedocs.io/)- [Gymnasium Documentation](https://gymnasium.farama.org/)---**Disclaimer**: This software is for educational and research purposes. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results. Always consult with a financial advisor before making investment decisions.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406"""Alpaca Broker Integration for Algorithmic Trading
This module provides integration with Alpaca Markets for real trading capabilities,including paper trading and live trading support."""
import osimport loggingimport timefrom typing import Dict, Any, Optional, Listfrom datetime import datetime, timedeltaimport pandas as pdimport numpy as np
try: from alpaca.trading.client import TradingClient from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest from alpaca.trading.enums import OrderSide, TimeInForce from alpaca.data.historical import StockHistoricalDataClient from alpaca.data.requests import StockBarsRequest from alpaca.data.timeframe import TimeFrame from alpaca.data.enums import Adjustment from alpaca.account import Account ALPACA_AVAILABLE = Trueexcept ImportError: ALPACA_AVAILABLE = False logging.warning("Alpaca SDK not available. Install with: pip install alpaca-py")
logger = logging.getLogger(__name__)
class AlpacaBroker: """ Alpaca broker integration for algorithmic trading """ def __init__(self, config: Dict[str, Any]): """ Initialize Alpaca broker connection Args: config: Configuration dictionary containing Alpaca settings """ self.config = config self.alpaca_config = config.get('alpaca', {}) # Get API credentials from environment or config self.api_key = os.getenv('ALPACA_API_KEY') or self.alpaca_config.get('api_key', '') self.secret_key = os.getenv('ALPACA_SECRET_KEY') or self.alpaca_config.get('secret_key', '') # Determine if using paper or live trading self.paper_trading = self.alpaca_config.get('paper_trading', True) self.account_type = self.alpaca_config.get('account_type', 'paper') # Set URLs based on account type if self.account_type == 'live': self.base_url = self.alpaca_config.get('live_url', 'https://api.alpaca.markets') self.data_url = self.alpaca_config.get('data_url', 'https://data.alpaca.markets') else: self.base_url = self.alpaca_config.get('base_url', 'https://paper-api.alpaca.markets') self.data_url = self.alpaca_config.get('data_url', 'https://data.alpaca.markets') # Initialize clients self.trading_client = None self.data_client = None self.account = None # Initialize connection self._initialize_connection() logger.info(f"Alpaca broker initialized for {self.account_type} trading") def _initialize_connection(self): """Initialize Alpaca API connections""" if not ALPACA_AVAILABLE: logger.error("Alpaca SDK not available") return False if not self.api_key or not self.secret_key: logger.error("Alpaca API credentials not provided") return False try: # Initialize trading client self.trading_client = TradingClient( api_key=self.api_key, secret_key=self.secret_key, paper=self.paper_trading ) # Initialize data client self.data_client = StockHistoricalDataClient( api_key=self.api_key, secret_key=self.secret_key ) # Get account information self.account = self.trading_client.get_account() logger.info(f"Connected to Alpaca {self.account_type} account: {self.account.id}") logger.info(f"Account status: {self.account.status}") logger.info(f"Buying power: ${self.account.buying_power}") return True except Exception as e: logger.error(f"Failed to initialize Alpaca connection: {e}") return False def get_account_info(self) -> Dict[str, Any]: """Get account information""" if not self.account: return {} return { 'account_id': self.account.id, 'status': self.account.status, 'buying_power': float(self.account.buying_power), 'cash': float(self.account.cash), 'portfolio_value': float(self.account.portfolio_value), 'equity': float(self.account.equity), 'daytrade_count': self.account.daytrade_count, 'trading_blocked': self.account.trading_blocked, 'transfers_blocked': self.account.transfers_blocked, 'account_blocked': self.account.account_blocked } def get_positions(self) -> List[Dict[str, Any]]: """Get current positions""" if not self.trading_client: return [] try: positions = self.trading_client.get_all_positions() return [ { 'symbol': pos.symbol, 'quantity': int(pos.qty), 'market_value': float(pos.market_value), 'unrealized_pl': float(pos.unrealized_pl), 'current_price': float(pos.current_price) } for pos in positions ] except Exception as e: logger.error(f"Error getting positions: {e}") return [] def get_market_data(self, symbol: str, timeframe: str = '1Min', start_date: Optional[str] = None, end_date: Optional[str] = None, limit: int = 1000) -> Optional[pd.DataFrame]: """ Get historical market data from Alpaca Args: symbol: Stock symbol timeframe: Timeframe for data (1Min, 5Min, 15Min, 1Hour, 1Day) start_date: Start date (ISO format) end_date: End date (ISO format) limit: Maximum number of bars to return Returns: DataFrame with OHLCV data or None if error """ if not self.data_client: logger.error("Data client not initialized") return None try: # Convert timeframe string to TimeFrame enum tf_map = { '1Min': TimeFrame.Minute, '5Min': TimeFrame.Minute_5, '15Min': TimeFrame.Minute_15, '1Hour': TimeFrame.Hour, '1Day': TimeFrame.Day } time_frame = tf_map.get(timeframe, TimeFrame.Minute) # Set default dates if not provided if not end_date: end_date = datetime.now().isoformat() if not start_date: start_date = (datetime.now() - timedelta(days=30)).isoformat() # Create request request = StockBarsRequest( symbol_or_symbols=symbol, timeframe=time_frame, start=start_date, end=end_date, adjustment=Adjustment.ALL, limit=limit ) # Get data bars = self.data_client.get_stock_bars(request) if bars and symbol in bars: # Convert to DataFrame df = bars[symbol].df df = df.reset_index() df.columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume', 'vwap', 'trade_count'] # Select relevant columns df = df[['timestamp', 'open', 'high', 'low', 'close', 'volume']] logger.info(f"Retrieved {len(df)} bars for {symbol}") return df else: logger.warning(f"No data returned for {symbol}") return None except Exception as e: logger.error(f"Error getting market data for {symbol}: {e}") return None def place_market_order(self, symbol: str, quantity: int, side: str) -> Dict[str, Any]: """ Place a market order Args: symbol: Stock symbol quantity: Number of shares side: 'buy' or 'sell' Returns: Order result dictionary """ if not self.trading_client: return {'success': False, 'error': 'Trading client not initialized'} try: # Convert side to Alpaca enum order_side = OrderSide.BUY if side.lower() == 'buy' else OrderSide.SELL # Create order request order_request = MarketOrderRequest( symbol=symbol, qty=quantity, side=order_side, time_in_force=TimeInForce.DAY ) # Place order order = self.trading_client.submit_order(order_request) # Wait for order to be processed time.sleep(1) # Get updated order status order = self.trading_client.get_order_by_id(order.id) result = { 'success': order.status == 'filled', 'order_id': order.id, 'status': order.status, 'symbol': order.symbol, 'quantity': int(order.qty), 'side': order.side.value, 'filled_quantity': int(order.filled_qty) if order.filled_qty else 0, 'filled_avg_price': float(order.filled_avg_price) if order.filled_avg_price else 0, 'submitted_at': order.submitted_at.isoformat() if order.submitted_at else None, 'filled_at': order.filled_at.isoformat() if order.filled_at else None, 'error': None } if order.status == 'rejected': result['error'] = 'Order rejected' logger.info(f"Market order placed: {result}") return result except Exception as e: logger.error(f"Error placing market order: {e}") return { 'success': False, 'order_id': None, 'status': 'error', 'error': str(e) } def place_limit_order(self, symbol: str, quantity: int, side: str, limit_price: float) -> Dict[str, Any]: """ Place a limit order Args: symbol: Stock symbol quantity: Number of shares side: 'buy' or 'sell' limit_price: Limit price for the order Returns: Order result dictionary """ if not self.trading_client: return {'success': False, 'error': 'Trading client not initialized'} try: # Convert side to Alpaca enum order_side = OrderSide.BUY if side.lower() == 'buy' else OrderSide.SELL # Create order request order_request = LimitOrderRequest( symbol=symbol, qty=quantity, side=order_side, time_in_force=TimeInForce.DAY, limit_price=limit_price ) # Place order order = self.trading_client.submit_order(order_request) result = { 'success': True, 'order_id': order.id, 'status': order.status, 'symbol': order.symbol, 'quantity': int(order.qty), 'side': order.side.value, 'limit_price': float(order.limit_price), 'submitted_at': order.submitted_at.isoformat() if order.submitted_at else None, 'error': None } logger.info(f"Limit order placed: {result}") return result except Exception as e: logger.error(f"Error placing limit order: {e}") return { 'success': False, 'order_id': None, 'status': 'error', 'error': str(e) } def cancel_order(self, order_id: str) -> Dict[str, Any]: """Cancel an existing order""" if not self.trading_client: return {'success': False, 'error': 'Trading client not initialized'} try: self.trading_client.cancel_order_by_id(order_id) return {'success': True, 'order_id': order_id, 'status': 'cancelled'} except Exception as e: logger.error(f"Error cancelling order {order_id}: {e}") return {'success': False, 'order_id': order_id, 'error': str(e)} def get_orders(self, status: str = 'all') -> List[Dict[str, Any]]: """Get order history""" if not self.trading_client: return [] try: orders = self.trading_client.get_orders(status=status) return [ { 'order_id': order.id, 'symbol': order.symbol, 'quantity': int(order.qty), 'side': order.side.value, 'status': order.status, 'order_type': order.order_type.value, 'submitted_at': order.submitted_at.isoformat() if order.submitted_at else None, 'filled_at': order.filled_at.isoformat() if order.filled_at else None } for order in orders ] except Exception as e: logger.error(f"Error getting orders: {e}") return [] def is_market_open(self) -> bool: """Check if market is currently open""" if not self.trading_client: return False try: clock = self.trading_client.get_clock() return clock.is_open except Exception as e: logger.error(f"Error checking market status: {e}") return False def get_market_hours(self) -> Dict[str, Any]: """Get market hours information""" if not self.trading_client: return {} try: clock = self.trading_client.get_clock() return { 'is_open': clock.is_open, 'next_open': clock.next_open.isoformat() if clock.next_open else None, 'next_close': clock.next_close.isoformat() if clock.next_close else None, 'timestamp': clock.timestamp.isoformat() if clock.timestamp else None } except Exception as e: logger.error(f"Error getting market hours: {e}") return {} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149import pandas as pdimport loggingimport osfrom typing import Dict, Anyfrom .synthetic_data_generator import SyntheticDataGeneratorlogger = logging.getLogger(__name__)def load_data(config: Dict[str, Any]) -> pd.DataFrame:"""Load market data from file or generate synthetic data if needed.Args:config: Configuration dictionaryReturns:DataFrame with market data"""logger.info("Starting data ingestion process")try:data_source = config['data_source']data_type = data_source['type']if data_type == 'csv':return _load_csv_data(config)elif data_type == 'synthetic':return _generate_synthetic_data(config)else:raise ValueError(f"Unsupported data source type: {data_type}")except Exception as e:logger.error(f"Error in data ingestion: {e}", exc_info=True)raisedef _load_csv_data(config: Dict[str, Any]) -> pd.DataFrame:"""Load data from CSV file"""path = config['data_source']['path']if not os.path.exists(path):logger.warning(f"CSV file not found at {path}, generating synthetic data instead")return _generate_synthetic_data(config)logger.info(f"Loading data from CSV: {path}")df = pd.read_csv(path)# Validate datarequired_columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']missing_columns = [col for col in required_columns if col not in df.columns]if missing_columns:logger.warning(f"Missing columns in CSV: {missing_columns}")logger.info("Generating synthetic data instead")return _generate_synthetic_data(config)# Convert timestamp to datetimedf['timestamp'] = pd.to_datetime(df['timestamp'])logger.info(f"Successfully loaded {len(df)} data points from CSV")return dfdef _generate_synthetic_data(config: Dict[str, Any]) -> pd.DataFrame:"""Generate synthetic data using the SyntheticDataGenerator"""logger.info("Generating synthetic market data")try:# Create data directory if it doesn't existdata_path = config['synthetic_data']['data_path']os.makedirs(os.path.dirname(data_path), exist_ok=True)# Initialize synthetic data generatorgenerator = SyntheticDataGenerator(config)# Generate OHLCV datadf = generator.generate_ohlcv_data(symbol=config['trading']['symbol'],start_date='2024-01-01',end_date='2024-12-31',frequency=config['trading']['timeframe'])# Save to CSV if configuredif config['synthetic_data'].get('generate_data', True):generator.save_to_csv(df, data_path)logger.info(f"Saved synthetic data to {data_path}")return dfexcept Exception as e:logger.error(f"Error generating synthetic data: {e}", exc_info=True)raisedef validate_data(df: pd.DataFrame) -> bool:"""Validate the loaded data for required fields and data quality.Args:df: DataFrame to validateReturns:True if data is valid, False otherwise"""logger.info("Validating data quality")try:# Check for required columnsrequired_columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']missing_columns = [col for col in required_columns if col not in df.columns]if missing_columns:logger.error(f"Missing required columns: {missing_columns}")return False# Check for null valuesnull_counts = df[required_columns].isnull().sum()if null_counts.sum() > 0:logger.warning(f"Found null values: {null_counts.to_dict()}")# Check for negative pricesprice_columns = ['open', 'high', 'low', 'close']negative_prices = df[price_columns].lt(0).any().any()if negative_prices:logger.error("Found negative prices in data")return False# Check for negative volumesif (df['volume'] < 0).any():logger.error("Found negative volumes in data")return False# Check OHLC consistencyinvalid_ohlc = ((df['high'] < df['low']) |(df['open'] > df['high']) |(df['open'] < df['low']) |(df['close'] > df['high']) |(df['close'] < df['low']))if invalid_ohlc.any():logger.error(f"Found {invalid_ohlc.sum()} rows with invalid OHLC data")return Falselogger.info("Data validation passed")return Trueexcept Exception as e:logger.error(f"Error during data validation: {e}", exc_info=True)return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292import pandas as pdimport numpy as npimport loggingimport osfrom typing import Dict, Any, Optionalfrom datetime import datetime, timedeltalogger = logging.getLogger(__name__)def load_data(config: Dict[str, Any]) -> Optional[pd.DataFrame]:"""Load market data based on configuration.Args:config: Configuration dictionaryReturns:DataFrame with market data or None if error"""try:data_source = config['data_source']['type']logger.info(f"Loading data from source: {data_source}")if data_source == 'alpaca':return _load_alpaca_data(config)elif data_source == 'csv':return _load_csv_data(config)elif data_source == 'synthetic':return _load_synthetic_data(config)else:logger.error(f"Unsupported data source: {data_source}")return Noneexcept Exception as e:logger.error(f"Error loading data: {e}")return Nonedef _load_alpaca_data(config: Dict[str, Any]) -> Optional[pd.DataFrame]:"""Load market data from Alpaca"""try:from .alpaca_broker import AlpacaBroker# Initialize Alpaca brokeralpaca_broker = AlpacaBroker(config)# Get symbol and timeframe from configsymbol = config['trading']['symbol']timeframe = config['trading']['timeframe']# Convert timeframe to Alpaca formattf_map = {'1m': '1Min','5m': '5Min','15m': '15Min','1h': '1Hour','1d': '1Day'}alpaca_timeframe = tf_map.get(timeframe, '1Min')# Get market datadata = alpaca_broker.get_market_data(symbol=symbol,timeframe=alpaca_timeframe,limit=1000)if data is not None and not data.empty:logger.info(f"Loaded {len(data)} data points from Alpaca for {symbol}")return dataelse:logger.error(f"No data returned from Alpaca for {symbol}")return Noneexcept Exception as e:logger.error(f"Error loading Alpaca data: {e}")return Nonedef _load_csv_data(config: Dict[str, Any]) -> Optional[pd.DataFrame]:"""Load market data from CSV file"""try:file_path = config['data_source']['path']if not os.path.exists(file_path):logger.error(f"CSV file not found: {file_path}")return None# Load CSV datadata = pd.read_csv(file_path)# Ensure required columns existrequired_columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']missing_columns = [col for col in required_columns if col not in data.columns]if missing_columns:logger.error(f"Missing required columns: {missing_columns}")return None# Convert timestamp to datetimedata['timestamp'] = pd.to_datetime(data['timestamp'])# Sort by timestampdata = data.sort_values('timestamp').reset_index(drop=True)logger.info(f"Loaded {len(data)} data points from CSV: {file_path}")return dataexcept Exception as e:logger.error(f"Error loading CSV data: {e}")return Nonedef _load_synthetic_data(config: Dict[str, Any]) -> Optional[pd.DataFrame]:"""Load or generate synthetic market data"""try:synthetic_config = config.get('synthetic_data', {})data_path = synthetic_config.get('data_path', 'data/synthetic_market_data.csv')# Check if synthetic data file existsif os.path.exists(data_path):logger.info(f"Loading existing synthetic data from: {data_path}")return _load_csv_data({'data_source': {'path': data_path}})# Generate new synthetic datalogger.info("Generating new synthetic market data")from .synthetic_data_generator import SyntheticDataGeneratorgenerator = SyntheticDataGenerator(config)data = generator.generate_data()# Save generated dataos.makedirs(os.path.dirname(data_path), exist_ok=True)data.to_csv(data_path, index=False)logger.info(f"Saved synthetic data to: {data_path}")return dataexcept Exception as e:logger.error(f"Error loading synthetic data: {e}")return Nonedef validate_data(data: pd.DataFrame) -> bool:"""Validate market data quality.Args:data: DataFrame with market dataReturns:True if data is valid, False otherwise"""try:if data is None or data.empty:logger.error("Data is None or empty")return False# Check required columnsrequired_columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']missing_columns = [col for col in required_columns if col not in data.columns]if missing_columns:logger.error(f"Missing required columns: {missing_columns}")return False# Check for NaN valuesnan_counts = data[required_columns].isna().sum()if nan_counts.sum() > 0:logger.warning(f"Found NaN values: {nan_counts.to_dict()}")# Remove rows with NaN valuesdata.dropna(subset=required_columns, inplace=True)logger.info(f"Removed {nan_counts.sum()} rows with NaN values")# Check for negative pricesprice_columns = ['open', 'high', 'low', 'close']negative_prices = data[price_columns] < 0if negative_prices.any().any():logger.error("Found negative prices in data")return False# Check for zero volumeszero_volumes = data['volume'] == 0if zero_volumes.sum() > len(data) * 0.5: # More than 50% zero volumeslogger.warning("High percentage of zero volumes detected")# Check OHLC consistencyinvalid_ohlc = ((data['high'] < data['low']) |(data['open'] > data['high']) |(data['close'] > data['high']) |(data['open'] < data['low']) |(data['close'] < data['low']))if invalid_ohlc.any():logger.error("Found invalid OHLC relationships")return False# Check timestamp consistencyif 'timestamp' in data.columns:timestamps = pd.to_datetime(data['timestamp'])if not timestamps.is_monotonic_increasing:logger.warning("Timestamps are not in ascending order")data = data.sort_values('timestamp').reset_index(drop=True)logger.info(f"Data validation passed: {len(data)} valid records")return Trueexcept Exception as e:logger.error(f"Error validating data: {e}")return Falsedef add_technical_indicators(data: pd.DataFrame) -> pd.DataFrame:"""Add technical indicators to market data.Args:data: DataFrame with OHLCV dataReturns:DataFrame with technical indicators added"""try:df = data.copy()# Simple Moving Averagesdf['sma_20'] = df['close'].rolling(window=20).mean()df['sma_50'] = df['close'].rolling(window=50).mean()df['sma_200'] = df['close'].rolling(window=200).mean()# Exponential Moving Averagesdf['ema_12'] = df['close'].ewm(span=12).mean()df['ema_26'] = df['close'].ewm(span=26).mean()# MACDdf['macd'] = df['ema_12'] - df['ema_26']df['macd_signal'] = df['macd'].ewm(span=9).mean()df['macd_histogram'] = df['macd'] - df['macd_signal']# RSIdelta = df['close'].diff()gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()rs = gain / lossdf['rsi'] = 100 - (100 / (1 + rs))# Bollinger Bandsdf['bb_middle'] = df['close'].rolling(window=20).mean()bb_std = df['close'].rolling(window=20).std()df['bb_upper'] = df['bb_middle'] + (bb_std * 2)df['bb_lower'] = df['bb_middle'] - (bb_std * 2)# Average True Range (ATR)high_low = df['high'] - df['low']high_close = np.abs(df['high'] - df['close'].shift())low_close = np.abs(df['low'] - df['close'].shift())true_range = np.maximum(high_low, np.maximum(high_close, low_close))df['atr'] = true_range.rolling(window=14).mean()# Volume indicatorsdf['volume_sma'] = df['volume'].rolling(window=20).mean()df['volume_ratio'] = df['volume'] / df['volume_sma']# Price momentumdf['price_change'] = df['close'].pct_change()df['price_change_5'] = df['close'].pct_change(periods=5)df['price_change_20'] = df['close'].pct_change(periods=20)logger.info("Technical indicators added successfully")return dfexcept Exception as e:logger.error(f"Error adding technical indicators: {e}")return datadef get_latest_data(data: pd.DataFrame, n_periods: int = 100) -> pd.DataFrame:"""Get the latest n periods of data.Args:data: DataFrame with market datan_periods: Number of periods to returnReturns:DataFrame with latest n periods"""try:if len(data) <= n_periods:return datareturn data.tail(n_periods).reset_index(drop=True)except Exception as e:logger.error(f"Error getting latest data: {e}")return data
9 unmodified lines10111213141514 unmodified lines30313233343536374 unmodified lines42434445464726 unmodified lines74757677787980818283848586878889909192939495969798991001019 unmodified linesself.order_size = config['execution']['order_size']self.execution_delay = config.get('execution', {}).get('delay_ms', 100)self.success_rate = config.get('execution', {}).get('success_rate', 0.95)self.logger.info(f"Execution agent initialized with {self.broker_api} broker")def act(self, signal: Dict[str, Any]) -> Dict[str, Any]:14 unmodified linesself.logger.warning("Invalid signal received, skipping execution")return self._generate_execution_result(signal, success=False, error="Invalid signal")# Simulate order executionexecution_result = self._execute_order(signal)# Log execution resultself.log_action(execution_result)4 unmodified linesself.log_error(e, "Error in order execution")return self._generate_execution_result(signal, success=False, error=str(e))def _validate_signal(self, signal: Dict[str, Any]) -> bool:"""Validate trading signal"""try:26 unmodified linesself.log_error(e, "Error validating signal")return Falsedef _execute_order(self, signal: Dict[str, Any]) -> Dict[str, Any]:"""Execute order with broker simulation"""try:# Simulate execution delaytime.sleep(self.execution_delay / 1000.0)# Simulate execution success/failureimport randomsuccess = random.random() < self.success_rateif signal['action'] == 'hold':success = True # Hold actions always succeedif success:return self._simulate_successful_execution(signal)else:return self._simulate_failed_execution(signal)except Exception as e:self.log_error(e, "Error in order execution simulation")return self._generate_execution_result(signal, success=False, error=str(e))def _simulate_successful_execution(self, signal: Dict[str, Any]) -> Dict[str, Any]:"""Simulate successful order execution"""try:9 unmodified lines10111213141516171819202122232425262714 unmodified lines42434445464748495051524 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415526 unmodified lines1821831841851861879 unmodified linesself.order_size = config['execution']['order_size']self.execution_delay = config.get('execution', {}).get('delay_ms', 100)self.success_rate = config.get('execution', {}).get('success_rate', 0.95)# Initialize Alpaca broker if configuredself.alpaca_broker = Noneif self.broker_api in ['alpaca_paper', 'alpaca_live']:try:from .alpaca_broker import AlpacaBrokerself.alpaca_broker = AlpacaBroker(config)self.logger.info(f"Alpaca broker initialized for {self.broker_api}")except Exception as e:self.logger.error(f"Failed to initialize Alpaca broker: {e}")self.broker_api = 'paper' # Fallback to simulationself.logger.info(f"Execution agent initialized with {self.broker_api} broker")def act(self, signal: Dict[str, Any]) -> Dict[str, Any]:14 unmodified linesself.logger.warning("Invalid signal received, skipping execution")return self._generate_execution_result(signal, success=False, error="Invalid signal")# Execute order based on broker typeif self.broker_api in ['alpaca_paper', 'alpaca_live'] and self.alpaca_broker:execution_result = self._execute_alpaca_order(signal)else:execution_result = self._execute_simulated_order(signal)# Log execution resultself.log_action(execution_result)4 unmodified linesself.log_error(e, "Error in order execution")return self._generate_execution_result(signal, success=False, error=str(e))def _execute_alpaca_order(self, signal: Dict[str, Any]) -> Dict[str, Any]:"""Execute order using Alpaca broker"""try:if signal['action'] == 'hold':return self._generate_execution_result(signal, success=True, error=None)# Place market order with Alpacaresult = self.alpaca_broker.place_market_order(symbol=signal['symbol'],quantity=signal['quantity'],side=signal['action'])# Convert Alpaca result to our formatexecution_result = {'order_id': result.get('order_id'),'status': result.get('status', 'unknown'),'action': signal['action'],'symbol': signal['symbol'],'quantity': signal['quantity'],'price': result.get('filled_avg_price', signal.get('price', 0)),'execution_time': time.time(),'commission': self._calculate_commission(signal),'total_value': result.get('filled_avg_price', 0) * signal['quantity'] if result.get('filled_avg_price') else 0,'success': result.get('success', False),'error': result.get('error')}if execution_result['success']:self.logger.info(f"Alpaca order executed successfully: {execution_result['order_id']}")else:self.logger.error(f"Alpaca order failed: {execution_result['error']}")return execution_resultexcept Exception as e:self.log_error(e, "Error in Alpaca order execution")return self._generate_execution_result(signal, success=False, error=str(e))def _execute_simulated_order(self, signal: Dict[str, Any]) -> Dict[str, Any]:"""Execute order with broker simulation"""try:# Simulate execution delaytime.sleep(self.execution_delay / 1000.0)# Simulate execution success/failureimport randomsuccess = random.random() < self.success_rateif signal['action'] == 'hold':success = True # Hold actions always succeedif success:return self._simulate_successful_execution(signal)else:return self._simulate_failed_execution(signal)except Exception as e:self.log_error(e, "Error in order execution simulation")return self._generate_execution_result(signal, success=False, error=str(e))def get_account_info(self) -> Dict[str, Any]:"""Get account information"""if self.alpaca_broker:return self.alpaca_broker.get_account_info()else:# Return simulated account inforeturn {'account_id': 'SIM_ACCOUNT','status': 'ACTIVE','buying_power': 100000.0,'cash': 100000.0,'portfolio_value': 100000.0,'equity': 100000.0,'trading_blocked': False}def get_positions(self) -> list:"""Get current positions"""if self.alpaca_broker:return self.alpaca_broker.get_positions()else:# Return simulated positionsreturn []def is_market_open(self) -> bool:"""Check if market is open"""if self.alpaca_broker:return self.alpaca_broker.is_market_open()else:# Assume market is always open for simulationreturn Truedef _validate_signal(self, signal: Dict[str, Any]) -> bool:"""Validate trading signal"""try:26 unmodified linesself.log_error(e, "Error validating signal")return Falsedef _simulate_successful_execution(self, signal: Dict[str, Any]) -> Dict[str, Any]:"""Simulate successful order execution"""try:
2 unmodified lines345678941 unmodified lines5152535455565758596061626364656661 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719810 unmodified lines20921021121221321421521621721821922022119 unmodified lines2412422432442452462472482492502512522532547 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464472 unmodified linesThis module provides a FinRL-based reinforcement learning agent that can be integratedwith the existing algorithmic trading system. It supports various RL algorithmsincluding PPO, A2C, DDPG, and TD3."""import numpy as np41 unmodified lines- Buy, sell, or hold positions- Use technical indicators for decision making- Manage portfolio value and risk"""def __init__(self, data: pd.DataFrame, initial_balance: float = 100000,transaction_fee: float = 0.001, max_position: int = 100):super().__init__()self.data = dataself.initial_balance = initial_balanceself.transaction_fee = transaction_feeself.max_position = max_position# Reset stateself.reset()61 unmodified linesif action == 0: # Sellif self.position > 0:shares_to_sell = min(self.position, self.max_position)sell_value = shares_to_sell * current_price * (1 - self.transaction_fee)self.balance += sell_valueself.position -= shares_to_sellelif action == 2: # Buyif self.balance > 0:max_shares = min(int(self.balance / current_price),self.max_position - self.position)if max_shares > 0:buy_value = max_shares * current_price * (1 + self.transaction_fee)self.balance -= buy_valueself.position += max_shares# Update portfolio valueself.previous_portfolio_value = self.portfolio_valueself.portfolio_value = self._calculate_portfolio_value()self.total_return = (self.portfolio_value - self.initial_balance) / self.initial_balance# Calculate rewardreward = self._calculate_reward()# Move to next stepself.current_step += 1# Check if episode is donedone = self.current_step >= len(self.data) - 1# Get observationif not done:observation = self._get_features(self.data.iloc[self.current_step])else:# Use last available data for final observationobservation = self._get_features(self.data.iloc[-1])info = {'balance': self.balance,'position': self.position,'portfolio_value': self.portfolio_value,'total_return': self.total_return,'current_price': current_price}return observation, reward, done, False, info9 unmodified linesself.previous_portfolio_value = self.initial_balanceself.total_return = 0.0observation = self._get_features(self.data.iloc[self.current_step])info = {'balance': self.balance,'position': self.position,'portfolio_value': self.portfolio_value,'total_return': self.total_return}return observation, infoclass FinRLAgent:10 unmodified lineslogger.info(f"Initializing FinRL agent with algorithm: {config.algorithm}")def create_environment(self, data: pd.DataFrame, initial_balance: float = 100000) -> TradingEnvironment:"""Create trading environment from market data"""return TradingEnvironment(data=data,initial_balance=initial_balance,transaction_fee=0.001,max_position=100)def prepare_data(self, data: pd.DataFrame) -> pd.DataFrame:19 unmodified linesreturn dfdef _calculate_rsi(self, prices: pd.Series, period: int = 14) -> pd.Series:"""Calculate RSI indicator"""delta = prices.diff()gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()rs = gain / lossrsi = 100 - (100 / (1 + rs))return rsidef _calculate_bollinger_bands(self, prices: pd.Series, period: int = 20, std_dev: int = 2) -> Tuple[pd.Series, pd.Series]:"""Calculate Bollinger Bands"""7 unmodified lines"""Calculate MACD indicator"""ema_fast = prices.ewm(span=fast).mean()ema_slow = prices.ewm(span=slow).mean()macd_line = ema_fast - ema_slowreturn macd_linedef train(self, data: pd.DataFrame, total_timesteps: int = 100000,eval_freq: int = 10000, eval_data: Optional[pd.DataFrame] = None) -> Dict[str, Any]:"""Train the FinRL agent"""logger.info("Starting FinRL agent training")# Prepare datatrain_data = self.prepare_data(data)# Create training environmentself.env = DummyVecEnv([lambda: self.create_environment(train_data)])# Create evaluation environment if providedif eval_data is not None:eval_data = self.prepare_data(eval_data)self.eval_env = DummyVecEnv([lambda: self.create_environment(eval_data)])self.callback = EvalCallback(self.eval_env,best_model_save_path="models/finrl_best/",log_path="logs/finrl_eval/",eval_freq=eval_freq,deterministic=True,render=False)# Initialize model based on algorithmif self.config.algorithm == "PPO":self.model = PPO("MlpPolicy",self.env,learning_rate=self.config.learning_rate,batch_size=self.config.batch_size,gamma=self.config.gamma,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)elif self.config.algorithm == "A2C":self.model = A2C("MlpPolicy",self.env,learning_rate=self.config.learning_rate,gamma=self.config.gamma,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)elif self.config.algorithm == "DDPG":self.model = DDPG("MlpPolicy",self.env,learning_rate=self.config.learning_rate,buffer_size=self.config.buffer_size,learning_starts=self.config.learning_starts,gamma=self.config.gamma,tau=self.config.tau,train_freq=self.config.train_freq,gradient_steps=self.config.gradient_steps,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)elif self.config.algorithm == "TD3":self.model = TD3("MlpPolicy",self.env,learning_rate=self.config.learning_rate,buffer_size=self.config.buffer_size,learning_starts=self.config.learning_starts,gamma=self.config.gamma,tau=self.config.tau,train_freq=self.config.train_freq,gradient_steps=self.config.gradient_steps,target_update_interval=self.config.target_update_interval,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)else:raise ValueError(f"Unsupported algorithm: {self.config.algorithm}")# Train the modelcallbacks = [self.callback] if self.callback else Noneself.model.learn(total_timesteps=total_timesteps,callback=callbacks)logger.info("FinRL agent training completed")return {'algorithm': self.config.algorithm,'total_timesteps': total_timesteps,'model_path': f"models/finrl_{self.config.algorithm.lower()}"}def predict(self, data: pd.DataFrame) -> List[int]:"""Generate trading predictions using the trained model"""if self.model is None:raise ValueError("Model not trained. Call train() first.")# Prepare datatest_data = self.prepare_data(data)# Create test environmenttest_env = self.create_environment(test_data)predictions = []obs, _ = test_env.reset()done = Falsewhile not done:action, _ = self.model.predict(obs, deterministic=True)predictions.append(action)obs, _, done, _, _ = test_env.step(action)return predictionsdef evaluate(self, data: pd.DataFrame) -> Dict[str, float]:"""Evaluate the trained model on test data"""if self.model is None:raise ValueError("Model not trained. Call train() first.")# Prepare datatest_data = self.prepare_data(data)# Create test environmenttest_env = self.create_environment(test_data)obs, _ = test_env.reset()done = Falsetotal_reward = 0steps = 0while not done:action, _ = self.model.predict(obs, deterministic=True)obs, reward, done, _, info = test_env.step(action)total_reward += rewardsteps += 1# Calculate metricsfinal_portfolio_value = info['portfolio_value']initial_balance = test_env.initial_balancetotal_return = (final_portfolio_value - initial_balance) / initial_balancereturn {'total_reward': total_reward,'total_return': total_return,'final_portfolio_value': final_portfolio_value,'steps': steps,'sharpe_ratio': total_reward / steps if steps > 0 else 0}def save_model(self, path: str):"""Save the trained model"""if self.model is None:raise ValueError("No model to save. Train the model first.")self.model.save(path)logger.info(f"Model saved to {path}")def load_model(self, path: str):"""Load a trained model"""if self.config.algorithm == "PPO":self.model = PPO.load(path)elif self.config.algorithm == "A2C":self.model = A2C.load(path)elif self.config.algorithm == "DDPG":self.model = DDPG.load(path)elif self.config.algorithm == "TD3":self.model = TD3.load(path)else:raise ValueError(f"Unsupported algorithm: {self.config.algorithm}")logger.info(f"Model loaded from {path}")def create_finrl_agent_from_config(config_path: str) -> FinRLAgent:"""Create FinRL agent from configuration file"""with open(config_path, 'r') as file:config_data = yaml.safe_load(file)finrl_config = FinRLConfig(**config_data.get('finrl', {}))return FinRLAgent(finrl_config)2 unmodified lines345678941 unmodified lines5152535455565758596061626364656667686970717273747576777879808161 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252269 unmodified lines23623723823924024124224324424510 unmodified lines25625725825926026126226326426526626726826927027119 unmodified lines2912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055067 unmodified lines5145155165175182 unmodified linesThis module provides a FinRL-based reinforcement learning agent that can be integratedwith the existing algorithmic trading system. It supports various RL algorithmsincluding PPO, A2C, DDPG, and TD3, and can work with Alpaca broker for real trading."""import numpy as np41 unmodified lines- Buy, sell, or hold positions- Use technical indicators for decision making- Manage portfolio value and risk- Integrate with Alpaca broker for real trading"""def __init__(self, data: pd.DataFrame, config: Dict[str, Any],initial_balance: float = 100000, transaction_fee: float = 0.001,max_position: int = 100, use_real_broker: bool = False):super().__init__()self.data = dataself.config = configself.initial_balance = initial_balanceself.transaction_fee = transaction_feeself.max_position = max_positionself.use_real_broker = use_real_broker# Initialize Alpaca broker if using real tradingself.alpaca_broker = Noneif use_real_broker:try:from .alpaca_broker import AlpacaBrokerself.alpaca_broker = AlpacaBroker(config)logger.info("Alpaca broker initialized for FinRL environment")except Exception as e:logger.error(f"Failed to initialize Alpaca broker: {e}")self.use_real_broker = False# Reset stateself.reset()61 unmodified linesif action == 0: # Sellif self.position > 0:shares_to_sell = min(self.position, self.max_position)if self.use_real_broker and self.alpaca_broker:# Execute real order with Alpacaresult = self.alpaca_broker.place_market_order(symbol=self.config['trading']['symbol'],quantity=shares_to_sell,side='sell')if result['success']:sell_value = result['filled_avg_price'] * shares_to_sell * (1 - self.transaction_fee)self.balance += sell_valueself.position -= shares_to_selllogger.info(f"Real sell order executed: {result['order_id']}")else:logger.warning(f"Real sell order failed: {result['error']}")else:# Simulate order executionsell_value = shares_to_sell * current_price * (1 - self.transaction_fee)self.balance += sell_valueself.position -= shares_to_sellelif action == 2: # Buyif self.balance > 0:max_shares = min(int(self.balance / current_price),self.max_position - self.position)if max_shares > 0:if self.use_real_broker and self.alpaca_broker:# Execute real order with Alpacaresult = self.alpaca_broker.place_market_order(symbol=self.config['trading']['symbol'],quantity=max_shares,side='buy')if result['success']:buy_value = result['filled_avg_price'] * max_shares * (1 + self.transaction_fee)self.balance -= buy_valueself.position += max_shareslogger.info(f"Real buy order executed: {result['order_id']}")else:logger.warning(f"Real buy order failed: {result['error']}")else:# Simulate order executionbuy_value = max_shares * current_price * (1 + self.transaction_fee)self.balance -= buy_valueself.position += max_shares# Update portfolio valueself.previous_portfolio_value = self.portfolio_valueself.portfolio_value = self._calculate_portfolio_value()self.total_return = (self.portfolio_value - self.initial_balance) / self.initial_balance# Move to next stepself.current_step += 1# Check if episode is donedone = self.current_step >= len(self.data) - 1# Get observation for next stepif not done:observation = self._get_features(self.data.iloc[self.current_step])else:observation = self._get_features(self.data.iloc[-1])# Calculate rewardreward = self._calculate_reward()# Additional infoinfo = {'portfolio_value': self.portfolio_value,'total_return': self.total_return,'position': self.position,'balance': self.balance,'step': self.current_step}return observation, reward, done, False, info9 unmodified linesself.previous_portfolio_value = self.initial_balanceself.total_return = 0.0# Get initial observationobservation = self._get_features(self.data.iloc[0])return observation, {}class FinRLAgent:10 unmodified lineslogger.info(f"Initializing FinRL agent with algorithm: {config.algorithm}")def create_environment(self, data: pd.DataFrame, config: Dict[str, Any],initial_balance: float = 100000, use_real_broker: bool = False) -> TradingEnvironment:"""Create trading environment from market data"""return TradingEnvironment(data=data,config=config,initial_balance=initial_balance,transaction_fee=0.001,max_position=100,use_real_broker=use_real_broker)def prepare_data(self, data: pd.DataFrame) -> pd.DataFrame:19 unmodified linesreturn dfdef train(self, data: pd.DataFrame, config: Dict[str, Any],total_timesteps: int = 100000, use_real_broker: bool = False) -> Dict[str, Any]:"""Train the FinRL agentArgs:data: Market data for trainingconfig: Configuration dictionarytotal_timesteps: Number of timesteps for traininguse_real_broker: Whether to use real Alpaca broker during trainingReturns:Training results dictionary"""try:# Prepare dataprepared_data = self.prepare_data(data)# Create environmentself.env = self.create_environment(prepared_data, config, use_real_broker=use_real_broker)# Create evaluation environment (without real broker)eval_data = prepared_data.copy()self.eval_env = self.create_environment(eval_data, config, use_real_broker=False)# Create callback for evaluationself.callback = EvalCallback(self.eval_env,best_model_save_path=config['finrl']['training']['model_save_path'],log_path=config['finrl']['tensorboard_log'],eval_freq=config['finrl']['training']['eval_freq'],deterministic=True,render=False)# Initialize model based on algorithmif self.config.algorithm == "PPO":self.model = PPO("MlpPolicy",self.env,learning_rate=self.config.learning_rate,batch_size=self.config.batch_size,buffer_size=self.config.buffer_size,learning_starts=self.config.learning_starts,gamma=self.config.gamma,train_freq=self.config.train_freq,gradient_steps=self.config.gradient_steps,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)elif self.config.algorithm == "A2C":self.model = A2C("MlpPolicy",self.env,learning_rate=self.config.learning_rate,gamma=self.config.gamma,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)elif self.config.algorithm == "DDPG":self.model = DDPG("MlpPolicy",self.env,learning_rate=self.config.learning_rate,buffer_size=self.config.buffer_size,learning_starts=self.config.learning_starts,gamma=self.config.gamma,tau=self.config.tau,train_freq=self.config.train_freq,gradient_steps=self.config.gradient_steps,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)elif self.config.algorithm == "TD3":self.model = TD3("MlpPolicy",self.env,learning_rate=self.config.learning_rate,buffer_size=self.config.buffer_size,learning_starts=self.config.learning_starts,gamma=self.config.gamma,tau=self.config.tau,train_freq=self.config.train_freq,gradient_steps=self.config.gradient_steps,verbose=self.config.verbose,tensorboard_log=self.config.tensorboard_log)else:raise ValueError(f"Unsupported algorithm: {self.config.algorithm}")# Train the modellogger.info(f"Starting training with {total_timesteps} timesteps")self.model.learn(total_timesteps=total_timesteps,callback=self.callback,progress_bar=True)# Save the final modelmodel_path = f"{config['finrl']['training']['model_save_path']}/final_model"self.model.save(model_path)logger.info(f"Training completed. Model saved to {model_path}")return {'success': True,'algorithm': self.config.algorithm,'total_timesteps': total_timesteps,'model_path': model_path}except Exception as e:logger.error(f"Error during training: {e}")return {'success': False,'error': str(e)}def predict(self, data: pd.DataFrame, config: Dict[str, Any],use_real_broker: bool = False) -> Dict[str, Any]:"""Make predictions using the trained modelArgs:data: Market data for predictionconfig: Configuration dictionaryuse_real_broker: Whether to use real Alpaca broker for executionReturns:Prediction results dictionary"""try:if self.model is None:# Try to load modelmodel_path = config['finrl']['inference']['model_path']if config['finrl']['inference']['use_trained_model']:self.model = self._load_model(model_path, config)if self.model is None:return {'success': False, 'error': 'No trained model available'}else:return {'success': False, 'error': 'No model available for prediction'}# Prepare dataprepared_data = self.prepare_data(data)# Create environmentenv = self.create_environment(prepared_data, config, use_real_broker=use_real_broker)# Run predictionobs, _ = env.reset()done = Falseactions = []rewards = []portfolio_values = []while not done:action, _ = self.model.predict(obs, deterministic=True)obs, reward, done, _, info = env.step(action)actions.append(action)rewards.append(reward)portfolio_values.append(info['portfolio_value'])# Calculate final metricsinitial_value = config['trading']['capital']final_value = portfolio_values[-1] if portfolio_values else initial_valuetotal_return = (final_value - initial_value) / initial_valuereturn {'success': True,'actions': actions,'rewards': rewards,'portfolio_values': portfolio_values,'initial_value': initial_value,'final_value': final_value,'total_return': total_return,'total_trades': len([a for a in actions if a != 1]) # Count non-hold actions}except Exception as e:logger.error(f"Error during prediction: {e}")return {'success': False,'error': str(e)}def _load_model(self, model_path: str, config: Dict[str, Any]):"""Load a trained model"""try:if config['finrl']['algorithm'] == "PPO":return PPO.load(model_path)elif config['finrl']['algorithm'] == "A2C":return A2C.load(model_path)elif config['finrl']['algorithm'] == "DDPG":return DDPG.load(model_path)elif config['finrl']['algorithm'] == "TD3":return TD3.load(model_path)else:logger.error(f"Unsupported algorithm for model loading: {config['finrl']['algorithm']}")return Noneexcept Exception as e:logger.error(f"Error loading model: {e}")return Nonedef _calculate_rsi(self, prices: pd.Series, period: int = 14) -> pd.Series:"""Calculate RSI indicator"""delta = prices.diff()gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()rs = gain / lossreturn 100 - (100 / (1 + rs))def _calculate_bollinger_bands(self, prices: pd.Series, period: int = 20, std_dev: int = 2) -> Tuple[pd.Series, pd.Series]:"""Calculate Bollinger Bands"""7 unmodified lines"""Calculate MACD indicator"""ema_fast = prices.ewm(span=fast).mean()ema_slow = prices.ewm(span=slow).mean()macd = ema_fast - ema_slowreturn macd
12 unmodified lines131415161718192012 unmodified linesmax_drawdown: 0.05execution:broker_api: 'paper'order_size: 10# Synthetic data generation settingssynthetic_data:12 unmodified lines13141516171819202122232425262728293031323312 unmodified linesmax_drawdown: 0.05execution:broker_api: 'paper' # Options: 'paper', 'alpaca_paper', 'alpaca_live'order_size: 10delay_ms: 100success_rate: 0.95# Alpaca configurationalpaca:api_key: '' # Set via environment variable ALPACA_API_KEYsecret_key: '' # Set via environment variable ALPACA_SECRET_KEYpaper_trading: true # Use paper trading by defaultbase_url: 'https://paper-api.alpaca.markets' # Paper trading URLlive_url: 'https://api.alpaca.markets' # Live trading URLdata_url: 'https://data.alpaca.markets' # Market data URLwebsocket_url: 'wss://stream.data.alpaca.markets/v2/iex' # WebSocket URLaccount_type: 'paper' # 'paper' or 'live'# Synthetic data generation settingssynthetic_data:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148#!/usr/bin/env python3"""Demonstration script for the Algorithmic Trading SystemThis script demonstrates the key features of the system:- Synthetic data generation- Trading workflow execution- Backtesting- Logging"""import yamlimport pandas as pdfrom agentic_ai_system.synthetic_data_generator import SyntheticDataGeneratorfrom agentic_ai_system.logger_config import setup_loggingfrom agentic_ai_system.orchestrator import run, run_backtestfrom agentic_ai_system.main import load_configdef main():"""Main demonstration function"""print("🚀 Algorithmic Trading System Demo")print("=" * 50)# Load configurationtry:config = load_config()print("✅ Configuration loaded successfully")except Exception as e:print(f"❌ Error loading configuration: {e}")return# Setup loggingsetup_logging(config)print("✅ Logging system initialized")# Demo 1: Synthetic Data Generationprint("\n📊 Demo 1: Synthetic Data Generation")print("-" * 30)try:generator = SyntheticDataGenerator(config)# Generate OHLCV dataprint("Generating OHLCV data...")ohlcv_data = generator.generate_ohlcv_data(symbol='AAPL',start_date='2024-01-01',end_date='2024-01-02',frequency='1H')print(f"✅ Generated {len(ohlcv_data)} OHLCV data points")# Show sample dataprint("\nSample OHLCV data:")print(ohlcv_data.head())# Generate different market scenariosprint("\nGenerating market scenarios...")scenarios = ['normal', 'volatile', 'trending', 'crash']for scenario in scenarios:scenario_data = generator.generate_market_scenarios(scenario)avg_price = scenario_data['close'].mean()print(f" {scenario.capitalize()} market: {len(scenario_data)} points, avg price: ${avg_price:.2f}")except Exception as e:print(f"❌ Error in synthetic data generation: {e}")# Demo 2: Trading Workflowprint("\n🤖 Demo 2: Trading Workflow")print("-" * 30)try:print("Running trading workflow...")result = run(config)if result['success']:print("✅ Trading workflow completed successfully")print(f" Data loaded: {result['data_loaded']}")print(f" Signal generated: {result['signal_generated']}")print(f" Order executed: {result['order_executed']}")print(f" Execution time: {result['execution_time']:.2f} seconds")if result['order_executed'] and result['execution_result']:exec_result = result['execution_result']print(f" Order details: {exec_result['action']} {exec_result['quantity']} {exec_result['symbol']} @ ${exec_result['price']:.2f}")else:print("❌ Trading workflow failed")print(f" Errors: {result['errors']}")except Exception as e:print(f"❌ Error in trading workflow: {e}")# Demo 3: Backtestingprint("\n📈 Demo 3: Backtesting")print("-" * 30)try:print("Running backtest...")backtest_result = run_backtest(config, '2024-01-01', '2024-01-07')if backtest_result['success']:print("✅ Backtest completed successfully")print(f" Initial capital: ${backtest_result['initial_capital']:,.2f}")print(f" Final value: ${backtest_result['final_value']:,.2f}")print(f" Total return: {backtest_result['total_return']:.2%}")print(f" Total trades: {backtest_result['total_trades']}")print(f" Positions: {backtest_result['positions']}")else:print("❌ Backtest failed")print(f" Error: {backtest_result['error']}")except Exception as e:print(f"❌ Error in backtesting: {e}")# Demo 4: System Statisticsprint("\n📊 Demo 4: System Statistics")print("-" * 30)try:# Show configuration summaryprint("Configuration Summary:")print(f" Trading symbol: {config['trading']['symbol']}")print(f" Timeframe: {config['trading']['timeframe']}")print(f" Capital: ${config['trading']['capital']:,.2f}")print(f" Max position: {config['risk']['max_position']}")print(f" Max drawdown: {config['risk']['max_drawdown']:.1%}")print(f" Broker API: {config['execution']['broker_api']}")# Show synthetic data parametersprint("\nSynthetic Data Parameters:")print(f" Base price: ${config['synthetic_data']['base_price']:.2f}")print(f" Volatility: {config['synthetic_data']['volatility']:.3f}")print(f" Trend: {config['synthetic_data']['trend']:.3f}")print(f" Noise level: {config['synthetic_data']['noise_level']:.3f}")except Exception as e:print(f"❌ Error showing statistics: {e}")print("\n🎉 Demo completed!")print("\n📝 Check the logs directory for detailed logs:")print(" - logs/trading_system.log")print(" - logs/trading.log")print(" - logs/performance.log")print(" - logs/errors.log")if __name__ == '__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329#!/usr/bin/env python3"""Demo script for the Algorithmic Trading System with FinRL and Alpaca IntegrationThis script demonstrates the complete trading workflow including:- Data ingestion from multiple sources (CSV, Alpaca, Synthetic)- Strategy generation with technical indicators- Order execution with Alpaca broker- FinRL reinforcement learning integration- Real-time trading capabilities"""import osimport sysimport timeimport loggingfrom datetime import datetime, timedeltafrom typing import Dict, Any# Add the project root to the pathsys.path.append(os.path.dirname(os.path.abspath(__file__)))from agentic_ai_system.main import load_configfrom agentic_ai_system.orchestrator import run, run_backtest, run_live_tradingfrom agentic_ai_system.data_ingestion import load_data, validate_data, add_technical_indicatorsfrom agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfigfrom agentic_ai_system.alpaca_broker import AlpacaBrokerdef setup_logging():"""Setup logging configuration"""logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[logging.StreamHandler(),logging.FileHandler('logs/demo.log')])def print_system_info(config: Dict[str, Any]):"""Print system configuration information"""print("\n" + "="*60)print("🤖 ALGORITHMIC TRADING SYSTEM WITH FINRL & ALPACA")print("="*60)print(f"\n📊 Data Source: {config['data_source']['type']}")print(f"📈 Trading Symbol: {config['trading']['symbol']}")print(f"💰 Capital: ${config['trading']['capital']:,}")print(f"⏱️ Timeframe: {config['trading']['timeframe']}")print(f"🔧 Broker API: {config['execution']['broker_api']}")if config['execution']['broker_api'] in ['alpaca_paper', 'alpaca_live']:print(f"🏦 Alpaca Account Type: {config['alpaca']['account_type']}")print(f"📡 Alpaca Base URL: {config['alpaca']['base_url']}")print(f"🧠 FinRL Algorithm: {config['finrl']['algorithm']}")print(f"📚 Learning Rate: {config['finrl']['learning_rate']}")print(f"🎯 Training Steps: {config['finrl']['training']['total_timesteps']:,}")print("\n" + "="*60)def demo_data_ingestion(config: Dict[str, Any]):"""Demonstrate data ingestion capabilities"""print("\n📥 DATA INGESTION DEMO")print("-" * 30)try:# Load dataprint(f"Loading data from source: {config['data_source']['type']}")data = load_data(config)if data is not None and not data.empty:print(f"✅ Successfully loaded {len(data)} data points")print(f"📅 Date range: {data['timestamp'].min()} to {data['timestamp'].max()}")print(f"💰 Price range: ${data['close'].min():.2f} - ${data['close'].max():.2f}")# Validate dataif validate_data(data):print("✅ Data validation passed")# Add technical indicatorsdata_with_indicators = add_technical_indicators(data)print(f"✅ Added {len(data_with_indicators.columns) - len(data.columns)} technical indicators")return data_with_indicatorselse:print("❌ Data validation failed")return Noneelse:print("❌ Failed to load data")return Noneexcept Exception as e:print(f"❌ Error in data ingestion: {e}")return Nonedef demo_alpaca_integration(config: Dict[str, Any]):"""Demonstrate Alpaca broker integration"""print("\n🏦 ALPACA INTEGRATION DEMO")print("-" * 30)if config['execution']['broker_api'] not in ['alpaca_paper', 'alpaca_live']:print("⚠️ Alpaca integration not configured (using simulation mode)")return Nonetry:# Initialize Alpaca brokerprint("Connecting to Alpaca...")alpaca_broker = AlpacaBroker(config)# Get account informationaccount_info = alpaca_broker.get_account_info()if account_info:print(f"✅ Connected to Alpaca {config['alpaca']['account_type']} account")print(f" Account ID: {account_info['account_id']}")print(f" Status: {account_info['status']}")print(f" Buying Power: ${account_info['buying_power']:,.2f}")print(f" Portfolio Value: ${account_info['portfolio_value']:,.2f}")print(f" Equity: ${account_info['equity']:,.2f}")# Check market statusmarket_hours = alpaca_broker.get_market_hours()if market_hours:print(f"📈 Market Status: {'🟢 OPEN' if market_hours['is_open'] else '🔴 CLOSED'}")if market_hours['next_open']:print(f" Next Open: {market_hours['next_open']}")if market_hours['next_close']:print(f" Next Close: {market_hours['next_close']}")# Get current positionspositions = alpaca_broker.get_positions()if positions:print(f"📊 Current Positions: {len(positions)}")for pos in positions:print(f" {pos['symbol']}: {pos['quantity']} shares @ ${pos['current_price']:.2f}")else:print("📊 No current positions")return alpaca_brokerexcept Exception as e:print(f"❌ Error connecting to Alpaca: {e}")return Nonedef demo_finrl_training(config: Dict[str, Any], data):"""Demonstrate FinRL training"""print("\n🧠 FINRL TRAINING DEMO")print("-" * 30)try:# Initialize FinRL agentfinrl_config = FinRLConfig(algorithm=config['finrl']['algorithm'],learning_rate=config['finrl']['learning_rate'],batch_size=config['finrl']['batch_size'],buffer_size=config['finrl']['buffer_size'],learning_starts=config['finrl']['learning_starts'],gamma=config['finrl']['gamma'],tau=config['finrl']['tau'],train_freq=config['finrl']['train_freq'],gradient_steps=config['finrl']['gradient_steps'],verbose=config['finrl']['verbose'],tensorboard_log=config['finrl']['tensorboard_log'])agent = FinRLAgent(finrl_config)# Use a subset of data for demo trainingdemo_data = data.tail(500) if len(data) > 500 else dataprint(f"Training on {len(demo_data)} data points...")# Train the agent (shorter training for demo)training_steps = min(10000, config['finrl']['training']['total_timesteps'])result = agent.train(data=demo_data,config=config,total_timesteps=training_steps,use_real_broker=False # Use simulation for demo training)if result['success']:print(f"✅ Training completed successfully!")print(f" Algorithm: {result['algorithm']}")print(f" Timesteps: {result['total_timesteps']:,}")print(f" Model saved: {result['model_path']}")# Test predictionprint("\n🔮 Testing predictions...")prediction_result = agent.predict(data=demo_data.tail(100),config=config,use_real_broker=False)if prediction_result['success']:print(f"✅ Prediction completed!")print(f" Initial Value: ${prediction_result['initial_value']:,.2f}")print(f" Final Value: ${prediction_result['final_value']:,.2f}")print(f" Total Return: {prediction_result['total_return']:.2%}")print(f" Total Trades: {prediction_result['total_trades']}")return agentelse:print(f"��� Training failed: {result['error']}")return Noneexcept Exception as e:print(f"❌ Error in FinRL training: {e}")return Nonedef demo_trading_workflow(config: Dict[str, Any], data):"""Demonstrate complete trading workflow"""print("\n🔄 TRADING WORKFLOW DEMO")print("-" * 30)try:# Run single trading cycleprint("Running trading workflow...")result = run(config)if result['success']:print("✅ Trading workflow completed successfully!")print(f" Data Loaded: {'✅' if result['data_loaded'] else '❌'}")print(f" Signal Generated: {'✅' if result['signal_generated'] else '❌'}")print(f" Order Executed: {'✅' if result['order_executed'] else '❌'}")print(f" Execution Time: {result['execution_time']:.2f} seconds")if result['order_executed'] and result['execution_result']:exec_result = result['execution_result']print(f" Order ID: {exec_result.get('order_id', 'N/A')}")print(f" Action: {exec_result['action']}")print(f" Symbol: {exec_result['symbol']}")print(f" Quantity: {exec_result['quantity']}")print(f" Price: ${exec_result['price']:.2f}")print(f" Total Value: ${exec_result['total_value']:.2f}")else:print("❌ Trading workflow failed!")for error in result['errors']:print(f" Error: {error}")return resultexcept Exception as e:print(f"❌ Error in trading workflow: {e}")return Nonedef demo_backtest(config: Dict[str, Any], data):"""Demonstrate backtesting capabilities"""print("\n📊 BACKTESTING DEMO")print("-" * 30)try:# Run backtest on recent dataend_date = datetime.now().strftime('%Y-%m-%d')start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')print(f"Running backtest from {start_date} to {end_date}...")result = run_backtest(config, start_date, end_date)if result['success']:print("✅ Backtest completed successfully!")print(f" Initial Capital: ${result['initial_capital']:,.2f}")print(f" Final Value: ${result['final_value']:,.2f}")print(f" Total Return: {result['total_return']:.2%}")print(f" Total Trades: {result['total_trades']}")# Calculate additional metricsif result['total_trades'] > 0:win_rate = len([t for t in result['trades'] if t.get('execution', {}).get('success', False)]) / result['total_trades']print(f" Win Rate: {win_rate:.2%}")else:print(f"❌ Backtest failed: {result.get('error', 'Unknown error')}")return resultexcept Exception as e:print(f"❌ Error in backtesting: {e}")return Nonedef main():"""Main demo function"""setup_logging()try:# Load configurationconfig = load_config()print_system_info(config)# Demo 1: Data Ingestiondata = demo_data_ingestion(config)if data is None:print("❌ Cannot proceed without data")return# Demo 2: Alpaca Integrationalpaca_broker = demo_alpaca_integration(config)# Demo 3: FinRL Trainingfinrl_agent = demo_finrl_training(config, data)# Demo 4: Trading Workflowworkflow_result = demo_trading_workflow(config, data)# Demo 5: Backtestingbacktest_result = demo_backtest(config, data)# Summaryprint("\n" + "="*60)print("🎉 DEMO COMPLETED SUCCESSFULLY!")print("="*60)print("\n📋 Summary:")print(f" ✅ Data Ingestion: {'Working' if data is not None else 'Failed'}")print(f" ✅ Alpaca Integration: {'Working' if alpaca_broker is not None else 'Simulation Mode'}")print(f" ✅ FinRL Training: {'Working' if finrl_agent is not None else 'Failed'}")print(f" ✅ Trading Workflow: {'Working' if workflow_result and workflow_result['success'] else 'Failed'}")print(f" ✅ Backtesting: {'Working' if backtest_result and backtest_result['success'] else 'Failed'}")print("\n🚀 Next Steps:")print(" 1. Set up your Alpaca API credentials in .env file")print(" 2. Configure your trading strategy in config.yaml")print(" 3. Run live trading with: python -m agentic_ai_system.main --mode live")print(" 4. Monitor performance in logs/ directory")except Exception as e:print(f"❌ Demo failed with error: {e}")logging.error(f"Demo error: {e}", exc_info=True)if __name__ == "__main__":main()
12345678910111213141516171819202122232425262728# Alpaca API Configuration# Copy this file to .env and fill in your actual API credentials
# Alpaca API Keys (get from https://app.alpaca.markets/paper/dashboard/overview)ALPACA_API_KEY=your_paper_api_key_hereALPACA_SECRET_KEY=your_paper_secret_key_here
# For live trading (use with caution!)# ALPACA_API_KEY=your_live_api_key_here# ALPACA_SECRET_KEY=your_live_secret_key_here
# Optional: Override default URLs# ALPACA_PAPER_URL=https://paper-api.alpaca.markets# ALPACA_LIVE_URL=https://api.alpaca.markets# ALPACA_DATA_URL=https://data.alpaca.markets
# Trading ConfigurationTRADING_SYMBOL=AAPLTRADING_CAPITAL=100000TRADING_TIMEFRAME=1m
# Risk ManagementMAX_POSITION_SIZE=100MAX_DRAWDOWN=0.05
# LoggingLOG_LEVEL=INFOLOG_DIR=logs 12 unmodified lines13141512 unmodified linestensorboardtorchopencv-python-headless12 unmodified lines1314151617181912 unmodified linestensorboardtorchopencv-python-headlessalpaca-pypython-dotenvrequestswebsocket-client
README.md+266-382
agentic_ai_system/alpaca_broker.pyAdded+406
agentic_ai_system/data_ingestion.py+231-88
agentic_ai_system/execution_agent.py+110-24
agentic_ai_system/finrl_agent.py+283-212
config.yaml+14-1
demo.py+283-102
env.exampleAdded+28
requirements.txt+4