I'm trying to get the previous trading day in relation to a given trading day. To start I am simply trying to make a function which returns the previous business day when given a date, like so:
import datetime
def get_previous_trading_day(day):
day = pd.to_datetime(day)
previous_trading_day = day - datetime.timedelta(days=1)
return previous_trading_day
But when I call my function and print the current vs previous date, the previous date is not the previous day:
2021-05-01 curr
1885-02-22 00:00:00 prev
How do I make this work?
CodePudding user response:
If you change the calculation to use pd.tseries.offsets.BDay
instead, you will get the previous business day (instead of the day before). I realise this will not work for bank holidays where no trading occurs. Your function works well when I try it for returning the previous day's date.
def get_previous_trading_day(day):
day = pd.to_datetime(day)
previous_trading_day = day - pd.tseries.offsets.BDay(1)
return previous_trading_day
Calling the function for tomorrow's date will return Friday's date:
get_previous_trading_day("2022-05-16")
#Out: Timestamp('2022-05-13 00:00:00')
For your returned date, you may have put a date format that was not read correctly by the pd.to_datetime
. If you require a specific format, add the kwarg format=
to this.