Of course! Here is a complete, step-by-step guide to forecasting your occupancy data using SARIMA with a grid search, validating the model, and then forecasting into the future.
We will follow these steps:
- Setup and Data Preparation: We'll create a sample DataFrame that mimics typical occupancy data with trends and seasonality.
- Part 1: Model Validation (Backtesting)
- Split the data into a training set and a test set (the last 365 days).
- Perform a grid search to find the best SARIMA parameters (
p,d,q,P,D,Q) on the training data using the AIC score.
- Train the best model on the training set and forecast over the test set period.
- Calculate the Symmetric Mean Absolute Percentage Error (SMAPE) to evaluate the forecast.
- Visualize the backtest results.
- Part 2: Future Forecasting
- Re-train the best model on the entire dataset.
- Forecast the next 365 days.
- Visualize the historical data along with the future forecast and confidence intervals.
Prerequisites
First, make sure you have the necessary libraries installed.
pip install pandas numpy matplotlib statsmodels scikit-learn
Step 1: Setup and Data Preparation
Since you have your own DataFrame (df), you can skip this data generation part. Just make sure your df has a ds column converted to datetime objects and set as the index, and a y column with your occupancy percentage.
For demonstration purposes, let's create a realistic sample dataset.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.metrics import mean_absolute_percentage_error
import itertools
import warnings
warnings.filterwarnings("ignore") # supress warnings from SARIMA
# --- Create a sample DataFrame ---
# (You can replace this with your own df)
# Let's create 4 years of daily data
date_rng = pd.date_range(start='2020-01-01', end='2023-12-31', freq='D')
# Create some realistic data with seasonality and trend
np.random.seed(42)
trend = np.linspace(0, 8, len(date_rng)) # Gentle upward trend
# Yearly seasonality
yearly_seasonality = 15 * np.sin(2 * np.pi * date_rng.dayofyear / 365.25)
# Weekly seasonality (e.g., weekends are busier)
weekly_seasonality = 7 * np.sin(2 * np.pi * date_rng.dayofweek / 7)
noise = np.random.normal(0, 3, len(date_rng))
base_occupancy = 60
# Combine components
y = base_occupancy + trend + yearly_seasonality + weekly_seasonality + noise
y = np.clip(y, 10, 100) # Keep occupancy between 10% and 100%
df = pd.DataFrame(date_rng, columns=['ds'])
df['y'] = y
# --- IMPORTANT: Prepare your DataFrame ---
# 1. Convert 'ds' to datetime
df['ds'] = pd.to_datetime(df['ds'])
# 2. Set 'ds' as the index
df.set_index('ds', inplace=True)
print("Data Head:")
print(df.head())
print("\nData Tail:")
print(df.tail())
# Plot the raw data to see what it looks like
plt.figure(figsize=(14, 7))
plt.plot(df.index, df['y'])
plt.title('Daily Occupancy (%) Over Time')
plt.xlabel('Date')
plt.ylabel('Occupancy %')
plt.grid(True)
plt.show()
Step 2: Part 1 - Model Validation on Recent 365 Days
Here, we find the best model and test its performance on data it has never seen before.
2a. Split Data and Define SMAPE
We'll hold out the last 365 days as our test set. We also define our evaluation metric, SMAPE, which is a good choice for percentage-based forecasts.
# Split data into training and test sets
train_size = 365
train_df = df[:-train_size]
test_df = df[-train_size:]
print(f"Training data size: {len(train_df)}")
print(f"Test data size: {len(test_df)}")
# Define the SMAPE metric
def smape(y_true, y_pred):
"""
Calculates the Symmetric Mean Absolute Percentage Error.
"""
numerator = np.abs(y_pred - y_true)
denominator = (np.abs(y_true) + np.abs(y_pred)) / 2
# Handle the case where both true and predicted are zero
# to avoid division by zero
ratio = np.where(denominator == 0, 0, numerator / denominator)
return np.mean(ratio) * 100
2b. Grid Search for Best SARIMA Parameters
This is the most computationally intensive part. We'll search through a small range of parameters to find the combination that results in the lowest AIC (Akaike Information Criterion) on the training data. A lower AIC suggests a better fit with less complexity.
Note on Seasonality (s or m): The seasonal period is crucial. For daily data with a yearly pattern, s=365 is technically correct but computationally very slow. A common, practical approach for daily data is to focus on the weekly seasonality (s=7). We will use s=7 here for a faster demonstration. If your primary goal is the yearly pattern and you have the computational resources, you can change s to 365.
# Define the p, d, and q parameters to take any value between 0 and 2
p = d = q = range(0, 2)
# Generate all different combinations of p, d, and q triplets
pdq = list(itertools.product(p, d, q))
# Generate all different combinations of seasonal p, d, and q triplets
seasonal_pdq = [(x[0], x[1], x[2], 7) for x in list(itertools.product(p, d, q))] # s=7 for weekly
print('Searching for best SARIMA parameters...')
best_aic = np.inf
best_pdq = None
best_seasonal_pdq = None
best_model = None
# Grid search
for param in pdq:
for param_seasonal in seasonal_pdq:
try:
temp_model = SARIMAX(train_df['y'],
order=param,
seasonal_order=param_seasonal,
enforce_stationarity=False,
enforce_invertibility=False)
results = temp_model.fit(disp=False)
# print(f'ARIMA{param}x{param_seasonal} - AIC:{results.aic}')
if results.aic < best_aic:
best_aic = results.aic
best_pdq = param
best_seasonal_pdq = param_seasonal
except Exception as e:
# print(f"Error with params {param} & {param_seasonal}: {e}")
continue
print(f'\nBest SARIMA Parameters Found:')
print(f'Order (p,d,q): {best_pdq}')
print(f'Seasonal Order (P,D,Q,s): {best_seasonal_pdq}')
print(f'Best AIC: {best_aic:.2f}')
2c. Fit, Forecast, and Evaluate
Now we use the best parameters found to train a model and predict on the test set.
# Fit the best model on the training data
final_model_on_train = SARIMAX(train_df['y'],
order=best_pdq,
seasonal_order=best_seasonal_pdq,
enforce_stationarity=False,
enforce_invertibility=False)
results_on_train = final_model_on_train.fit(disp=False)
# Make predictions on the test set
predictions = results_on_train.get_prediction(start=test_df.index[0], end=test_df.index[-1])
predicted_mean = predictions.predicted_mean
# Evaluate the model
smape_score = smape(test_df['y'], predicted_mean)
print(f'\nSMAPE on the last 365 days (test set): {smape_score:.2f}%')
2d. Visualize the Backtest
Let's plot the training data, the actual test data, and our forecast to see how well we did.
# Plot the results
plt.figure(figsize=(15, 8))
plt.plot(train_df.index, train_df['y'], label='Training Data')
plt.plot(test_df.index, test_df['y'], label='Actual Occupancy (Test Set)', color='orange')
plt.plot(predicted_mean.index, predicted_mean, label='SARIMA Forecast', color='green')
plt.title('SARIMA Forecast vs. Actuals (Last 365 Days)')
plt.xlabel('Date')
plt.ylabel('Occupancy %')
plt.legend()
plt.grid(True)
plt.show()
Step 3: Part 2 - Forecast Future 365 Days
Now that we have validated our model's parameters, we'll re-train it on the full dataset to make the most informed forecast for the future.
# Re-train the model on the ENTIRE dataset using the best parameters
full_data_model = SARIMAX(df['y'],
order=best_pdq,
seasonal_order=best_seasonal_pdq,
enforce_stationarity=False,
enforce_invertibility=False)
full_data_results = full_data_model.fit(disp=False)
# Get the forecast for the next 365 days
forecast_object = full_data_results.get_forecast(steps=365)
# Extract the forecast mean
forecast_mean = forecast_object.predicted_mean
# Extract the confidence intervals
conf_int = forecast_object.conf_int()
lower_conf = conf_int.iloc[:, 0]
upper_conf = conf_int.iloc[:, 1]
# --- Visualize the Future Forecast ---
plt.figure(figsize=(15, 8))
# Plot historical data
plt.plot(df.index, df['y'], label='Historical Daily Occupancy')
# Plot the forecast
plt.plot(forecast_mean.index, forecast_mean, label='Future Forecast', color='red')
# Plot the confidence interval
plt.fill_between(conf_int.index,
lower_conf,
upper_conf,
color='pink',
alpha=0.6,
label='95% Confidence Interval')
plt.title('Future Occupancy Forecast for Next 365 Days')
plt.xlabel('Date')
plt.ylabel('Occupancy %')
plt.legend(loc='upper left')
plt.grid(True)
plt.show()
# Display the forecasted values
print("\nForecast for the next 365 days:")
future_forecast_df = pd.DataFrame({'ds': forecast_mean.index, 'yhat': forecast_mean})
print(future_forecast_df.head())
This comprehensive script provides a robust framework for time series forecasting. You can easily adapt it by loading your own data and adjusting the grid search ranges or the seasonal period s to fit your specific needs.