Home > Mobile >  How to get a range of business days for a given date and add the result as a column?
How to get a range of business days for a given date and add the result as a column?

Time:06-21

I have a dataframe which has a date in one column. I want to add 5 business days to the bottom of the dataframe based on the first date. Then I want to minus 5 business days and have that at the top of the dataframe, again based on the central date.

I have no idea how to do this. Can anyone help?

Here is the dataframe:

    ticker           ex_date
0   6762 JP Equity  2021-09-29  

And the desired result:

    ticker           ex_date
0   6762 JP Equity  2021-09-24  
0   6762 JP Equity  2021-09-27  
0   6762 JP Equity  2021-09-28  
0   6762 JP Equity  2021-09-29
0   6762 JP Equity  2021-09-30  
0   6762 JP Equity  2021-10-01  
0   6762 JP Equity  2021-10-04  

CodePudding user response:

With the help of pandas.bdate_range, here is one way to do it:

import pandas as pd

df = pd.DataFrame({"ticker": ["6762 JP Equity"], "ex_date": ["2021-09-29"]}).astype(
    {"ex_date": "datetime64[ns]"}
)
central = df.loc[0, "ex_date"]
delta = pd.Timedelta(5, unit="day")

df = (
    pd.DataFrame(
        data=pd.bdate_range(start=central - delta, end=central   delta)
        .strftime("%Y-%m-%d")
        .to_list(),
        columns=["ex_date"],
    )
    .assign(ticker=df.loc[0, "ticker"])
    .reindex(columns=["ticker", "ex_date"])
)
print(df)
# Output
           ticker     ex_date
0  6762 JP Equity  2021-09-24
1  6762 JP Equity  2021-09-27
2  6762 JP Equity  2021-09-28
3  6762 JP Equity  2021-09-29
4  6762 JP Equity  2021-09-30
5  6762 JP Equity  2021-10-01
6  6762 JP Equity  2021-10-04
  • Related