To run any options based trading system we need the tradingsymbol for the latest expiring call and put options.
The format for weekly expiring options is: BANKNIFTY<YY><M><DD>strike<PE/CE>
Where M is given as 1 for JAN, 2 for FEB, 3, 4, 5, 6, 7, 8, 9, O(capital o) for October, N for November, D for December
With the help of Nsepython module we can get the latest expiry date for the option as:
from nsepython import *
import calendar
from datetime import datetime, timedelta
now = datetime.now()
expiry = (expiry_list('BANKNIFTY'))
print(expiry)
Upon running the above code we get the expiry details as:

The next part of the code is as follows:
curr_expiry = expiry[0]
#The monthrange() method is used to get weekday of first day of the month
# and number of days in month, for the specified year and month.
last_day_of_month = calendar.monthrange(now.year,now.month)[1]
today = datetime.today()
last = today.replace(day=last_day_of_month)
ab = now.isocalendar()
cd = last.isocalendar()
index = (nse_index())
next_thur = (today + timedelta( (3-today.weekday()) % 7 )).day
#print(next_thur)
month = calendar.monthcalendar(datetime.today().year, datetime.today().month)
last_thu = max(month[-1][calendar.THURSDAY], month[-2][calendar.THURSDAY])
#print(last_thu)
if ( ( next_thur == last_thu) or (now.isocalendar()[1] == (last.isocalendar()[1]) and (now.isoweekday() == 3)) ):
option = ("BANKNIFTY21" + (str(now.strftime('%b')).upper()))
#print(str(option))
else:
datetime_object = datetime.strptime(curr_expiry, '%d-%b-%Y')
date_string = datetime_object.strftime("%y%#m%d")
option = ("BANKNIFTY" + date_string)
#print(str(option))
with open('expiry_details.txt', 'w') as file:
file.write(option)
Finally we can save the expiry details to a text file.

For October, November and December we need to use different format: O(capital o) for October, N for November, D for December.
So we can add the following blocks to the above code
m = datetime_object.strftime(“%y%#b”)
option = (“BANKNIFTY” + m[0:3])
If you liked what i post here regularly then kindly subscribe and visit me at https://twitter.com/rahul_12gh
