Nexo-S commited on
Commit
fbb2dd4
·
verified ·
1 Parent(s): ae72006

Update ml_model.py

Browse files
Files changed (1) hide show
  1. ml_model.py +91 -91
ml_model.py CHANGED
@@ -1,92 +1,92 @@
1
- import pandas as pd
2
- import pandas_ta as ta
3
- from sklearn.ensemble import RandomForestClassifier
4
- import joblib
5
- import os
6
-
7
- # Nouveau nom pour forcer la création d'un modèle neuf
8
- ML_MODEL_FILE = "H:/Mon Drive/Alpha_Memory/ml_model_v9.pkl"
9
-
10
- def prepare_ml_features(df):
11
- """
12
- Extrait la structure du marché (Market Structure).
13
- C'est ici qu'on donne la vision 'Pro' au bot.
14
- """
15
- df = df.copy()
16
-
17
- # 1. Base technique classique
18
- df["RSI"] = df.ta.rsi(length=14)
19
- df["EMA50"] = df.ta.ema(length=50)
20
- df["ATR"] = df.ta.atr(length=14)
21
-
22
- # 2. Nouvelles Features V9 PRO (Market Structure & Dynamique)
23
- # Distance au plus haut/plus bas des dernières 24h
24
- df["High_24h"] = df["high"].rolling(24).max()
25
- df["Low_24h"] = df["low"].rolling(24).min()
26
-
27
- # Ex: 0.05 signifie qu'on est à 5% du plus haut journalier
28
- df["Dist_High_24h"] = (df["High_24h"] - df["close"]) / df["close"]
29
- df["Dist_Low_24h"] = (df["close"] - df["Low_24h"]) / df["close"]
30
-
31
- # Distance et pente de l'EMA (Tendance locale)
32
- df["EMA_dist"] = (df["close"] - df["EMA50"]) / df["EMA50"]
33
- df["EMA_slope"] = (df["EMA50"] / df["EMA50"].shift(5)) - 1
34
-
35
- # Ratio de Volatilité (L'ATR relativisé au prix)
36
- df["ATR_ratio"] = df["ATR"] / df["close"]
37
-
38
- # Ratio de Volume (Confirmation des pros)
39
- df["vol_mean_24"] = df["vol"].rolling(24).mean()
40
- df["VOL_ratio"] = df["vol"] / df["vol_mean_24"]
41
-
42
- # 3. Target (Prédiction de la prochaine bougie)
43
- df['target'] = (df['close'].shift(-1) > df['close']).astype(int)
44
-
45
- # Nettoyage
46
- df = df.dropna()
47
-
48
- # Les 7 piliers de la décision
49
- features = [
50
- "RSI", "Dist_High_24h", "Dist_Low_24h",
51
- "EMA_dist", "EMA_slope", "ATR_ratio", "VOL_ratio"
52
- ]
53
-
54
- return df[features], df['target']
55
-
56
- def train_model(df):
57
- """
58
- Entraîne le RandomForest avec une limitation stricte pour protéger la RAM.
59
- """
60
- print("🧠 [V9] Entraînement du Core ML (RandomForest) avec Market Structure...")
61
- X, y = prepare_ml_features(df)
62
-
63
- # Optimisation Quant pour CPU 2 cœurs / 4 threads
64
- model = RandomForestClassifier(
65
- n_estimators=100,
66
- max_depth=5, # Anti-overfitting + RAM light
67
- min_samples_split=10,
68
- n_jobs=-1, # Utilise 100% du CPU dispo
69
- random_state=42
70
- )
71
- model.fit(X, y)
72
-
73
- joblib.dump(model, ML_MODEL_FILE)
74
- print("✅ [V9] Core ML sauvegardé ! (Spécialiste des Ranges)")
75
- return model
76
-
77
- def load_model():
78
- if os.path.exists(ML_MODEL_FILE):
79
- return joblib.load(ML_MODEL_FILE)
80
- return None
81
-
82
- def predict_prob(model, df):
83
- """
84
- Renvoie la probabilité (0 à 1) que la prochaine bougie soit verte.
85
- """
86
- X, _ = prepare_ml_features(df)
87
- if len(X) == 0:
88
- return 0.5
89
-
90
- # On isole la toute dernière ligne du marché
91
- last_row = X.iloc[[-1]]
92
  return model.predict_proba(last_row)[0][1]
 
1
+ import pandas as pd
2
+ import pandas_ta as ta
3
+ from sklearn.ensemble import RandomForestClassifier
4
+ import joblib
5
+ import os
6
+
7
+ # Nouveau nom pour forcer la création d'un modèle neuf
8
+ ML_MODEL_FILE = "ml_model_v9.pkl"
9
+
10
+ def prepare_ml_features(df):
11
+ """
12
+ Extrait la structure du marché (Market Structure).
13
+ C'est ici qu'on donne la vision 'Pro' au bot.
14
+ """
15
+ df = df.copy()
16
+
17
+ # 1. Base technique classique
18
+ df["RSI"] = df.ta.rsi(length=14)
19
+ df["EMA50"] = df.ta.ema(length=50)
20
+ df["ATR"] = df.ta.atr(length=14)
21
+
22
+ # 2. Nouvelles Features V9 PRO (Market Structure & Dynamique)
23
+ # Distance au plus haut/plus bas des dernières 24h
24
+ df["High_24h"] = df["high"].rolling(24).max()
25
+ df["Low_24h"] = df["low"].rolling(24).min()
26
+
27
+ # Ex: 0.05 signifie qu'on est à 5% du plus haut journalier
28
+ df["Dist_High_24h"] = (df["High_24h"] - df["close"]) / df["close"]
29
+ df["Dist_Low_24h"] = (df["close"] - df["Low_24h"]) / df["close"]
30
+
31
+ # Distance et pente de l'EMA (Tendance locale)
32
+ df["EMA_dist"] = (df["close"] - df["EMA50"]) / df["EMA50"]
33
+ df["EMA_slope"] = (df["EMA50"] / df["EMA50"].shift(5)) - 1
34
+
35
+ # Ratio de Volatilité (L'ATR relativisé au prix)
36
+ df["ATR_ratio"] = df["ATR"] / df["close"]
37
+
38
+ # Ratio de Volume (Confirmation des pros)
39
+ df["vol_mean_24"] = df["vol"].rolling(24).mean()
40
+ df["VOL_ratio"] = df["vol"] / df["vol_mean_24"]
41
+
42
+ # 3. Target (Prédiction de la prochaine bougie)
43
+ df['target'] = (df['close'].shift(-1) > df['close']).astype(int)
44
+
45
+ # Nettoyage
46
+ df = df.dropna()
47
+
48
+ # Les 7 piliers de la décision
49
+ features = [
50
+ "RSI", "Dist_High_24h", "Dist_Low_24h",
51
+ "EMA_dist", "EMA_slope", "ATR_ratio", "VOL_ratio"
52
+ ]
53
+
54
+ return df[features], df['target']
55
+
56
+ def train_model(df):
57
+ """
58
+ Entraîne le RandomForest avec une limitation stricte pour protéger la RAM.
59
+ """
60
+ print("🧠 [V9] Entraînement du Core ML (RandomForest) avec Market Structure...")
61
+ X, y = prepare_ml_features(df)
62
+
63
+ # Optimisation Quant pour CPU 2 cœurs / 4 threads
64
+ model = RandomForestClassifier(
65
+ n_estimators=100,
66
+ max_depth=5, # Anti-overfitting + RAM light
67
+ min_samples_split=10,
68
+ n_jobs=-1, # Utilise 100% du CPU dispo
69
+ random_state=42
70
+ )
71
+ model.fit(X, y)
72
+
73
+ joblib.dump(model, ML_MODEL_FILE)
74
+ print("✅ [V9] Core ML sauvegardé ! (Spécialiste des Ranges)")
75
+ return model
76
+
77
+ def load_model():
78
+ if os.path.exists(ML_MODEL_FILE):
79
+ return joblib.load(ML_MODEL_FILE)
80
+ return None
81
+
82
+ def predict_prob(model, df):
83
+ """
84
+ Renvoie la probabilité (0 à 1) que la prochaine bougie soit verte.
85
+ """
86
+ X, _ = prepare_ml_features(df)
87
+ if len(X) == 0:
88
+ return 0.5
89
+
90
+ # On isole la toute dernière ligne du marché
91
+ last_row = X.iloc[[-1]]
92
  return model.predict_proba(last_row)[0][1]