File size: 19,171 Bytes
81964c7 6b4e60d 81964c7 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 6cd35fc 1e265d1 6cd35fc 1abb0e9 46590b0 1e265d1 6cd35fc 1e265d1 46590b0 1e265d1 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 859af74 1e265d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 |
---
title: Algorithmic Trading System
emoji: π
colorFrom: blue
colorTo: green
sdk: streamlit
sdk_version: 1.46.1
app_file: streamlit_app.py
pinned: false
license: apache-2.0
---
# Algorithmic Trading System with FinRL and Alpaca Integration
A 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
### π¨ Comprehensive UI System
- **Streamlit UI**: Quick prototyping and data science workflows
- **Dash UI**: Enterprise-grade interactive dashboards
- **Jupyter UI**: Interactive notebook-based interfaces
- **WebSocket API**: Real-time trading data streaming
- **Multi-interface Support**: Choose the right UI for your needs
### 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
```bash
git clone https://huggingface.co/ParallelLLC/algorithmic_trading
cd algorithmic_trading
```
### 2. Install Dependencies
```bash
pip install -r requirements.txt
```
### 3. Set Up Alpaca API Credentials
Create a `.env` file in the project root:
```bash
cp env.example .env
```
Edit `.env` with your Alpaca credentials:
```env
# Get these from https://app.alpaca.markets/paper/dashboard/overview
ALPACA_API_KEY=your_paper_api_key_here
ALPACA_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 Parameters
Edit `config.yaml` to customize your trading strategy:
```yaml
# Data source configuration
data_source:
type: 'alpaca' # Options: 'alpaca', 'csv', 'synthetic'
# Trading parameters
trading:
symbol: 'AAPL'
timeframe: '1m'
capital: 100000
# Risk management
risk:
max_position: 100
max_drawdown: 0.05
# Execution settings
execution:
broker_api: 'alpaca_paper' # Options: 'paper', 'alpaca_paper', 'alpaca_live'
order_size: 10
# FinRL configuration
finrl:
algorithm: 'PPO'
learning_rate: 0.0003
training:
total_timesteps: 100000
save_best_model: true
```
## π Quick Start
### 1. Launch the UI (Recommended)
```bash
# Launch Streamlit UI (best for beginners)
python ui_launcher.py streamlit
# Launch Dash UI (best for production)
python ui_launcher.py dash
# Launch Jupyter Lab
python ui_launcher.py jupyter
# Launch all UIs
python ui_launcher.py all
```
### 2. Run the Demo
```bash
python demo.py
```
This will:
- Test data ingestion from Alpaca
- Demonstrate FinRL training
- Show trading workflow execution
- Run backtesting on historical data
### 3. Start Paper Trading
```bash
python -m agentic_ai_system.main --mode live --duration 60
```
### 4. Run Backtesting
```bash
python -m agentic_ai_system.main --mode backtest --start-date 2024-01-01 --end-date 2024-01-31
```
## π Usage Examples
### Basic Trading Workflow
```python
from agentic_ai_system.main import load_config
from agentic_ai_system.orchestrator import run
# Load configuration
config = load_config()
# Run single trading cycle
result = run(config)
print(f"Trading result: {result}")
```
### FinRL Training
```python
from agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfig
from agentic_ai_system.data_ingestion import load_data
# Load data and configuration
config = load_config()
data = load_data(config)
# Initialize FinRL agent
finrl_config = FinRLConfig(algorithm='PPO', learning_rate=0.0003)
agent = FinRLAgent(finrl_config)
# Train the agent
result = agent.train(
data=data,
config=config,
total_timesteps=100000,
use_real_broker=False # Use simulation for training
)
print(f"Training completed: {result}")
```
### Alpaca Integration
```python
from agentic_ai_system.alpaca_broker import AlpacaBroker
# Initialize Alpaca broker
config = load_config()
broker = AlpacaBroker(config)
# Get account information
account_info = broker.get_account_info()
print(f"Account balance: ${account_info['buying_power']:,.2f}")
# Place a market order
result = broker.place_market_order(
symbol='AAPL',
quantity=10,
side='buy'
)
print(f"Order result: {result}")
```
### Real-time Trading with FinRL
```python
from agentic_ai_system.finrl_agent import FinRLAgent
# Load trained model
agent = FinRLAgent(FinRLConfig())
agent.model = agent._load_model('models/finrl_best/best_model', config)
# Make predictions with real execution
result = 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 Flow
1. **Data Ingestion**: Market data from Alpaca, CSV, or synthetic sources
2. **Preprocessing**: Technical indicators, data validation, and feature engineering
3. **Strategy Generation**: Traditional technical analysis or FinRL predictions
4. **Risk Management**: Position sizing and portfolio protection
5. **Order Execution**: Real-time order placement through Alpaca
6. **Performance Tracking**: Continuous monitoring and logging
## π Project Directory Structure
```
algorithmic_trading/
βββ π README.md # Project documentation
βββ π LICENSE # Apache License 2.0
βββ π requirements.txt # Python dependencies
βββ π config.yaml # Main configuration file
βββ π env.example # Environment variables template
βββ π .gitignore # Git ignore rules
βββ π pytest.ini # Test configuration
β
βββ π³ Docker/
β βββ π Dockerfile # Container definition
β βββ π docker-entrypoint.sh # Container startup script
β βββ π .dockerignore # Docker ignore rules
β βββ π docker-compose.yml # Default compose file
β βββ π docker-compose.dev.yml # Development environment
β βββ π docker-compose.prod.yml # Production environment
β βββ π docker-compose.hub.yml # Docker Hub deployment
β βββ π docker-compose.prod.yml # Production environment
β
βββ π€ agentic_ai_system/ # Core AI trading system
β βββ π main.py # Main entry point
β βββ π orchestrator.py # System coordination
β βββ π agent_base.py # Base agent class
β βββ π data_ingestion.py # Market data processing
β βββ π strategy_agent.py # Trading strategy logic
β βββ π execution_agent.py # Order execution
β βββ π finrl_agent.py # FinRL reinforcement learning
β βββ π alpaca_broker.py # Alpaca API integration
β βββ π synthetic_data_generator.py # Test data generation
β βββ π logger_config.py # Logging configuration
β
βββ π¨ ui/ # User interface system
β βββ π __init__.py # UI package initialization
β βββ π streamlit_app.py # Streamlit web application
β βββ π dash_app.py # Dash enterprise dashboard
β βββ π jupyter_widgets.py # Jupyter interactive widgets
β βββ π websocket_server.py # Real-time WebSocket server
β
βββ π§ͺ tests/ # Test suite
β βββ π __init__.py
β βββ π test_data_ingestion.py
β βββ π test_strategy_agent.py
β βββ π test_execution_agent.py
β βββ π test_finrl_agent.py
β βββ π test_synthetic_data_generator.py
β βββ π test_integration.py
β
βββ π data/ # Market data storage
β βββ π synthetic_market_data.csv
β
βββ π§ models/ # Trained AI models
β βββ π finrl_best/ # Best FinRL models
β
βββ π plots/ # Generated charts/visualizations
β
βββ π logs/ # System logs
β βββ π trading_system.log
β βββ π trading.log
β βββ π performance.log
β βββ π errors.log
β βββ π finrl_tensorboard/ # FinRL training logs
β βββ π finrl_eval/ # Model evaluation logs
β
βββ π§ scripts/ # Utility scripts
β βββ π docker-build.sh # Docker build automation
β βββ π docker-hub-deploy.sh # Docker Hub deployment
β
βββ π demo.py # Main demo script
βββ π finrl_demo.py # FinRL-specific demo
βββ π ui_launcher.py # UI launcher script
βββ π UI_SETUP.md # UI setup documentation
βββ π DOCKER_HUB_SETUP.md # Docker Hub documentation
β
βββ π .venv/ # Python virtual environment
```
## ποΈ Architecture Overview
### Core Components:
- **Data Layer**: Market data ingestion and preprocessing
- **Strategy Layer**: Technical analysis and signal generation
- **AI Layer**: FinRL reinforcement learning agents
- **Execution Layer**: Order management and broker integration
- **Orchestration**: System coordination and workflow management
### Key Features:
- **Modular Design**: Each component is independent and testable
- **Docker Support**: Complete containerization for deployment
- **Testing**: Comprehensive test suite for all components
- **Logging**: Detailed logging for monitoring and debugging
- **Configuration**: Centralized configuration management
- **Documentation**: Extensive documentation and examples
### Development Workflow:
1. **Data Ingestion** β Market data from Alpaca/CSV/synthetic sources
2. **Strategy Generation** β Technical indicators and FinRL predictions
3. **Risk Management** β Position sizing and portfolio protection
4. **Order Execution** β Real-time trading through Alpaca
5. **Performance Tracking** β Continuous monitoring and logging
## π§ Configuration
### Alpaca Settings
```yaml
alpaca:
api_key: '' # Set via environment variable
secret_key: '' # Set via environment variable
paper_trading: true
base_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
```yaml
finrl:
algorithm: 'PPO' # PPO, A2C, DDPG, TD3
learning_rate: 0.0003
batch_size: 64
buffer_size: 1000000
training:
total_timesteps: 100000
eval_freq: 10000
save_best_model: true
model_save_path: 'models/finrl_best/'
inference:
use_trained_model: false
model_path: 'models/finrl_best/best_model'
```
### Risk Management
```yaml
risk:
max_position: 100
max_drawdown: 0.05
stop_loss: 0.02
take_profit: 0.05
```
## π¨ User Interface System
The project includes a comprehensive UI system with multiple interface options:
### Available UIs
#### Streamlit UI (Recommended for beginners)
- **URL**: http://localhost:8501
- **Features**: Interactive widgets, real-time data visualization, easy configuration
- **Best for**: Data scientists, quick experiments, rapid prototyping
#### Dash UI (Recommended for production)
- **URL**: http://localhost:8050
- **Features**: Enterprise-grade dashboards, advanced charts, professional styling
- **Best for**: Production dashboards, real-time monitoring, complex analytics
#### Jupyter UI (For research)
- **URL**: http://localhost:8888
- **Features**: Interactive notebooks, code execution, rich documentation
- **Best for**: Research, experimentation, educational purposes
#### WebSocket API (For developers)
- **URL**: ws://localhost:8765
- **Features**: Real-time data streaming, trading signals, portfolio updates
- **Best for**: Real-time trading signals, live data streaming
### Quick UI Launch
```bash
# Launch individual UIs
python ui_launcher.py streamlit # Streamlit UI
python ui_launcher.py dash # Dash UI
python ui_launcher.py jupyter # Jupyter Lab
python ui_launcher.py websocket # WebSocket server
# Launch all UIs at once
python ui_launcher.py all
```
### UI Features
- **Real-time Data Visualization**: Live market data charts and indicators
- **Portfolio Monitoring**: Real-time portfolio value and P&L tracking
- **Trading Controls**: Start/stop trading, backtesting, risk management
- **FinRL Training**: Interactive model training and evaluation
- **Alpaca Integration**: Account management and order execution
- **Configuration Management**: Easy parameter tuning and strategy setup
For detailed UI documentation, see [UI_SETUP.md](UI_SETUP.md).
## π Performance Monitoring
### Logging
The 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 information
account_info = broker.get_account_info()
print(f"Portfolio Value: ${account_info['portfolio_value']:,.2f}")
# Get current positions
positions = broker.get_positions()
for pos in positions:
print(f"{pos['symbol']}: {pos['quantity']} shares")
# Check market status
market_open = broker.is_market_open()
print(f"Market: {'OPEN' if market_open else 'CLOSED'}")
```
## π³ Docker Deployment
### Build and Run
```bash
# Build the image
docker build -t algorithmic-trading .
# Run with environment variables
docker run -it --env-file .env algorithmic-trading
# Run with Jupyter Lab for development
docker-compose -f docker-compose.dev.yml up
```
### Production Deployment
```bash
# Use production compose file
docker-compose -f docker-compose.prod.yml up -d
# Monitor logs
docker-compose -f docker-compose.prod.yml logs -f
```
## π§ͺ Testing
### Run All Tests
```bash
pytest tests/ -v
```
### Test Specific Components
```bash
# Test Alpaca integration
pytest tests/test_alpaca_integration.py -v
# Test FinRL agent
pytest tests/test_finrl_agent.py -v
# Test trading workflow
pytest 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
## π€ Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request
## π License
This project is licensed under the Apache License 2.0 - see the [LICENSE](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/)
|