pythontime

Python: how do i find the next business day for different countries


In python, I have a a set of dates for different countries. How do i find their next business date if the date given is a holiday for that country, given that different countries have different holiday calendars.

enter image description here

For example, if date is 23th Jan, 2023.Next business day for Hong Kong is 26th Jan 2023. For India, 23th Jan 2023 is not a public holiday, so it will return 23th Jan, 2023. For Singapore, next business date would be 25th Jan, 2023.


Solution

  • Import the following modules.

    !pip install --upgrade holidays # https://python-holidays.readthedocs.io/en/latest
    
    import pandas as pd 
    import numpy as np 
    import holidays
    

    Define the following functions.

    def is_next_day(date):
        return pd.to_datetime(date).date() + pd.Timedelta(days=1)
    
    def is_holiday(date, code):
        if date in holidays.country_holidays(code):
            return is_holiday(is_next_day(date), code)
        elif date.weekday() in [5, 6]:
            return is_holiday(is_next_day(date), code)
        else:
            return date
    
    def is_next_business_day(date, code):
        next_date = is_next_day(date)
        next_date = is_holiday(next_date, code)
        next_date = next_date.strftime('%m/%d/%Y')
        return next_date
    

    Here is the sample. (The Code is by using its ISO 3166-1 alpha-2 code.)

    df = pd.DataFrame([['1/23/2023', 'HongKong'],
                       ['1/23/2023', 'India'],
                       ['1/23/2023', 'Singapore']], columns=['DATE', 'Country'])
    
    df['Code'] = np.where(df['Country']=='HongKong', 'HK',
                    np.where(df['Country']=='India', 'IN',
                       np.where(df['Country']=='Singapore', 'SG', None)))
    

    print df

    The next business day can be calculated as below.

    df['NEXT_BDAY'] = df.apply(lambda x: is_next_business_day(x.DATE, x.Code), axis=1)
    

    print df