What you need to import NSE option chain data into Python

To import NSE (National Stock Exchange of India) option chain data into Python, you will need three things: a data source that provides the data, a Python library that can fetch it, and a way to store or process it once it arrives. The most direct route is to use the nsetools library or the yfinance library, both of which can pull live or historical option data from NSE. You will also need Python 3.6 or later installed on your machine, along with pandas for organizing the data into tables.

NSE publishes option chain data through its website and through third-party APIs. The data includes strike prices, call and put premiums, open interest, and implied volatility for each contract. Some libraries fetch this data directly from NSE's servers, while others pull from financial data aggregators. The method you choose depends on whether you need real-time data, historical data, or both, and whether you want to write the data to a file or work with it in memory.

Key Takeaways

  • The nsetools library connects directly to NSE servers and requires no API key, but it can be slower than alternatives and may break if NSE changes its website structure.
  • yfinance pulls NSE data through Yahoo Finance and works reliably for historical data, though real-time option chain data through yfinance is limited compared to nsetools.
  • You will need to install the required library using pip, import it into your Python script, and specify the stock symbol and expiry date before fetching the data.
  • Once imported, pandas can reshape the data into a DataFrame, filter by strike price or Greeks, and export to CSV or Excel for further analysis.
  • Rate limiting and connection timeouts are common when fetching live data, so adding delays between requests and error handling prevents your script from crashing.

Installing nsetools and setting up your environment

The nsetools library is the most direct way to fetch NSE option chain data. Install it by opening your terminal or command prompt and typing pip install nsetools. This single command downloads the library and makes it available to any Python script on your machine. You will also need pandas for organizing the data, which you can install with pip install pandas. If you do not have pip installed, you likely need to install Python itself from python.org.

Once both libraries are installed, create a new Python file (for example, fetch_options.py) and add these lines at the top:

from nsetools import Nse import pandas as pd from datetime import datetime

These three import statements load the NSE connection tool, the data organization library, and the date handling tools you will need. If Python returns an error saying the module does not exist, go back and check that pip installed the libraries without errors.

Fetching option chain data for a specific stock

To fetch option chain data, you first create an NSE object and then call its option chain method with a stock symbol and expiry date. Here is the basic structure:

nse = Nse() option_chain = nse.get_option_chain('INFY', '27-JUN-2024') print(option_chain)

Replace 'INFY' with any NSE stock symbol (such as TCS, RELIANCE, HDFC, or WIPRO) and '27-JUN-2024' with an actual expiry date. NSE option contracts expire on the last Thursday of each month, so valid dates follow that pattern. If you use an invalid date, the library will return an error. You can find valid expiry dates by calling nse.get_option_chain_expiry_dates('INFY'), which returns a list of all available expiry dates for that stock.

The data returned is a dictionary, not a table. To make it readable and usable, convert it to a pandas DataFrame:

df = pd.DataFrame(option_chain['records']) print(df.head())

The head() method shows the first five rows. At this point you will see columns like strikePrice, expiryDate, CE (call option) data, and PE (put option) data, each with its own nested columns for premium, open interest, and Greeks.

Organizing nested option data into usable columns

NSE option chain data comes with nested structures — the call option data and put option data are each stored as dictionaries within the main record. To flatten this into separate columns you can actually work with, you need to unpack these nested dictionaries. Here is a function that does this:

def flatten_option_chain(option_chain):     records = []     for item in option_chain['records']:         strike = item['strikePrice']         ce = item.get('CE', {})         pe = item.get('PE', {})         records.append({             'strike': strike,             'ce_premium': ce.get('lastPrice', None),             'ce_oi': ce.get('openInterest', None),             'pe_premium': pe.get('lastPrice', None),             'pe_oi': pe.get('openInterest', None)         })     return pd.DataFrame(records)

Call this function with your option chain data: df = flatten_option_chain(option_chain). Now you have a clean table with strike prices in one column, call premiums in another, put premiums in another, and open interest for each. You can filter, sort, and export this table without wrestling with nested dictionaries.

Saving option data to a file

Once you have your data organized in a DataFrame, you can save it to a CSV file, Excel file, or JSON file. CSV is the most portable format and works with any spreadsheet program or data analysis tool:

df.to_csv('option_chain_infy.csv', index=False)

This creates a file called option_chain_infy.csv in the same folder as your Python script. The index=False argument prevents pandas from adding a row number column. If you prefer Excel, use df.to_excel('option_chain_infy.xlsx', index=False) instead — you may need to install openpyxl first with pip install openpyxl.

You can also add a timestamp to your filename so each run creates a new file instead of overwriting the old one:

timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') df.to_csv(f'option_chain_infy_{timestamp}.csv', index=False)

This creates filenames like option_chain_infy_20240627_143022.csv, making it easy to keep multiple snapshots of the data.

Handling errors and rate limits

NSE servers can be slow or temporarily unavailable, and fetching data too quickly in a loop can trigger rate limiting. Wrap your fetch calls in a try-except block to catch errors gracefully:

import time try:     option_chain = nse.get_option_chain('INFY', '27-JUN-2024') except Exception as e:     print(f'Error fetching data: {e}')     option_chain = None

If you are fetching data for multiple stocks or multiple expiry dates in a loop, add a delay between requests to avoid overwhelming the server:

symbols = ['INFY', 'TCS', 'WIPRO'] for symbol in symbols:     option_chain = nse.get_option_chain(symbol, '27-JUN-2024')     time.sleep(2) # Wait 2 seconds before the next request

A two-second delay between requests is usually safe and prevents connection timeouts. If you still get errors, increase the delay to three or four seconds. NSE does not publish official rate limits, but respecting these delays keeps your script stable and avoids getting temporarily blocked.

Using yfinance as an alternative

If nsetools is unreliable or you need historical option data, yfinance is a stable alternative. Install it with pip install yfinance and fetch data like this:

import yfinance as yf ticker = yf.Ticker('INFY.NS') options_dates = ticker.options opt_chain = ticker.option_chain(options_dates[0])

The .NS suffix tells yfinance to use NSE data. The options property returns all available expiry dates, and option_chain() fetches the data for a specific date. yfinance returns two DataFrames — one for calls and one for puts — which you can access with opt_chain.calls and opt_chain.puts.

yfinance is generally more stable than nsetools because it pulls from Yahoo Finance's infrastructure rather than directly from NSE servers. However, the data may lag by a few minutes, and some fields like Greeks (delta, gamma, theta) may not be available. For real-time data with full Greeks, nsetools is still the better choice despite its occasional instability.

Frequently Asked Questions

What is the difference between CE and PE in the data?

CE stands for Call European and PE stands for Put European. A call option gives the buyer the right to buy the stock at a set price; a put option gives the right to sell. The data for each includes the premium (price), open interest (number of contracts), and Greeks (delta, gamma, theta, vega) that measure how the option price changes with stock price, time, and volatility.

Why does my script crash with a connection error?

NSE servers are sometimes slow or temporarily unavailable, especially during market hours. Add a try-except block around your fetch call and increase the delay between requests if you are fetching multiple symbols. If errors persist, wait a few minutes and try again. You can also check NSE's website directly to confirm the data is available before troubleshooting your script.

Can I get historical option data, or only current data?

nsetools provides only current option chain data for the current trading day. yfinance can fetch historical option data, though the availability and completeness vary by stock. For deep historical analysis, you may need to store snapshots of the data yourself over time by running your script daily and appending results to a file.

How do I filter the data for specific strike prices?

Once your data is in a pandas DataFrame, use standard filtering: df[df['strike'] == 50] returns only rows where the strike price is 50, and df[(df['strike'] >= 45) & (df['strike'] <= 55)] returns a range. You can also filter by open interest, premium, or any other column using the same syntax.

Do I need an API key to use nsetools or yfinance?

No. Both libraries fetch data from public sources without requiring authentication. nsetools connects directly to NSE, and yfinance uses Yahoo Finance's public data. You can start using them immediately after installation with no registration or API key setup.