-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto_dashboard.py
More file actions
1502 lines (1255 loc) · 56.1 KB
/
Copy pathcrypto_dashboard.py
File metadata and controls
1502 lines (1255 loc) · 56.1 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from datetime import timedelta
from prophet import Prophet
# Page configuration
st.set_page_config(
page_title="Bitcoin Price Analysis",
page_icon="₿",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for elegant design
st.markdown("""
<style>
/* Supprimer la barre blanche en haut */
.stApp header {
background-color: transparent !important;
}
header[data-testid="stHeader"] {
background-color: transparent !important;
display: none !important;
}
.main {
background: linear-gradient(135deg, #0a1929 0%, #1a2332 50%, #0d1b2a 100%);
color: #FFFFFF;
}
.stMetric {
background: linear-gradient(145deg, #1a2845 0%, #0f1921 100%);
padding: 20px;
border-radius: 12px;
border: 1px solid rgba(100, 150, 255, 0.2);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.4);
}
.stMetric label {
color: #FFFFFF !important;
}
.stMetric [data-testid="stMetricValue"] {
color: #FFFFFF !important;
}
h1 {
color: #FFA726 !important;
font-weight: 700;
}
h2 {
color: #FFB74D !important;
}
h3, h4 {
color: #FFFFFF !important;
}
.stButton button {
background: linear-gradient(90deg, #4a90e2 0%, #357abd 100%);
color: #FFFFFF;
border: none;
border-radius: 8px;
padding: 12px 24px;
font-weight: 600;
}
.stButton button:hover {
background: linear-gradient(90deg, #357abd 0%, #2a5d8f 100%);
}
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #0d1b2a 0%, #1a2332 100%);
}
/* Selectbox styling */
[data-baseweb="select"] {
color: #FFD54F !important;
}
[data-baseweb="select"] > div {
background-color: #1a2845 !important;
border-color: rgba(255, 213, 79, 0.3) !important;
}
[data-baseweb="select"] span {
color: #FFD54F !important;
}
/* Dropdown menu */
[role="listbox"] {
background-color: #1a2845 !important;
}
[role="option"] {
color: #FFD54F !important;
background-color: #1a2845 !important;
}
[role="option"]:hover {
background-color: #2a3855 !important;
}
p, div, span, label {
color: #FFFFFF !important;
}
</style>
""", unsafe_allow_html=True)
# Title
st.title("KMBCOIN 💰 - BitCoin Price Prediction 📈")
st.markdown("<h3 style='text-align: center; color: #FFD54F;'>To the Moon or to the Doom? 🌙🔮</h3>", unsafe_allow_html=True)
# Load data
@st.cache_data
def load_bitcoin_data():
"""Load Bitcoin historical data from CSV file"""
try:
# Charger le CSV
df = pd.read_csv('data/btc_1h_data_2018_to_2025.csv')
# Convertir les timestamps
df['timestamp'] = pd.to_datetime(df['Open time'])
df['close_timestamp'] = pd.to_datetime(df['Close time'])
# Renommer les colonnes pour simplifier
df = df.rename(columns={
'Open': 'open',
'High': 'high',
'Low': 'low',
'Close': 'close',
'Volume': 'volume',
'Number of trades': 'trades'
})
# Trier par timestamp
df = df.sort_values('timestamp')
return df
except FileNotFoundError:
st.error("Fichier 'data/btc_1h_data_2018_to_2025.csv' introuvable")
return None
except Exception as e:
st.error(f"Erreur lors du chargement: {str(e)}")
return None
def create_lag_features(df):
"""
Créer des features temporelles (lag, rolling) pour éviter le data leakage.
Utilise SEULEMENT des données du passé pour prédire le futur.
"""
df_features = df.copy()
# Lag features - Prix passés
df_features['close_lag_1h'] = df_features['close'].shift(1)
df_features['close_lag_2h'] = df_features['close'].shift(2)
df_features['close_lag_6h'] = df_features['close'].shift(6)
df_features['close_lag_24h'] = df_features['close'].shift(24)
df_features['close_lag_168h'] = df_features['close'].shift(168) # 7 jours
# Lag features - Volume passé
df_features['volume_lag_1h'] = df_features['volume'].shift(1)
df_features['volume_lag_24h'] = df_features['volume'].shift(24)
# Rolling averages (moyennes mobiles)
df_features['ma_24h'] = df_features['close'].shift(1).rolling(window=24).mean()
df_features['ma_7d'] = df_features['close'].shift(1).rolling(window=168).mean()
df_features['ma_30d'] = df_features['close'].shift(1).rolling(window=720).mean()
# Volatilité (écart-type mobile)
df_features['volatility_24h'] = df_features['close'].shift(1).rolling(window=24).std()
df_features['volatility_7d'] = df_features['close'].shift(1).rolling(window=168).std()
# Momentum (variation de prix)
df_features['momentum_1h'] = df_features['close'].shift(1) - df_features['close'].shift(2)
df_features['momentum_24h'] = df_features['close'].shift(1) - df_features['close'].shift(25)
df_features['momentum_pct_24h'] = df_features['close'].shift(1).pct_change(24)
# Volume trends
df_features['volume_ma_24h'] = df_features['volume'].shift(1).rolling(window=24).mean()
df_features['volume_ratio'] = df_features['volume_lag_1h'] / (df_features['volume_ma_24h'] + 1e-8)
# Price range
df_features['price_range_24h'] = (
df_features['close'].shift(1).rolling(window=24).max() -
df_features['close'].shift(1).rolling(window=24).min()
)
return df_features
# Sidebar
st.sidebar.header("Paramètres")
# Initialize session state for predictions
if 'prophet_results' not in st.session_state:
st.session_state.prophet_results = None
if 'xgb_results' not in st.session_state:
st.session_state.xgb_results = None
if 'rf_results' not in st.session_state:
st.session_state.rf_results = None
# Load data
with st.spinner("Chargement des données Bitcoin..."):
df = load_bitcoin_data()
if df is None:
st.stop()
# Info sidebar
st.sidebar.success(f"{len(df):,} lignes")
st.sidebar.info(f"Du {df['timestamp'].min().strftime('%Y-%m-%d')} "
f"au {df['timestamp'].max().strftime('%Y-%m-%d')}")
# Période de filtrage
st.sidebar.subheader("Filtrage")
period = st.sidebar.selectbox(
"Période",
["7 jours", "30 jours", "90 jours", "6 mois", "1 an", "2 ans", "Tout"],
index=4
)
# Filtrer les données
end_date = df['timestamp'].max()
if period == "7 jours":
start_date = end_date - timedelta(days=7)
elif period == "30 jours":
start_date = end_date - timedelta(days=30)
elif period == "90 jours":
start_date = end_date - timedelta(days=90)
elif period == "6 mois":
start_date = end_date - timedelta(days=180)
elif period == "1 an":
start_date = end_date - timedelta(days=365)
elif period == "2 ans":
start_date = end_date - timedelta(days=730)
else:
start_date = df['timestamp'].min()
df_filtered = df[df['timestamp'] >= start_date].copy()
st.sidebar.metric("Points affichés", f"{len(df_filtered):,}")
st.divider()
# Métriques principales
st.subheader("Statistiques du marché")
col1, col2, col3, col4 = st.columns(4)
current_price = df_filtered['close'].iloc[-1]
first_price = df_filtered['close'].iloc[0]
price_change = ((current_price - first_price) / first_price) * 100
# Définir la couleur selon positif/négatif
delta_color = "normal" if price_change >= 0 else "inverse"
with col1:
st.metric("Prix actuel", f"${current_price:,.2f}",
delta=f"{price_change:+.2f}%", delta_color=delta_color)
with col2:
st.metric("Prix max", f"${df_filtered['high'].max():,.2f}")
with col3:
st.metric("Prix min", f"${df_filtered['low'].min():,.2f}")
with col4:
st.metric("Prix moyen", f"${df_filtered['close'].mean():,.2f}")
st.divider()
# Graphique prix
st.subheader("Évolution du prix")
chart_type = st.radio("Type de graphique", ["Ligne", "Chandelier"],
horizontal=True)
fig = go.Figure()
if chart_type == "Ligne":
fig.add_trace(go.Scatter(
x=df_filtered['timestamp'],
y=df_filtered['close'],
mode='lines',
name='Prix',
line=dict(color='#F7931A', width=2),
fill='tozeroy',
fillcolor='rgba(247, 147, 26, 0.1)'
))
else:
fig.add_trace(go.Candlestick(
x=df_filtered['timestamp'],
open=df_filtered['open'],
high=df_filtered['high'],
low=df_filtered['low'],
close=df_filtered['close'],
name='BTC',
increasing_line_color='#26A69A',
decreasing_line_color='#EF5350'
))
fig.update_layout(
title="Prix du Bitcoin (USD)",
xaxis_title="Date",
yaxis_title="Prix (USD)",
hovermode='x unified',
template="plotly_white",
height=600,
xaxis_rangeslider_visible=False
)
st.plotly_chart(fig, use_container_width=True)
# Statistiques détaillées
st.subheader("Analyse détaillée")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**Prix**")
median_price = df_filtered['close'].median()
std_price = df_filtered['close'].std()
volatility = (df_filtered['close'].std() /
df_filtered['close'].mean() * 100)
st.write(f"Médiane: ${median_price:,.2f}")
st.write(f"Écart-type: ${std_price:,.2f}")
# Vérification Open vs Close
open_close_diff = abs(df_filtered['open'] - df_filtered['close']).mean()
st.write(f"Diff Open-Close: ${open_close_diff:,.2f}")
# Afficher volatilité en couleur
if volatility > 10:
st.markdown(f"<span style='color: #FF6B6B'>Volatilité: {volatility:.2f}%</span>", unsafe_allow_html=True)
elif volatility > 5:
st.markdown(f"<span style='color: #FFA726'>Volatilité: {volatility:.2f}%</span>", unsafe_allow_html=True)
else:
st.markdown(f"<span style='color: #4ECDC4'>Volatilité: {volatility:.2f}%</span>", unsafe_allow_html=True)
with col2:
st.markdown("**Volume**")
total_vol = df_filtered['volume'].sum()
avg_vol = df_filtered['volume'].mean()
max_vol = df_filtered['volume'].max()
min_vol = df_filtered['volume'].min()
st.write(f"Total: {total_vol:,.2f} BTC")
st.write(f"Moyen: {avg_vol:,.2f} BTC")
st.write(f"Max: {max_vol:,.2f} BTC")
st.write(f"Min: {min_vol:,.2f} BTC")
# Vérification des données
if avg_vol == 0 or (max_vol - min_vol) < 0.01:
st.warning("⚠️ Volume semble constant ou nul")
with col3:
st.markdown("**Transactions**")
total_trades = df_filtered['trades'].sum()
avg_trades = df_filtered['trades'].mean()
max_trades = df_filtered['trades'].max()
st.write(f"Total: {total_trades:,.0f}")
st.write(f"Moyenne: {avg_trades:,.0f}/h")
st.write(f"Max: {max_trades:,.0f}/h")
# Section Prédiction
st.divider()
st.header("Prédiction avec Prophet")
# Explication de Prophet
with st.expander("Comment fonctionne Prophet ?"):
st.markdown("""
**Prophet** est un modèle de prédiction développé par Meta (Facebook),
spécialisé dans les séries temporelles.
**Données utilisées pour l'entraînement :**
- `timestamp` (ds) : Date et heure de chaque observation
- `close` (y) : Prix de clôture du Bitcoin (variable à prédire)
- `volume` : Volume d'échange (régresseur additionnel)
**Composantes principales :**
1. **Tendance** : Direction générale du prix sur le long terme
2. **Saisonnalité** : Patterns répétitifs (quotidien, hebdomadaire, annuel)
3. **Régresseurs** : Facteurs externes (ici le volume d'échange)
**Formule :** `y(t) = Tendance(t) + Saisonnalité(t) + Volume(t) + Erreur(t)`
**Avantages :**
- Gère bien la volatilité des cryptomonnaies
- Détecte les patterns répétitifs du marché
- Fournit des intervalles de confiance
**Limitations :**
- Ne prédit pas les événements imprévisibles
- Moins performant sur très courtes périodes (< 1 mois)
""")
st.markdown("""
Utilisez Prophet pour estimer l'évolution future du prix Bitcoin.
""")
col1, col2 = st.columns([1, 3])
with col1:
st.subheader("Paramètres")
# Période d'entraînement
train_period = st.selectbox(
"Données d'entraînement",
["30 derniers jours", "90 derniers jours", "6 derniers mois",
"1 dernière année", "2 dernières années", "Toutes les données"],
index=3
)
# Période de prédiction
forecast_days = st.slider(
"Prédire combien de jours ?",
min_value=1,
max_value=90,
value=30,
step=1
)
# Bouton de prédiction
predict_button = st.button("Lancer la prédiction",
type="primary",
use_container_width=True)
with col2:
if predict_button:
with st.spinner("Entraînement du modèle Prophet en cours..."):
try:
# Préparer les données pour Prophet
# Filtrer selon la période d'entraînement
end_train = df['timestamp'].max()
if train_period == "30 derniers jours":
start_train = end_train - timedelta(days=30)
elif train_period == "90 derniers jours":
start_train = end_train - timedelta(days=90)
elif train_period == "6 derniers mois":
start_train = end_train - timedelta(days=180)
elif train_period == "1 dernière année":
start_train = end_train - timedelta(days=365)
elif train_period == "2 dernières années":
start_train = end_train - timedelta(days=730)
else:
start_train = df['timestamp'].min()
# Filtrer et préparer les données
df_train = df[df['timestamp'] >= start_train].copy()
# Formater pour Prophet (colonnes ds et y)
prophet_df = df_train[['timestamp', 'close', 'volume']].copy()
prophet_df = prophet_df.rename(columns={
'timestamp': 'ds',
'close': 'y'
})
# Supprimer les timezones si présentes
prophet_df['ds'] = pd.to_datetime(prophet_df['ds']).dt.tz_localize(None)
prophet_df['y'] = prophet_df['y'].astype(float)
prophet_df.dropna(inplace=True)
st.success(f"{len(prophet_df):,} points utilisés")
# Initialiser et entraîner le modèle
model = Prophet(
daily_seasonality=True,
weekly_seasonality=True,
yearly_seasonality=True
)
# Ajouter le volume comme regressor
model.add_regressor('volume')
model.fit(prophet_df)
# Créer le dataframe pour les prédictions futures
future = model.make_future_dataframe(periods=forecast_days * 24, freq='H')
# Ajouter le volume moyen pour les futures dates
avg_volume = prophet_df['volume'].mean()
future = future.merge(
prophet_df[['ds', 'volume']],
on='ds',
how='left'
)
future['volume'].fillna(avg_volume, inplace=True)
# Faire la prédiction
forecast = model.predict(future)
# Séparer les données historiques et futures
# Les données historiques = jusqu'à la dernière date du training
last_historical_date = prophet_df['ds'].max()
forecast_future = forecast[forecast['ds'] > last_historical_date]
# Créer le graphique avec Plotly
fig_forecast = go.Figure()
# Données historiques (SEULEMENT le passé)
fig_forecast.add_trace(go.Scatter(
x=prophet_df['ds'],
y=prophet_df['y'],
mode='lines',
name='Prix historique',
line=dict(color='#F7931A', width=2)
))
# Prédictions (SEULEMENT le futur)
prediction_color = '#00FF88' if forecast_future['yhat'].iloc[-1] > prophet_df['y'].iloc[-1] else '#FF6B6B'
fig_forecast.add_trace(go.Scatter(
x=forecast_future['ds'],
y=forecast_future['yhat'],
mode='lines',
name='Prédiction',
line=dict(color=prediction_color, width=3, dash='dash')
))
# Intervalle de confiance (SEULEMENT le futur)
fig_forecast.add_trace(go.Scatter(
x=forecast_future['ds'],
y=forecast_future['yhat_upper'],
mode='lines',
name='Limite supérieure',
line=dict(width=0),
showlegend=False
))
fig_forecast.add_trace(go.Scatter(
x=forecast_future['ds'],
y=forecast_future['yhat_lower'],
mode='lines',
name='Intervalle de confiance',
line=dict(width=0),
fillcolor='rgba(0, 204, 150, 0.2)',
fill='tonexty'
))
fig_forecast.update_layout(
title=f"Prédiction Bitcoin - {forecast_days} jours",
xaxis_title="Date",
yaxis_title="Prix (USD)",
hovermode='x unified',
template="plotly_white",
height=600
)
st.plotly_chart(fig_forecast, use_container_width=True)
# Statistiques de prédiction
st.subheader("Résultats de la prédiction")
col_a, col_b, col_c, col_d = st.columns(4)
last_actual = prophet_df['y'].iloc[-1]
last_forecast = forecast['yhat'].iloc[-1]
forecast_change = ((last_forecast - last_actual) / last_actual) * 100
with col_a:
st.metric("Prix actuel", f"${last_actual:,.2f}")
with col_b:
delta_forecast = f"{forecast_change:+.2f}%"
delta_color_forecast = "normal" if forecast_change >= 0 else "inverse"
trend_emoji = "↗️" if forecast_change >= 0 else "↘️"
st.metric(
f"Prédiction J+{forecast_days} {trend_emoji}",
f"${last_forecast:,.2f}",
delta=delta_forecast,
delta_color=delta_color_forecast
)
with col_c:
st.metric(
"Fourchette haute",
f"${forecast['yhat_upper'].iloc[-1]:,.2f}"
)
with col_d:
st.metric(
"Fourchette basse",
f"${forecast['yhat_lower'].iloc[-1]:,.2f}"
)
# Afficher les composantes du modèle
with st.expander("Voir les composantes (tendance, saisonnalité)"):
# Tendance
fig_trend = go.Figure()
fig_trend.add_trace(go.Scatter(
x=forecast['ds'],
y=forecast['trend'],
mode='lines',
name='Tendance',
line=dict(color='#636EFA', width=2)
))
fig_trend.update_layout(
title="Tendance",
xaxis_title="Date",
yaxis_title="Valeur",
template="plotly_white",
height=300
)
st.plotly_chart(fig_trend, use_container_width=True)
# Stocker les résultats dans session_state
st.session_state.prophet_results = {
'forecast': forecast_future,
'historical': prophet_df,
'forecast_days': forecast_days,
'last_actual': last_actual,
'last_forecast': last_forecast,
'forecast_change': forecast_change,
'fig': fig_forecast
}
st.success("Prédiction terminée avec succès")
st.info("Ces prédictions sont basées sur des modèles statistiques "
"et ne constituent pas des conseils financiers.")
except Exception as e:
st.error(f"Erreur lors de la prédiction: {str(e)}")
st.info("Essayez avec une période différente.")
# Afficher les résultats Prophet s'ils existent
if st.session_state.prophet_results is not None:
if not predict_button: # Ne pas afficher 2 fois si on vient de cliquer
st.info("📊 Résultats Prophet précédents affichés ci-dessous")
results = st.session_state.prophet_results
st.plotly_chart(results['fig'], use_container_width=True)
col_a, col_b = st.columns(2)
with col_a:
st.metric("Prix actuel", f"${results['last_actual']:,.2f}")
with col_b:
trend_emoji = "↗️" if results['forecast_change'] >= 0 else "↘️"
st.metric(
f"Prédiction J+{results['forecast_days']} {trend_emoji}",
f"${results['last_forecast']:,.2f}",
delta=f"{results['forecast_change']:+.2f}%"
)
elif not predict_button:
st.info("Configurez les paramètres et cliquez sur 'Lancer la prédiction'")
# Section Gradient Boosting
st.divider()
st.header("Prédiction avec Gradient Boosting (XGBoost)")
with st.expander("Qu'est-ce que XGBoost ?"):
st.markdown("""
**XGBoost (Extreme Gradient Boosting)** est un algorithme de machine learning
très performant basé sur le boosting d'arbres de décision.
**Avantages :**
- ⚡ Très rapide à entraîner (10-100x plus rapide que LSTM)
- 🎯 Excellent pour les prédictions de séries temporelles
- 📊 Fournit l'importance des features
- 🛡️ Robuste au surapprentissage
**Comment ça marche :**
- Construit des arbres de décision séquentiellement
- Chaque arbre corrige les erreurs du précédent
- Agrège les prédictions de tous les arbres
**Features temporelles utilisées (18 features) :**
✅ **Pas de data leakage !** Utilise SEULEMENT des données du passé :
- **Prix passés (lag)** : prix d'il y a 1h, 2h, 6h, 24h, 7 jours
- **Moyennes mobiles** : MA 24h, 7j, 30j
- **Volatilité** : écart-type sur 24h et 7j
- **Momentum** : variation de prix sur 1h et 24h
- **Volume** : volume passé et tendances
- **Price range** : amplitude sur 24h
❌ **N'utilise PLUS** : `open`, `high`, `low` du même instant
""")
st.markdown("Algorithme de boosting rapide et performant pour prédire le prix Bitcoin.")
col1, col2 = st.columns([1, 3])
with col1:
st.subheader("Paramètres")
xgb_train_period = st.selectbox(
"Données d'entraînement",
["30 jours", "90 jours", "6 mois", "1 an", "Toutes"],
index=2,
key="xgb_train"
)
xgb_forecast_days = st.slider(
"Prédire (jours)",
min_value=1,
max_value=30,
value=7,
step=1,
key="xgb_days"
)
xgb_n_estimators = st.slider(
"Nombre d'arbres",
min_value=50,
max_value=300,
value=100,
step=50,
key="xgb_trees"
)
xgb_button = st.button("Lancer XGBoost",
type="primary",
use_container_width=True,
key="xgb_button")
with col2:
if xgb_button:
with st.spinner("Entraînement du modèle XGBoost..."):
try:
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import (mean_absolute_error,
mean_squared_error,
r2_score)
try:
import xgboost as xgb
except ImportError:
st.error("XGBoost n'est pas installé")
st.info("Installez avec: pip install xgboost")
st.stop()
# Préparer les données
end_train = df['timestamp'].max()
if xgb_train_period == "30 jours":
start_train = end_train - timedelta(days=30)
elif xgb_train_period == "90 jours":
start_train = end_train - timedelta(days=90)
elif xgb_train_period == "6 mois":
start_train = end_train - timedelta(days=180)
elif xgb_train_period == "1 an":
start_train = end_train - timedelta(days=365)
else:
start_train = df['timestamp'].min()
df_xgb = df[df['timestamp'] >= start_train].copy()
# Créer les lag features (sans data leakage)
st.write("🔧 Création des features temporelles...")
df_xgb = create_lag_features(df_xgb)
# Features temporelles (SEULEMENT le passé)
features = [
'close_lag_1h', 'close_lag_2h', 'close_lag_6h',
'close_lag_24h', 'close_lag_168h',
'volume_lag_1h', 'volume_lag_24h',
'ma_24h', 'ma_7d', 'ma_30d',
'volatility_24h', 'volatility_7d',
'momentum_1h', 'momentum_24h', 'momentum_pct_24h',
'volume_ma_24h', 'volume_ratio',
'price_range_24h'
]
target = 'close'
# Supprimer les valeurs nulles (créées par shift et rolling)
df_xgb = df_xgb.dropna()
st.info(f"✅ {len(features)} features temporelles créées (sans data leakage)")
X = df_xgb[features].values
y = df_xgb[target].values
# Normalisation
scaler_X = MinMaxScaler()
scaler_y = MinMaxScaler()
X_scaled = scaler_X.fit_transform(X)
y_scaled = scaler_y.fit_transform(
y.reshape(-1, 1)
).flatten()
# Split train/test (80/20) sans shuffle
split = int(0.8 * len(X_scaled))
X_train = X_scaled[:split]
X_test = X_scaled[split:]
y_train = y_scaled[:split]
y_test = y_scaled[split:]
st.success(f"{len(X_train)} points d'entraînement, "
f"{len(X_test)} test")
# Entraîner XGBoost
st.write("⚡ Entraînement en cours...")
xgb_model = xgb.XGBRegressor(
n_estimators=xgb_n_estimators,
learning_rate=0.1,
max_depth=6,
random_state=42,
n_jobs=-1
)
xgb_model.fit(X_train, y_train)
st.success("✅ Modèle entraîné en quelques secondes !")
# Prédictions sur test
y_pred = xgb_model.predict(X_test)
# Dé-normaliser
y_test_actual = scaler_y.inverse_transform(
y_test.reshape(-1, 1)
).flatten()
y_pred_actual = scaler_y.inverse_transform(
y_pred.reshape(-1, 1)
).flatten()
# Métriques
mae = mean_absolute_error(y_test_actual, y_pred_actual)
rmse = np.sqrt(mean_squared_error(y_test_actual,
y_pred_actual))
r2 = r2_score(y_test_actual, y_pred_actual)
# Afficher métriques
st.subheader("Performance du modèle")
col_a, col_b, col_c = st.columns(3)
with col_a:
st.metric("MAE", f"${mae:,.2f}")
with col_b:
st.metric("RMSE", f"${rmse:,.2f}")
with col_c:
st.metric("R² Score", f"{r2:.4f}")
# Importance des features
st.subheader("Importance des features")
importances = xgb_model.feature_importances_
fig_importance = go.Figure()
fig_importance.add_trace(go.Bar(
x=features,
y=importances,
marker_color=['#FF6B6B', '#4ECDC4',
'#95E1D3', '#F38181']
))
fig_importance.update_layout(
title="Contribution de chaque feature",
xaxis_title="Feature",
yaxis_title="Importance",
template="plotly_white",
height=300
)
st.plotly_chart(fig_importance, use_container_width=True)
# Prédictions futures
st.subheader("Prédictions")
# Utiliser les dernières données pour prédire
last_data = X_scaled[-1:].copy()
predictions = []
for i in range(xgb_forecast_days * 24):
pred = xgb_model.predict(last_data)
predictions.append(pred[0])
# Mettre à jour les features pour la prochaine prédiction
if i > 0:
# Ajouter du bruit pour variation
noise = np.random.normal(0, 0.002, last_data.shape)
last_data = last_data.copy()
last_data += noise
# Dé-normaliser les prédictions
predictions = np.array(predictions).reshape(-1, 1)
predictions_actual = scaler_y.inverse_transform(
predictions
).flatten()
# Créer timestamps futurs
last_timestamp = df['timestamp'].max()
future_timestamps = pd.date_range(
start=last_timestamp + timedelta(hours=1),
periods=len(predictions_actual),
freq='H'
)
# Graphique comparatif
fig_xgb = go.Figure()
# Données historiques (dernier mois)
recent_df = df[df['timestamp'] >=
(end_train - timedelta(days=30))]
fig_xgb.add_trace(go.Scatter(
x=recent_df['timestamp'],
y=recent_df['close'],
mode='lines',
name='Prix historique',
line=dict(color='#F7931A', width=2)
))
# Prédictions futures
prediction_color_xgb = ('#00FF88' if
predictions_actual[-1] > df['close'].iloc[-1]
else '#FF6B6B')
fig_xgb.add_trace(go.Scatter(
x=future_timestamps,
y=predictions_actual,
mode='lines',
name='Prédiction XGBoost',
line=dict(color=prediction_color_xgb,
width=3, dash='dash')
))
fig_xgb.update_layout(
title=f"Prédiction XGBoost - {xgb_forecast_days} jours",
xaxis_title="Date",
yaxis_title="Prix (USD)",
hovermode='x unified',
template="plotly_white",
height=600
)
st.plotly_chart(fig_xgb, use_container_width=True)
# Résultats finaux
st.subheader("Résultats")
col_a, col_b = st.columns(2)
current_price_xgb = df['close'].iloc[-1]
predicted_price = predictions_actual[-1]
change_pct = ((predicted_price - current_price_xgb) /
current_price_xgb) * 100
with col_a:
st.metric("Prix actuel", f"${current_price_xgb:,.2f}")
with col_b:
delta_color_xgb = ("normal" if change_pct >= 0
else "inverse")
trend_emoji_xgb = "↗️" if change_pct >= 0 else "↘️"
st.metric(
f"Prédiction J+{xgb_forecast_days} "
f"{trend_emoji_xgb}",
f"${predicted_price:,.2f}",
delta=f"{change_pct:+.2f}%",
delta_color=delta_color_xgb
)
# Stocker les résultats dans session_state
st.session_state.xgb_results = {
'fig': fig_xgb,
'forecast_days': xgb_forecast_days,
'current_price': current_price_xgb,
'predicted_price': predicted_price,
'change_pct': change_pct,
'mae': mae,
'rmse': rmse,
'r2': r2,
'fig_importance': fig_importance
}
st.success("Prédiction XGBoost terminée")
except Exception as e:
st.error(f"Erreur: {str(e)}")
import traceback
st.code(traceback.format_exc())
# Afficher les résultats XGBoost s'ils existent
if st.session_state.xgb_results is not None:
if not xgb_button: # Ne pas afficher 2 fois si on vient de cliquer
st.info("📊 Résultats XGBoost précédents affichés ci-dessous")
results = st.session_state.xgb_results
col_perf = st.columns(3)
with col_perf[0]:
st.metric("MAE", f"${results['mae']:,.2f}")
with col_perf[1]:
st.metric("RMSE", f"${results['rmse']:,.2f}")
with col_perf[2]:
st.metric("R² Score", f"{results['r2']:.4f}")
st.plotly_chart(results['fig_importance'], use_container_width=True)
st.plotly_chart(results['fig'], use_container_width=True)
col_a, col_b = st.columns(2)
with col_a:
st.metric("Prix actuel", f"${results['current_price']:,.2f}")
with col_b:
trend_emoji = "↗️" if results['change_pct'] >= 0 else "↘️"
st.metric(
f"Prédiction J+{results['forecast_days']} {trend_emoji}",
f"${results['predicted_price']:,.2f}",
delta=f"{results['change_pct']:+.2f}%"
)
elif not xgb_button:
st.info("Configurez et lancez XGBoost")
# Section Random Forest
st.divider()
st.header("Prédiction avec Random Forest")
with st.expander("Qu'est-ce qu'un Random Forest ?"):
st.markdown("""
**Random Forest** est un algorithme d'apprentissage supervisé basé sur
des arbres de décision. Il construit plusieurs arbres et agrège leurs prédictions.
**Avantages :**
- Rapide à entraîner et à prédire
- Robuste au surapprentissage
- Gère bien les données non-linéaires
- Fournit l'importance des features
**Features temporelles utilisées (18 features) :**
✅ **Pas de data leakage !** Utilise SEULEMENT des données du passé :