Spaces:
Paused
Paused
Update ml_engine/indicators.py
Browse files123419 unmodified lines24252627282930313233343536373810 unmodified lines495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132152 unmodified lines285286287288# ml_engine/indicators.py (V10.2 - Bug FIX)import pandas as pdimport pandas_ta as taimport numpy as np19 unmodified lines'cycle': ['hull_ma', 'supertrend', 'zigzag', 'fisher_transform']}# 🔴 --- (V10.2 - تم إصلاح الأخطاء هنا) --- 🔴def calculate_v9_smart_features(self, dataframe: pd.DataFrame) -> Dict[str, float]:"""(محدث V10.2) - (إصلاح أخطاء 'hurst' و 'atr_normalized_return')"""if dataframe.empty or dataframe is None or len(dataframe) < 100:return {}features = {}try:# --- جلب البيانات الأساسية (Series) ---close = dataframe['close']10 unmodified linesobv_series = ta.obv(close, volume)# --- 2. ميزات "نسب السعر" (Price Ratios) ---ema_50 = ta.ema(close, length=50).iloc[-1]ema_200 = ta.ema(close, length=200).iloc[-1]if ema_50 and ema_50 > 0: features['price_to_ema_50'] = (current_price / ema_50) - 1if ema_200 and ema_200 > 0: features['price_to_ema_200'] = (current_price / ema_200) - 1min_100 = low.tail(100).min(); max_100 = high.tail(100).max()if min_100 and min_100 > 0: features['price_to_min_100'] = (current_price / min_100) - 1if max_100 and max_100 > 0: features['price_to_max_100'] = (current_price / max_100) - 1# --- 3. ميزات "الميل" (Slope) ---ema_14 = ta.ema(close, length=14).iloc[-1]if ema_14 and ema_50: features['slope_14_50'] = (ema_14 - ema_50) / 14if adx_data is not None and not adx_data.empty:adx_series = adx_data['ADX_14']if adx_series is not None and not adx_series.empty:adx_ema_5 = ta.ema(adx_series, length=5).iloc[-1]; adx_ema_15 = ta.ema(adx_series, length=15).iloc[-1]if adx_ema_5 and adx_ema_15: features['adx_slope'] = (adx_ema_5 - adx_ema_15) / 5# --- 4. ميزات "الحجم" (Volume) و "السيولة" ---vol_ma_50 = volume.tail(50).mean(); vol_std_50 = volume.tail(50).std()if vol_std_50 and vol_std_50 > 0: features['volume_zscore_50'] = (volume.iloc[-1] - vol_ma_50) / vol_std_50vwap = ta.vwap(high, low, close, volume).iloc[-1]if vwap and vwap > 0: features['vwap_gap'] = (current_price - vwap) / vwapcmf = ta.cmf(high, low, close, volume, length=20)if cmf is not None and not cmf.empty: features['cmf_20'] = cmf.iloc[-1]vroc = ta.roc(volume, length=12)if vroc is not None and not vroc.empty: features['vroc_12'] = vroc.iloc[-1]if obv_series is not None and not obv_series.empty:obv_ema_10 = ta.ema(obv_series, length=10).iloc[-1]; obv_ema_30 = ta.ema(obv_series, length=30).iloc[-1]if obv_ema_10 and obv_ema_30: features['obv_slope'] = (obv_ema_10 - obv_ema_30) / 10# --- 5. ميزات "تجميعية" (Aggregative) ---if rsi_series is not None and not rsi_series.empty:features['rsi_14'] = rsi_series.iloc[-1]; features['rsi_mean_10'] = rsi_series.tail(10).mean(); features['rsi_std_10'] = rsi_series.tail(10).std()if mfi_series is not None and not mfi_series.empty:features['mfi_14'] = mfi_series.iloc[-1]; features['mfi_mean_10'] = mfi_series.tail(10).mean()if adx_data is not None and not adx_data.empty:adx_val = adx_data['ADX_14'].iloc[-1]if adx_val is not None: features['adx_14'] = adx_val# 🔴 --- (V10.2 - إصلاح 'atr_val') --- 🔴atr_val = None # (تعريف المتغير أولاً)if atr_series is not None and not atr_series.empty:atr_val = atr_series.iloc[-1]if atr_val and current_price > 0: features['atr_percent'] = (atr_val / current_price) * 100vol_of_vol_series = ta.atr(atr_series, length=10) # (Vol-of-Vol)if vol_of_vol_series is not None and not vol_of_vol_series.empty: features['vol_of_vol'] = vol_of_vol_series.iloc[-1]last_return = close.pct_change().iloc[-1]if atr_val and atr_val > 0:features['atr_normalized_return'] = last_return / atr_valelse:features['atr_normalized_return'] = 0.0 # (قيمة افتراضية إذا فشل ATR)# 🔴 --- (V10.2 - إصلاح 'hurst') --- 🔴if HURST_AVAILABLE:try:hurst_series = close.tail(100).to_numpy()H, c, data = compute_Hc(hurst_series, kind='price', simplified=True)features['hurst'] = Hexcept Exception:features['hurst'] = 0.5 # (محايد إذا فشلت المكتبة)else:features['hurst'] = 0.5 # (محايد إذا لم يتم تثبيت المكتبة)ppo_data = ta.ppo(close, fast=12, slow=26, signal=9)if ppo_data is not None and not ppo_data.empty:features['ppo_hist'] = ppo_data['PPOh_12_26_9'].iloc[-1]features['ppo_line'] = ppo_data['PPO_12_26_9'].iloc[-1]except Exception as e:# print(f"⚠️ خطأ في حساب ميزات V9.8 الذكية: {e}");passfinal_features = {};for key, value in features.items():if value is not None and np.isfinite(value): final_features[key] = float(value)else: final_features[key] = 0.0return final_features# -----------------------------------------------------------------# --- (الدوال القديمة تبقى كما هي للاستخدامات الأخرى مثل Sentry 1m) ---152 unmodified linesexcept Exception as e: pass;return {key: value for key, value in cycle.items() if value is not None and not np.isnan(value)};print("✅ ML Module: Technical Indicators loaded (V10.2 - Bug FIX)")123419 unmodified lines2425262728293031323334353637383940414243444546474849505110 unmodified lines6263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158152 unmodified lines311312313314# ml_engine/indicators.py (V10.2 - Anti-Fragile FIX)import pandas as pdimport pandas_ta as taimport numpy as np19 unmodified lines'cycle': ['hull_ma', 'supertrend', 'zigzag', 'fisher_transform']}# 🔴 --- START OF UPDATED FUNCTION (V10.2 - Anti-Fragile) --- 🔴def calculate_v9_smart_features(self, dataframe: pd.DataFrame) -> Dict[str, float]:"""(محدث V10.2) - (إصلاح خطأ "الميزات المفقودة" بشكل نهائي)- استخدام "قالب الميزات" لضمان إرجاع جميع الميزات دائماً."""if dataframe.empty or dataframe is None or len(dataframe) < 100:return {}# --- (V10.2) الخطوة 1: تعريف "قالب الميزات" بالقيم الافتراضية ---# (هذه هي جميع الميزات التي تدرب عليها نموذج V9.8)features = {'price_to_ema_50': 0.0, 'price_to_ema_200': 0.0, 'price_to_min_100': 0.0,'price_to_max_100': 0.0, 'slope_14_50': 0.0, 'adx_slope': 0.0,'volume_zscore_50': 0.0, 'vwap_gap': 0.0, 'cmf_20': 0.0, 'vroc_12': 0.0,'obv_slope': 0.0, 'rsi_14': 50.0, 'rsi_mean_10': 50.0, 'rsi_std_10': 0.0,'mfi_14': 50.0, 'mfi_mean_10': 50.0, 'adx_14': 20.0, 'atr_percent': 0.0,'vol_of_vol': 0.0, 'atr_normalized_return': 0.0, 'hurst': 0.5,'ppo_hist': 0.0, 'ppo_line': 0.0# (ميزات مونت كارلو ستضاف لاحقاً في data_manager)}try:# --- جلب البيانات الأساسية (Series) ---close = dataframe['close']10 unmodified linesobv_series = ta.obv(close, volume)# --- 2. ميزات "نسب السعر" (Price Ratios) ---try:ema_50 = ta.ema(close, length=50).iloc[-1]ema_200 = ta.ema(close, length=200).iloc[-1]if ema_50 and ema_50 > 0: features['price_to_ema_50'] = (current_price / ema_50) - 1if ema_200 and ema_200 > 0: features['price_to_ema_200'] = (current_price / ema_200) - 1min_100 = low.tail(100).min(); max_100 = high.tail(100).max()if min_100 and min_100 > 0: features['price_to_min_100'] = (current_price / min_100) - 1if max_100 and max_100 > 0: features['price_to_max_100'] = (current_price / max_100) - 1ema_14 = ta.ema(close, length=14).iloc[-1]if ema_14 and ema_50: features['slope_14_50'] = (ema_14 - ema_50) / 14except Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)# --- 3. ميزات "الميل" (Slope) ---try:if adx_data is not None and not adx_data.empty:adx_series = adx_data['ADX_14']if adx_series is not None and not adx_series.empty:adx_ema_5 = ta.ema(adx_series, length=5).iloc[-1]; adx_ema_15 = ta.ema(adx_series, length=15).iloc[-1]if adx_ema_5 and adx_ema_15: features['adx_slope'] = (adx_ema_5 - adx_ema_15) / 5except Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)# --- 4. ميزات "الحجم" (Volume) و "السيولة" ---try:vol_ma_50 = volume.tail(50).mean(); vol_std_50 = volume.tail(50).std()if vol_std_50 and vol_std_50 > 0: features['volume_zscore_50'] = (volume.iloc[-1] - vol_ma_50) / vol_std_50vwap = ta.vwap(high, low, close, volume).iloc[-1]if vwap and vwap > 0: features['vwap_gap'] = (current_price - vwap) / vwapcmf = ta.cmf(high, low, close, volume, length=20)if cmf is not None and not cmf.empty: features['cmf_20'] = cmf.iloc[-1]vroc = ta.roc(volume, length=12)if vroc is not None and not vroc.empty: features['vroc_12'] = vroc.iloc[-1]if obv_series is not None and not obv_series.empty:obv_ema_10 = ta.ema(obv_series, length=10).iloc[-1]; obv_ema_30 = ta.ema(obv_series, length=30).iloc[-1]if obv_ema_10 and obv_ema_30: features['obv_slope'] = (obv_ema_10 - obv_ema_30) / 10except Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)# --- 5. ميزات "تجميعية" (Aggregative) ---try:if rsi_series is not None and not rsi_series.empty:features['rsi_14'] = rsi_series.iloc[-1]; features['rsi_mean_10'] = rsi_series.tail(10).mean(); features['rsi_std_10'] = rsi_series.tail(10).std()if mfi_series is not None and not mfi_series.empty:features['mfi_14'] = mfi_series.iloc[-1]; features['mfi_mean_10'] = mfi_series.tail(10).mean()if adx_data is not None and not adx_data.empty:adx_val = adx_data['ADX_14'].iloc[-1]if adx_val is not None: features['adx_14'] = adx_valexcept Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)# --- 6. ميزات "التقلب" (Volatility) ---try:atr_val = Noneif atr_series is not None and not atr_series.empty:atr_val = atr_series.iloc[-1]if atr_val and current_price > 0: features['atr_percent'] = (atr_val / current_price) * 100vol_of_vol_series = ta.atr(atr_series, length=10) # (Vol-of-Vol)if vol_of_vol_series is not None and not vol_of_vol_series.empty: features['vol_of_vol'] = vol_of_vol_series.iloc[-1]last_return = close.pct_change().iloc[-1]if atr_val and atr_val > 0:features['atr_normalized_return'] = last_return / atr_val# (لا نحتاج else، القيمة الافتراضية 0.0 موجودة)except Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)# --- 7. ميزات النظام (Regime Features) ---try:if HURST_AVAILABLE:hurst_series = close.tail(100).to_numpy()H, c, data = compute_Hc(hurst_series, kind='price', simplified=True)features['hurst'] = H# (لا نحتاج else، القيمة الافتراضية 0.5 موجودة)except Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)try:ppo_data = ta.ppo(close, fast=12, slow=26, signal=9)if ppo_data is not None and not ppo_data.empty:features['ppo_hist'] = ppo_data['PPOh_12_26_9'].iloc[-1]features['ppo_line'] = ppo_data['PPO_12_26_9'].iloc[-1]except Exception: pass # (فشل هذا الجزء، ستبقى القيم الافتراضية)except Exception as e:# (فشل كبير، سنعيد القالب الافتراضي)# print(f"⚠️ خطأ كارثي في حساب ميزات V9.8: {e}");pass# (تنظيف نهائي للتأكد من عدم وجود NaN/Inf)for key, value in features.items():if not np.isfinite(value):features[key] = 0.0 # (إعادة التعيين إلى 0.0 إذا كان الحساب NaN)return features# 🔴 --- END OF UPDATED FUNCTION (V10.2) --- 🔴# -----------------------------------------------------------------# --- (الدوال القديمة تبقى كما هي للاستخدامات الأخرى مثل Sentry 1m) ---152 unmodified linesexcept Exception as e: pass;return {key: value for key, value in cycle.items() if value is not None and not np.isnan(value)};print("✅ ML Module: Technical Indicators loaded (V10.2 - Anti-Fragile FIX)")
ml_engine/indicators.py+92-66