Pandas Time Series Holiday Rule Offset

Nowadays, it's not possible define both offset and observance parameters in the same holiday rule.

I found this issue with the Boxing holiday day in England. The Boxing Day is the next workday after Christmas day.

I coded the solution using the observance parameter pointing to the appropriate rule, in this case: after_nearest_workday

    Holiday('Christmas', month=12, day=25, observance=nearest_workday),
    Holiday('Boxing Day', month=12, day=25, observance=after_nearest_workday)

after_nearest_workday is a function. If you need another observance rule, you can create your own function like the following original Pandas observance functions:

def nearest_workday(dt):
    """
    If holiday falls on Saturday, use day before (Friday) instead;
    if holiday falls on Sunday, use day thereafter (Monday) instead.
    """
    if dt.weekday() == 5:
        return dt - timedelta(1)
    elif dt.weekday() == 6:
        return dt + timedelta(1)
    return dt

def after_nearest_workday(dt):
    """
    returns next workday after nearest workday
    needed for Boxing day or multiple holidays in a series
    """
    return next_workday(nearest_workday(dt))

With the latest pandas 0.23.4, it's pretty easy to do this now.

import pandas as pd
from pandas.tseries.offsets import Day
from dateutil.relativedelta import TH

BlackFriday = Holiday("Black Friday", month=11, day=1, 
        offset=[pd.DateOffset(weekday=TH(4)), Day(1)])

Tags:

Python

Pandas