Sub topic 7
Calendar features: day of week, month, holidays
This chapter assumes you can build a pandas DataFrame with a DatetimeIndex, you know how lag features work from the previous chapters, and you know that tree models split on feature thresholds.
Why calendar features help
Lag features describe what happened recently. They do not tell the model what kind of day it is predicting. A lag of 7 can hint at weekly seasonality, but the model has to infer it from noisy values. A dayofweek column states it directly.
Calendar features are also safe from leakage. The calendar for any future date is known today, so you can compute these features for every row you will ever forecast.
Extracting date parts
Pandas exposes the parts of a date through the index. Build them from the index of the row being predicted, not from a shifted index.
import pandas as pd
def add_calendar(df: pd.DataFrame) -> pd.DataFrame:
# df must have a DatetimeIndex
out = df.copy()
idx = out.index
out['dayofweek'] = idx.dayofweek # Monday=0 ... Sunday=6
out['month'] = idx.month # 1..12
out['dayofmonth'] = idx.day
out['weekofyear'] = idx.isocalendar().week.astype(int).to_numpy()
out['is_weekend'] = (idx.dayofweek >= 5).astype(int)
out['is_month_end'] = idx.is_month_end.astype(int)
return outInteger codes or cyclic encoding
Day of week and month are cyclic. Sunday (6) is next to Monday (0), but the integers are far apart. For tree models this rarely matters, because a tree can isolate any single value with a few splits. Plain integers are a good default for gradient boosting.
Cyclic encoding with sine and cosine helps linear models and neural networks more than trees.
import numpy as np
def add_cyclic_month(df: pd.DataFrame) -> pd.DataFrame:
out = df.copy()
angle = 2 * np.pi * (out.index.month - 1) / 12
out['month_sin'] = np.sin(angle)
out['month_cos'] = np.cos(angle)
return outHolidays
Holidays shift demand in ways a weekday does not capture. A Tuesday holiday behaves more like a Sunday. Add a binary flag, and consider flags for the days before and after, because effects often spread.
import pandas as pd
holidays = pd.to_datetime(['2024-12-25', '2025-01-01', '2025-12-25'])
def add_holidays(df: pd.DataFrame) -> pd.DataFrame:
out = df.copy()
flag = out.index.isin(holidays)
out['is_holiday'] = flag.astype(int)
out['day_before_holiday'] = out.index.map(
lambda d: int((d + pd.Timedelta(days=1)) in holidays)
)
return outFor real projects, a library such as holidays can generate dates per country. Make sure the list covers the full forecast horizon, not only the training period.
Common errors
- Treating
monthas a trend. With only a year or two of data,monthcan memorize one-off events. Check that a pattern repeats before you trust it. - Using
yearas a feature. Trees cannot extrapolate to a year they have not seen, so it adds nothing for future dates. - Holiday lists that stop at the end of the training data. Every future row then gets a flag of 0.
- Mixing time zones. Convert the index to one zone before extracting
dayofweek, or late-night records land on the wrong day.
Exercise
Your model predicts daily sales, and the training data ends on 2025-06-30. You build is_holiday from a list that ends on 2025-06-30, then forecast July to December. What goes wrong, and how do you fix it?
Show answer
Every forecast row after 2025-06-30 gets is_holiday = 0, even on real holidays such as 2025-12-25. The model never sees the holiday signal it learned from. Fix it by generating the holiday list for the whole forecast horizon, for example with the holidays library for the right country, before computing the feature.