Riy777 commited on
Commit
cd047ad
·
1 Parent(s): b1e3f65

Update ml_engine/monte_carlo.py

Browse files
Files changed (1) hide show
  1. ml_engine/monte_carlo.py +20 -6
ml_engine/monte_carlo.py CHANGED
@@ -1,4 +1,4 @@
1
- # ml_engine/monte_carlo.py
2
  import numpy as np
3
  import pandas as pd
4
  from arch import arch_model
@@ -12,7 +12,6 @@ except ImportError:
12
  print("⚠️ مكتبة pandas_ta غير موجودة، سيتم استخدام حسابات يدوية للمؤشرات.")
13
  ta = None
14
 
15
- # 🔴 --- START OF CHANGE (FIX NumPy 2.0 Crash) --- 🔴
16
  def _sanitize_results_for_json(results_dict):
17
  """
18
  Recursively converts numpy types (ndarray, np.float64, etc.)
@@ -33,7 +32,6 @@ def _sanitize_results_for_json(results_dict):
33
  return int(results_dict)
34
  else:
35
  return results_dict
36
- # 🔴 --- END OF CHANGE --- 🔴
37
 
38
 
39
  class MonteCarloAnalyzer:
@@ -76,6 +74,14 @@ class MonteCarloAnalyzer:
76
  mean_return = np.mean(log_returns)
77
  std_return = np.std(log_returns)
78
 
 
 
 
 
 
 
 
 
79
  num_simulations = 5000
80
  t_df = 10
81
  jump_lambda = 0.05
@@ -155,9 +161,18 @@ class MonteCarloAnalyzer:
155
  df['log_returns'] = np.log(df['close'] / df['close'].shift(1)).fillna(0)
156
  log_returns_series = df['log_returns'].replace([np.inf, -np.inf], 0)
157
 
 
 
 
 
 
 
 
 
 
 
158
  # 3. (Phase 2) توقع التقلب باستخدام GARCH(1,1)
159
  try:
160
- # 🔴 --- START OF CHANGE (FIX GARCH Warning) --- 🔴
161
  # (Rescale by 100, and set rescale=False to stop GARCH from auto-scaling)
162
  garch_model = arch_model(log_returns_series * 100, vol='Garch', p=1, q=1, dist='t', rescale=False)
163
  res = garch_model.fit(update_freq=0, disp='off')
@@ -165,9 +180,8 @@ class MonteCarloAnalyzer:
165
  # (Divide by 100^2 = 10000)
166
  forecasted_var = forecast.variance.iloc[-1, 0] / (100**2)
167
  forecasted_std_return = np.sqrt(forecasted_var)
168
- # 🔴 --- END OF CHANGE --- 🔴
169
  except Exception as garch_err:
170
- forecasted_std_return = np.std(log_returns_series.iloc[-30:])
171
  print(f"⚠️ GARCH failed, using std: {garch_err}")
172
 
173
 
 
1
+ # ml_engine/monte_carlo.py (Updated to V6.2 - Stablecoin Guard)
2
  import numpy as np
3
  import pandas as pd
4
  from arch import arch_model
 
12
  print("⚠️ مكتبة pandas_ta غير موجودة، سيتم استخدام حسابات يدوية للمؤشرات.")
13
  ta = None
14
 
 
15
  def _sanitize_results_for_json(results_dict):
16
  """
17
  Recursively converts numpy types (ndarray, np.float64, etc.)
 
32
  return int(results_dict)
33
  else:
34
  return results_dict
 
35
 
36
 
37
  class MonteCarloAnalyzer:
 
74
  mean_return = np.mean(log_returns)
75
  std_return = np.std(log_returns)
76
 
77
+ # 🔴 --- START OF CHANGE (V6.2 - STABLECOIN GUARD) --- 🔴
78
+ # واقي العملة المستقرة: إذا كان الانحراف المعياري (التقلب) شبه صفري، أوقف التحليل
79
+ if std_return < 1e-5: # (1e-5 هو 0.00001)
80
+ print(f" [MC Guard] {ohlcv_data.get('symbol', 'Symbol')} - Zero volatility detected. Stopping MC.")
81
+ self.simulation_results = {'error': 'Zero volatility detected (Stablecoin?)'}
82
+ return None
83
+ # 🔴 --- END OF CHANGE --- 🔴
84
+
85
  num_simulations = 5000
86
  t_df = 10
87
  jump_lambda = 0.05
 
161
  df['log_returns'] = np.log(df['close'] / df['close'].shift(1)).fillna(0)
162
  log_returns_series = df['log_returns'].replace([np.inf, -np.inf], 0)
163
 
164
+ # 🔴 --- START OF CHANGE (V6.2 - STABLECOIN GUARD) --- 🔴
165
+ # واقي العملة المستقرة: التحقق من التقلب قبل بدء التحليل
166
+ std_return_check = np.std(log_returns_series.iloc[-30:])
167
+ if std_return_check < 1e-5: # (1e-5 هو 0.00001)
168
+ print(f" [MC Guard Adv] {ohlcv_data.get('symbol', 'Symbol')} - Zero volatility detected. Stopping GARCH/LGBM.")
169
+ self.simulation_results = {'error': 'Zero volatility detected (Stablecoin?)'}
170
+ # العودة إلى المرحلة 1 (التي ستمسك بها أيضاً وترجع None)
171
+ return await self.generate_1h_price_distribution(ohlcv_data, target_profit_percent)
172
+ # 🔴 --- END OF CHANGE --- 🔴
173
+
174
  # 3. (Phase 2) توقع التقلب باستخدام GARCH(1,1)
175
  try:
 
176
  # (Rescale by 100, and set rescale=False to stop GARCH from auto-scaling)
177
  garch_model = arch_model(log_returns_series * 100, vol='Garch', p=1, q=1, dist='t', rescale=False)
178
  res = garch_model.fit(update_freq=0, disp='off')
 
180
  # (Divide by 100^2 = 10000)
181
  forecasted_var = forecast.variance.iloc[-1, 0] / (100**2)
182
  forecasted_std_return = np.sqrt(forecasted_var)
 
183
  except Exception as garch_err:
184
+ forecasted_std_return = std_return_check # (استخدام القيمة التي تم التحقق منها)
185
  print(f"⚠️ GARCH failed, using std: {garch_err}")
186
 
187