You're right—aggregating daily data into weekly data can often simplify forecasting, especially when daily data is noisy or has structural patterns like zero activity on weekends. Below is an updated version of the code that:
Aggregates your daily data into weekly sums (Monday to Friday only, since weekends have no activity).
Performs a backtest over the last 52 weeks (equivalent to 365 business days in daily data).
Uses Prophet with Optuna for hyperparameter tuning.
Reports SMAPE on the weekly forecasts.
Here’s the complete code:
python
import pandas as pd
import numpy as np
from prophet import Prophet
import optuna
import matplotlib.pyplot as plt
# ------------------------------------------------------------------
# 1. Load your data (ds = date, y = daily contract count)
# ------------------------------------------------------------------
# Example data (replace with your actual data)
data = {
'ds': ['2022-01-17', '2022-01-18', '2022-01-19', '2022-01-20', '2022-01-21'],
'y': [24.0, 18.0, 3.0, 7.0, 23.0]
}
df = pd.DataFrame(data)
df['ds'] = pd.to_datetime(df['ds'])
# ------------------------------------------------------------------
# 2. Keep only business days (drop Sat/Sun)
# ------------------------------------------------------------------
df = df[df['ds'].dt.weekday < 5].reset_index(drop=True)
# ------------------------------------------------------------------
# 3. Aggregate daily data into weekly sums
# ------------------------------------------------------------------
# Add a 'week_start' column (Monday of each week)
df['week_start'] = df['ds'] - pd.to_timedelta(df['ds'].dt.weekday, unit='D')
# Group by week_start and sum the 'y' values
weekly_df = df.groupby('week_start').agg({'y': 'sum'}).reset_index()
weekly_df.columns = ['ds', 'y'] # Prophet expects 'ds' and 'y'
# ------------------------------------------------------------------
# 4. Train / test split -> last 52 weeks as hold-out
# ------------------------------------------------------------------
HOLDOUT_WEEKS = 52
train_df = weekly_df.iloc[:-HOLDOUT_WEEKS]
test_df = weekly_df.iloc[-HOLDOUT_WEEKS:]
# ------------------------------------------------------------------
# 5. SMAPE helper
# ------------------------------------------------------------------
def smape(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return 100 * np.mean(2 * np.abs(y_pred - y_true) /
(np.abs(y_true) + np.abs(y_pred) + 1e-8))
# ------------------------------------------------------------------
# 6. Optuna objective
# ------------------------------------------------------------------
def objective(trial):
params = {
'changepoint_prior_scale': trial.suggest_float('changepoint_prior_scale', 0.001, 0.5, log=True),
'seasonality_prior_scale': trial.suggest_float('seasonality_prior_scale', 0.01, 10, log=True),
'changepoint_range': trial.suggest_float('changepoint_range', 0.8, 0.95),
'n_changepoints': trial.suggest_int('n_changepoints', 10, 30), # Fewer changepoints for weekly data
'seasonality_mode': trial.suggest_categorical('seasonality_mode', ['additive', 'multiplicative']),
'interval_width': trial.suggest_float('interval_width', 0.90, 0.95)
}
m = Prophet(
daily_seasonality=False,
weekly_seasonality=False, # Disable weekly seasonality (data is already weekly)
yearly_seasonality=True,
**params
)
m.fit(train_df)
# Forecast exactly the test period
future = pd.DataFrame({'ds': test_df['ds']})
fcst = m.predict(future)
# Align and compute SMAPE
merged = pd.merge(test_df, fcst[['ds', 'yhat']], on='ds', how='inner')
return smape(merged['y'], merged['yhat'])
# ------------------------------------------------------------------
# 7. Run Bayesian optimisation
# ------------------------------------------------------------------
study = optuna.create_study(direction='minimize')
study.optimize(objective, n_trials=30, show_progress_bar=True)
print("Best SMAPE:", round(study.best_value, 2))
print("Best params:", study.best_params)
# ------------------------------------------------------------------
# 8. Final model on best parameters
# ------------------------------------------------------------------
best = study.best_params
m_final = Prophet(
daily_seasonality=False,
weekly_seasonality=False, # Disable weekly seasonality (data is weekly)
yearly_seasonality=True,
**best
)
m_final.fit(train_df)
future = pd.DataFrame({'ds': test_df['ds']})
fcst = m_final.predict(future)
merged = pd.merge(test_df, fcst[['ds', 'yhat', 'yhat_lower', 'yhat_upper']], on='ds')
final_smape = smape(merged['y'], merged['yhat'])
print("Final back-test SMAPE:", round(final_smape, 2))
# ------------------------------------------------------------------
# 9. Quick plot
# ------------------------------------------------------------------
plt.figure(figsize=(14, 4))
plt.plot(merged['ds'], merged['y'], label='actual')
plt.plot(merged['ds'], merged['yhat'], label='forecast')
plt.fill_between(merged['ds'], merged['yhat_lower'], merged['yhat_upper'], alpha=0.2)
plt.axvline(train_df['ds'].iloc[-1], color='k', ls='--')
plt.legend()
plt.title(f"Weekly Back-test SMAPE = {final_smape:.2f}%")
plt.show()
Key Changes and Notes:
Weekly Aggregation:
The daily data is aggregated into weekly sums, with each week starting on Monday (week_start).
This removes the need to handle weekends explicitly, as they are already excluded from the daily data.
Holdout Period:
The holdout period is now 52 weeks (equivalent to roughly 365 business days in daily data).
Prophet Seasonality:
weekly_seasonality is disabled because the data is already aggregated into weeks.
daily_seasonality is disabled because we no longer have daily data.
yearly_seasonality is kept to capture annual patterns.
Hyperparameter Tuning:
The range for n_changepoints is reduced (10–30) because weekly data has fewer data points than daily data, so fewer changepoints are needed.
SMAPE:
SMAPE is calculated on the weekly sums, which should be more stable than daily data, especially given the weekend zeros in the original data.
How to Use:
Replace the example data (data) with your actual data (e.g., df = pd.read_csv('your_file.csv', parse_dates=['ds'])).
Run the code as-is. It will:
Aggregate your data into weekly sums.
Perform a backtest over the last 52 weeks.
Tune Prophet hyperparameters using Optuna.
Plot the results and report the final SMAPE.
Benefits of Weekly Aggregation:
Smoother Data: Weekly sums reduce noise and make trends and seasonality easier to model.
Fewer Data Points: Weekly data has fewer points, making the model faster to train and tune.
No Weekend Issues: Aggregating to weeks naturally handles the zero activity on weekends.
If you find that weekly data is still too noisy or doesn't capture important patterns, you could experiment with other aggregations (e.g., biweekly or monthly) or revisit daily modeling with more sophisticated handling of weekends (e.g., custom regressors in Prophet).