Initial commit — Trading AI Secure project complet
Architecture Docker (8 services), FastAPI, TimescaleDB, Redis, Streamlit. Stratégies : scalping, intraday, swing. MLEngine + RegimeDetector (HMM). BacktestEngine + WalkForwardAnalyzer + Optuna optimizer. Routes API complètes dont /optimize async. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
411
src/README.md
Normal file
411
src/README.md
Normal file
@@ -0,0 +1,411 @@
|
||||
# 📁 Source Code - Trading AI Secure
|
||||
|
||||
## 🎯 Vue d'ensemble
|
||||
|
||||
Ce dossier contient tout le code source de l'application Trading AI Secure.
|
||||
|
||||
---
|
||||
|
||||
## 📂 Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── __init__.py # Package principal
|
||||
├── main.py # Point d'entrée
|
||||
│
|
||||
├── core/ # Modules centraux
|
||||
│ ├── __init__.py
|
||||
│ ├── risk_manager.py # Risk Manager (Singleton)
|
||||
│ └── strategy_engine.py # Orchestrateur stratégies
|
||||
│
|
||||
├── strategies/ # Stratégies de trading
|
||||
│ ├── __init__.py
|
||||
│ ├── base_strategy.py # Classe abstraite
|
||||
│ ├── scalping/ # À créer
|
||||
│ ├── intraday/ # À créer
|
||||
│ └── swing/ # À créer
|
||||
│
|
||||
├── data/ # Connecteurs données (À créer)
|
||||
├── ml/ # Machine Learning (À créer)
|
||||
├── backtesting/ # Backtesting (À créer)
|
||||
├── ui/ # Interface (À créer)
|
||||
├── monitoring/ # Monitoring (À créer)
|
||||
└── utils/ # Utilitaires
|
||||
├── __init__.py
|
||||
├── logger.py # Système de logging
|
||||
└── config_loader.py # Chargeur configuration
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Utilisation
|
||||
|
||||
### Lancer l'Application
|
||||
|
||||
```bash
|
||||
# Backtesting
|
||||
python src/main.py --mode backtest --strategy intraday --symbol EURUSD
|
||||
|
||||
# Paper trading
|
||||
python src/main.py --mode paper --strategy all
|
||||
|
||||
# Optimisation
|
||||
python src/main.py --mode optimize --strategy scalping
|
||||
```
|
||||
|
||||
### Importer des Modules
|
||||
|
||||
```python
|
||||
# Risk Manager
|
||||
from src.core.risk_manager import RiskManager
|
||||
|
||||
risk_manager = RiskManager()
|
||||
is_valid, error = risk_manager.validate_trade(...)
|
||||
|
||||
# Strategy Engine
|
||||
from src.core.strategy_engine import StrategyEngine
|
||||
|
||||
engine = StrategyEngine(config, risk_manager)
|
||||
await engine.load_strategy('intraday')
|
||||
await engine.run()
|
||||
|
||||
# Logging
|
||||
from src.utils.logger import setup_logger, get_logger
|
||||
|
||||
setup_logger(level='INFO')
|
||||
logger = get_logger(__name__)
|
||||
logger.info("Message")
|
||||
|
||||
# Configuration
|
||||
from src.utils.config_loader import ConfigLoader
|
||||
|
||||
config = ConfigLoader.load_all()
|
||||
risk_limits = config['risk_limits']
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Modules Détaillés
|
||||
|
||||
### Core
|
||||
|
||||
#### RiskManager (`core/risk_manager.py`)
|
||||
|
||||
**Responsabilités** :
|
||||
- Validation pré-trade (10 vérifications)
|
||||
- Gestion des positions
|
||||
- Calcul métriques de risque (VaR, CVaR, drawdown)
|
||||
- Circuit breakers
|
||||
- Statistiques
|
||||
|
||||
**Usage** :
|
||||
```python
|
||||
risk_manager = RiskManager()
|
||||
risk_manager.initialize(config)
|
||||
|
||||
# Valider trade
|
||||
is_valid, error = risk_manager.validate_trade(
|
||||
symbol='EURUSD',
|
||||
quantity=1000,
|
||||
price=1.1000,
|
||||
stop_loss=1.0950,
|
||||
take_profit=1.1100,
|
||||
strategy='intraday'
|
||||
)
|
||||
|
||||
# Métriques
|
||||
metrics = risk_manager.get_risk_metrics()
|
||||
print(f"VaR: ${metrics.portfolio_var:.2f}")
|
||||
```
|
||||
|
||||
#### StrategyEngine (`core/strategy_engine.py`)
|
||||
|
||||
**Responsabilités** :
|
||||
- Chargement dynamique des stratégies
|
||||
- Boucle principale de trading
|
||||
- Distribution données marché
|
||||
- Collecte et filtrage signaux
|
||||
- Exécution ordres
|
||||
|
||||
**Usage** :
|
||||
```python
|
||||
engine = StrategyEngine(config, risk_manager)
|
||||
|
||||
# Charger stratégies
|
||||
await engine.load_strategy('scalping')
|
||||
await engine.load_strategy('intraday')
|
||||
|
||||
# Lancer
|
||||
await engine.run()
|
||||
```
|
||||
|
||||
### Strategies
|
||||
|
||||
#### BaseStrategy (`strategies/base_strategy.py`)
|
||||
|
||||
**Classe abstraite** pour toutes les stratégies.
|
||||
|
||||
**Méthodes à implémenter** :
|
||||
- `analyze(market_data)` : Génère signaux
|
||||
- `calculate_indicators(data)` : Calcule indicateurs
|
||||
|
||||
**Méthodes fournies** :
|
||||
- `calculate_position_size()` : Kelly Criterion
|
||||
- `update_parameters()` : Paramètres adaptatifs
|
||||
- `record_trade()` : Enregistrement trades
|
||||
|
||||
**Usage** :
|
||||
```python
|
||||
from src.strategies.base_strategy import BaseStrategy
|
||||
|
||||
class MyStrategy(BaseStrategy):
|
||||
def analyze(self, market_data):
|
||||
# Implémenter logique
|
||||
df = self.calculate_indicators(market_data)
|
||||
|
||||
if condition:
|
||||
return Signal(...)
|
||||
return None
|
||||
|
||||
def calculate_indicators(self, data):
|
||||
# Calculer indicateurs
|
||||
data['sma_20'] = data['close'].rolling(20).mean()
|
||||
return data
|
||||
```
|
||||
|
||||
### Utils
|
||||
|
||||
#### Logger (`utils/logger.py`)
|
||||
|
||||
**Fonctionnalités** :
|
||||
- Logs console colorés
|
||||
- Logs fichiers avec rotation
|
||||
- Niveaux configurables
|
||||
|
||||
**Usage** :
|
||||
```python
|
||||
from src.utils.logger import setup_logger, get_logger
|
||||
|
||||
# Setup (une fois au démarrage)
|
||||
setup_logger(level='INFO', log_dir='logs')
|
||||
|
||||
# Utiliser
|
||||
logger = get_logger(__name__)
|
||||
logger.info("Info message")
|
||||
logger.warning("Warning message")
|
||||
logger.error("Error message")
|
||||
```
|
||||
|
||||
#### ConfigLoader (`utils/config_loader.py`)
|
||||
|
||||
**Fonctionnalités** :
|
||||
- Chargement YAML
|
||||
- Accès centralisé
|
||||
|
||||
**Usage** :
|
||||
```python
|
||||
from src.utils.config_loader import ConfigLoader
|
||||
|
||||
# Charger toute la config
|
||||
config = ConfigLoader.load_all()
|
||||
|
||||
# Ou spécifique
|
||||
risk_limits = ConfigLoader.get_risk_limits()
|
||||
strategy_params = ConfigLoader.get_strategy_params('intraday')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Tests
|
||||
|
||||
### Lancer les Tests
|
||||
|
||||
```bash
|
||||
# Tous les tests
|
||||
pytest tests/
|
||||
|
||||
# Tests spécifiques
|
||||
pytest tests/unit/test_risk_manager.py
|
||||
|
||||
# Avec couverture
|
||||
pytest --cov=src tests/
|
||||
```
|
||||
|
||||
### Écrire des Tests
|
||||
|
||||
```python
|
||||
# tests/unit/test_risk_manager.py
|
||||
|
||||
import pytest
|
||||
from src.core.risk_manager import RiskManager
|
||||
|
||||
def test_singleton():
|
||||
rm1 = RiskManager()
|
||||
rm2 = RiskManager()
|
||||
assert rm1 is rm2
|
||||
|
||||
def test_validate_trade():
|
||||
rm = RiskManager()
|
||||
is_valid, error = rm.validate_trade(...)
|
||||
assert is_valid is True
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 Conventions de Code
|
||||
|
||||
### Style
|
||||
|
||||
- **PEP 8** : Respecter PEP 8
|
||||
- **Type Hints** : Obligatoires sur tous les paramètres et retours
|
||||
- **Docstrings** : Google style pour toutes les classes et méthodes
|
||||
- **Imports** : Organisés (stdlib, third-party, local)
|
||||
|
||||
### Exemple
|
||||
|
||||
```python
|
||||
"""
|
||||
Module description.
|
||||
|
||||
Detailed explanation of what this module does.
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
import numpy as np
|
||||
|
||||
from src.core.risk_manager import RiskManager
|
||||
|
||||
|
||||
class MyClass:
|
||||
"""
|
||||
Brief description.
|
||||
|
||||
Detailed description of the class.
|
||||
|
||||
Attributes:
|
||||
attr1: Description
|
||||
attr2: Description
|
||||
"""
|
||||
|
||||
def __init__(self, param1: str, param2: int):
|
||||
"""
|
||||
Initialize MyClass.
|
||||
|
||||
Args:
|
||||
param1: Description
|
||||
param2: Description
|
||||
"""
|
||||
self.attr1 = param1
|
||||
self.attr2 = param2
|
||||
|
||||
def my_method(self, arg1: float) -> bool:
|
||||
"""
|
||||
Brief description.
|
||||
|
||||
Detailed description of what the method does.
|
||||
|
||||
Args:
|
||||
arg1: Description
|
||||
|
||||
Returns:
|
||||
Description of return value
|
||||
|
||||
Raises:
|
||||
ValueError: When something is wrong
|
||||
"""
|
||||
if arg1 < 0:
|
||||
raise ValueError("arg1 must be positive")
|
||||
|
||||
return True
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Développement
|
||||
|
||||
### Ajouter une Nouvelle Stratégie
|
||||
|
||||
1. **Créer fichier** : `src/strategies/my_strategy/my_strategy.py`
|
||||
|
||||
2. **Hériter de BaseStrategy** :
|
||||
```python
|
||||
from src.strategies.base_strategy import BaseStrategy, Signal
|
||||
|
||||
class MyStrategy(BaseStrategy):
|
||||
def analyze(self, market_data):
|
||||
# Implémenter
|
||||
pass
|
||||
|
||||
def calculate_indicators(self, data):
|
||||
# Implémenter
|
||||
pass
|
||||
```
|
||||
|
||||
3. **Ajouter configuration** : `config/strategy_params.yaml`
|
||||
|
||||
4. **Charger dans StrategyEngine** : Modifier `strategy_engine.py`
|
||||
|
||||
5. **Tester** : Créer `tests/unit/test_my_strategy.py`
|
||||
|
||||
### Ajouter un Nouveau Module
|
||||
|
||||
1. **Créer dossier** : `src/my_module/`
|
||||
|
||||
2. **Créer `__init__.py`** : Exports du module
|
||||
|
||||
3. **Créer fichiers** : Implémenter fonctionnalités
|
||||
|
||||
4. **Documenter** : Ajouter README dans le module
|
||||
|
||||
5. **Tester** : Créer tests unitaires
|
||||
|
||||
---
|
||||
|
||||
## 📊 Métriques de Code
|
||||
|
||||
### Couverture Actuelle
|
||||
|
||||
| Module | Fichiers | Lignes | Couverture | Statut |
|
||||
|--------|----------|--------|------------|--------|
|
||||
| core | 2 | ~1,000 | 0% | ⏳ À tester |
|
||||
| strategies | 1 | ~450 | 0% | ⏳ À tester |
|
||||
| utils | 2 | ~270 | 0% | ⏳ À tester |
|
||||
| **TOTAL** | **5** | **~1,720** | **0%** | **⏳ À tester** |
|
||||
|
||||
**Objectif** : 85% de couverture
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Debugging
|
||||
|
||||
### Activer Debug Logging
|
||||
|
||||
```bash
|
||||
python src/main.py --log-level DEBUG --mode backtest --strategy intraday
|
||||
```
|
||||
|
||||
### Profiling
|
||||
|
||||
```bash
|
||||
# CPU profiling
|
||||
python -m cProfile -o profile.stats src/main.py --mode backtest
|
||||
python -m pstats profile.stats
|
||||
|
||||
# Memory profiling
|
||||
python -m memory_profiler src/main.py --mode backtest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Ressources
|
||||
|
||||
- [Documentation Complète](../docs/)
|
||||
- [Guide de Contribution](../docs/CONTRIBUTING.md)
|
||||
- [Architecture](../docs/ARCHITECTURE.md)
|
||||
- [Risk Framework](../docs/RISK_FRAMEWORK.md)
|
||||
|
||||
---
|
||||
|
||||
**Code maintenu par l'équipe Trading AI Secure**
|
||||
**Version** : 0.1.0-alpha
|
||||
**Dernière mise à jour** : 2024-01-15
|
||||
Reference in New Issue
Block a user