لإضافة ميزات اكتشاف الشذوذ (Anomaly Detection) إلى الكود الحالي، يمكننا استخدام قيم Z-score لتحديد النقاط التي تتجاوز حدودًا معينة، مما يشير إلى حركات مفاجئة أو غير متوقعة في الأسعار. سنقوم بتحديد العتبات (على سبيل المثال، Z-score أكبر من 3 أو أصغر من -3) ووسم هذه النقاط كحالات شاذة. بعد ذلك، سنقوم بتظليل هذه النقاط على الرسم البياني لتمييزها بوضوح.
إليك كيفية تعديل الكود لتحقيق ذلك:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import yfinance as yf
# إعدادات الرسومات
plt.style.use('seaborn-darkgrid')
# جلب البيانات
data = yf.download(tickers="EURUSD=X", period="1mo", interval="1h")['Close']
# حذف القيم الناقصة
data.dropna(inplace=True)
# حساب Z-score
window = 35
rolling_mean = data.rolling(window=window).mean()
rolling_std = data.rolling(window=window).std()
z_score = (data - rolling_mean) / rolling_std
# تحديد العتبات لاكتشاف الشذوذ
threshold_upper = 3
threshold_lower = -3
# تحديد نقاط الشذوذ
anomalies = data[(z_score > threshold_upper) | (z_score < threshold_lower)]
# رسم الأسعار وZ-score مع تمييز الشذوذ
fig, ax1 = plt.subplots(figsize=(20,10))
# رسم أسعار الإغلاق
color = 'tab:red'
ax1.set_xlabel('التاريخ')
ax1.set_ylabel('أسعار الإغلاق', color=color)
ax1.plot(data.index, data, color=color, label='سعر الإغلاق')
ax1.tick_params(axis='y', labelcolor=color)
# تمييز نقاط الشذوذ على أسعار الإغلاق
ax1.scatter(anomalies.index, anomalies, color='orange', label='شذوذ', zorder=5)
# رسم Z-score
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Z-Score', color=color)
ax2.plot(z_score.index, z_score, color=color, label='Z-Score')
ax2.axhline(0, color='black', linestyle='--')
ax2.axhline(threshold_upper, color='red', linestyle='--', label='حد أعلى 3')
ax2.axhline(threshold_lower, color='green', linestyle='--', label='حد أدنى -3')
# تمييز نقاط الشذوذ على Z-score
ax2.scatter(anomalies.index, z_score[anomalies.index], color='orange', zorder=5)
# إضافة العناوين والتسميات
fig.tight_layout()
plt.title('أسعار الإغلاق و Z-Score مع اكتشاف الشذوذ')
fig.legend(loc="upper left", bbox_to_anchor=(0.1,0.9))
plt.show()
شرح التعديلات:
-
تحديد العتبات للشذوذ:
- حددنا العتبات العليا والسفلى لـ Z-score بقيم 3 و-3 على التوالي. هذه القيم تعتبر عادةً مؤشرات قوية على الشذوذ في البيانات المالية.
threshold_upper = 3
threshold_lower = -3
-
اكتشاف النقاط الشاذة:
- استخدمنا شرطًا لتحديد النقاط التي يتجاوز فيها Z-score العتبات المحددة.
anomalies = data[(z_score > threshold_upper) | (z_score < threshold_lower)]
-
تمييز الشذوذ على الرسم البياني:
- استخدمنا
ax1.scatter و ax2.scatter لتمييز نقاط الشذوذ على كل من أسعار الإغلاق وZ-score بالألوان البرتقالية، مما يجعلها بارزة وسهلة التمييز.
ax1.scatter(anomalies.index, anomalies, color='orange', label='شذوذ', zorder=5)
ax2.scatter(anomalies.index, z_score[anomalies.index], color='orange', zorder=5)
-
تحسين مظهر الرسم البياني:
- استخدمنا
plt.style.use('seaborn-darkgrid') لتحسين مظهر الرسم البياني وجعله أكثر احترافية.
- تم إضافة تسميات وعناوين واضحة لكل من المحاور والرسم البياني بشكل عام.
- أضفنا وسيلة إيضاح لتوضيح ما تمثله النقاط المختلفة على الرسم.
توسيع إمكانية اكتشاف الشذوذ:
إذا كنت ترغب في استخدام تقنيات أكثر تقدمًا لاكتشاف الشذوذ، يمكنك دمج مكتبات مثل Scikit-learn واستخدام خوارزميات مثل Isolation Forest أو Local Outlier Factor. إليك مثالًا مبسطًا باستخدام Isolation Forest:
from sklearn.ensemble import IsolationForest
# تحويل البيانات إلى إطار بيانات للتوافق مع Scikit-learn
df = pd.DataFrame({
'Close': data,
'Rolling_Mean': rolling_mean,
'Rolling_Std': rolling_std,
'Z_Score': z_score
}).dropna()
# تدريب نموذج Isolation Forest
model = IsolationForest(contamination=0.01) # نسبة الشذوذ المتوقعة
model.fit(df[['Close', 'Z_Score']])
# توقع الشذوذ
df['Anomaly'] = model.predict(df[['Close', 'Z_Score']])
df['Anomaly'] = df['Anomaly'].apply(lambda x: True if x == -1 else False)
# استخراج النقاط الشاذة
anomalies_if = df[df['Anomaly']]
# رسم الشذوذ باستخدام Isolation Forest
fig, ax1 = plt.subplots(figsize=(20,10))
# رسم أسعار الإغلاق
color = 'tab:red'
ax1.set_xlabel('التاريخ')
ax1.set_ylabel('أسعار الإغلاق', color=color)
ax1.plot(df.index, df['Close'], color=color, label='سعر الإغلاق')
ax1.tick_params(axis='y', labelcolor=color)
# تمييز نقاط الشذوذ
ax1.scatter(anomalies_if.index, anomalies_if['Close'], color='purple', label='شذوذ (Isolation Forest)', zorder=5)
# رسم Z-score
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Z-Score', color=color)
ax2.plot(df.index, df['Z_Score'], color=color, label='Z-Score')
ax2.axhline(0, color='black', linestyle='--')
ax2.axhline(threshold_upper, color='red', linestyle='--')
ax2.axhline(threshold_lower, color='green', linestyle='--')
fig.tight_layout()
plt.title('أسعار الإغلاق و Z-Score مع اكتشاف الشذوذ باستخدام Isolation Forest')
fig.legend(loc="upper left", bbox_to_anchor=(0.1,0.9))
plt.show()
شرح إضافي للتوسع باستخدام Isolation Forest:
-
تحضير البيانات:
- قمنا بتجهيز إطار بيانات يحتوي على أسعار الإغلاق، المتوسط المتحرك، الانحراف المعياري، وZ-score.
-
تدريب النموذج:
- استخدمنا
IsolationForest مع نسبة شذوذ متوقعة (مثلاً 1%) لتدريب النموذج على البيانات.
-
التنبؤ بالشذوذ:
- النموذج يتنبأ بالنقاط الشاذة ويعلمها كـ
-1.
-
تمييز الشذوذ على الرسم البياني:
- تم تمييز النقاط الشاذة التي اكتشفها النموذج بلون مختلف (الأرجواني في هذا المثال).
باستخدام هذه الطرق، يمكنك تحسين قدرات اكتشاف الشذوذ في بياناتك المالية، مما يساعدك في الكشف عن الحركات المفاجئة وغير المتوقعة في السوق بفعالية أكبر.