Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Python Code for Generating Nifty Weekly Expiry Dates Using ChatGPT-4

2 min read

The National Stock Exchange of India (NSE) is one of the largest stock exchanges in the world, with Nifty being its flagship index. Nifty weekly options contracts have a significant impact on the Indian financial markets. These contracts expire on Thursdays, but if a holiday falls on a Thursday, the expiry date moves to the previous trading day. In this blog post, we will discuss how to generate Nifty weekly expiry dates for the year 2023 using Python, taking into account the list of holidays provided by the NSEIndia Portal.

Getting the NSE Holiday Calendar from the NSEIndia Portal. Copy the table content and prepare the following prompt.

2)Now open ChatGPT and ensure that you have access to chatgpt plus subscription to access gpt4 model

Now copy the following prompt and paste in your chatgpt.

List of Holidays in 2023

Here is the detailed share market holiday list 2023-

SR. NO DATE DAY DESCRIPTION
1	26-Jan-2023	Thursday	Republic Day
2	07-Mar-2023	Tuesday	Holi
3	30-Mar-2023	Thursday	Ram Navami
4	04-Apr-2023	Tuesday	Mahavir Jayanti
5	07-Apr-2023	Friday	Good Friday
6	14-Apr-2023	Friday	Dr. Baba Saheb Ambedkar Jayanti
7	01-May-2023	Monday	Maharashtra Day
8	28-Jun-2023	Wednesday	Bakri Id
9	15-Aug-2023	Tuesday	Independence Day
10	19-Sep-2023	Tuesday	Ganesh Chaturthi
11	02-Oct-2023	Monday	Mahatma Gandhi Jayanti
12	24-Oct-2023	Tuesday	Dussehra
13	14-Nov-2023	Tuesday	Diwali-Balipratipada
14	27-Nov-2023	Monday	Gurunanak Jayanti
15	25-Dec-2023	Monday	Christmas

Write a Python Code to Generate All Nifty Weekly Expiry Dates in a list for the year 2023.  
Nifty expiry is usually on Thursday Also check if the expiry day is a holiday in NSE Exchange 
if yes then use the previous trading day as an expiry day. 
Generate the Expriy date list in DD-MM-YYYY format. 

If thursday is a holiday then weekly expiry points to one day prior to the holiday
that needs to be factored in properly

Here is the following Python Code generated by chatGPT. Tried the same prompt with GPT3.5 show how the generated python code always ignored the thusday holidays while generating the code. But GPT4 recognized the context very well and generated the code at the very first attempt.

from datetime import datetime, timedelta

holidays = [
    "26-01-2023",
    "07-03-2023",
    "30-03-2023",
    "04-04-2023",
    "07-04-2023",
    "14-04-2023",
    "01-05-2023",
    "28-06-2023",
    "15-08-2023",
    "19-09-2023",
    "02-10-2023",
    "24-10-2023",
    "14-11-2023",
    "27-11-2023",
    "25-12-2023",
]

holidays = [datetime.strptime(h, "%d-%m-%Y") for h in holidays]

def generate_expiry_dates(year):
    expiry_dates = []
    start_date = datetime(year, 1, 1)
    end_date = datetime(year, 12, 31)

    while start_date.weekday() != 3:  # Find the first Thursday of the year
        start_date += timedelta(days=1)

    while start_date <= end_date:
        if start_date not in holidays:
            expiry_dates.append(start_date.strftime("%d-%m-%Y"))
        else:  # If Thursday is a holiday, use the previous trading day as expiry day
            adjusted_expiry_date = start_date - timedelta(days=1)
            while adjusted_expiry_date in holidays:
                adjusted_expiry_date -= timedelta(days=1)
            expiry_dates.append(adjusted_expiry_date.strftime("%d-%m-%Y"))
        start_date += timedelta(weeks=1)

    return expiry_dates

expiry_dates_list = generate_expiry_dates(2023)
print(expiry_dates_list)

Python Output

['05-01-2023', '12-01-2023', '19-01-2023', '25-01-2023', '02-02-2023', '09-02-2023', '16-02-2023',
 '23-02-2023', '02-03-2023', '09-03-2023', '16-03-2023', '23-03-2023', '29-03-2023', '06-04-2023',
 '13-04-2023', '20-04-2023', '27-04-2023', '04-05-2023', '11-05-2023', '18-05-2023', '25-05-2023', 
 '01-06-2023', '08-06-2023', '15-06-2023', '22-06-2023', '29-06-2023', '06-07-2023', '13-07-2023',
 '20-07-2023', '27-07-2023', '03-08-2023', '10-08-2023', '17-08-2023', '24-08-2023', '31-08-2023',
 '07-09-2023', '14-09-2023', '21-09-2023', '28-09-2023', '05-10-2023', '12-10-2023', '19-10-2023',
 '26-10-2023', '02-11-2023', '09-11-2023', '16-11-2023', '23-11-2023', '30-11-2023', '07-12-2023',
 '14-12-2023', '21-12-2023', '28-12-2023']

Code Explanation:

  • We import the necessary libraries, datetime and timedelta, for handling dates and time calculations.
  • We define the list of holidays and convert the holiday dates into datetime objects.
  • We create a function called generate_expiry_dates that takes a year as input and generates the Nifty weekly expiry dates for that year.
  • Inside the function, we first find the first Thursday of the year and loop through all Thursdays until the end of the year.
  • We check if the current Thursday is a holiday. If it’s not, we add it to the expiry_dates list. If it is, we find the previous trading day and add that to the list instead.
  • Finally, we generate the expiry dates for 2023 and print the list.
Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

How to Place Orders Concurrently using ThreadPoolExecutor – Python…

Creating concurrent orders is essential for active traders, especially those handling large funds, as it allows for executing multiple trade orders simultaneously, thereby maximizing...
Rajandran R
2 min read

Host your Python Flask Web Application using pyngrok and…

Ngrok offers several significant advantages for developers, especially when it comes to testing applications or hosting machine learning models. Ngrok allows you to expose...
Rajandran R
1 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More