Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -124,12 +124,19 @@ def restore_db_from_hf():
|
|
| 124 |
print(f"⚠️ Aucun backup ADN trouvé (1er lancement) : {e}")
|
| 125 |
|
| 126 |
# 2. Tentative de restauration du modèle DINO
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
def backup_db_to_hf():
|
| 135 |
if not HF_TOKEN: return
|
|
@@ -367,8 +374,15 @@ async def predict_signal(symbol, timeframe="1h"):
|
|
| 367 |
ml_prob = float(ml_model.predict_proba(last_row[ml_cols])[0][1])
|
| 368 |
time_cols = ['return_1h', 'return_3h', 'return_12h', 'RSI_lag1', 'RSI_lag2', 'vol_lag1', 'VOL_RATIO']
|
| 369 |
time_prob = float(time_model.predict_proba(last_row[time_cols])[0][1])
|
| 370 |
-
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
# ⚡ 4. ENSEMBLE V30
|
| 373 |
final_p, wt, wm, wl, ws = combine_scores(symbol, timeframe, time_prob, ml_prob, dino_prob, p_sent, final_scenario)
|
| 374 |
|
|
@@ -792,16 +806,25 @@ def detect_chart_scenario(df, df_1m=None, df_5m=None, df_15m=None, df_1h=None):
|
|
| 792 |
return 3
|
| 793 |
|
| 794 |
|
|
|
|
| 795 |
# --- 🧠 TRAINING ENGINE ---
|
| 796 |
def trigger_training(symbol="BTC/USD"):
|
| 797 |
try:
|
| 798 |
memory_guard()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
bars = exchange_sync.fetch_ohlcv(symbol, timeframe='1h', limit=1500)
|
| 800 |
df = pd.DataFrame(bars, columns=['ts', 'open', 'high', 'low', 'close', 'vol'])
|
| 801 |
-
if len(df) < 500: return f"❌ Historique insuffisant."
|
| 802 |
|
| 803 |
df_final = prepare_features_sync(symbol, '1h', limit_bars=1000)
|
| 804 |
-
if df_final.empty or len(df_final) < 100: return f"❌ Données vides."
|
| 805 |
|
| 806 |
if LGBM_AVAILABLE:
|
| 807 |
ml_cols = ["RSI", "Dist_High_24h", "Dist_Low_24h", "EMA_dist", "EMA_slope", "ATR_ratio", "VOL_ratio"]
|
|
@@ -809,28 +832,43 @@ def trigger_training(symbol="BTC/USD"):
|
|
| 809 |
df_train = df_final.dropna(subset=ml_cols + ['Target'])
|
| 810 |
X, y = df_train[ml_cols], df_train['Target']
|
| 811 |
params = {'objective': 'binary', 'metric': 'binary_logloss', 'boosting_type': 'gbdt', 'learning_rate': 0.05, 'num_leaves': 31, 'verbose': -1}
|
|
|
|
| 812 |
model = lgb.train(params, lgb.Dataset(X, label=y), 100)
|
| 813 |
-
|
|
|
|
|
|
|
|
|
|
| 814 |
try:
|
| 815 |
api = HfApi()
|
| 816 |
api.upload_file(
|
| 817 |
-
path_or_fileobj=
|
| 818 |
-
path_in_repo=
|
| 819 |
-
repo_id=HF_REPO_ID,
|
| 820 |
repo_type="dataset",
|
| 821 |
token=HF_TOKEN
|
| 822 |
)
|
| 823 |
-
print("☁️ [BACKUP]
|
| 824 |
except Exception as e:
|
| 825 |
-
print(f"⚠️ Erreur backup modèle : {e}")
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 829 |
global ml_model, time_model
|
| 830 |
-
|
|
|
|
|
|
|
|
|
|
| 831 |
gc.collect()
|
| 832 |
-
return f"✅ IA ré-entraînée."
|
| 833 |
-
except Exception as e: return f"❌ Erreur Training : {e}"
|
|
|
|
|
|
|
| 834 |
|
| 835 |
# --- 🚀 MOTEURS AUTO-PILOTE ---
|
| 836 |
AUTO_SYMBOLS = ["BTC/USD", "ETH/USD"]
|
|
|
|
| 124 |
print(f"⚠️ Aucun backup ADN trouvé (1er lancement) : {e}")
|
| 125 |
|
| 126 |
# 2. Tentative de restauration du modèle DINO
|
| 127 |
+
# 2. Tentative de restauration des modèles DINO (Multiples)
|
| 128 |
+
global dino_brains
|
| 129 |
+
dino_brains = {}
|
| 130 |
+
|
| 131 |
+
for crypto in ["BTC", "ETH"]:
|
| 132 |
+
filename = f"dino_lgbm_{crypto}.txt"
|
| 133 |
+
try:
|
| 134 |
+
print(f"🔄 [SYSTEM] Restauration du DINO {crypto} depuis HF...")
|
| 135 |
+
hf_hub_download(repo_id=HF_REPO_ID, filename=filename, repo_type="dataset", local_dir=".", token=HF_TOKEN)
|
| 136 |
+
dino_brains[crypto] = lgb.Booster(model_file=filename)
|
| 137 |
+
print(f"✅ [RESTORE] Modèle Dino {crypto} récupéré et chargé !")
|
| 138 |
+
except Exception:
|
| 139 |
+
print(f"⚠️ Aucun modèle trouvé pour {crypto}. Pense à Forcer l'Entraînement de {crypto}.")
|
| 140 |
|
| 141 |
def backup_db_to_hf():
|
| 142 |
if not HF_TOKEN: return
|
|
|
|
| 374 |
ml_prob = float(ml_model.predict_proba(last_row[ml_cols])[0][1])
|
| 375 |
time_cols = ['return_1h', 'return_3h', 'return_12h', 'RSI_lag1', 'RSI_lag2', 'vol_lag1', 'VOL_RATIO']
|
| 376 |
time_prob = float(time_model.predict_proba(last_row[time_cols])[0][1])
|
| 377 |
+
|
| 378 |
+
# 🧠 SÉLECTION DU CERVEAU DINO (Schizophrénie)
|
| 379 |
+
sym_clean = symbol.replace("/", "").replace("USDT", "").replace("USD", "").upper()
|
| 380 |
+
if 'dino_brains' in globals() and sym_clean in dino_brains:
|
| 381 |
+
dino_prob = float(dino_brains[sym_clean].predict(last_row[ml_cols].values)[0])
|
| 382 |
+
elif 'dino_brain' in globals() and dino_brain: # Sécurité : Fallback sur l'ancien modèle si besoin
|
| 383 |
+
dino_prob = float(dino_brain.predict(last_row[ml_cols].values)[0])
|
| 384 |
+
else:
|
| 385 |
+
dino_prob = 0.5 # Si aucun cerveau n'est entraîné, on reste neutre
|
| 386 |
# ⚡ 4. ENSEMBLE V30
|
| 387 |
final_p, wt, wm, wl, ws = combine_scores(symbol, timeframe, time_prob, ml_prob, dino_prob, p_sent, final_scenario)
|
| 388 |
|
|
|
|
| 806 |
return 3
|
| 807 |
|
| 808 |
|
| 809 |
+
# --- 🧠 TRAINING ENGINE ---
|
| 810 |
# --- 🧠 TRAINING ENGINE ---
|
| 811 |
def trigger_training(symbol="BTC/USD"):
|
| 812 |
try:
|
| 813 |
memory_guard()
|
| 814 |
+
|
| 815 |
+
# 🎯 1. Nettoyage du symbole pour le nom de fichier (ex: BTC/USDT -> BTC)
|
| 816 |
+
sym_clean = symbol.replace("/", "").replace("USDT", "").replace("USD", "").upper()
|
| 817 |
+
if not sym_clean: sym_clean = "DEFAULT"
|
| 818 |
+
|
| 819 |
+
# On crée un nom de fichier unique par crypto
|
| 820 |
+
model_filename = f"dino_lgbm_{sym_clean}.txt"
|
| 821 |
+
|
| 822 |
bars = exchange_sync.fetch_ohlcv(symbol, timeframe='1h', limit=1500)
|
| 823 |
df = pd.DataFrame(bars, columns=['ts', 'open', 'high', 'low', 'close', 'vol'])
|
| 824 |
+
if len(df) < 500: return f"❌ Historique insuffisant pour {symbol}."
|
| 825 |
|
| 826 |
df_final = prepare_features_sync(symbol, '1h', limit_bars=1000)
|
| 827 |
+
if df_final.empty or len(df_final) < 100: return f"❌ Données vides pour {symbol}."
|
| 828 |
|
| 829 |
if LGBM_AVAILABLE:
|
| 830 |
ml_cols = ["RSI", "Dist_High_24h", "Dist_Low_24h", "EMA_dist", "EMA_slope", "ATR_ratio", "VOL_ratio"]
|
|
|
|
| 832 |
df_train = df_final.dropna(subset=ml_cols + ['Target'])
|
| 833 |
X, y = df_train[ml_cols], df_train['Target']
|
| 834 |
params = {'objective': 'binary', 'metric': 'binary_logloss', 'boosting_type': 'gbdt', 'learning_rate': 0.05, 'num_leaves': 31, 'verbose': -1}
|
| 835 |
+
|
| 836 |
model = lgb.train(params, lgb.Dataset(X, label=y), 100)
|
| 837 |
+
|
| 838 |
+
# 💾 2. Sauvegarde avec le nom unique
|
| 839 |
+
model.save_model(model_filename)
|
| 840 |
+
|
| 841 |
try:
|
| 842 |
api = HfApi()
|
| 843 |
api.upload_file(
|
| 844 |
+
path_or_fileobj=model_filename,
|
| 845 |
+
path_in_repo=model_filename,
|
| 846 |
+
repo_id=HF_REPO_ID,
|
| 847 |
repo_type="dataset",
|
| 848 |
token=HF_TOKEN
|
| 849 |
)
|
| 850 |
+
print(f"☁️ [BACKUP] {model_filename} sauvegardé sur le Cloud !")
|
| 851 |
except Exception as e:
|
| 852 |
+
print(f"⚠️ Erreur backup modèle {sym_clean} : {e}")
|
| 853 |
+
|
| 854 |
+
# 🧠 3. On met à jour le dictionnaire global des cerveaux DINO
|
| 855 |
+
global dino_brains
|
| 856 |
+
if 'dino_brains' not in globals():
|
| 857 |
+
dino_brains = {}
|
| 858 |
+
dino_brains[sym_clean] = lgb.Booster(model_file=model_filename)
|
| 859 |
+
print(f"🧠 [IA] Cerveau {sym_clean} chargé en mémoire vive.")
|
| 860 |
+
|
| 861 |
+
# Ces deux là restent uniques car ils sont sûrement génériques dans ton code
|
| 862 |
global ml_model, time_model
|
| 863 |
+
try:
|
| 864 |
+
ml_model, time_model = joblib.load("ml_model_v9.pkl"), joblib.load("time_model.pkl")
|
| 865 |
+
except: pass # Si les pkl n'existent pas, on ne crashe pas tout
|
| 866 |
+
|
| 867 |
gc.collect()
|
| 868 |
+
return f"✅ IA ré-entraînée et sauvegardée pour {symbol} ({model_filename})."
|
| 869 |
+
except Exception as e: return f"❌ Erreur Training {symbol} : {e}"
|
| 870 |
+
|
| 871 |
+
def training_wrapper(symbol, *args): return trigger_training(str(symbol).strip().upper() if isinstance(symbol, str) else "BTC/USDT")
|
| 872 |
|
| 873 |
# --- 🚀 MOTEURS AUTO-PILOTE ---
|
| 874 |
AUTO_SYMBOLS = ["BTC/USD", "ETH/USD"]
|