python Copy code
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from itertools import product
from statsmodels.tsa.statespace.sarimax import SARIMAX
sns.set(style="whitegrid", context="talk")
# --- Utility: SMAPE ---
def smape(y_true, y_pred):
"""
Symmetric mean absolute percentage error
smape = 1/n * sum( 2 * |F - T| / (|F| + |T|) )
"""
denom = (np.abs(y_true) + np.abs(y_pred))
diff = np.abs(y_true - y_pred)
# avoid div by zero
mask = denom == 0
denom[mask] = 1.0
diff [mask] = 0.0
return 100 * np.mean(2 * diff/denom)
# --- 1. Load your DataFrame (replace this with your df) ---
# df should have columns ['ds','y'], where ds is a datetime and y is numeric
df = pd.read_csv("your_timeseries.csv",
parse_dates=['ds'],
index_col='ds').sort_index()
# If you already have df in memory, skip the read_csv above
# --- 2. Train/Test Split: last 365 days as test ---
forecast_horizon = 365
train = df.iloc[:-forecast_horizon]
test = df.iloc[-forecast_horizon:]
# --- 3. Grid Search for best SARIMA on the test SMAPE ---
# seasonality (e.g. weekly => m=7, yearly=>365, monthly=>12)
m = 7
# small grid (you can expand these ranges!)
p = d = q = range(0, 3)
P = D = Q = range(0, 2)
best_cfg = None
best_smape = np.inf
results = []
total = len(list(product(p, d, q, P, D, Q)))
print(f"Grid‐searching over ~{total} combinations...")
for (pp, dd, qq, PP, DD, QQ) in product(p, d, q, P, D, Q):
try:
model = SARIMAX(
train['y'],
order=(pp, dd, qq),
seasonal_order=(PP, DD, QQ, m),
enforce_stationarity=False,
enforce_invertibility=False
).fit(disp=False)
# forecast test set
preds = model.predict(start=test.index[0], end=test.index[-1])
val_smape = smape(test['y'].values, preds.values)
# store
results.append(((pp,dd,qq,PP,DD,QQ), val_smape, model.aic))
if val_smape < best_smape:
best_smape = val_smape
best_cfg = (pp,dd,qq,PP,DD,QQ)
except Exception:
continue
print(f"Best SARIMA{best_cfg} → test SMAPE = {best_smape:.2f}%")
# Optional: view the top 5 configs by smape
results.sort(key=lambda x: x[1])
print("\nTop 5 configs (smape, aic):")
for cfg, s, a in results[:5]:
print(f" SARIMA{cfg} smape={s:.2f} aic={a:.1f}")
# --- 4. Plot train/test & best‐model predictions on test ---
best_model = SARIMAX(
train['y'],
order=best_cfg[:3],
seasonal_order=(*best_cfg[3:], m),
enforce_stationarity=False,
enforce_invertibility=False
).fit(disp=False)
pred_test = best_model.predict(start=test.index[0], end=test.index[-1])
plt.figure(figsize=(14,5))
plt.plot(train.index, train['y'], label="Train", color="C0", alpha=0.6)
plt.plot(test.index, test['y'], label="Actual (Test)", color="C1")
plt.plot(pred_test.index, pred_test, label="Predicted (Test)", color="C2", linestyle="--")
plt.title(f"SARIMA{best_cfg} → Test SMAPE = {best_smape:.2f}%")
plt.legend(loc="upper left")
plt.tight_layout()
plt.show()
# --- 5. Refit on the full history and forecast the next 365 days ---
full_model = SARIMAX(
df['y'],
order=best_cfg[:3],
seasonal_order=(*best_cfg[3:], m),
enforce_stationarity=False,
enforce_invertibility=False
).fit(disp=False)
future = full_model.get_forecast(steps=forecast_horizon)
fc_index = pd.date_range(start=df.index[-1] + pd.Timedelta(days=1),
periods=forecast_horizon, freq='D')
fc_mean = future.predicted_mean
fc_ci = future.conf_int()
plt.figure(figsize=(14,5))
plt.plot(df.index, df['y'], label="History", color="C0", alpha=0.6)
plt.plot(fc_index, fc_mean, label="Forecast", color="C3")
plt.fill_between(fc_index,
fc_ci.iloc[:,0],
fc_ci.iloc[:,1],
color="C3", alpha=0.2)
plt.title(f"365-Day Forecast with SARIMA{best_cfg}")
plt.legend(loc="upper left")
plt.tight_layout()
plt.show()