My question is different than the following:
Question1: Week of a month pandas Quesiton2: Week number of the month
The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.
My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.
My attempts has been the look ahead which isn't optimal:
def is_third_friday(s):
d = datetime.datetime.strptime(s, '%Y-%m-%d')
return d.weekday() == 5 and 15 <= d.day <= 21
dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True
I don't know how to provide some sample data
but if you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.
The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.
Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.