Sub topic 7
Calendar features: day of week, month, holidays
This chapter assumes you can build a lag feature table with pandas and fit a scikit-learn regressor. It also assumes you know that a tree model splits on feature thresholds. Calendar features add information that lag and rolling features can only learn indirectly: which day of the week, month or special day the target falls on.
Why calendar features help
A lag feature tells the model what happened recently. It does not say what kind of day the target is. Suppose daily sales drop every Sunday. A model with lag_7 can learn this, but only if the series is regular and the lag is in the feature set. A dayofweek column states the pattern directly, and a tree can split on it in one step.
Calendar features also have a property the other features lack. You know them for every future timestamp. The date of the row you are predicting is not the target's value, so using it does not leak anything. You do not shift calendar features by one step as you do rolling statistics.
Basic calendar fields
Pandas exposes most of what you need on DatetimeIndex:
dayofweek: Monday is 0, Sunday is 6.month: 1 to 12.day: day of the month, useful for pay-day or billing effects.dayofyear: 1 to 366.is_month_end,is_month_start,is_quarter_end: boolean flags.isocalendar().week: ISO week number, which can reach 53.
Tree models handle integer codes well. A tree can isolate weekends with the splits dayofweek > 4.5, or isolate Mondays with dayofweek <= 0.5 and Tuesday-to-Sunday with the complement. You do not need one-hot encoding for gradient boosting, although it does no harm on a 7-value field.
Cyclical encoding
Integer codes place December (12) far from January (1), even though they are neighbors. Trees can work around this with two splits, but linear models and neural networks cannot. If you may compare model families later, add sine and cosine pairs:
sin(2 * pi * value / period), cos(2 * pi * value / period)Use period = 7 for day of week and period = 12 for month. You need both functions. Sine alone maps two different positions to the same value.
For gradient boosting alone, the integer code is usually enough. Add the cyclical pair if it improves your walk-forward score, not by default.
Holidays
Holidays break the weekly pattern, and no lag feature can predict them well. A lag of 7 days on Christmas Day points to the previous Christmas Day's neighbor, which is a normal day. The model needs an explicit holiday signal.
Three kinds of holiday feature are common:
- Flag: 1 if the date is a holiday, otherwise 0.
- Distance: days until the next holiday and days since the last one, capped at a small number such as 14. These capture the ramp-up before a holiday and the dip after it.
- Holiday name: a categorical code, when different holidays behave differently. Christmas and Labor Day rarely look alike.
The example below uses USFederalHolidayCalendar, which ships with pandas. Replace it with the calendar for your region.
import numpy as np
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
def add_calendar_features(df: pd.DataFrame, cap: int = 14) -> pd.DataFrame:
"""Add calendar and holiday columns derived only from df.index."""
idx = df.index
out = df.copy()
out["dayofweek"] = idx.dayofweek
out["month"] = idx.month
out["day_of_month"] = idx.day
out["is_weekend"] = (idx.dayofweek >= 5).astype(int)
out["is_month_end"] = idx.is_month_end.astype(int)
# Cyclical encoding (optional for trees)
out["dow_sin"] = np.sin(2 * np.pi * idx.dayofweek / 7)
out["dow_cos"] = np.cos(2 * np.pi * idx.dayofweek / 7)
# Pad the holiday range so every date has a next and a previous holiday.
pad = pd.Timedelta(days=120)
hol = USFederalHolidayCalendar().holidays(start=idx.min() - pad, end=idx.max() + pad)
hol_vals = hol.values
dates = idx.normalize().values
out["is_holiday"] = idx.normalize().isin(hol).astype(int)
nxt = hol_vals[np.clip(np.searchsorted(hol_vals, dates, side="left"), 0, len(hol_vals) - 1)]
prv = hol_vals[np.clip(np.searchsorted(hol_vals, dates, side="right") - 1, 0, len(hol_vals) - 1)]
one_day = np.timedelta64(1, "D")
out["days_to_holiday"] = np.minimum((nxt - dates) / one_day, cap)
out["days_since_holiday"] = np.minimum((dates - prv) / one_day, cap)
return out
if __name__ == "__main__":
idx = pd.date_range("2024-12-20", "2025-01-05", freq="D")
demo = pd.DataFrame({"y": np.arange(len(idx), dtype=float)}, index=idx)
cols = ["dayofweek", "is_weekend", "is_holiday", "days_to_holiday", "days_since_holiday"]
print(add_calendar_features(demo)[cols])In the output, 2024-12-25 and 2025-01-01 have is_holiday = 1. days_to_holiday counts down to 0 on those dates and then resets to the distance to the next holiday.
Combining with lag features
Call the calendar function after make_features from the lag chapter. Because make_features drops rows with missing lags, the calendar function sees a clean index:
data = add_calendar_features(make_features(series))
feature_cols = [c for c in data.columns if c != "y"]The dayofweek column already exists in make_features, so the call above overwrites it with the same values. In your own code, keep one function as the single place that defines each feature.
When you forecast recursively, compute the calendar values for each future timestamp from that timestamp, exactly as recursive_forecast does with ts.dayofweek. If training and forecasting use different feature code, the model sees inputs at forecast time that differ from what it learned on. Put the calendar logic in one function and call it in both places.
Edge cases and common errors
- Holiday calendar too short. If the calendar ends before your forecast horizon, every future date silently gets
is_holiday = 0. Generate holidays past the last date you will forecast, and check this explicitly. - Moving holidays. Easter, Lunar New Year and Ramadan shift each year. Fixed
month/dayrules miss them. Use a library calendar, such as theholidayspackage, that knows the rules. - Observed holidays. When a holiday falls on a weekend, the day off often moves to Friday or Monday.
USFederalHolidayCalendarincludes the observed date. Check what your calendar returns. - Regional differences. One national calendar is wrong for a store in a state with its own holidays. Match the calendar to where the series is measured.
- Too little history for month. A
monthfeature can only learn a yearly pattern if the training data contains several full years. With 8 months of data,monthbecomes a stand-in for time, and the model memorizes it. The test set then contains months the model never saw. dayofyearoverfitting. With 365 distinct values and a few years of data, each value has only a few rows. Prefermonth, or week of year, unless you have many years.- Time zones and daylight saving. Compute calendar fields in the local time zone of the business, not UTC. Otherwise late-evening events land on the wrong weekday. On hourly data, daylight-saving days have 23 or 25 hours, which can break a strict frequency check.
- Mixed granularity. Hour-of-day matters only for sub-daily data. Adding it to daily data produces a constant column.
Checking that the features help
Do not assume calendar features improve the forecast. Compare two models on the same walk-forward splits: one with lag and rolling features only, one with calendar features added. Use the TimeSeriesSplit loop from the validation chapter. Keep the change if the mean MAE falls and the improvement shows up in most folds, not in one lucky fold. Check the holiday weeks separately, because a flag can help there while barely moving the overall average.
Exercise
Your daily model uses lag1, lag7 and a rolling mean. It forecasts 30 days ahead, and its errors are large around Thanksgiving. You add is_holiday from a calendar built with holidays up to the last date in the training data. In production, the model still ignores Thanksgiving. What is the most likely cause, and how do you fix it?
Show answer
The holiday calendar ends at the last training date, so every forecast date gets isholiday = 0 and the model never sees the holiday signal at forecast time. Build the holiday list to cover the whole forecast horizon (the last date plus the horizon, with some padding), and use the same feature function for training and forecasting. Adding daystoholiday and dayssince_holiday also helps the model learn the days around the holiday.
Exercise
Why can you add dayofweek to the feature table without shifting it, while rolling means must be computed on s.shift(1)?
Show answer
dayofweek is derived from the timestamp of the row being predicted, which is known in advance for any future date and carries no information about the target's value. A rolling mean computed from the target includes values at or after the prediction time unless it is shifted, which would leak the answer into the features.