File size: 7,584 Bytes
859af74 |
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 |
# Algorithmic Trading System
A comprehensive algorithmic trading system with synthetic data generation, comprehensive logging, and extensive testing capabilities.
## 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
### 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
1. Clone the repository:
```bash
git clone <repository-url>
cd algorithmic_trading
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
## Configuration
The system is configured via `config.yaml`:
```yaml
# Data source configuration
data_source:
type: 'synthetic' # or 'csv'
path: 'data/market_data.csv'
# Trading parameters
trading:
symbol: 'AAPL'
timeframe: '1min'
capital: 100000
# Risk management
risk:
max_position: 100
max_drawdown: 0.05
# Order execution
execution:
broker_api: 'paper'
order_size: 10
delay_ms: 100
success_rate: 0.95
# Synthetic data generation
synthetic_data:
base_price: 150.0
volatility: 0.02
trend: 0.001
noise_level: 0.005
generate_data: true
data_path: 'data/synthetic_market_data.csv'
# Logging configuration
logging:
log_level: 'INFO'
log_dir: 'logs'
enable_console: true
enable_file: true
max_file_size_mb: 10
backup_count: 5
```
## Usage
### Standard Trading Mode
```bash
python -m agentic_ai_system.main
```
### Backtest Mode
```bash
python -m agentic_ai_system.main --mode backtest --start-date 2024-01-01 --end-date 2024-12-31
```
### Live Trading Mode
```bash
python -m agentic_ai_system.main --mode live --duration 60
```
### Custom Configuration
```bash
python -m agentic_ai_system.main --config custom_config.yaml
```
## Running Tests
### All Tests
```bash
pytest
```
### Unit Tests Only
```bash
pytest -m unit
```
### Integration Tests Only
```bash
pytest -m integration
```
### With Coverage Report
```bash
pytest --cov=agentic_ai_system --cov-report=html
```
### Specific Test File
```bash
pytest tests/test_synthetic_data_generator.py
```
## System Architecture
### Components
1. **SyntheticDataGenerator**: Generates realistic market data for testing
2. **DataIngestion**: Loads and validates market data from various sources
3. **StrategyAgent**: Analyzes market data and generates trading signals
4. **ExecutionAgent**: Executes trading orders with broker simulation
5. **Orchestrator**: Coordinates the entire trading workflow
6. **LoggerConfig**: Manages comprehensive logging throughout the system
### Data Flow
```
Synthetic Data Generator β Data Ingestion β Strategy Agent β Execution Agent
β
Logging System
```
## Synthetic Data Generation
### Features
- **Geometric Brownian Motion**: Realistic price movement simulation
- **OHLCV Data**: Complete market data with open, high, low, close, and volume
- **Market Scenarios**: Different market conditions for testing
- **Configurable Parameters**: Adjustable volatility, trend, and noise levels
### Usage Examples
```python
from agentic_ai_system.synthetic_data_generator import SyntheticDataGenerator
# Initialize generator
generator = SyntheticDataGenerator(config)
# Generate OHLCV data
data = generator.generate_ohlcv_data(
symbol='AAPL',
start_date='2024-01-01',
end_date='2024-12-31',
frequency='1min'
)
# Generate tick data
tick_data = generator.generate_tick_data(
symbol='AAPL',
duration_minutes=60,
tick_interval_ms=1000
)
# Generate market scenarios
crash_data = generator.generate_market_scenarios('crash')
volatile_data = generator.generate_market_scenarios('volatile')
```
## Logging System
### Log Files
- `logs/trading_system.log`: General system logs
- `logs/trading.log`: Trading-specific logs
- `logs/performance.log`: Performance metrics
- `logs/errors.log`: Error logs
### Log Levels
- **DEBUG**: Detailed debugging information
- **INFO**: General information about system operation
- **WARNING**: Warning messages for potential issues
- **ERROR**: Error messages for failed operations
- **CRITICAL**: Critical system failures
### Usage Examples
```python
import logging
from agentic_ai_system.logger_config import setup_logging, get_logger
# Setup logging
setup_logging(config)
# Get logger for specific module
logger = get_logger(__name__)
# Log messages
logger.info("Trading signal generated")
logger.warning("High volatility detected")
logger.error("Order execution failed", exc_info=True)
```
## Testing
### Test Structure
```
tests/
βββ __init__.py
βββ test_synthetic_data_generator.py
βββ test_strategy_agent.py
βββ test_execution_agent.py
βββ test_data_ingestion.py
βββ test_integration.py
```
### Test Categories
- **Unit Tests**: Test individual components in isolation
- **Integration Tests**: Test complete workflows
- **Performance Tests**: Test system performance and scalability
- **Error Handling Tests**: Test error conditions and edge cases
### Running Specific Tests
```bash
# Run tests with specific markers
pytest -m unit
pytest -m integration
pytest -m slow
# Run tests with coverage
pytest --cov=agentic_ai_system --cov-report=html
# Run tests in parallel
pytest -n auto
# Run tests with verbose output
pytest -v
```
## Performance Monitoring
The system includes comprehensive performance monitoring:
- **Execution Time Tracking**: Monitor workflow execution times
- **Trade Statistics**: Track successful vs failed trades
- **Performance Metrics**: Calculate returns and drawdowns
- **Resource Usage**: Monitor memory and CPU usage
## Error Handling
The system includes robust error handling:
- **Graceful Degradation**: System continues operation despite component failures
- **Error Logging**: Comprehensive error logging with stack traces
- **Fallback Mechanisms**: Automatic fallback to synthetic data when CSV files are missing
- **Validation**: Data validation at multiple levels
## Contributing
1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass
5. Submit a pull request
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Disclaimer
This is a simulation system for educational and testing purposes. It is not intended for real trading and should not be used with real money. Always test thoroughly before using any trading system with real funds. |