This code is forecasting then number of mortgage contract, but it is grouping by weeks, I need it to be divided proportionally on each day of week, by the proprtions according to the last year before forecast import pandas as pd
import numpy as np
from prophet import Prophet
import optuna
import matplotlib.pyplot as plt
I'll modify the code to distribute the weekly forecasts proportionally across each day of the week based on the previous year's daily patterns. Here's how to implement this:
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)
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. Calculate daily proportions from previous year
# ------------------------------------------------------------------
# Add weekday information
df['weekday'] = df['ds'].dt.weekday # 0=Monday, 4=Friday
# Determine the cutoff date for the previous year
forecast_start_date = df['ds'].max() - pd.DateOffset(weeks=HOLDOUT_WEEKS)
previous_year_start = forecast_start_date - pd.DateOffset(weeks=52)
# Filter data for the previous year before forecast
previous_year_data = df[(df['ds'] >= previous_year_start) & (df['ds'] < forecast_start_date)]
# Calculate the proportion of contracts by weekday
weekday_totals = previous_year_data.groupby('weekday')['y'].sum()
weekday_proportions = weekday_totals / weekday_totals.sum()
# ------------------------------------------------------------------
# 4. Aggregate daily data into weekly sums for Prophet
# ------------------------------------------------------------------
# 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'
# ------------------------------------------------------------------
# 5. 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:]
# ------------------------------------------------------------------
# 6. 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))
# ------------------------------------------------------------------
# 7. 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),
'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,
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'])
# ------------------------------------------------------------------
# 8. 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)
# ------------------------------------------------------------------
# 9. Final model on best parameters
# ------------------------------------------------------------------
best = study.best_params
m_final = Prophet(
daily_seasonality=False,
weekly_seasonality=False,
yearly_seasonality=True,
**best
)
m_final.fit(weekly_df) # Use all data for final model
# ------------------------------------------------------------------
# 10. Create future dataframe for forecast period
# ------------------------------------------------------------------
# Determine how many weeks to forecast (e.g., 52 weeks)
forecast_weeks = 52
last_date = weekly_df['ds'].max()
future_weekly = pd.DataFrame({
'ds': [last_date + pd.DateOffset(weeks=i+1) for i in range(forecast_weeks)]
})
# Get weekly forecasts
weekly_forecast = m_final.predict(future_weekly)
# ------------------------------------------------------------------
# 11. Distribute weekly forecasts to daily values
# ------------------------------------------------------------------
# Create a list to store daily forecasts
daily_forecasts = []
# For each forecasted week
for _, week_row in weekly_forecast.iterrows():
week_start = week_row['ds']
week_total = week_row['yhat']
# Create business days for this week
week_days = [week_start + pd.DateOffset(days=i) for i in range(5)]
# Distribute the weekly total according to weekday proportions
for day in week_days:
weekday = day.weekday()
daily_forecast = {
'ds': day,
'yhat': week_total * weekday_proportions[weekday],
'yhat_lower': week_row['yhat_lower'] * weekday_proportions[weekday],
'yhat_upper': week_row['yhat_upper'] * weekday_proportions[weekday]
}
daily_forecasts.append(daily_forecast)
# Convert to DataFrame
daily_forecast_df = pd.DataFrame(daily_forecasts)
# ------------------------------------------------------------------
# 12. Create backtest forecasts with daily distribution
# ------------------------------------------------------------------
# Get the weekly backtest forecasts
backtest_forecast = fcst
# Create a list to store daily backtest forecasts
daily_backtest_forecasts = []
# For each forecasted week in the backtest period
for _, week_row in backtest_forecast.iterrows():
week_start = week_row['ds']
week_total = week_row['yhat']
# Create business days for this week
week_days = [week_start + pd.DateOffset(days=i) for i in range(5)]
# Distribute the weekly total according to weekday proportions
for day in week_days:
weekday = day.weekday()
daily_forecast = {
'ds': day,
'yhat': week_total * weekday_proportions[weekday],
'yhat_lower': week_row['yhat_lower'] * weekday_proportions[weekday],
'yhat_upper': week_row['yhat_upper'] * weekday_proportions[weekday]
}
daily_backtest_forecasts.append(daily_forecast)
# Convert to DataFrame
fcst_backtest_CNT = pd.DataFrame(daily_backtest_forecasts)
Would you like me to explain or break down this code?