How to Install Python on Windows 10

Do you want to learn how to install Python 3.10 on Windows 10 Computer in depth so you can install it in any computer without help. Then, you are at the right place, just keep reading till the end and you will be able to do it yourself. What is Python? Python is a powerful, […]

Continue reading...

Recent Post

31 May 2025

How to Create a Virtual Machine in VirtualBox and Install Ubuntu

Continue reading

Featured Post

25 May 2023

How to Fetch Stock’s Historical Data From NSE India in Python

Continue reading

If you’re an algorithmic trader, data analyst, or finance enthusiast looking to retrieve Futures and Options (F&O) data directly from the NSE India website, this guide is for you! Below, we’ll walk through a Python script that does exactly that — including how it works and how to use it and at the end you will be able to fetch future and option data of any index or stock from NSE India in python.

Prerequisites

Before we dive into the code, ensure you should have Python 3.8+ installed with the following Python packages:

pip install pandas requests

What Does the Script Do?

The script uses the NSE India F&O historical API to fetch:

  • Futures or Options data
  • For any stock or index (like NIFTY, BANKNIFTY, RELIANCE, etc.)
  • For a specified date range, strike price, and expiry

Step-by-Step Breakdown of the Script

Step 1: Import Required Libraries

import pandas as pd
import requests
from datetime import datetime, timedelta
  • pandas: For handling data as DataFrames
  • requests: To send HTTP requests to the NSE website
  • datetime: For managing dates

Step 2: Initialize the NSE Session

class IndexReport:
    def __init__(self) -> None:
        self.base_url = 'https://www.nseindia.com'
        self.session = requests.sessions.Session()
        self.session.headers['User-Agent'] = 'Mozilla/5.0 ...'
        self.session.get(self.base_url, timeout=10)
  • NSE’s site requires a valid user-agent header to prevent blocking.
  • A session is created and the homepage is visited to initiate cookies.

Step 3: Define the Data Fetching Method

def fetch_historical_index_data(self, instrumentType, symbol, ...)

This method dynamically constructs the NSE API URL based on parameters like:

  • instrumentType: 'OPTIDX' (Options Index), 'FUTSTK' (Futures Stock), etc.
  • symbol: The name of the index or stock (e.g., 'NIFTY', 'RELIANCE')
  • optionType: 'PE' for Put, 'CE' for Call (only required for options)
  • strikePrice: Specific strike price (optional)
  • expiryDate: Contract expiry date (important for options)
  • from_date, to_date: Date range for historical data

Note: If no from_date is given, it automatically sets it to yesterday (or last trading day).

Step 4: Build the URL & Make Request

res = self.session.get(self.base_url + api_url, timeout=10)
  • Sends a GET request to the API endpoint.
  • Parses the JSON response into a DataFrame using pd.json_normalize.

Step 5: Running the Script

if __name__ == '__main__':
    ir = IndexReport()
    df = ir.fetch_historical_index_data(
        instrumentType='OPTIDX',
        symbol='NIFTY',
        optionType='PE',
        expiryDate='10-Aug-2023'
    )
    print(df)
    print(df.iloc[0])

This example fetches Put Options data for NIFTY expiring on 10-Aug-2023.

Sample Output

You’ll see tabular data printed to your console, like:

      DATE    SYMBOL  OPEN_PRICE  HIGH_PRICE  LOW_PRICE  ...
0  2023-08-09  NIFTY       100.5      120.0       95.0   ...

Now you can further analyze, save, or visualize this data as per your need.

Customize the Call

Here are some useful options you can play with:

ParameterExampleDescription
instrumentType'OPTSTK', 'FUTIDX'Type of contract
symbol'BANKNIFTY', 'RELIANCE'Stock or Index symbol
optionType'CE', 'PE'Call or Put (for options only)
strikePrice17000Strike price (optional for filters)
year2023Filter by year (optional)
expiryDate’10-Aug-2023′Expiry date in 'DD-MMM-YYYY' format

Troubleshooting

  • Make sure your system is connected to the internet.
  • If you get HTTP errors, try changing the user-agent string.
  • NSE may block automated access — avoid too many requests in short time.

The Complete Source Code

With this single python script you should be able to fetch future and option data of any index or stock from NSE India without any issue.

Conclusion

With this simple and efficient Python script, you can pull rich F&O data from NSE directly for your trading analysis, dashboards, or ML models. Feel free to customize and expand the script for:

  • Auto-fetching multiple expiry dates
  • Saving to CSV
  • Visualizing open interest and volume

If you are interest in more guides related to trading, you can visit here trading.

And for more python guides visit here Python.

You can explore more informative videos at my YouTube Channel.



About

In TutLogic, we want to share our knowledge with all of the Internet community and welcome your feedback as well. Whether you want to learn with videos or textual articles, it is all available for everyone at tutlogic.com and at our YouTube Channel.