File size: 2,483 Bytes
a6e25ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import gradio as gr
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier

def predict_trading_signal(open_prices, high_prices, low_prices, close_prices, volume):
    try:
        df = pd.DataFrame({
            'open': open_prices,
            'high': high_prices,
            'low': low_prices,
            'close': close_prices,
            'volume': volume
        })
    except Exception as e:
        return {"signal": "ERROR", "reason": str(e)}

    if len(df) < 50:
        return {"signal": "NEUTRAL", "reason": "Not enough data"}

    # حساب المؤشرات الهندسية (Features)
    df['returns'] = df['close'].pct_change()
    df['range'] = df['high'] - df['low']
    
    # حساب مؤشر RSI
    delta = df['close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(14).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(14).mean()
    rs = gain / (loss + 1e-9)
    df['rsi'] = 100 - (100 / (1 + rs))

    df['target'] = (df['close'].shift(-1) > df['close']).astype(int)
    
    clean_df = df.dropna()
    features = ['open', 'high', 'low', 'close', 'volume', 'returns', 'range', 'rsi']
    
    X = clean_df[features]
    y = clean_df['target']

    # تدريب نموذج الذكاء الاصطناعي
    X_train, y_train = X[:-1], y[:-1]
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)

    # التنبؤ بالشمعة الحالية
    latest_feature = X.iloc[[-1]]
    prediction = model.predict(latest_feature)[0]
    probabilities = model.predict_proba(latest_feature)[0]
    confidence = float(probabilities[prediction] * 100)
    rsi_val = float(clean_df['rsi'].iloc[-1])

    # فلترة الإشارة
    signal = "NEUTRAL"
    if prediction == 1 and confidence >= 60.0 and rsi_val <= 50:
        signal = "BUY"
    elif prediction == 0 and confidence >= 60.0 and rsi_val >= 50:
        signal = "SELL"

    return {
        "signal": signal,
        "confidence": round(confidence, 2),
        "rsi": round(rsi_val, 2)
    }

# واجهة Gradio وتفعيل الـ API تلقائياً
demo = gr.Interface(
    fn=predict_trading_signal,
    inputs=[
        gr.JSON(label="Open"),
        gr.JSON(label="High"),
        gr.JSON(label="Low"),
        gr.JSON(label="Close"),
        gr.JSON(label="Volume")
    ],
    outputs=gr.JSON(label="Signal"),
    title="Eslam AI Trading Brain"
)

if __name__ == "__main__":
    demo.launch()