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:
148
examples/simple_backtest.py
Normal file
148
examples/simple_backtest.py
Normal file
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
Exemple Simple - Premier Backtest.
|
||||
|
||||
Cet exemple montre comment:
|
||||
1. Configurer le système
|
||||
2. Charger une stratégie
|
||||
3. Lancer un backtest
|
||||
4. Analyser les résultats
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# Ajouter src au path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from src.core.risk_manager import RiskManager
|
||||
from src.core.strategy_engine import StrategyEngine
|
||||
from src.backtesting.backtest_engine import BacktestEngine
|
||||
from src.utils.logger import setup_logger
|
||||
|
||||
|
||||
async def main():
|
||||
"""Fonction principale."""
|
||||
|
||||
# 1. Setup logging
|
||||
setup_logger(level='INFO')
|
||||
|
||||
print("=" * 60)
|
||||
print("EXEMPLE SIMPLE - PREMIER BACKTEST")
|
||||
print("=" * 60)
|
||||
|
||||
# 2. Configuration
|
||||
config = {
|
||||
'risk_limits': {
|
||||
'initial_capital': 10000.0,
|
||||
'global_limits': {
|
||||
'max_portfolio_risk': 0.05,
|
||||
'max_position_size': 0.10,
|
||||
'max_drawdown': 0.15,
|
||||
'max_daily_loss': 0.03,
|
||||
'max_correlation': 0.7,
|
||||
},
|
||||
'strategy_limits': {
|
||||
'intraday': {
|
||||
'risk_per_trade': 0.02,
|
||||
'max_trades_per_day': 20,
|
||||
}
|
||||
}
|
||||
},
|
||||
'strategy_params': {
|
||||
'intraday_strategy': {
|
||||
'name': 'intraday',
|
||||
'timeframe': '1h',
|
||||
'risk_per_trade': 0.02,
|
||||
'max_holding_time': 28800,
|
||||
'max_trades_per_day': 20,
|
||||
'adaptive_params': {
|
||||
'ema_fast': 9,
|
||||
'ema_slow': 21,
|
||||
'ema_trend': 50,
|
||||
'adx_threshold': 25,
|
||||
}
|
||||
}
|
||||
},
|
||||
'backtesting_config': {
|
||||
'transaction_costs': {
|
||||
'commission_pct': 0.0001,
|
||||
'slippage_pct': 0.0005,
|
||||
'spread_pct': 0.0002,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 3. Initialiser Risk Manager
|
||||
print("\n📊 Initialisation du Risk Manager...")
|
||||
risk_manager = RiskManager()
|
||||
risk_manager.initialize(config['risk_limits'])
|
||||
|
||||
# 4. Initialiser Strategy Engine
|
||||
print("🎯 Initialisation du Strategy Engine...")
|
||||
strategy_engine = StrategyEngine(
|
||||
config=config['strategy_params'],
|
||||
risk_manager=risk_manager
|
||||
)
|
||||
|
||||
# 5. Charger stratégie Intraday
|
||||
print("📈 Chargement de la stratégie Intraday...")
|
||||
await strategy_engine.load_strategy('intraday')
|
||||
|
||||
# 6. Créer Backtest Engine
|
||||
print("🔄 Création du Backtest Engine...")
|
||||
backtest_engine = BacktestEngine(
|
||||
strategy_engine=strategy_engine,
|
||||
config=config
|
||||
)
|
||||
|
||||
# 7. Lancer backtest
|
||||
print("\n🚀 Lancement du backtest...")
|
||||
print("Symbole: EURUSD")
|
||||
print("Période: 6 mois")
|
||||
print("Capital initial: $10,000")
|
||||
|
||||
results = await backtest_engine.run(
|
||||
symbols=['EURUSD'],
|
||||
period='6m',
|
||||
initial_capital=10000.0
|
||||
)
|
||||
|
||||
# 8. Afficher résultats
|
||||
if results:
|
||||
print("\n" + "=" * 60)
|
||||
print("RÉSULTATS DU BACKTEST")
|
||||
print("=" * 60)
|
||||
|
||||
metrics = results['metrics']
|
||||
|
||||
print(f"\n📈 PERFORMANCE")
|
||||
print(f"Return Total: {metrics['total_return']:>10.2%}")
|
||||
print(f"Sharpe Ratio: {metrics['sharpe_ratio']:>10.2f}")
|
||||
print(f"Max Drawdown: {metrics['max_drawdown']:>10.2%}")
|
||||
|
||||
print(f"\n💼 TRADING")
|
||||
print(f"Total Trades: {metrics['total_trades']:>10}")
|
||||
print(f"Win Rate: {metrics['win_rate']:>10.2%}")
|
||||
print(f"Profit Factor: {metrics['profit_factor']:>10.2f}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
|
||||
# 9. Validation
|
||||
if results['is_valid']:
|
||||
print("✅ STRATÉGIE VALIDE pour paper trading!")
|
||||
print("\nProchaine étape: Lancer paper trading pendant 30 jours")
|
||||
else:
|
||||
print("❌ STRATÉGIE NON VALIDE")
|
||||
print("\nActions recommandées:")
|
||||
print("1. Optimiser les paramètres")
|
||||
print("2. Tester sur différentes périodes")
|
||||
print("3. Analyser les trades perdants")
|
||||
|
||||
else:
|
||||
print("\n❌ Backtest échoué - Vérifier les logs")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user