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|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from sklearn.metrics import mean_squared_error
|
| 6 |
+
from tensorflow.keras.models import load_model
|
| 7 |
+
from neuralprophet import NeuralProphet
|
| 8 |
+
import pickle
|
| 9 |
+
from datetime import timedelta
|
| 10 |
+
import yfinance as yf
|
| 11 |
+
import tensorflow as tf
|
| 12 |
+
|
| 13 |
+
tf.get_logger().setLevel('ERROR') # Pour réduire les logs TensorFlow
|
| 14 |
+
|
| 15 |
+
# === Fonction pour charger les données boursières ===
|
| 16 |
+
@st.cache_data
|
| 17 |
+
def load_data():
|
| 18 |
+
# Télécharger les données sur 4 ans pour AMD
|
| 19 |
+
df = yf.download('AMD', period='4y')
|
| 20 |
+
|
| 21 |
+
# Vérifier si les colonnes sont de type MultiIndex
|
| 22 |
+
if isinstance(df.columns, pd.MultiIndex):
|
| 23 |
+
# Aplatir les MultiIndex (au cas où les colonnes sont hiérarchiques)
|
| 24 |
+
df.columns = ['_'.join(col).strip() for col in df.columns.values]
|
| 25 |
+
|
| 26 |
+
# Extraire uniquement la colonne 'Close'
|
| 27 |
+
for col in df.columns:
|
| 28 |
+
if "Close" in col:
|
| 29 |
+
df = df[[col]]
|
| 30 |
+
df.columns = ['Close']
|
| 31 |
+
break
|
| 32 |
+
|
| 33 |
+
# Réinitialiser l'index pour avoir 'Date' comme colonne
|
| 34 |
+
df.reset_index(inplace=True)
|
| 35 |
+
df.rename(columns={'Date': 'ds', 'Close': 'y'}, inplace=True)
|
| 36 |
+
|
| 37 |
+
return df
|
| 38 |
+
|
| 39 |
+
# === Fonctions de chargement des modèles ===
|
| 40 |
+
@st.cache_resource
|
| 41 |
+
def load_gru_model(path):
|
| 42 |
+
return load_model(path)
|
| 43 |
+
|
| 44 |
+
@st.cache_resource
|
| 45 |
+
def load_neural_prophet_model(path):
|
| 46 |
+
with open(path, 'rb') as f:
|
| 47 |
+
return pickle.load(f)
|
| 48 |
+
|
| 49 |
+
# === Prédiction NeuralProphet ===
|
| 50 |
+
def predict_neural_prophet(model, df):
|
| 51 |
+
future = model.make_future_dataframe(df, periods=21)
|
| 52 |
+
forecast = model.predict(future)
|
| 53 |
+
return forecast[['ds', 'yhat1']].tail(21)
|
| 54 |
+
|
| 55 |
+
# === Préparation des données pour GRU ===
|
| 56 |
+
def prepare_gru_data(series, window_size=20):
|
| 57 |
+
last_data = series[-window_size:]
|
| 58 |
+
return np.array(last_data).reshape((1, window_size, 1))
|
| 59 |
+
|
| 60 |
+
# === Prédiction GRU ===
|
| 61 |
+
def predict_gru(model, df, forecast_days):
|
| 62 |
+
data = df['y'].values
|
| 63 |
+
window_size = 20
|
| 64 |
+
predictions = []
|
| 65 |
+
input_seq = data[-window_size:]
|
| 66 |
+
|
| 67 |
+
for _ in range(forecast_days):
|
| 68 |
+
X_input = input_seq.reshape((1, window_size, 1))
|
| 69 |
+
pred = model.predict(X_input)[0][0]
|
| 70 |
+
predictions.append(pred)
|
| 71 |
+
input_seq = np.append(input_seq[1:], pred)
|
| 72 |
+
|
| 73 |
+
last_date = df['ds'].max()
|
| 74 |
+
future_dates = []
|
| 75 |
+
while len(future_dates) < forecast_days:
|
| 76 |
+
last_date += timedelta(days=1)
|
| 77 |
+
if last_date.weekday() < 5: # Exclure les week-ends
|
| 78 |
+
future_dates.append(last_date)
|
| 79 |
+
|
| 80 |
+
return pd.DataFrame({'ds': future_dates, 'yhat': predictions})
|
| 81 |
+
|
| 82 |
+
# === Calcul du RMSE ===
|
| 83 |
+
def calculate_rmse(y_true, y_pred):
|
| 84 |
+
return np.sqrt(mean_squared_error(y_true, y_pred))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# Chargement des données
|
| 88 |
+
data = load_data()
|
| 89 |
+
# Titre
|
| 90 |
+
st.title("KEYCE INFORMATIQUE ET IA, MASTER II ")
|
| 91 |
+
st.title("CONTROLE CONTINU DE RNN SUR LES MODELES GRU ET NEURAL PROPHET")
|
| 92 |
+
st.subheader("NOM DE L'ETUDIANT: TATSA TCHINDA Colince ")
|
| 93 |
+
# Affichage des données historiques
|
| 94 |
+
st.subheader("Données")
|
| 95 |
+
|
| 96 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 97 |
+
ax.plot(data['ds'], data['y'], label="Historique", color='black')
|
| 98 |
+
ax.set_xlabel("Date")
|
| 99 |
+
ax.set_ylabel("Prix de clôture")
|
| 100 |
+
ax.set_title("historiques des actions AMD")
|
| 101 |
+
ax.legend()
|
| 102 |
+
st.pyplot(fig)
|
| 103 |
+
|
| 104 |
+
# Chargement des modèles
|
| 105 |
+
|
| 106 |
+
gru_model = load_gru_model("model_gru.keras")
|
| 107 |
+
neural_model = load_neural_prophet_model("neuralprophet_model.pkl")
|
| 108 |
+
|
| 109 |
+
# Prédictions
|
| 110 |
+
st.subheader("🔮 Prédictions sur les 3 prochaines semaines")
|
| 111 |
+
|
| 112 |
+
np_forecast = predict_neural_prophet(neural_model, data)
|
| 113 |
+
gru_forecast = predict_gru(gru_model, data, 21)
|
| 114 |
+
|
| 115 |
+
# --- Affichage des graphiques de chaque modèle avec ses prédictions ---
|
| 116 |
+
|
| 117 |
+
# Graphique pour NeuralProphet
|
| 118 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 119 |
+
ax.plot(data['ds'], data['y'], label="Historique", color='black')
|
| 120 |
+
ax.plot(np_forecast['ds'], np_forecast['yhat1'], label="NeuralProphet", linestyle='--')
|
| 121 |
+
ax.legend()
|
| 122 |
+
ax.set_title("Prédictions NeuralProphet")
|
| 123 |
+
st.pyplot(fig)
|
| 124 |
+
|
| 125 |
+
# Calcul du RMSE pour NeuralProphet
|
| 126 |
+
true_vals = data['y'].values[-20:]
|
| 127 |
+
np_pred_backtest = neural_model.predict(data.tail(20))[['yhat1']].values.flatten()
|
| 128 |
+
np_rmse = calculate_rmse(true_vals, np_pred_backtest)
|
| 129 |
+
|
| 130 |
+
# Graphique pour GRU
|
| 131 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 132 |
+
ax.plot(data['ds'], data['y'], label="Historique", color='black')
|
| 133 |
+
ax.plot(gru_forecast['ds'], gru_forecast['yhat'], label="GRU", linestyle='--')
|
| 134 |
+
ax.legend()
|
| 135 |
+
ax.set_title("Prédictions GRU")
|
| 136 |
+
st.pyplot(fig)
|
| 137 |
+
|
| 138 |
+
# Calcul du RMSE pour GRU
|
| 139 |
+
gru_input = data['y'].values[-40:-20]
|
| 140 |
+
gru_backtest_preds = []
|
| 141 |
+
input_seq = gru_input
|
| 142 |
+
for _ in range(20):
|
| 143 |
+
X_input = input_seq[-20:].reshape((1, 20, 1))
|
| 144 |
+
pred = gru_model.predict(X_input)[0][0]
|
| 145 |
+
gru_backtest_preds.append(pred)
|
| 146 |
+
input_seq = np.append(input_seq[1:], pred)
|
| 147 |
+
|
| 148 |
+
gru_rmse = calculate_rmse(true_vals, gru_backtest_preds)
|
| 149 |
+
|
| 150 |
+
# Résumé des scores RMSE
|
| 151 |
+
st.subheader("Résultats")
|
| 152 |
+
st.table(pd.DataFrame({
|
| 153 |
+
"Modèle": ["NeuralProphet", "GRU"],
|
| 154 |
+
"RMSE": [np_rmse, gru_rmse]
|
| 155 |
+
}))
|
| 156 |
+
|
| 157 |
+
# Afficher et télécharger les prédictions
|
| 158 |
+
final_forecast = pd.merge(np_forecast, gru_forecast, on='ds', how='outer')
|
| 159 |
+
st.subheader("Prédictions Combinées ")
|
| 160 |
+
styled_df = final_forecast.style.format({'yhat1': '{:.2f}', 'yhat': '{:.2f}'})
|
| 161 |
+
st.dataframe(styled_df)
|
| 162 |
+
csv = final_forecast.to_csv(index=False).encode('utf-8')
|
| 163 |
+
st.download_button("Télécharger les prédictions (.csv)", csv, "predictions.csv", "text/csv")
|
| 164 |
+
|