How to pull NSE option chain data into Python
You can import NSE (National Stock Exchange of India) option chain data into Python using the nsetools library, which connects directly to NSE's public data without requiring API keys. The most straightforward approach is to install nsetools, import the NSE class, and call the get_option_chain() method with a stock symbol — this returns a dictionary containing strike prices, call and put volumes, open interest, and implied volatility for each expiration date.
If nsetools is unavailable or outdated, you can fetch the same data by making HTTP requests to NSE's website directly using the requests library and parsing the JSON response. Both methods store the data in a format Python can work with — usually a dictionary or pandas DataFrame — so you can filter, calculate, or export it for further analysis.
Key Takeaways
- The nsetools library is the fastest way to get option chain data; install it with pip install nsetools and call get_option_chain() with a stock symbol.
- NSE's website returns data as JSON, which you can parse with the requests library if you prefer to avoid third-party packages or need more control over the request.
- Option chain data includes strike price, call and put open interest, implied volatility, and bid-ask spreads for each expiration date.
- Store the data in a pandas DataFrame to filter by strike range, expiration date, or Greeks, then export to CSV or Excel for spreadsheet analysis.
- NSE updates option chain data during market hours; requests made outside 9:15 AM to 3:30 PM IST may return incomplete or stale data.
Using nsetools to fetch option chain data
Install nsetools from the command line using pip, then import the NSE class and call get_option_chain() with the stock symbol as a string. For example, to fetch option data for Reliance Industries (RELIANCE), write:
from nsetools import NSE nse = NSE() data = nse.get_option_chain('RELIANCE')
The method returns a dictionary where the key 'records' holds a list of dictionaries, each representing one strike price. Each strike includes the call side (CE) and put side (PE) data: open interest, volume, implied volatility, bid price, ask price, and Greeks if available. The data also includes the expiration date, usually the last Thursday of the month.
To convert this into a pandas DataFrame for easier filtering and analysis, loop through the records and extract the fields you need. Create a list of dictionaries with columns for strike price, call open interest, put open interest, call IV, put IV, and any other metrics, then pass the list to pd.DataFrame(). This structure lets you sort by strike, filter by IV range, or calculate spreads between call and put prices.
Fetching data directly from NSE's website
If nsetools is not available or you need more control over the request, you can fetch option chain data directly from NSE's servers using the requests library. NSE publishes option chain JSON at a URL that includes the stock symbol and expiration date. The URL format is:
https://www.nseindia.com/api/option-chain-equities?symbol=RELIANCE&expiryDate=29-AUG-2024
Use the requests library to fetch this URL, then parse the JSON response. You will need to set a User-Agent header because NSE blocks requests that do not identify themselves as a browser. A minimal example looks like:
import requests import json headers = {'User-Agent': 'Mozilla/5.0'} url = 'https://www.nseindia.com/api/option-chain-equities?symbol=RELIANCE&expiryDate=29-AUG-2024' response = requests.get(url, headers=headers) data = response.json()
The response includes the same fields as nsetools: strike price, call and put open interest, volume, implied volatility, and bid-ask prices. You can then convert the 'records' list into a DataFrame the same way as before. This approach is useful if you want to fetch data for multiple expiration dates in a loop or if you need to customize the request headers.
Converting option chain data to a pandas DataFrame
Once you have the raw data, create a DataFrame to organize it by columns. Extract the strike price, call side data, and put side data from each record, then build a list of dictionaries with clear column names:
import pandas as pd rows = [] for record in data['records']: if 'CE' in record and 'PE' in record: rows.append({ 'Strike': record['strikePrice'], 'Call_OI': record['CE']['openInterest'], 'Call_IV': record['CE']['impliedVolatility'], 'Put_OI': record['PE']['openInterest'], 'Put_IV': record['PE']['impliedVolatility'], }) df = pd.DataFrame(rows)
This creates a DataFrame with one row per strike price and columns for each metric. You can now filter by strike range using df[df['Strike'] >= 2000], sort by open interest, or calculate the put-call ratio by dividing put open interest by call open interest. If you want to add more columns like bid price, ask price, or Greeks, extract them the same way from the 'CE' and 'PE' dictionaries.
Filtering and analyzing the data
Once the data is in a DataFrame, you can filter for specific strike ranges, expiration dates, or volatility levels. For example, to find all strikes where call open interest exceeds 100,000, write:
high_oi_calls = df[df['Call_OI'] > 100000]
To calculate the put-call ratio (a measure of market sentiment), divide put open interest by call open interest for each strike:
df['PCR'] = df['Put_OI'] / df['Call_OI']
You can also identify support and resistance levels by finding strikes with the highest open interest — these are often where traders cluster their positions. Sort the DataFrame by call open interest in descending order and look at the top 5 or 10 strikes. For volatility analysis, compare call IV and put IV across strikes to see where the market expects the most price movement.
Saving option chain data to a file
Export your DataFrame to CSV or Excel so you can open it in a spreadsheet or use it in other programs. To save as CSV, use:
df.to_csv('reliance_options.csv', index=False)
To save as Excel with formatting, use:
df.to_excel('reliance_options.xlsx', index=False, sheet_name='Options')
If you are collecting data over multiple days, add a timestamp column before saving so you can track how open interest and volatility change over time. This lets you build a historical record and spot trends — for example, whether open interest is rising or falling as expiration approaches, or whether implied volatility is climbing before earnings announcements.
Handling errors and timing issues
NSE updates option chain data only during market hours (9:15 AM to 3:30 PM IST on trading days). If you request data outside these hours, the API may return incomplete data, stale data from the previous close, or an error. Wrap your request in a try-except block to catch connection errors or JSON parsing failures:
try: data = nse.get_option_chain('RELIANCE') except Exception as e: print(f"Error fetching data: {e}")
If you are automating data collection, schedule your script to run only during market hours. If you need to fetch data for a past expiration date, NSE does not keep historical option chain snapshots in the same format, so you will need to either store snapshots yourself as you collect them or use a paid data provider that archives this information.
Frequently Asked Questions
What is the difference between nsetools and fetching data directly from NSE?
nsetools is a wrapper that handles the HTTP request and JSON parsing for you, so you write less code. Fetching directly gives you more control over headers and error handling, and works if nsetools is outdated or unavailable. Both return the same data from NSE's servers.
Can I get historical option chain data from NSE?
NSE does not publish historical option chain snapshots through its public API. You must collect and store snapshots yourself during market hours if you want a historical record. Some paid data providers like NSE's own DataCenter or third-party vendors archive this data.
What do the CE and PE fields mean?
CE stands for Call European (call option), and PE stands for Put European (put option). Each strike price has both a call side and a put side, with separate open interest, volume, implied volatility, and bid-ask prices for each.
How do I get the Greeks (delta, gamma, theta, vega)?
NSE's public API does not include Greeks. You can calculate them yourself using a Black-Scholes model library like mibian or py_vollib, or fetch pre-calculated Greeks from a paid data provider.
Why am I getting an error when I request data outside market hours?
NSE updates option chain data only during trading hours. Requests outside 9:15 AM to 3:30 PM IST may fail or return stale data. Schedule your script to run during market hours, or add error handling to skip requests when the market is closed.