- New ml_signal_predictor.py with XGBoost model - Feature extraction from historical trades (17 features) - 5-fold cross-validation for robust training - Integrated into enhanced_trading_check_wrapper as optional layer - Disabled by default until model improves (AUC: 0.508) - Key insight: Asian session is strongest predictor of success Features used: - Signal: confidence, threshold, regime_strength - Session: asian/london/ny/overlap (one-hot) - Time: hour (cyclical), day_of_week - Quality: signal_quality score - Direction: long/short Usage: - train_ml_model() to train - enable_ml_predictor() to activate - get_ml_status() for info Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
170 lines
4.6 KiB
Python
170 lines
4.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
ML SIGNAL PREDICTOR INTEGRATION
|
|
Einfache Integration des ML Predictors in den Trading Bot
|
|
|
|
VERWENDUNG IM NOTEBOOK:
|
|
from ml_integration import (
|
|
ml_predictor,
|
|
check_ml_signal,
|
|
train_ml_model,
|
|
get_ml_status,
|
|
enable_ml_predictor,
|
|
disable_ml_predictor,
|
|
ML_CONFIG
|
|
)
|
|
|
|
# Status anzeigen
|
|
print(get_ml_status())
|
|
|
|
# Model trainieren (falls genug Daten)
|
|
train_ml_model()
|
|
|
|
# In enhanced_trading_check_wrapper:
|
|
ml_result = check_ml_signal(signal_info)
|
|
if not ml_result['should_trade']:
|
|
print(f"TRADE BLOCKIERT durch ML Predictor!")
|
|
return None
|
|
"""
|
|
|
|
import logging
|
|
from typing import Dict
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ==========================================
|
|
# IMPORT ML PREDICTOR
|
|
# ==========================================
|
|
|
|
try:
|
|
from ml_signal_predictor import (
|
|
MLSignalPredictor,
|
|
ML_CONFIG,
|
|
get_ml_predictor,
|
|
check_ml_signal,
|
|
train_ml_model,
|
|
get_ml_status,
|
|
enable_ml_predictor,
|
|
disable_ml_predictor
|
|
)
|
|
|
|
# Initialize global predictor
|
|
ml_predictor = get_ml_predictor()
|
|
|
|
ML_AVAILABLE = True
|
|
print("ML Signal Predictor loaded successfully")
|
|
|
|
except ImportError as e:
|
|
logger.warning(f"ML Signal Predictor not available: {e}")
|
|
ML_AVAILABLE = False
|
|
|
|
# Fallback functions
|
|
ML_CONFIG = {'enabled': False}
|
|
ml_predictor = None
|
|
|
|
def check_ml_signal(signal_info: Dict) -> Dict:
|
|
return {
|
|
'win_probability': 0.5,
|
|
'should_trade': True,
|
|
'lot_multiplier': 1.0,
|
|
'action': 'ALLOW',
|
|
'reason': 'ML not available'
|
|
}
|
|
|
|
def train_ml_model(force: bool = False) -> Dict:
|
|
return {'error': 'ML not available'}
|
|
|
|
def get_ml_status() -> str:
|
|
return "ML Signal Predictor: NOT AVAILABLE (install xgboost)"
|
|
|
|
def enable_ml_predictor():
|
|
print("ML Signal Predictor not available")
|
|
|
|
def disable_ml_predictor():
|
|
print("ML Signal Predictor not available")
|
|
|
|
|
|
# ==========================================
|
|
# INTEGRATION HELPER
|
|
# ==========================================
|
|
|
|
def check_ml_and_get_multiplier(signal_info: Dict, debug: bool = True) -> tuple:
|
|
"""
|
|
Prüft ML Signal und gibt (should_trade, lot_multiplier, result) zurück
|
|
|
|
Für einfache Integration in enhanced_trading_check_wrapper
|
|
|
|
Returns:
|
|
(should_trade: bool, lot_multiplier: float, ml_result: Dict)
|
|
"""
|
|
if not ML_AVAILABLE or not ML_CONFIG.get('enabled', False):
|
|
return True, 1.0, {'action': 'SKIP', 'reason': 'ML disabled'}
|
|
|
|
ml_result = check_ml_signal(signal_info)
|
|
|
|
if debug:
|
|
action_emoji = {
|
|
'ALLOW': '',
|
|
'CAUTION': '',
|
|
'REDUCE': '',
|
|
'BLOCK': ''
|
|
}.get(ml_result['action'], '')
|
|
|
|
print(f"\n{action_emoji} ML SIGNAL CHECK:")
|
|
print("-" * 50)
|
|
print(f" Win Probability: {ml_result['win_probability']:.1%}")
|
|
print(f" Action: {ml_result['action']}")
|
|
print(f" Lot Multiplier: {ml_result['lot_multiplier']:.0%}")
|
|
print(f" Reason: {ml_result['reason']}")
|
|
print("-" * 50)
|
|
|
|
return ml_result['should_trade'], ml_result['lot_multiplier'], ml_result
|
|
|
|
|
|
# ==========================================
|
|
# AUTO-TRAINING CHECK
|
|
# ==========================================
|
|
|
|
def auto_train_if_needed():
|
|
"""
|
|
Prüft ob genug neue Trades für Retraining vorhanden sind
|
|
und trainiert automatisch falls nötig
|
|
"""
|
|
if not ML_AVAILABLE or ml_predictor is None:
|
|
return
|
|
|
|
if ml_predictor.should_retrain():
|
|
print("\n Auto-Retraining triggered...")
|
|
train_ml_model()
|
|
|
|
|
|
# ==========================================
|
|
# QUICK STATUS
|
|
# ==========================================
|
|
|
|
def ml_quick_status() -> str:
|
|
"""Kurzer Status für Startup-Output"""
|
|
if not ML_AVAILABLE:
|
|
return " ML Predictor: NOT INSTALLED (pip install xgboost)"
|
|
|
|
if not ML_CONFIG.get('enabled', False):
|
|
return " ML Predictor: DISABLED"
|
|
|
|
if ml_predictor and ml_predictor.is_trained:
|
|
stats = ml_predictor.training_stats
|
|
auc = stats.get('cv_auc_mean', 0)
|
|
trades = stats.get('total_trades', 0)
|
|
return f" ML Predictor: ACTIVE (AUC: {auc:.2f}, trained on {trades} trades)"
|
|
else:
|
|
return " ML Predictor: NOT TRAINED (run train_ml_model())"
|
|
|
|
|
|
# ==========================================
|
|
# STANDALONE TEST
|
|
# ==========================================
|
|
|
|
if __name__ == "__main__":
|
|
print(ml_quick_status())
|
|
print()
|
|
print(get_ml_status())
|