I wrote a function that moves the date by specified number of working days in respect to the weekends and holidays. It works fine when I use it with scalar values however I have issue trying to use on the pandas DataFrame. The function itself looks as follow:
def move_date_by_days(init_date, roll=1, nwd_key=None, hol_key=None):
'''
moves date by n-number of working days forward or backward
init_date: date, initial caluclation date
roll: integer, number of days to move forward (+) or backward (-)
nwd_key: string that stands for currency iso code, it is a key in non_working_days dictionary
hol_key: string that stands for currency iso code, it is a key in holidays dictonary
return: date
'''
nwd = non_working_days.get(nwd_key, [])
hol = holidays.get(hol_key,[])
moved_date = init_date + datetime.timedelta(days=roll)
if (moved_date.isoweekday() in nwd) or (moved_date in hol):
if roll >= 0:
moved_date=move_date_by_days(init_date + datetime.timedelta(days=1), roll=roll, nwd_key=nwd_key, hol_key=hol_key)
else:
moved_date=move_date_by_days(init_date + datetime.timedelta(days=-1), roll=roll, nwd_key=nwd_key, hol_key=hol_key)
return moved_date
Now, I have DataFrame 'df' with the columns 'start_date' and 'end_date'
start_date end_date
0 2020-01-31 2020-04-30
1 2020-04-30 2020-07-31
2 2020-07-31 2020-10-31
3 2020-10-31 2020-11-28
and I would like to create the third column named 'fixing' that would be 2 working days before 'start_date'. I am trying this:
dates_table['fixing'] = move_date_by_days(self.dates_table['start_date'], -2, self.ccy, self.ccy)
but it returns AttributeError: 'Series' object has no attribute 'isoweekday'
Please note the function works fine when I refer to scalar data of the DataFrame, for instance
d1 = s1.dates_table.iat[0,0]
move_date_by_days(d1, -2, 'pln', 'pln')
it returns what I have expected: datetime.date(2020, 1, 29)
Any hint how could I use the function on the whole column of the data frame, please?
IIUC, why not use offsets.BDay
or offsets.CustomBusinessDay
which takes a list of holidays
:
df['fixing'] = df['start_date'] - pd.offsets.BDay(2)
df['fixing'] = df['start_date'] - pd.offsets.CustomBusinessDay(2, holidays=holidays['pln'])
[out]
start_date end_date fixing
0 2020-01-31 2020-04-30 2020-01-29
1 2020-04-30 2020-07-31 2020-04-28
2 2020-07-31 2020-10-31 2020-07-29
3 2020-10-31 2020-11-28 2020-10-29
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加