Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,14 +4,15 @@ import numpy as np
|
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
from plotly.subplots import make_subplots
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
-
from prophet import
|
| 8 |
from statsmodels.tsa.arima.model import ARIMA
|
| 9 |
from statsmodels.tsa.stattools import adfuller
|
| 10 |
from sklearn.preprocessing import MinMaxScaler
|
| 11 |
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
|
| 12 |
import tensorflow as tf
|
| 13 |
-
from tensorflow.keras.models import Sequential
|
| 14 |
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
|
|
|
| 15 |
import warnings
|
| 16 |
warnings.filterwarnings('ignore')
|
| 17 |
|
|
@@ -66,85 +67,52 @@ def test_stationarity(timeseries):
|
|
| 66 |
# MODEL 1: ARIMA
|
| 67 |
# ============================================================================
|
| 68 |
|
| 69 |
-
def
|
| 70 |
-
"""
|
| 71 |
try:
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
return fitted_model
|
| 77 |
except Exception as e:
|
| 78 |
-
print(f"ARIMA Error: {e}")
|
| 79 |
return None
|
| 80 |
|
| 81 |
# ============================================================================
|
| 82 |
# MODEL 2: PROPHET
|
| 83 |
# ============================================================================
|
| 84 |
|
| 85 |
-
def
|
| 86 |
-
"""
|
| 87 |
try:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
})
|
| 93 |
-
|
| 94 |
-
model = Prophet(
|
| 95 |
-
daily_seasonality=True,
|
| 96 |
-
yearly_seasonality=True,
|
| 97 |
-
weekly_seasonality=True,
|
| 98 |
-
changepoint_prior_scale=0.05,
|
| 99 |
-
seasonality_prior_scale=10.0
|
| 100 |
-
)
|
| 101 |
-
model.fit(prophet_df)
|
| 102 |
-
print("Prophet trained successfully")
|
| 103 |
return model
|
| 104 |
except Exception as e:
|
| 105 |
-
print(f"Prophet Error: {e}")
|
| 106 |
return None
|
| 107 |
|
| 108 |
# ============================================================================
|
| 109 |
# MODEL 3: LSTM
|
| 110 |
# ============================================================================
|
| 111 |
|
| 112 |
-
def
|
| 113 |
-
"""
|
| 114 |
-
X, y = [], []
|
| 115 |
-
for i in range(look_back, len(data)):
|
| 116 |
-
X.append(data[i-look_back:i, 0])
|
| 117 |
-
y.append(data[i, 0])
|
| 118 |
-
return np.array(X), np.array(y)
|
| 119 |
-
|
| 120 |
-
def train_lstm_model(data, look_back=60, epochs=50):
|
| 121 |
-
"""Train LSTM model"""
|
| 122 |
try:
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 126 |
-
scaled_data = scaler.fit_transform(data.reshape(-1, 1))
|
| 127 |
-
|
| 128 |
-
X, y = create_lstm_dataset(scaled_data, look_back)
|
| 129 |
-
X = X.reshape((X.shape[0], X.shape[1], 1))
|
| 130 |
-
|
| 131 |
-
model = Sequential([
|
| 132 |
-
LSTM(50, return_sequences=True, input_shape=(look_back, 1)),
|
| 133 |
-
Dropout(0.2),
|
| 134 |
-
LSTM(50, return_sequences=False),
|
| 135 |
-
Dropout(0.2),
|
| 136 |
-
Dense(25, activation='relu'),
|
| 137 |
-
Dense(1)
|
| 138 |
-
])
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
|
|
|
| 142 |
|
| 143 |
-
print("LSTM
|
| 144 |
-
return
|
| 145 |
except Exception as e:
|
| 146 |
-
print(f"LSTM Error: {e}")
|
| 147 |
-
return None, None
|
| 148 |
|
| 149 |
# ============================================================================
|
| 150 |
# EDA FUNCTION
|
|
@@ -271,7 +239,7 @@ def rolling_window_evaluation(df, test_size=90):
|
|
| 271 |
}
|
| 272 |
|
| 273 |
# ARIMA
|
| 274 |
-
arima_model =
|
| 275 |
if arima_model:
|
| 276 |
arima_forecast = arima_model.forecast(steps=test_size)
|
| 277 |
results['ARIMA']['predictions'] = arima_forecast
|
|
@@ -280,7 +248,7 @@ def rolling_window_evaluation(df, test_size=90):
|
|
| 280 |
print(f"ARIMA - RMSE: {rmse:.2f}, MAE: {mae:.2f}, MAPE: {mape:.2f}%, R2: {r2:.4f}")
|
| 281 |
|
| 282 |
# Prophet
|
| 283 |
-
prophet_model =
|
| 284 |
if prophet_model:
|
| 285 |
future = prophet_model.make_future_dataframe(periods=test_size)
|
| 286 |
forecast = prophet_model.predict(future)
|
|
@@ -291,15 +259,15 @@ def rolling_window_evaluation(df, test_size=90):
|
|
| 291 |
print(f"Prophet - RMSE: {rmse:.2f}, MAE: {mae:.2f}, MAPE: {mape:.2f}%, R2: {r2:.4f}")
|
| 292 |
|
| 293 |
# LSTM
|
| 294 |
-
lstm_model, scaler
|
| 295 |
if lstm_model and scaler:
|
| 296 |
all_data = df['Close'].values
|
| 297 |
-
test_inputs = all_data[len(train_data) -
|
| 298 |
test_inputs = scaler.transform(test_inputs.reshape(-1, 1))
|
| 299 |
|
| 300 |
X_test = []
|
| 301 |
-
for i in range(
|
| 302 |
-
X_test.append(test_inputs[i-
|
| 303 |
X_test = np.array(X_test)
|
| 304 |
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
|
| 305 |
|
|
@@ -329,26 +297,26 @@ def predict_future(df, days_to_predict=30):
|
|
| 329 |
predictions = {}
|
| 330 |
|
| 331 |
# ARIMA
|
| 332 |
-
arima_model =
|
| 333 |
if arima_model:
|
| 334 |
arima_forecast = arima_model.forecast(steps=days_to_predict)
|
| 335 |
predictions['ARIMA'] = arima_forecast
|
| 336 |
|
| 337 |
# Prophet
|
| 338 |
-
prophet_model =
|
| 339 |
if prophet_model:
|
| 340 |
future = prophet_model.make_future_dataframe(periods=days_to_predict)
|
| 341 |
forecast = prophet_model.predict(future)
|
| 342 |
predictions['Prophet'] = forecast['yhat'].iloc[-days_to_predict:].values
|
| 343 |
|
| 344 |
# LSTM
|
| 345 |
-
lstm_model, scaler
|
| 346 |
if lstm_model and scaler:
|
| 347 |
-
last_sequence = scaler.transform(full_data[-
|
| 348 |
lstm_predictions = []
|
| 349 |
|
| 350 |
for _ in range(days_to_predict):
|
| 351 |
-
X_test = last_sequence.reshape((1,
|
| 352 |
pred = lstm_model.predict(X_test, verbose=0)
|
| 353 |
lstm_predictions.append(pred[0, 0])
|
| 354 |
last_sequence = np.append(last_sequence[1:], pred).reshape(-1, 1)
|
|
|
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
from plotly.subplots import make_subplots
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
+
from prophet.serialize import model_from_json
|
| 8 |
from statsmodels.tsa.arima.model import ARIMA
|
| 9 |
from statsmodels.tsa.stattools import adfuller
|
| 10 |
from sklearn.preprocessing import MinMaxScaler
|
| 11 |
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
|
| 12 |
import tensorflow as tf
|
| 13 |
+
from tensorflow.keras.models import Sequential, load_model
|
| 14 |
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
| 15 |
+
import pickle
|
| 16 |
import warnings
|
| 17 |
warnings.filterwarnings('ignore')
|
| 18 |
|
|
|
|
| 67 |
# MODEL 1: ARIMA
|
| 68 |
# ============================================================================
|
| 69 |
|
| 70 |
+
def load_arima_model():
|
| 71 |
+
"""Load pre-trained ARIMA model"""
|
| 72 |
try:
|
| 73 |
+
with open('models/arima_model.pkl', 'rb') as f:
|
| 74 |
+
model = pickle.load(f)
|
| 75 |
+
print("ARIMA model loaded successfully")
|
| 76 |
+
return model
|
|
|
|
| 77 |
except Exception as e:
|
| 78 |
+
print(f"ARIMA Load Error: {e}")
|
| 79 |
return None
|
| 80 |
|
| 81 |
# ============================================================================
|
| 82 |
# MODEL 2: PROPHET
|
| 83 |
# ============================================================================
|
| 84 |
|
| 85 |
+
def load_prophet_model():
|
| 86 |
+
"""Load pre-trained Prophet model"""
|
| 87 |
try:
|
| 88 |
+
# Load the model from JSON
|
| 89 |
+
with open('models/prophet_model.json', 'r') as f:
|
| 90 |
+
model = model_from_json(f.read())
|
| 91 |
+
print("Prophet model loaded successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return model
|
| 93 |
except Exception as e:
|
| 94 |
+
print(f"Prophet Load Error: {e}")
|
| 95 |
return None
|
| 96 |
|
| 97 |
# ============================================================================
|
| 98 |
# MODEL 3: LSTM
|
| 99 |
# ============================================================================
|
| 100 |
|
| 101 |
+
def load_lstm_model():
|
| 102 |
+
"""Load pre-trained LSTM model and scaler"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
try:
|
| 104 |
+
# Load the model
|
| 105 |
+
lstm_model = load_model('models/lstm_model.h5')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
# Load the scaler
|
| 108 |
+
with open('models/lstm_scaler.pkl', 'rb') as f:
|
| 109 |
+
scaler = pickle.load(f)
|
| 110 |
|
| 111 |
+
print("LSTM model and scaler loaded successfully")
|
| 112 |
+
return lstm_model, scaler
|
| 113 |
except Exception as e:
|
| 114 |
+
print(f"LSTM Load Error: {e}")
|
| 115 |
+
return None, None
|
| 116 |
|
| 117 |
# ============================================================================
|
| 118 |
# EDA FUNCTION
|
|
|
|
| 239 |
}
|
| 240 |
|
| 241 |
# ARIMA
|
| 242 |
+
arima_model = load_arima_model()
|
| 243 |
if arima_model:
|
| 244 |
arima_forecast = arima_model.forecast(steps=test_size)
|
| 245 |
results['ARIMA']['predictions'] = arima_forecast
|
|
|
|
| 248 |
print(f"ARIMA - RMSE: {rmse:.2f}, MAE: {mae:.2f}, MAPE: {mape:.2f}%, R2: {r2:.4f}")
|
| 249 |
|
| 250 |
# Prophet
|
| 251 |
+
prophet_model = load_prophet_model()
|
| 252 |
if prophet_model:
|
| 253 |
future = prophet_model.make_future_dataframe(periods=test_size)
|
| 254 |
forecast = prophet_model.predict(future)
|
|
|
|
| 259 |
print(f"Prophet - RMSE: {rmse:.2f}, MAE: {mae:.2f}, MAPE: {mape:.2f}%, R2: {r2:.4f}")
|
| 260 |
|
| 261 |
# LSTM
|
| 262 |
+
lstm_model, scaler = load_lstm_model()
|
| 263 |
if lstm_model and scaler:
|
| 264 |
all_data = df['Close'].values
|
| 265 |
+
test_inputs = all_data[len(train_data) - 60:] # Using look_back=60 as in original code
|
| 266 |
test_inputs = scaler.transform(test_inputs.reshape(-1, 1))
|
| 267 |
|
| 268 |
X_test = []
|
| 269 |
+
for i in range(60, len(test_inputs)):
|
| 270 |
+
X_test.append(test_inputs[i-60:i, 0])
|
| 271 |
X_test = np.array(X_test)
|
| 272 |
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
|
| 273 |
|
|
|
|
| 297 |
predictions = {}
|
| 298 |
|
| 299 |
# ARIMA
|
| 300 |
+
arima_model = load_arima_model()
|
| 301 |
if arima_model:
|
| 302 |
arima_forecast = arima_model.forecast(steps=days_to_predict)
|
| 303 |
predictions['ARIMA'] = arima_forecast
|
| 304 |
|
| 305 |
# Prophet
|
| 306 |
+
prophet_model = load_prophet_model()
|
| 307 |
if prophet_model:
|
| 308 |
future = prophet_model.make_future_dataframe(periods=days_to_predict)
|
| 309 |
forecast = prophet_model.predict(future)
|
| 310 |
predictions['Prophet'] = forecast['yhat'].iloc[-days_to_predict:].values
|
| 311 |
|
| 312 |
# LSTM
|
| 313 |
+
lstm_model, scaler = load_lstm_model()
|
| 314 |
if lstm_model and scaler:
|
| 315 |
+
last_sequence = scaler.transform(full_data[-60:].reshape(-1, 1)) # Using look_back=60
|
| 316 |
lstm_predictions = []
|
| 317 |
|
| 318 |
for _ in range(days_to_predict):
|
| 319 |
+
X_test = last_sequence.reshape((1, 60, 1))
|
| 320 |
pred = lstm_model.predict(X_test, verbose=0)
|
| 321 |
lstm_predictions.append(pred[0, 0])
|
| 322 |
last_sequence = np.append(last_sequence[1:], pred).reshape(-1, 1)
|