Fetch Free NSE Options and Futures Historical Data for Free

The Significance of Free Historical Data:

Forget just guts, conquering the Indian markets with options and Futures demands historical data: your fuel for backtesting, optimizing, and analyzing every move. But let’s be honest, paid data feels like feeding cash to a flickering chart.
We all crave strategy backtesting, but not everyone can stomach pricey historical data. While stocks and futures data might be within reach, options data lurks behind a paywall, absent on NSE and other sources. But today, that wall crumbles! In This post, we will see how you can fetch historical options and futures data for the Indian stock market for Free!

Fetch Free Historical Data for NSE Options and Futures

How To Fetch Data:

While numerous open-source GitHub libraries like Nse-Py or Nse Bhavcopy exist for fetching historical data, they often fall short regarding weekly options historical data—a crucial dataset. In this guide, I’ll introduce you to a distinct method using an API developed by Bytesmith, a Twitter user. The data, hosted on the Python trader server, provides access to a broader spectrum, including weekly options. let us dig into the world of enhanced data retrieval and explore the Python Trader Telegram channel, a valuable resource for newcomers venturing into algo trading. Check out their Telegram channel for invaluable insights  and Help regarding algo trading Projects.

 Fetching historical data via this API requires a basic understanding of Python. To get started, you’ll need to initialize the code, enabling seamless data retrieval from the specified URL whenever requested.

The Code Is Given Below:

				
					from __future__ import annotations
from time import sleep
from typing import List
from requests.sessions import Session
from requests.exceptions import RequestException
from pandas import json_normalize  # Import directly from pandas

URL: str = "https://stagingapi.pythontrader.in/hdata"

				
			

Fetching NSE weekly options Historical Data:

In this example, I’ll guide you through fetching weekly options data. Let’s define a historical symbol, ‘NIFTY23D2120000CE,’ representing a Nifty Call option with a strike price of 20,000 and a weekly expiry date of 21 December 2023.

				
					tradingsymbols: List[str] = [
    "NIFTY23D2120000CE"
]

s = Session()
				
			
				
					data_list = []

for tradingsymbol in tradingsymbols:
    try:
        resp = s.get(URL, params={"tradingsymbol": tradingsymbol})
    except RequestException as exception:
        print(f"{exception=}")
    else:
        json_data = resp.json()
        if json_data["success"]:
            data_list.extend(json_data["data"])  # Extend the list with the data
            print(
                tradingsymbol,
                json_data["data"],
                sep="\n",
                end="\n\n",
            )
    finally:
        sleep(0.5)
				
			

The Response Of this code Below:

Fetch NSe Weekly Options Historical Data Free

Fetching NSE Futures Historical Data:

For Futures Data we have to Define Our Future Symbol Like This: 

				
					tradingsymbols: List[str] = ["NIFTY23DECFUT"]

				
			

To Convert this data in pandas Dataframe you can use this code. The Response in pandas Dataframe Shown  Below:

				
					if data_list:
    df = pd.DataFrame(data_list)
    print("DataFrame:")
    print(df)
else:
    print("No data to create DataFrame.")
				
			
Fetch Nifty Futures Historical Data For Free

it’s crucial to note that when fetching NSE historical data for free, defining symbols for a specific expiry is essential. In the presented example, I demonstrated the process using a single symbol (‘NIFTY23D2120000CE’). However, for comprehensive backtesting of your algo trading strategy, you’ll need to fetch data for multiple symbols related to the desired expiry.

Final Thoughts:

As we conclude this exploration into fetching NSE historical data for free. The method we’ve discussed offers a unique approach, particularly for accessing weekly options data.

For more in-depth discussions on algo trading, and data analysis, be sure to check out my other blogs. I have a Blog Where I showed how you can convert Tick Data To candlestick(OHLC) Using WebSocket Live Feed, So don’t forget to check out this post also. Continuously increasing your knowledge base is key to staying ahead in the dynamic world of financial markets, Yesterday I saw a post from a fund manager stopping his fund and returning investment to its shareholders because he thinks he lost his edge in the market so continuously learning new trends in the market is important. Happy trading!