DEV Community

dustin liang
dustin liang

Posted on Edited on

pandas CustomBusinessDay with Holidays: Building a Trading-Day Calendar for Daily News and Attention Data

Daily market-related data never lines up with the plain calendar. News, filings and discussion keep arriving on weekends and during exchange holidays, while prices and trading activity only exist on trading days. If you count mentions per calendar day and then join them to anything that lives on trading days, you get silent misalignments: weekend items vanish, a rolling "5-day" window covers a different number of sessions each week, and shift(1) after a long holiday points to a day that is a week old.

pandas has a direct tool for this: CustomBusinessDay, a date offset that knows your weekmask and your holiday list. This tutorial builds a trading-day calendar with it, uses it for date arithmetic, maps weekend and holiday items to the next session, reindexes counts onto a gap-free trading grid, and shows where rolling windows and shifts behave differently on that grid.

Code runs on pandas 3.1 and NumPy 2.5. The closure dates below are examples chosen to show a long holiday block. For real work, load your exchange's official holiday list each year instead of typing dates by hand.

A holiday list and a CustomBusinessDay offset

import numpy as np
import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay

closures = pd.to_datetime([
    "2026-09-25",                      # one-off closure (example)
    "2026-10-01", "2026-10-02", "2026-10-05", "2026-10-06", "2026-10-07",  # holiday block (example)
])
cbd = CustomBusinessDay(holidays=closures)
Enter fullscreen mode Exit fullscreen mode

The default weekmask is Monday to Friday, so cbd steps over weekends and the six listed dates. Only weekdays need to be in the holiday list. Weekends are already excluded by the weekmask.

Generating the trading-day range

days = pd.date_range("2026-09-21", "2026-10-12", freq=cbd)
print(len(days), "trading days")
print(days.strftime("%a %m-%d").tolist())
print(len(pd.bdate_range("2026-09-21", "2026-10-12")), "plain business days")
same = pd.bdate_range("2026-09-21", "2026-10-12", freq="C", holidays=closures)
print("bdate_range freq='C' identical:", same.equals(days))
Enter fullscreen mode Exit fullscreen mode
10 trading days
['Mon 09-21', 'Tue 09-22', 'Wed 09-23', 'Thu 09-24', 'Mon 09-28', 'Tue 09-29', 'Wed 09-30', 'Thu 10-08', 'Fri 10-09', 'Mon 10-12']
16 plain business days
bdate_range freq='C' identical: True
Enter fullscreen mode Exit fullscreen mode

Plain business days would give 16 sessions for these three weeks. The real calendar has 10. pd.bdate_range(..., freq="C", holidays=...) is a shortcut that builds the same offset internally, which is handy for one-off ranges. Keep the explicit cbd object when you also need date arithmetic.

Trading-day arithmetic: next, previous, n sessions later

Adding the offset moves by sessions, not by calendar days:

d = pd.Timestamp("2026-09-30")
print("next trading day after", d.date(), "->", (d + cbd).date())
print("3 trading days later ->", (d + 3 * cbd).date())
print("previous trading day ->", (d - cbd).date())
sat = pd.Timestamp("2026-10-03")
print("rollforward", sat.date(), "->", cbd.rollforward(sat).date())
print("rollback", sat.date(), "->", cbd.rollback(sat).date())
print("is_on_offset 2026-10-08:", cbd.is_on_offset(pd.Timestamp("2026-10-08")))
Enter fullscreen mode Exit fullscreen mode
next trading day after 2026-09-30 -> 2026-10-08
3 trading days later -> 2026-10-12
previous trading day -> 2026-09-29
rollforward 2026-10-03 -> 2026-10-08
rollback 2026-10-03 -> 2026-09-30
is_on_offset 2026-10-08: True
Enter fullscreen mode Exit fullscreen mode

Note the difference between + cbd and rollforward. Adding the offset always moves at least one session forward. rollforward leaves a date that is already a trading day unchanged and only moves non-trading days. For "which session does this item belong to?" you want rollforward. For "what is the next session after this one?" you want + cbd.

Counting trading days between dates

For many date pairs at once, NumPy's busday_count is vectorised and accepts the same holidays. It counts days in the half-open interval [start, end):

hol = closures.values.astype("datetime64[D]")
print("trading days in [09-21, 10-12):",
      np.busday_count("2026-09-21", "2026-10-12", holidays=hol))
starts = np.array(["2026-09-21", "2026-09-28", "2026-10-08"], dtype="datetime64[D]")
ends = np.array(["2026-09-28", "2026-10-08", "2026-10-12"], dtype="datetime64[D]")
print(np.busday_count(starts, ends, holidays=hol))
Enter fullscreen mode Exit fullscreen mode
trading days in [09-21, 10-12): 9
[4 3 2]
Enter fullscreen mode Exit fullscreen mode

That gives you holding periods, "sessions since the last event" or "sessions until the next earnings date" without a loop.

Mapping weekend and holiday items to the next session

Now some timestamped items, for example news headlines tagged with a ticker, spread across the same three weeks including weekends:

rng = np.random.default_rng(7)
stamps = pd.to_datetime("2026-09-21") + pd.to_timedelta(rng.integers(0, 22 * 24 * 60, 60), unit="min")
news = pd.DataFrame({"ts": np.sort(stamps), "ticker": rng.choice(["T01", "T02"], 60)})
news["day"] = news["ts"].dt.normalize()
news["trade_day"] = news["day"].map(cbd.rollforward)
off_days = news[news["day"] != news["trade_day"]]
print(len(off_days), "of", len(news), "items fall on non-trading days")
print(off_days[["ts", "trade_day"]].head(6).to_string(index=False))
Enter fullscreen mode Exit fullscreen mode
31 of 60 items fall on non-trading days
                 ts  trade_day
2026-09-25 17:40:00 2026-09-28
2026-09-25 22:54:00 2026-09-28
2026-09-26 14:34:00 2026-09-28
2026-09-27 03:00:00 2026-09-28
2026-09-27 06:30:00 2026-09-28
2026-09-27 14:29:00 2026-09-28
Enter fullscreen mode Exit fullscreen mode

Over half of the items land on a day without a session, because the window contains a long holiday block. A naive join on calendar date would drop all of them. Rolling forward assigns each item to the first session where the market could react to it, which is also the correct choice for avoiding look-ahead in a backtest.

Many pipelines also apply a cut-off time, so an item published after the close counts toward the next session. If you need that, shift timestamps after the cut-off by one calendar day before normalising, then roll forward as above.

Reindexing counts onto a gap-free trading grid

Group by session and ticker, then reindex onto the full list of trading days so that sessions with no items show 0 rather than disappearing:

counts = (news.groupby(["trade_day", "ticker"]).size()
              .unstack(fill_value=0))
grid = counts.reindex(days, fill_value=0)
grid.index.name = "trade_day"
print(grid.shape, "rows on trading calendar; raw groups:", counts.shape[0])
print(grid.loc["2026-09-29":"2026-10-09"])
Enter fullscreen mode Exit fullscreen mode
(10, 2) rows on trading calendar; raw groups: 9
ticker      T01  T02
trade_day           
2026-09-29    0    0
2026-09-30    1    2
2026-10-08    9   16
2026-10-09    3    2
Enter fullscreen mode Exit fullscreen mode

One session had no items at all and would have been missing from the grouped result. After reindexing it is an explicit zero, which matters for any rolling statistic or z-score computed downstream. The first session after the holiday collects everything published during the closure: 9 and 16 items against single digits around it. Whether you keep that pile-up or spread it out depends on the question, but you should know it is there.

Rolling windows: rows versus calendar time

On a trading grid, an integer window counts sessions, while a string window like "7D" counts calendar time:

cal = pd.DataFrame({"T01": grid["T01"]})
cal["sum_5_rows"] = cal["T01"].rolling(5).sum()
cal["sum_7D"] = cal["T01"].rolling("7D").sum()
print(cal.loc["2026-10-08":"2026-10-12"])
Enter fullscreen mode Exit fullscreen mode
            T01  sum_5_rows  sum_7D
trade_day                          
2026-10-08    9        15.0     9.0
2026-10-09    3        17.0    12.0
2026-10-12    5        18.0    17.0
Enter fullscreen mode Exit fullscreen mode

On 10-08 the five-session window reaches back to before the holiday, while the seven-calendar-day window contains only that one session. Neither is wrong, but they answer different questions. For anything compared against trading activity, the session-based window is usually what you want, and it only works if the grid has exactly one row per session, which is what the reindex step guarantees.

shift() after a holiday

shift(1) moves by one row, so on the trading grid it means "previous session":

s = grid["T01"]
print(pd.DataFrame({"T01": s, "prev_row": s.shift(1)}).loc["2026-09-30":"2026-10-09"])
Enter fullscreen mode Exit fullscreen mode
            T01  prev_row
trade_day                
2026-09-30    1       0.0
2026-10-08    9       1.0
2026-10-09    3       9.0
Enter fullscreen mode Exit fullscreen mode

The value for 10-08 compares against 09-30, eight calendar days earlier. That is correct for day-over-day comparisons in session terms. If your feature needs "change versus the same time a week ago", use calendar logic instead, and be aware that the two disagree around every long closure.

Six-day weeks and other weekmasks

Some markets occasionally run a make-up session on a weekend, and some datasets (such as crypto or certain commodity sessions) follow a different week. The weekmask argument handles that:

six = CustomBusinessDay(weekmask="Mon Tue Wed Thu Fri Sat", holidays=closures)
print(pd.date_range("2026-09-24", "2026-09-30", freq=six).strftime("%a %m-%d").tolist())
Enter fullscreen mode Exit fullscreen mode
['Thu 09-24', 'Sat 09-26', 'Mon 09-28', 'Tue 09-29', 'Wed 09-30']
Enter fullscreen mode Exit fullscreen mode

A single extra working Saturday is easier to handle by building the range from the normal offset and then using DatetimeIndex.union to add that one date. Changing the weekmask adds every Saturday.

Rule-based holidays with AbstractHolidayCalendar

For fixed-date holidays you can define rules once instead of listing every year. nearest_workday moves a holiday that falls on a weekend to the adjacent Friday or Monday:

from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday

class ExampleCalendar(AbstractHolidayCalendar):
    rules = [
        Holiday("New Year", month=1, day=1, observance=nearest_workday),
        Holiday("Example Day", month=5, day=1),
    ]
cal_hol = ExampleCalendar().holidays("2026-01-01", "2027-12-31")
print(cal_hol.strftime("%Y-%m-%d %a").tolist())
combined = CustomBusinessDay(holidays=cal_hol.union(closures))
print(pd.Timestamp("2026-04-30") + combined)
Enter fullscreen mode Exit fullscreen mode
['2026-01-01 Thu', '2026-05-01 Fri', '2027-01-01 Fri', '2027-05-01 Sat', '2027-12-31 Fri']
2026-05-04 00:00:00
Enter fullscreen mode Exit fullscreen mode

The next session after 04-30 is 05-04, because 05-01 is a holiday and the weekend follows. Also note the surprise in the list: 2027-12-31 Fri appears. That is New Year 2028, which falls on a Saturday, observed on the preceding Friday and therefore inside the requested range. Rules like this are convenient, but lunar-calendar holidays and ad-hoc closures cannot be expressed as simple rules, so for most exchanges a downloaded list is still the reliable source. Combine both with union, as shown.

Weekly aggregation on trading weeks

Grouping the grid by weekly periods ending on Friday gives totals per trading week and, with size, the number of sessions in each week:

wk = grid.groupby(grid.index.to_period("W-FRI")).agg(["sum", "size"])
print(wk)
Enter fullscreen mode Exit fullscreen mode
ticker                T01      T02     
                      sum size sum size
trade_day                              
2026-09-19/2026-09-25   7    4   2    4
2026-09-26/2026-10-02   5    3   7    3
2026-10-03/2026-10-09  12    2  18    2
2026-10-10/2026-10-16   5    1   4    1
Enter fullscreen mode Exit fullscreen mode

The session count is the important column: the holiday week has two sessions, so its raw total is not comparable with a five-session week. Divide by size for a per-session average before comparing weeks. (The last week only has one session because the sample ends on 10-12.)

FAQ

What is the difference between BDay and CustomBusinessDay?
BDay (BusinessDay) only skips weekends. CustomBusinessDay adds a holiday list and a configurable weekmask. For any exchange data you need the custom version.

Is CustomBusinessDay slow?
Building a range with date_range is fast. Adding the offset to many timestamps one at a time with map is slower. For large frames, build the trading-day index once and use searchsorted on it to find the next session for each date.

Does CustomBusinessDay work with timezones?
Yes, but normalise to the exchange's local date first. A timestamp in UTC can fall on a different calendar day than in the exchange's time zone, which changes which session it maps to.

Conclusion

pandas CustomBusinessDay with holidays turns trading-day logic into ordinary pandas operations: a range of sessions, next and previous session arithmetic, rollforward to assign weekend and holiday items to the first session that can react to them, and a gap-free grid for rolling windows and shifts. Keep one calendar object per market, load holidays from an official source, and check session counts whenever you compare weeks or windows that span a closure.

If you want to see daily attention data already aligned to the trading calendar, Lava's stock heat monitoring page shows how news and discussion heat for A-share tickers is tracked session by session.

中文简介:本文讲 pandas 的 CustomBusinessDay 如何配合节假日列表构建交易日历:用 date_range/bdate_range(freq='C') 生成交易日序列,用 +cbd、rollforward/rollback 做交易日加减与归属,用 numpy.busday_count 批量计算交易日间隔;把周末与长假期间的新闻按 rollforward 归到下一交易日并 reindex 到无缺口的交易日网格;对比按行(交易日)与按 "7D" 日历时间的 rolling 窗口、长假后 shift(1) 的含义;并介绍 weekmask、AbstractHolidayCalendar 规则节假日(含 nearest_workday 跨年陷阱)与按交易周聚合时需按交易日数归一化。示例节假日为演示用日期,实际请使用交易所官方日历。

Top comments (0)