Riy777 commited on
Commit
55c88d4
·
1 Parent(s): 56b50dd

Update ML.py

Browse files
Files changed (1) hide show
  1. ML.py +78 -92
ML.py CHANGED
@@ -302,7 +302,7 @@ class MonteCarloAnalyzer:
302
  """
303
  try:
304
  if not ohlcv_data or '1h' not in ohlcv_data or len(ohlcv_data['1h']) < 24:
305
- return 0.5
306
 
307
  # استخدام بيانات 1h و 15m معاً لدقة أفضل
308
  all_closes = []
@@ -316,7 +316,7 @@ class MonteCarloAnalyzer:
316
  all_closes.extend(recent_15m)
317
 
318
  if len(all_closes) < 30:
319
- return 0.5
320
 
321
  closes = np.array(all_closes)
322
  current_price = closes[-1]
@@ -329,7 +329,7 @@ class MonteCarloAnalyzer:
329
  log_returns.append(log_return)
330
 
331
  if len(log_returns) < 20:
332
- return 0.5
333
 
334
  log_returns = np.array(log_returns)
335
  mean_return = np.mean(log_returns)
@@ -382,7 +382,7 @@ class MonteCarloAnalyzer:
382
 
383
  except Exception as e:
384
  print(f"❌ خطأ في محاكاة مونت كارلو: {e}")
385
- return 0.5
386
 
387
  def _calculate_trend_adjustment(self, closes):
388
  """حساب معامل تعديل الاتجاه"""
@@ -789,6 +789,7 @@ class MultiStrategyEngine:
789
  market_condition = market_context.get('market_trend', 'sideways_market')
790
  optimized_weights = await self.learning_engine.get_optimized_strategy_weights(market_condition)
791
  except Exception as e:
 
792
  optimized_weights = await self.get_default_weights()
793
  else:
794
  optimized_weights = await self.get_default_weights()
@@ -799,15 +800,16 @@ class MultiStrategyEngine:
799
  for strategy_name, strategy_function in self.strategies.items():
800
  try:
801
  base_score = await strategy_function(symbol_data, market_context)
 
 
802
  base_scores[strategy_name] = base_score
803
  weight = optimized_weights.get(strategy_name, 0.1)
804
  weighted_score = base_score * weight
805
  strategy_scores[strategy_name] = min(weighted_score, 1.0)
806
  except Exception as error:
807
  print(f"❌ خطأ في تقييم استراتيجية {strategy_name}: {error}")
808
- base_score = await self._fallback_strategy_score(strategy_name, symbol_data, market_context)
809
- base_scores[strategy_name] = base_score
810
- strategy_scores[strategy_name] = base_score * optimized_weights.get(strategy_name, 0.1)
811
 
812
  pattern_analysis = symbol_data.get('pattern_analysis')
813
  if pattern_analysis:
@@ -826,11 +828,11 @@ class MultiStrategyEngine:
826
 
827
  except Exception as error:
828
  print(f"❌ خطأ في تقييم الاستراتيجيات: {error}")
829
- fallback_scores = await self.get_fallback_scores()
830
- return fallback_scores, fallback_scores
831
 
832
  async def get_default_weights(self):
833
- """الأوزان الافتراضية للاستراتيجيات"""
834
  return {
835
  'trend_following': 0.15,
836
  'mean_reversion': 0.12,
@@ -841,18 +843,6 @@ class MultiStrategyEngine:
841
  'hybrid_ai': 0.10
842
  }
843
 
844
- async def get_fallback_scores(self):
845
- """الدرجات الاحتياطية عند الخطأ"""
846
- return {
847
- 'trend_following': 0.5,
848
- 'mean_reversion': 0.5,
849
- 'breakout_momentum': 0.5,
850
- 'volume_spike': 0.5,
851
- 'whale_tracking': 0.5,
852
- 'pattern_recognition': 0.5,
853
- 'hybrid_ai': 0.5
854
- }
855
-
856
  async def _trend_following_strategy(self, symbol_data, market_context):
857
  """استراتيجية تتبع الاتجاه"""
858
  try:
@@ -876,7 +866,8 @@ class MultiStrategyEngine:
876
 
877
  return min(score, 1.0)
878
  except Exception as error:
879
- return 0.3
 
880
 
881
  def _check_ema_alignment(self, indicators):
882
  """التحقق من محاذاة المتوسطات المتحركة"""
@@ -912,7 +903,8 @@ class MultiStrategyEngine:
912
 
913
  return min(score, 1.0)
914
  except Exception as error:
915
- return 0.3
 
916
 
917
  async def _breakout_momentum_strategy(self, symbol_data, market_context):
918
  """استراتيجية زخم الاختراق"""
@@ -945,7 +937,8 @@ class MultiStrategyEngine:
945
 
946
  return min(score, 1.0)
947
  except Exception as error:
948
- return 0.4
 
949
 
950
  async def _volume_spike_strategy(self, symbol_data, market_context):
951
  """استراتيجية ارتفاع الحجم"""
@@ -965,14 +958,15 @@ class MultiStrategyEngine:
965
 
966
  return min(score, 1.0)
967
  except Exception as error:
968
- return 0.3
 
969
 
970
  async def _whale_tracking_strategy(self, symbol_data, market_context):
971
  """استراتيجية تتبع الحيتان"""
972
  try:
973
  whale_data = symbol_data.get('whale_data', {})
974
  if not whale_data.get('data_available', False):
975
- return 0.2
976
 
977
  whale_signal = await self.data_manager.get_whale_trading_signal(
978
  symbol_data['symbol'], whale_data, market_context
@@ -985,9 +979,10 @@ class MultiStrategyEngine:
985
  elif whale_signal.get('action') in ['STRONG_SELL', 'SELL']:
986
  return min(confidence * 0.8, 1.0)
987
 
988
- return 0.3
989
  except Exception as error:
990
- return 0.2
 
991
 
992
  async def _pattern_recognition_strategy(self, symbol_data, market_context):
993
  """استراتيجية التعرف على الأنماط"""
@@ -1009,18 +1004,21 @@ class MultiStrategyEngine:
1009
 
1010
  return min(score, 1.0)
1011
  except Exception as error:
1012
- return 0.3
 
1013
 
1014
  async def _hybrid_ai_strategy(self, symbol_data, market_context):
1015
  """استراتيجية الهجين الذكية"""
1016
  try:
1017
  score = 0.0
1018
 
1019
- monte_carlo_probability = symbol_data.get('monte_carlo_probability', 0.5)
1020
- score += monte_carlo_probability * 0.4
 
1021
 
1022
- final_score = symbol_data.get('final_score', 0.5)
1023
- score += final_score * 0.3
 
1024
 
1025
  if market_context.get('btc_sentiment') == 'BULLISH':
1026
  score += 0.15
@@ -1034,48 +1032,8 @@ class MultiStrategyEngine:
1034
 
1035
  return max(0.0, min(score, 1.0))
1036
  except Exception as error:
1037
- return 0.3
1038
-
1039
- async def _fallback_strategy_score(self, strategy_name, symbol_data, market_context):
1040
- """الدرجة الاحتياطية للاستراتيجيات"""
1041
- try:
1042
- base_score = symbol_data.get('final_score', 0.5)
1043
-
1044
- if strategy_name == 'trend_following':
1045
- indicators = symbol_data.get('advanced_indicators', {})
1046
- if '1h' in indicators:
1047
- rsi_value = indicators['1h'].get('rsi', 50)
1048
- ema_9 = indicators['1h'].get('ema_9')
1049
- ema_21 = indicators['1h'].get('ema_21')
1050
- if ema_9 and ema_21 and ema_9 > ema_21 and 40 <= rsi_value <= 60:
1051
- return 0.6
1052
- return 0.4
1053
-
1054
- elif strategy_name == 'mean_reversion':
1055
- current_price = symbol_data.get('current_price', 0)
1056
- indicators = symbol_data.get('advanced_indicators', {})
1057
- if '1h' in indicators:
1058
- rsi_value = indicators['1h'].get('rsi', 50)
1059
- bb_lower = indicators['1h'].get('bb_lower')
1060
- if bb_lower and current_price <= bb_lower * 1.02 and rsi_value < 35:
1061
- return 0.7
1062
- return 0.3
1063
-
1064
- elif strategy_name == 'breakout_momentum':
1065
- volume_ratio = symbol_data.get('advanced_indicators', {}).get('1h', {}).get('volume_ratio', 0)
1066
- if volume_ratio > 1.5:
1067
- return 0.6
1068
- return 0.4
1069
-
1070
- elif strategy_name == 'whale_tracking':
1071
- whale_data = symbol_data.get('whale_data', {})
1072
- if not whale_data.get('data_available', False):
1073
- return 0.2
1074
- return 0.3
1075
-
1076
- return base_score
1077
- except Exception as error:
1078
- return 0.3
1079
 
1080
  class MLProcessor:
1081
  def __init__(self, market_context, data_manager, learning_engine):
@@ -1112,8 +1070,9 @@ class MLProcessor:
1112
  base_analysis['advanced_indicators'] = advanced_indicators
1113
 
1114
  monte_carlo_probability = await self.monte_carlo_analyzer.predict_1h_probability(raw_data['ohlcv'])
1115
- base_analysis['monte_carlo_probability'] = monte_carlo_probability
1116
- base_analysis['monte_carlo_details'] = self.monte_carlo_analyzer.simulation_results
 
1117
 
1118
  pattern_analysis = await self.pattern_analyzer.detect_chart_patterns(raw_data['ohlcv'])
1119
  base_analysis['pattern_analysis'] = pattern_analysis
@@ -1140,7 +1099,9 @@ class MLProcessor:
1140
  base_analysis['enhanced_final_score'] = enhanced_score
1141
 
1142
  print(f"✅ اكتمل التحليل المتقدم لـ {symbol}:")
1143
- print(f" 📊 النهائي: {enhanced_score:.3f} | 🎯 مونت كارلو: {monte_carlo_probability:.3f}")
 
 
1144
  print(f" 🎯 نمط: {pattern_analysis.get('pattern_detected')} (ثقة: {pattern_analysis.get('pattern_confidence', 0):.2f})")
1145
 
1146
  return base_analysis
@@ -1174,23 +1135,46 @@ class MLProcessor:
1174
  def _calculate_enhanced_final_score(self, analysis):
1175
  """حساب الدرجة النهائية المحسنة"""
1176
  try:
1177
- base_score = analysis.get('final_score', 0.5)
1178
- monte_carlo_score = analysis.get('monte_carlo_probability', 0.5)
1179
  pattern_confidence = analysis.get('pattern_analysis', {}).get('pattern_confidence', 0)
1180
- strategy_confidence = analysis.get('strategy_confidence', 0.3)
1181
 
1182
- enhanced_score = (
1183
- base_score * 0.25 +
1184
- monte_carlo_score * 0.30 +
1185
- pattern_confidence * 0.25 +
1186
- strategy_confidence * 0.20
1187
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1188
 
1189
  return min(enhanced_score, 1.0)
1190
 
1191
  except Exception as e:
1192
  print(f"❌ خطأ في حساب الدرجة المحسنة: {e}")
1193
- return analysis.get('final_score', 0.5)
1194
 
1195
  async def process_and_score_symbol(self, raw_data):
1196
  """المعالجة الأساسية للرمز"""
@@ -1202,7 +1186,7 @@ class MLProcessor:
1202
  return None
1203
 
1204
  current_price = raw_data.get('current_price', 0)
1205
- layer1_score = raw_data.get('layer1_score', 0.5)
1206
  reasons = raw_data.get('reasons_for_candidacy', [])
1207
 
1208
  final_score = layer1_score
@@ -1242,7 +1226,9 @@ class MLProcessor:
1242
  pattern = candidate.get('pattern_analysis', {}).get('pattern_detected', 'no_pattern')
1243
 
1244
  print(f" {i+1}. {candidate['symbol']}:")
1245
- print(f" 📊 النهائي: {score:.3f} | 🎯 مونت كارلو: {mc_score:.3f}")
 
 
1246
  print(f" 🎯 استراتيجية: {strategy} | نمط: {pattern}")
1247
 
1248
  return top_candidates
@@ -1263,4 +1249,4 @@ def safe_json_parse(json_string):
1263
  print(f"❌ فشل تحليل JSON بعد الإصلاح: {e}")
1264
  return None
1265
 
1266
- print("✅ ML Processor loaded - Fixed NoneType Errors & Enhanced Analysis")
 
302
  """
303
  try:
304
  if not ohlcv_data or '1h' not in ohlcv_data or len(ohlcv_data['1h']) < 24:
305
+ return None # ❌ لا نرجع قيمة افتراضية
306
 
307
  # استخدام بيانات 1h و 15m معاً لدقة أفضل
308
  all_closes = []
 
316
  all_closes.extend(recent_15m)
317
 
318
  if len(all_closes) < 30:
319
+ return None # ❌ لا نرجع قيمة افتراضية
320
 
321
  closes = np.array(all_closes)
322
  current_price = closes[-1]
 
329
  log_returns.append(log_return)
330
 
331
  if len(log_returns) < 20:
332
+ return None # ❌ لا نرجع قيمة افتراضية
333
 
334
  log_returns = np.array(log_returns)
335
  mean_return = np.mean(log_returns)
 
382
 
383
  except Exception as e:
384
  print(f"❌ خطأ في محاكاة مونت كارلو: {e}")
385
+ return None # ❌ لا نرجع قيمة افتراضية
386
 
387
  def _calculate_trend_adjustment(self, closes):
388
  """حساب معامل تعديل الاتجاه"""
 
789
  market_condition = market_context.get('market_trend', 'sideways_market')
790
  optimized_weights = await self.learning_engine.get_optimized_strategy_weights(market_condition)
791
  except Exception as e:
792
+ # ❌ لا نستخدم قيم افتراضية، نستخدم الأوزان الأساسية
793
  optimized_weights = await self.get_default_weights()
794
  else:
795
  optimized_weights = await self.get_default_weights()
 
800
  for strategy_name, strategy_function in self.strategies.items():
801
  try:
802
  base_score = await strategy_function(symbol_data, market_context)
803
+ if base_score is None: # ❌ إذا فشلت الاستراتيجية، لا نستخدم قيم افتراضية
804
+ continue
805
  base_scores[strategy_name] = base_score
806
  weight = optimized_weights.get(strategy_name, 0.1)
807
  weighted_score = base_score * weight
808
  strategy_scores[strategy_name] = min(weighted_score, 1.0)
809
  except Exception as error:
810
  print(f"❌ خطأ في تقييم استراتيجية {strategy_name}: {error}")
811
+ # لا نستخدم أي محاكاة أو قيم افتراضية
812
+ continue
 
813
 
814
  pattern_analysis = symbol_data.get('pattern_analysis')
815
  if pattern_analysis:
 
828
 
829
  except Exception as error:
830
  print(f"❌ خطأ في تقييم الاستراتيجيات: {error}")
831
+ # لا نستخدم أي محاكاة
832
+ return {}, {}
833
 
834
  async def get_default_weights(self):
835
+ """الأوزان الافتراضية للاستراتيجيات - هذه ليست محاكاة ولكن أوزان ابتدائية"""
836
  return {
837
  'trend_following': 0.15,
838
  'mean_reversion': 0.12,
 
843
  'hybrid_ai': 0.10
844
  }
845
 
 
 
 
 
 
 
 
 
 
 
 
 
846
  async def _trend_following_strategy(self, symbol_data, market_context):
847
  """استراتيجية تتبع الاتجاه"""
848
  try:
 
866
 
867
  return min(score, 1.0)
868
  except Exception as error:
869
+ print(f"❌ خطأ في استراتيجية تتبع الاتجاه: {error}")
870
+ return None # ❌ لا نرجع قيمة افتراضية
871
 
872
  def _check_ema_alignment(self, indicators):
873
  """التحقق من محاذاة المتوسطات المتحركة"""
 
903
 
904
  return min(score, 1.0)
905
  except Exception as error:
906
+ print(f"❌ خطأ في استراتيجية العودة للمتوسط: {error}")
907
+ return None # ❌ لا نرجع قيمة افتراضية
908
 
909
  async def _breakout_momentum_strategy(self, symbol_data, market_context):
910
  """استراتيجية زخم الاختراق"""
 
937
 
938
  return min(score, 1.0)
939
  except Exception as error:
940
+ print(f"❌ خطأ في استراتيجية زخم الاختراق: {error}")
941
+ return None # ❌ لا نرجع قيمة افتراضية
942
 
943
  async def _volume_spike_strategy(self, symbol_data, market_context):
944
  """استراتيجية ارتفاع الحجم"""
 
958
 
959
  return min(score, 1.0)
960
  except Exception as error:
961
+ print(f"❌ خطأ في استراتيجية ارتفاع الحجم: {error}")
962
+ return None # ❌ لا نرجع قيمة افتراضية
963
 
964
  async def _whale_tracking_strategy(self, symbol_data, market_context):
965
  """استراتيجية تتبع الحيتان"""
966
  try:
967
  whale_data = symbol_data.get('whale_data', {})
968
  if not whale_data.get('data_available', False):
969
+ return None # ❌ لا نرجع قيمة افتراضية
970
 
971
  whale_signal = await self.data_manager.get_whale_trading_signal(
972
  symbol_data['symbol'], whale_data, market_context
 
979
  elif whale_signal.get('action') in ['STRONG_SELL', 'SELL']:
980
  return min(confidence * 0.8, 1.0)
981
 
982
+ return None # ❌ لا نرجع قيمة افتراضية
983
  except Exception as error:
984
+ print(f"❌ خطأ في استراتيجية تتبع الحيتان: {error}")
985
+ return None # ❌ لا نرجع قيمة افتراضية
986
 
987
  async def _pattern_recognition_strategy(self, symbol_data, market_context):
988
  """استراتيجية التعرف على الأنماط"""
 
1004
 
1005
  return min(score, 1.0)
1006
  except Exception as error:
1007
+ print(f"❌ خطأ في استراتيجية التعرف على الأنماط: {error}")
1008
+ return None # ❌ لا نرجع قيمة افتراضية
1009
 
1010
  async def _hybrid_ai_strategy(self, symbol_data, market_context):
1011
  """استراتيجية الهجين الذكية"""
1012
  try:
1013
  score = 0.0
1014
 
1015
+ monte_carlo_probability = symbol_data.get('monte_carlo_probability')
1016
+ if monte_carlo_probability is not None:
1017
+ score += monte_carlo_probability * 0.4
1018
 
1019
+ final_score = symbol_data.get('final_score', 0)
1020
+ if final_score > 0:
1021
+ score += final_score * 0.3
1022
 
1023
  if market_context.get('btc_sentiment') == 'BULLISH':
1024
  score += 0.15
 
1032
 
1033
  return max(0.0, min(score, 1.0))
1034
  except Exception as error:
1035
+ print(f"❌ خطأ في استراتيجية الهجين الذكية: {error}")
1036
+ return None # ❌ لا نرجع قيمة افتراضية
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1037
 
1038
  class MLProcessor:
1039
  def __init__(self, market_context, data_manager, learning_engine):
 
1070
  base_analysis['advanced_indicators'] = advanced_indicators
1071
 
1072
  monte_carlo_probability = await self.monte_carlo_analyzer.predict_1h_probability(raw_data['ohlcv'])
1073
+ if monte_carlo_probability is not None:
1074
+ base_analysis['monte_carlo_probability'] = monte_carlo_probability
1075
+ base_analysis['monte_carlo_details'] = self.monte_carlo_analyzer.simulation_results
1076
 
1077
  pattern_analysis = await self.pattern_analyzer.detect_chart_patterns(raw_data['ohlcv'])
1078
  base_analysis['pattern_analysis'] = pattern_analysis
 
1099
  base_analysis['enhanced_final_score'] = enhanced_score
1100
 
1101
  print(f"✅ اكتمل التحليل المتقدم لـ {symbol}:")
1102
+ print(f" 📊 النهائي: {enhanced_score:.3f}")
1103
+ if monte_carlo_probability is not None:
1104
+ print(f" 🎯 مونت كارلو: {monte_carlo_probability:.3f}")
1105
  print(f" 🎯 نمط: {pattern_analysis.get('pattern_detected')} (ثقة: {pattern_analysis.get('pattern_confidence', 0):.2f})")
1106
 
1107
  return base_analysis
 
1135
  def _calculate_enhanced_final_score(self, analysis):
1136
  """حساب الدرجة النهائية المحسنة"""
1137
  try:
1138
+ base_score = analysis.get('final_score', 0)
1139
+ monte_carlo_score = analysis.get('monte_carlo_probability', 0)
1140
  pattern_confidence = analysis.get('pattern_analysis', {}).get('pattern_confidence', 0)
1141
+ strategy_confidence = analysis.get('strategy_confidence', 0)
1142
 
1143
+ # استخدام فقط البيانات المتاحة
1144
+ components = []
1145
+ weights = []
1146
+
1147
+ if base_score > 0:
1148
+ components.append(base_score)
1149
+ weights.append(0.25)
1150
+
1151
+ if monte_carlo_score > 0:
1152
+ components.append(monte_carlo_score)
1153
+ weights.append(0.30)
1154
+
1155
+ if pattern_confidence > 0:
1156
+ components.append(pattern_confidence)
1157
+ weights.append(0.25)
1158
+
1159
+ if strategy_confidence > 0:
1160
+ components.append(strategy_confidence)
1161
+ weights.append(0.20)
1162
+
1163
+ if not components:
1164
+ return 0 # ❌ لا توجد بيانات صالحة
1165
+
1166
+ # حساب المتوسط المرجح
1167
+ total_weight = sum(weights)
1168
+ if total_weight == 0:
1169
+ return 0
1170
+
1171
+ enhanced_score = sum(comp * weight for comp, weight in zip(components, weights)) / total_weight
1172
 
1173
  return min(enhanced_score, 1.0)
1174
 
1175
  except Exception as e:
1176
  print(f"❌ خطأ في حساب الدرجة المحسنة: {e}")
1177
+ return analysis.get('final_score', 0)
1178
 
1179
  async def process_and_score_symbol(self, raw_data):
1180
  """المعالجة الأساسية للرمز"""
 
1186
  return None
1187
 
1188
  current_price = raw_data.get('current_price', 0)
1189
+ layer1_score = raw_data.get('layer1_score', 0)
1190
  reasons = raw_data.get('reasons_for_candidacy', [])
1191
 
1192
  final_score = layer1_score
 
1226
  pattern = candidate.get('pattern_analysis', {}).get('pattern_detected', 'no_pattern')
1227
 
1228
  print(f" {i+1}. {candidate['symbol']}:")
1229
+ print(f" 📊 النهائي: {score:.3f}")
1230
+ if mc_score > 0:
1231
+ print(f" 🎯 مونت كارلو: {mc_score:.3f}")
1232
  print(f" 🎯 استراتيجية: {strategy} | نمط: {pattern}")
1233
 
1234
  return top_candidates
 
1249
  print(f"❌ فشل تحليل JSON بعد الإصلاح: {e}")
1250
  return None
1251
 
1252
+ print("✅ ML Processor loaded - No Default Values & Enhanced Analysis")