Delete ml_engine/strategies.py
Browse files- ml_engine/strategies.py +0 -300
ml_engine/strategies.py
DELETED
|
@@ -1,300 +0,0 @@
|
|
| 1 |
-
# ml_engine/strategies.py (Updated to use LearningHub for weights)
|
| 2 |
-
import asyncio
|
| 3 |
-
|
| 4 |
-
# (Import from internal modules)
|
| 5 |
-
from .patterns import ChartPatternAnalyzer
|
| 6 |
-
|
| 7 |
-
class PatternEnhancedStrategyEngine:
|
| 8 |
-
# 🔴 --- START OF CHANGE --- 🔴
|
| 9 |
-
def __init__(self, data_manager, learning_hub): # (Changed from learning_engine)
|
| 10 |
-
self.data_manager = data_manager
|
| 11 |
-
self.learning_hub = learning_hub # (Changed from learning_engine)
|
| 12 |
-
self.pattern_analyzer = ChartPatternAnalyzer()
|
| 13 |
-
# 🔴 --- END OF CHANGE --- 🔴
|
| 14 |
-
|
| 15 |
-
async def enhance_strategy_with_patterns(self, strategy_scores, pattern_analysis, symbol):
|
| 16 |
-
"""(Unchanged logic)"""
|
| 17 |
-
if not pattern_analysis or pattern_analysis.get('pattern_detected') in ['no_clear_pattern', 'insufficient_data']:
|
| 18 |
-
return strategy_scores
|
| 19 |
-
|
| 20 |
-
pattern_confidence = pattern_analysis.get('pattern_confidence', 0)
|
| 21 |
-
pattern_name = pattern_analysis.get('pattern_detected', '')
|
| 22 |
-
predicted_direction = pattern_analysis.get('predicted_direction', '')
|
| 23 |
-
|
| 24 |
-
if pattern_confidence >= 0.6:
|
| 25 |
-
enhancement_factor = self._calculate_pattern_enhancement(pattern_confidence, pattern_name)
|
| 26 |
-
enhanced_strategies = self._get_pattern_appropriate_strategies(pattern_name, predicted_direction)
|
| 27 |
-
|
| 28 |
-
# (Omitted print statements for brevity)
|
| 29 |
-
|
| 30 |
-
for strategy in enhanced_strategies:
|
| 31 |
-
if strategy in strategy_scores:
|
| 32 |
-
original_score = strategy_scores[strategy]
|
| 33 |
-
strategy_scores[strategy] = min(original_score * enhancement_factor, 1.0)
|
| 34 |
-
|
| 35 |
-
return strategy_scores
|
| 36 |
-
|
| 37 |
-
def _calculate_pattern_enhancement(self, pattern_confidence, pattern_name):
|
| 38 |
-
"""(Unchanged logic)"""
|
| 39 |
-
base_enhancement = 1.0 + (pattern_confidence * 0.3)
|
| 40 |
-
high_reliability_patterns = ['Double Top', 'Double Bottom', 'Head & Shoulders', 'Cup and Handle']
|
| 41 |
-
if pattern_name in high_reliability_patterns:
|
| 42 |
-
base_enhancement *= 1.1
|
| 43 |
-
return min(base_enhancement, 1.5)
|
| 44 |
-
|
| 45 |
-
def _get_pattern_appropriate_strategies(self, pattern_name, direction):
|
| 46 |
-
"""(Unchanged logic)"""
|
| 47 |
-
reversal_patterns = ['Double Top', 'Double Bottom', 'Head & Shoulders', 'Triple Top', 'Triple Bottom']
|
| 48 |
-
continuation_patterns = ['Flags', 'Pennants', 'Triangles', 'Rectangles']
|
| 49 |
-
|
| 50 |
-
if pattern_name in reversal_patterns:
|
| 51 |
-
if direction == 'down':
|
| 52 |
-
return ['breakout_momentum', 'trend_following']
|
| 53 |
-
else:
|
| 54 |
-
return ['mean_reversion', 'breakout_momentum']
|
| 55 |
-
elif pattern_name in continuation_patterns:
|
| 56 |
-
return ['trend_following', 'breakout_momentum']
|
| 57 |
-
else:
|
| 58 |
-
return ['breakout_momentum', 'hybrid_ai']
|
| 59 |
-
|
| 60 |
-
class MultiStrategyEngine:
|
| 61 |
-
# 🔴 --- START OF CHANGE --- 🔴
|
| 62 |
-
def __init__(self, data_manager, learning_hub): # (Changed from learning_engine)
|
| 63 |
-
self.data_manager = data_manager
|
| 64 |
-
self.learning_hub = learning_hub # (Changed from learning_engine)
|
| 65 |
-
|
| 66 |
-
# (Pass the hub to the enhancer)
|
| 67 |
-
self.pattern_enhancer = PatternEnhancedStrategyEngine(data_manager, learning_hub)
|
| 68 |
-
# 🔴 --- END OF CHANGE --- 🔴
|
| 69 |
-
|
| 70 |
-
self.strategies = {
|
| 71 |
-
'trend_following': self._trend_following_strategy,
|
| 72 |
-
'mean_reversion': self._mean_reversion_strategy,
|
| 73 |
-
'breakout_momentum': self._breakout_momentum_strategy,
|
| 74 |
-
'volume_spike': self._volume_spike_strategy,
|
| 75 |
-
'whale_tracking': self._whale_tracking_strategy,
|
| 76 |
-
'pattern_recognition': self._pattern_recognition_strategy,
|
| 77 |
-
'hybrid_ai': self._hybrid_ai_strategy
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
async def evaluate_all_strategies(self, symbol_data, market_context):
|
| 81 |
-
"""Evaluate all trading strategies"""
|
| 82 |
-
try:
|
| 83 |
-
# 🔴 --- START OF CHANGE --- 🔴
|
| 84 |
-
# (Get weights from the new Learning Hub)
|
| 85 |
-
if self.learning_hub and self.learning_hub.initialized:
|
| 86 |
-
try:
|
| 87 |
-
market_condition = market_context.get('market_trend', 'sideways_market')
|
| 88 |
-
# (Call the new hub function)
|
| 89 |
-
optimized_weights = await self.learning_hub.get_optimized_weights(market_condition)
|
| 90 |
-
except Exception as e:
|
| 91 |
-
print(f"⚠️ Error getting optimized weights from hub: {e}. Using defaults.")
|
| 92 |
-
optimized_weights = await self.get_default_weights()
|
| 93 |
-
else:
|
| 94 |
-
optimized_weights = await self.get_default_weights()
|
| 95 |
-
# 🔴 --- END OF CHANGE --- 🔴
|
| 96 |
-
|
| 97 |
-
strategy_scores = {}
|
| 98 |
-
base_scores = {}
|
| 99 |
-
|
| 100 |
-
primary_strategies = [s for s in self.strategies.keys() if s != 'hybrid_ai']
|
| 101 |
-
|
| 102 |
-
for strategy_name in primary_strategies:
|
| 103 |
-
strategy_function = self.strategies[strategy_name]
|
| 104 |
-
try:
|
| 105 |
-
base_score = await strategy_function(symbol_data, market_context)
|
| 106 |
-
if base_score is None:
|
| 107 |
-
continue
|
| 108 |
-
base_scores[strategy_name] = base_score
|
| 109 |
-
weight = optimized_weights.get(strategy_name, 0.1)
|
| 110 |
-
weighted_score = base_score * weight
|
| 111 |
-
strategy_scores[strategy_name] = min(weighted_score, 1.0)
|
| 112 |
-
except Exception as error:
|
| 113 |
-
print(f"❌ Error evaluating strategy {strategy_name}: {error}")
|
| 114 |
-
continue
|
| 115 |
-
|
| 116 |
-
try:
|
| 117 |
-
hybrid_score = await self._hybrid_ai_strategy(symbol_data, market_context, base_scores)
|
| 118 |
-
if hybrid_score is not None:
|
| 119 |
-
base_scores['hybrid_ai'] = hybrid_score
|
| 120 |
-
weight = optimized_weights.get('hybrid_ai', 0.1)
|
| 121 |
-
strategy_scores['hybrid_ai'] = min(hybrid_score * weight, 1.0)
|
| 122 |
-
except Exception as e:
|
| 123 |
-
print(f"❌ Error in hybrid_ai strategy: {e}")
|
| 124 |
-
|
| 125 |
-
# Pattern enhancement (Unchanged)
|
| 126 |
-
pattern_analysis = symbol_data.get('pattern_analysis')
|
| 127 |
-
if pattern_analysis:
|
| 128 |
-
strategy_scores = await self.pattern_enhancer.enhance_strategy_with_patterns(
|
| 129 |
-
strategy_scores, pattern_analysis, symbol_data.get('symbol')
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
if base_scores:
|
| 133 |
-
best_strategy = max(base_scores.items(), key=lambda x: x[1])
|
| 134 |
-
best_strategy_name = best_strategy[0]
|
| 135 |
-
best_strategy_score = best_strategy[1]
|
| 136 |
-
symbol_data['recommended_strategy'] = best_strategy_name
|
| 137 |
-
symbol_data['strategy_confidence'] = best_strategy_score
|
| 138 |
-
|
| 139 |
-
return strategy_scores, base_scores
|
| 140 |
-
|
| 141 |
-
except Exception as error:
|
| 142 |
-
print(f"❌ Error in evaluate_all_strategies: {error}")
|
| 143 |
-
return {}, {}
|
| 144 |
-
|
| 145 |
-
async def get_default_weights(self):
|
| 146 |
-
"""(Unchanged) Default weights"""
|
| 147 |
-
return {
|
| 148 |
-
'trend_following': 0.15,
|
| 149 |
-
'mean_reversion': 0.12,
|
| 150 |
-
'breakout_momentum': 0.20,
|
| 151 |
-
'volume_spike': 0.13,
|
| 152 |
-
'whale_tracking': 0.20,
|
| 153 |
-
'pattern_recognition': 0.10,
|
| 154 |
-
'hybrid_ai': 0.10
|
| 155 |
-
}
|
| 156 |
-
|
| 157 |
-
#
|
| 158 |
-
# (All individual strategy functions remain unchanged)
|
| 159 |
-
# (_trend_following_strategy, _mean_reversion_strategy, etc.)
|
| 160 |
-
# (Omitted for brevity)
|
| 161 |
-
#
|
| 162 |
-
async def _trend_following_strategy(self, symbol_data, market_context):
|
| 163 |
-
try:
|
| 164 |
-
score = 0.0
|
| 165 |
-
indicators = symbol_data.get('advanced_indicators', {})
|
| 166 |
-
for timeframe in ['1h', '15m', '5m']:
|
| 167 |
-
if timeframe in indicators:
|
| 168 |
-
tf_indicators = indicators[timeframe]
|
| 169 |
-
ema_21 = tf_indicators.get('ema_21')
|
| 170 |
-
ema_50 = tf_indicators.get('ema_50')
|
| 171 |
-
adx = tf_indicators.get('adx', 0)
|
| 172 |
-
if ema_21 is not None and ema_50 is not None:
|
| 173 |
-
if ema_21 > ema_50:
|
| 174 |
-
score += 0.2
|
| 175 |
-
if adx > 20:
|
| 176 |
-
score += 0.1
|
| 177 |
-
if symbol_data['current_price'] > ema_21:
|
| 178 |
-
score += 0.05
|
| 179 |
-
return min(score, 1.0)
|
| 180 |
-
except Exception: return None
|
| 181 |
-
|
| 182 |
-
def _check_ema_alignment(self, indicators):
|
| 183 |
-
required_emas = ['ema_9', 'ema_21', 'ema_50']
|
| 184 |
-
if all(ema in indicators for ema in required_emas):
|
| 185 |
-
return (indicators['ema_9'] > indicators['ema_21'] > indicators['ema_50'])
|
| 186 |
-
return False
|
| 187 |
-
|
| 188 |
-
async def _mean_reversion_strategy(self, symbol_data, market_context):
|
| 189 |
-
try:
|
| 190 |
-
score = 0.0
|
| 191 |
-
current_price = symbol_data['current_price']
|
| 192 |
-
indicators = symbol_data.get('advanced_indicators', {})
|
| 193 |
-
for timeframe in ['1h', '15m']:
|
| 194 |
-
if timeframe in indicators:
|
| 195 |
-
tf_indicators = indicators[timeframe]
|
| 196 |
-
rsi_value = tf_indicators.get('rsi', 50)
|
| 197 |
-
bb_lower = tf_indicators.get('bb_lower')
|
| 198 |
-
bb_upper = tf_indicators.get('bb_upper')
|
| 199 |
-
if bb_lower is None or bb_upper is None: continue
|
| 200 |
-
position_in_band = 0.5
|
| 201 |
-
if (bb_upper - bb_lower) > 0:
|
| 202 |
-
position_in_band = (current_price - bb_lower) / (bb_upper - bb_lower)
|
| 203 |
-
is_rsi_oversold = rsi_value < 25
|
| 204 |
-
is_bb_oversold = position_in_band < 0.1
|
| 205 |
-
if is_rsi_oversold or is_bb_oversold:
|
| 206 |
-
score += 0.4
|
| 207 |
-
if is_rsi_oversold and is_bb_oversold:
|
| 208 |
-
score += 0.2
|
| 209 |
-
return min(score, 1.0)
|
| 210 |
-
except Exception: return None
|
| 211 |
-
|
| 212 |
-
async def _breakout_momentum_strategy(self, symbol_data, market_context):
|
| 213 |
-
try:
|
| 214 |
-
score = 0.0
|
| 215 |
-
current_price = symbol_data['current_price']
|
| 216 |
-
indicators = symbol_data.get('advanced_indicators', {})
|
| 217 |
-
for timeframe in ['1h', '15m', '5m']:
|
| 218 |
-
if timeframe in indicators:
|
| 219 |
-
tf_indicators = indicators[timeframe]
|
| 220 |
-
volume_ratio = tf_indicators.get('volume_ratio', 0)
|
| 221 |
-
if volume_ratio < 1.5: continue
|
| 222 |
-
score += 0.2
|
| 223 |
-
macd_hist = tf_indicators.get('macd_hist', 0)
|
| 224 |
-
if macd_hist > 0:
|
| 225 |
-
score += 0.1
|
| 226 |
-
atr_percent = tf_indicators.get('atr_percent', 0)
|
| 227 |
-
if atr_percent > 1.5:
|
| 228 |
-
score += 0.1
|
| 229 |
-
vwap = tf_indicators.get('vwap')
|
| 230 |
-
if vwap and current_price > vwap:
|
| 231 |
-
score += 0.05
|
| 232 |
-
return min(score, 1.0)
|
| 233 |
-
except Exception: return None
|
| 234 |
-
|
| 235 |
-
async def _volume_spike_strategy(self, symbol_data, market_context):
|
| 236 |
-
try:
|
| 237 |
-
score = 0.0
|
| 238 |
-
indicators = symbol_data.get('advanced_indicators', {})
|
| 239 |
-
for timeframe in ['1h', '15m', '5m']:
|
| 240 |
-
if timeframe in indicators:
|
| 241 |
-
volume_ratio = indicators[timeframe].get('volume_ratio', 0)
|
| 242 |
-
if volume_ratio > 3.0: score += 0.45
|
| 243 |
-
elif volume_ratio > 2.0: score += 0.25
|
| 244 |
-
elif volume_ratio > 1.5: score += 0.15
|
| 245 |
-
return min(score, 1.0)
|
| 246 |
-
except Exception: return None
|
| 247 |
-
|
| 248 |
-
async def _whale_tracking_strategy(self, symbol_data, market_context):
|
| 249 |
-
try:
|
| 250 |
-
whale_data = symbol_data.get('whale_data', {})
|
| 251 |
-
if not whale_data.get('data_available', False):
|
| 252 |
-
return None
|
| 253 |
-
whale_signal = await self.data_manager.get_whale_trading_signal(
|
| 254 |
-
symbol_data['symbol'], whale_data, market_context
|
| 255 |
-
)
|
| 256 |
-
if whale_signal and whale_signal.get('action') != 'HOLD':
|
| 257 |
-
confidence = whale_signal.get('confidence', 0)
|
| 258 |
-
if whale_signal.get('action') in ['STRONG_BUY', 'BUY']:
|
| 259 |
-
return min(confidence * 1.2, 1.0)
|
| 260 |
-
return None
|
| 261 |
-
except Exception: return None
|
| 262 |
-
|
| 263 |
-
async def _pattern_recognition_strategy(self, symbol_data, market_context):
|
| 264 |
-
try:
|
| 265 |
-
score = 0.0
|
| 266 |
-
pattern_analysis = symbol_data.get('pattern_analysis')
|
| 267 |
-
if pattern_analysis and pattern_analysis.get('pattern_confidence', 0) > 0.6:
|
| 268 |
-
if pattern_analysis.get('predicted_direction') == 'up':
|
| 269 |
-
score += pattern_analysis.get('pattern_confidence', 0) * 0.8
|
| 270 |
-
else:
|
| 271 |
-
indicators = symbol_data.get('advanced_indicators', {})
|
| 272 |
-
if '1h' in indicators:
|
| 273 |
-
tf_indicators = indicators['1h']
|
| 274 |
-
if (tf_indicators.get('rsi', 50) > 60 and
|
| 275 |
-
tf_indicators.get('macd_hist', 0) > 0):
|
| 276 |
-
score += 0.3
|
| 277 |
-
return min(score, 1.0)
|
| 278 |
-
except Exception: return None
|
| 279 |
-
|
| 280 |
-
async def _hybrid_ai_strategy(self, symbol_data, market_context, base_scores):
|
| 281 |
-
try:
|
| 282 |
-
score = 0.0
|
| 283 |
-
monte_carlo_prob = symbol_data.get('monte_carlo_probability')
|
| 284 |
-
if monte_carlo_prob is not None:
|
| 285 |
-
score += monte_carlo_prob * 0.4
|
| 286 |
-
|
| 287 |
-
breakout_score = base_scores.get('breakout_momentum', 0)
|
| 288 |
-
volume_score = base_scores.get('volume_spike', 0)
|
| 289 |
-
whale_score = base_scores.get('whale_tracking', 0)
|
| 290 |
-
pattern_score = base_scores.get('pattern_recognition', 0)
|
| 291 |
-
|
| 292 |
-
if breakout_score > 0.7 and volume_score > 0.6: score += 0.3
|
| 293 |
-
if breakout_score > 0.6 and whale_score > 0.7: score += 0.4
|
| 294 |
-
if pattern_score > 0.7 and volume_score > 0.5: score += 0.2
|
| 295 |
-
if breakout_score > 0.7 and whale_score > 0.7 and volume_score > 0.7:
|
| 296 |
-
score = 1.0
|
| 297 |
-
return max(0.0, min(score, 1.0))
|
| 298 |
-
except Exception: return None
|
| 299 |
-
|
| 300 |
-
print("✅ ML Module: Strategy Engine loaded (V3 - Integrated LearningHub for weights)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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