Riy777 commited on
Commit
e756af2
·
verified ·
1 Parent(s): c1d31a7

Update ml_engine/monte_carlo.py

Browse files
Files changed (1) hide show
  1. ml_engine/monte_carlo.py +49 -64
ml_engine/monte_carlo.py CHANGED
@@ -1,7 +1,7 @@
1
  # ml_engine/monte_carlo.py
2
- # (V11.5 - GEM-Architect: Graded Sensitivity Edition)
3
- # - Tier 1: Light Check -> Now returns graded scores (-0.10 to +0.10) based on Z-Score.
4
- # - Tier 2: Advanced Simulation -> Remains high precision GBM.
5
 
6
  import numpy as np
7
  import pandas as pd
@@ -13,37 +13,37 @@ class MonteCarloEngine:
13
  """
14
  Advanced Stochastic Simulation Engine.
15
  Provides two tiers of analysis:
16
- 1. Light Check: For rapid screening (Graded Output).
17
- 2. Advanced Simulation: For deep risk assessment (GBM).
18
  """
19
 
20
  def __init__(self):
21
- print("✅ [MonteCarlo V11.5] Hybrid Engine Loaded (Graded Sensitivity).")
22
 
23
  # ==============================================================================
24
- # ⚡ TIER 1: Light Check (Graded Z-Score)
25
  # ==============================================================================
26
  def run_light_check(self, prices: List[float]) -> float:
27
  """
28
- فحص سريع جداً (Micro-Simulation) مع تدرج في النتيجة.
29
- بدلاً من 0 أو 0.1، يعطي درجة تعكس قوة الاتجاه (صعوداً أو هبوطاً).
 
 
 
30
 
31
  Logic:
32
- - Prob > 60% -> +0.10 (Strong Bull)
33
- - 55% < Prob <= 60% -> +0.05 (Weak Bull)
34
- - 45% <= Prob <= 55% -> 0.00 (Neutral / Noise)
35
- - 40% <= Prob < 45% -> -0.05 (Weak Bear)
36
- - Prob < 40% -> -0.10 (Strong Bear)
37
-
38
- Returns:
39
- float: Score between -0.10 and +0.10
40
  """
41
  try:
42
- # 1. تنظيف البيانات والتحقق منها
43
- if not prices or len(prices) < 30:
44
  return 0.0
45
 
46
- # [CRITICAL] تحويل القائمة إلى float صراحة لتجنب مشاكل النصوص
47
  clean_prices = []
48
  for p in prices:
49
  try:
@@ -51,63 +51,59 @@ class MonteCarloEngine:
51
  if val > 0: clean_prices.append(val)
52
  except: continue
53
 
54
- if len(clean_prices) < 30: return 0.0
55
 
56
- # 2. الحساب السريع (Vectorized)
57
  price_arr = np.array(clean_prices, dtype=np.float64)
58
-
59
- # ln(P_t / P_{t-1})
60
  log_returns = np.diff(np.log(price_arr))
61
 
62
  mu = np.mean(log_returns)
63
  sigma = np.std(log_returns)
64
 
65
- # إذا كان الانحراف صفراً (سعر ثابت)، العائد صفر
66
  if sigma == 0: return 0.0
67
 
68
- # حساب احتمالية أن يكون العائد القادم > 0
69
- # Z-Score Approach: P(X > 0)
70
  prob_up = norm.cdf(mu / sigma)
71
 
72
- # [LOGIC UPDATE] السلم المتدرج (Graded Ladder)
73
- score = 0.0
74
 
75
- if prob_up >= 0.60:
76
- score = 0.10
77
- elif prob_up >= 0.55:
78
- score = 0.05
79
- elif prob_up >= 0.45:
80
- score = 0.00 # منطقة الحياد والضوضاء
81
- elif prob_up >= 0.40:
82
- score = -0.05
83
- else:
84
- score = -0.10 # احتمالية الصعود ضعيفة جداً (< 40%)
85
-
86
- # [DEBUG LOG] طباعة الاحتمالية للمراقبة (اختياري)
87
- # print(f" 🎲 [Light MC] Prob: {prob_up:.2f} -> Score: {score}")
88
 
89
- return score
 
 
 
 
 
 
 
 
 
90
 
91
  except Exception as e:
92
  # print(f"⚠️ [Light MC] Error: {e}")
93
  return 0.0
94
 
95
  # ==============================================================================
96
- # 🧠 TIER 2: Advanced Simulation (For Top 10 Oracle Candidates)
97
  # ==============================================================================
98
  def run_advanced_simulation(self, prices: List[float], num_simulations=5000, time_horizon=24) -> float:
99
  """
100
- المحاكاة المتقدمة الكاملة (Geometric Brownian Motion).
 
101
  """
102
  try:
103
- if not prices or len(prices) < 50:
104
- return 0.0
105
-
106
- # تنظيف البيانات
107
  clean_prices = [float(p) for p in prices if p is not None]
108
  if len(clean_prices) < 50: return 0.0
109
 
110
- # 1. إحصائيات
111
  closing_prices = np.array(clean_prices, dtype=np.float64)
112
  log_returns = np.diff(np.log(closing_prices))
113
 
@@ -115,46 +111,35 @@ class MonteCarloEngine:
115
  daily_volatility = np.std(log_returns)
116
  last_price = closing_prices[-1]
117
 
118
- # 2. المحاكاة (GBM)
119
  random_shocks = np.random.normal(0, 1, (num_simulations, time_horizon))
120
  drift = (mean_daily_return - 0.5 * daily_volatility ** 2)
121
  diffusion = daily_volatility * random_shocks
122
-
123
  daily_returns_sim = np.exp(drift + diffusion)
124
 
125
- # مسارات الأسعار
126
  price_paths = np.zeros_like(daily_returns_sim)
127
  price_paths[:, 0] = last_price * daily_returns_sim[:, 0]
128
-
129
  for t in range(1, time_horizon):
130
  price_paths[:, t] = price_paths[:, t-1] * daily_returns_sim[:, t]
131
 
132
- # 3. النتائج
133
  final_prices = price_paths[:, -1]
134
 
135
- # المقاييس
136
  threshold = last_price * 1.002
137
  prob_profit = np.mean(final_prices > threshold)
138
  var_95 = np.percentile(final_prices, 5)
139
  drawdown_risk = (var_95 - last_price) / last_price
140
  expected_return = (np.mean(final_prices) - last_price) / last_price
141
 
142
- # print(f" 🎲 [Adv MC] ProfitProb:{prob_profit:.2f} | Risk:{drawdown_risk:.2%} | ExpRet:{expected_return:.2%}")
143
-
144
- # 4. التنقيط (محدث ليكون أكثر توازناً)
145
  mc_score = 0.0
146
-
147
- # المكافآت
148
  if prob_profit > 0.55: mc_score += 0.05
149
  if prob_profit > 0.65: mc_score += 0.05
150
  if expected_return > 0.005: mc_score += 0.05
151
-
152
- # العقوبات
153
  if drawdown_risk < -0.07: mc_score -= 0.05
154
  if drawdown_risk < -0.10: mc_score -= 0.05
155
 
156
  return round(max(-0.10, min(0.20, mc_score)), 2)
157
 
158
  except Exception as e:
159
- print(f"⚠️ [MonteCarlo] Advanced failed: {e}")
160
  return 0.0
 
1
  # ml_engine/monte_carlo.py
2
+ # (V11.7 - GEM-Architect: Fixed Light MC Sensitivity)
3
+ # - Tier 1: Light Check -> Continuous Score (No Dead Zones).
4
+ # - Tier 2: Advanced Simulation -> Standard GBM Logic (Top 10 Only).
5
 
6
  import numpy as np
7
  import pandas as pd
 
13
  """
14
  Advanced Stochastic Simulation Engine.
15
  Provides two tiers of analysis:
16
+ 1. Light Check: For rapid screening (All 150 Coins) -> Returns sensitive micro-scores.
17
+ 2. Advanced Simulation: For deep risk assessment (Top 10 Only).
18
  """
19
 
20
  def __init__(self):
21
+ print("✅ [MonteCarlo V11.7] Hybrid Engine Loaded (Corrected Sensitivity).")
22
 
23
  # ==============================================================================
24
+ # ⚡ TIER 1: Light Check (Applied to ALL 150 Coins)
25
  # ==============================================================================
26
  def run_light_check(self, prices: List[float]) -> float:
27
  """
28
+ فحص سريع يطبق على الـ 150 عملة.
29
+
30
+ [التعديل المطلوب]:
31
+ إلغاء المنطقة الميتة تماماً.
32
+ أي انحراف عن 0.50 يعطي نتيجة فوراً.
33
 
34
  Logic:
35
+ - Prob > 0.55 -> +0.10
36
+ - Prob > 0.52 -> +0.07
37
+ - Prob > 0.50 -> +0.03 (أي نبض إيجابي يعطي درجة)
38
+ - Prob < 0.50 -> -0.03 (أي نبض سلبي يخصم درجة)
39
+ - Prob < 0.48 -> -0.07
40
+ - Prob < 0.45 -> -0.10
 
 
41
  """
42
  try:
43
+ # 1. تنظيف البيانات
44
+ if not prices or len(prices) < 20:
45
  return 0.0
46
 
 
47
  clean_prices = []
48
  for p in prices:
49
  try:
 
51
  if val > 0: clean_prices.append(val)
52
  except: continue
53
 
54
+ if len(clean_prices) < 20: return 0.0
55
 
56
+ # 2. الحساب الإحصائي (Z-Score)
57
  price_arr = np.array(clean_prices, dtype=np.float64)
 
 
58
  log_returns = np.diff(np.log(price_arr))
59
 
60
  mu = np.mean(log_returns)
61
  sigma = np.std(log_returns)
62
 
 
63
  if sigma == 0: return 0.0
64
 
65
+ # احتمالية الصعود P(X > 0)
 
66
  prob_up = norm.cdf(mu / sigma)
67
 
68
+ # 3. سلم الحساسية (بدون أصفار - No Dead Zone)
69
+ # الهدف: التخلص من الـ 0.00 في الجدول
70
 
71
+ # --- المنطقة الإيجابية ---
72
+ if prob_up >= 0.55:
73
+ return 0.10 # صعود قوي
74
+ elif prob_up >= 0.52:
75
+ return 0.07 # صعود متوسط
76
+ elif prob_up > 0.5001:
77
+ return 0.03 # صعود طفيف جداً (لكي لا يكون صفر)
 
 
 
 
 
 
78
 
79
+ # --- المنطقة السلبية ---
80
+ elif prob_up <= 0.45:
81
+ return -0.10 # هبوط قوي
82
+ elif prob_up <= 0.48:
83
+ return -0.07 # هبوط متوسط
84
+ elif prob_up < 0.4999:
85
+ return -0.03 # هبوط طفيف جداً (لكي لا يكون صفر)
86
+
87
+ # الحالة النادرة جداً (التعادل التام)
88
+ return 0.00
89
 
90
  except Exception as e:
91
  # print(f"⚠️ [Light MC] Error: {e}")
92
  return 0.0
93
 
94
  # ==============================================================================
95
+ # 🧠 TIER 2: Advanced Simulation (Applied to Top 10 Only)
96
  # ==============================================================================
97
  def run_advanced_simulation(self, prices: List[float], num_simulations=5000, time_horizon=24) -> float:
98
  """
99
+ المحاكاة المتقدمة للعملات المختارة فقط.
100
+ تعتمد منطق المخاطرة والعائد (Sharpe/VaR).
101
  """
102
  try:
103
+ if not prices or len(prices) < 50: return 0.0
 
 
 
104
  clean_prices = [float(p) for p in prices if p is not None]
105
  if len(clean_prices) < 50: return 0.0
106
 
 
107
  closing_prices = np.array(clean_prices, dtype=np.float64)
108
  log_returns = np.diff(np.log(closing_prices))
109
 
 
111
  daily_volatility = np.std(log_returns)
112
  last_price = closing_prices[-1]
113
 
114
+ # GBM Simulation
115
  random_shocks = np.random.normal(0, 1, (num_simulations, time_horizon))
116
  drift = (mean_daily_return - 0.5 * daily_volatility ** 2)
117
  diffusion = daily_volatility * random_shocks
 
118
  daily_returns_sim = np.exp(drift + diffusion)
119
 
 
120
  price_paths = np.zeros_like(daily_returns_sim)
121
  price_paths[:, 0] = last_price * daily_returns_sim[:, 0]
 
122
  for t in range(1, time_horizon):
123
  price_paths[:, t] = price_paths[:, t-1] * daily_returns_sim[:, t]
124
 
 
125
  final_prices = price_paths[:, -1]
126
 
127
+ # Metrics
128
  threshold = last_price * 1.002
129
  prob_profit = np.mean(final_prices > threshold)
130
  var_95 = np.percentile(final_prices, 5)
131
  drawdown_risk = (var_95 - last_price) / last_price
132
  expected_return = (np.mean(final_prices) - last_price) / last_price
133
 
134
+ # Scoring (Standard Logic for Advanced)
 
 
135
  mc_score = 0.0
 
 
136
  if prob_profit > 0.55: mc_score += 0.05
137
  if prob_profit > 0.65: mc_score += 0.05
138
  if expected_return > 0.005: mc_score += 0.05
 
 
139
  if drawdown_risk < -0.07: mc_score -= 0.05
140
  if drawdown_risk < -0.10: mc_score -= 0.05
141
 
142
  return round(max(-0.10, min(0.20, mc_score)), 2)
143
 
144
  except Exception as e:
 
145
  return 0.0