<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=35476375865279447&ev=PageView&noscript=1"/>
Back to Blog
PythonNSE APIOption ChainAutomationData Tools

NSE Option Chain Data with Python: Automate Your Analysis in 30 Lines

T

Team MarketNetra

11 May 2026

9 min read
NSE Option Chain Data with Python: Automate Your Analysis in 30 Lines

Fetching nse option chain data python is the single most valuable automation skill an Indian derivatives trader can build today. The NSE option chain page — the one you manually refresh twenty times a session — contains real-time open interest, IV, bid-ask spreads, and volume across every strike. Yet most retail traders still eyeball it in a browser, missing shifts that happen in seconds. That's a structural disadvantage against algo desks that parse this data programmatically every 3-5 seconds.

This guide gives you a working Python script — under 30 lines — that pulls the full NIFTY or BANKNIFTY option chain from NSE, parses it into a clean DataFrame, and sets you up to layer your own analysis on top. No paid API. No scraping libraries that break every week. Just clean, repeatable code that works as of 2024-25.

If you've ever wanted to automate nse option chain data extraction python api india style, without depending on third-party vendors, read every section below.

Why the NSE Option Chain Matters More Than Price Charts

The option chain is the market's order book for derivatives. On any given expiry day, NIFTY options alone see 40-80 crore contracts in combined volume. That volume concentrates at specific strikes — and the distribution of open interest across those strikes tells you where institutional money expects support and resistance.

Here's a concrete example. On 23 May 2024, NIFTY 23,500 PE had open interest of 1.12 crore contracts while 24,000 CE had 98 lakh. That OI wall at 23,500 on the put side and 24,000 on the call side defined the week's range almost perfectly — NIFTY traded between 23,480 and 23,870. No indicator on a candlestick chart gave you that information. The option chain did.

When you pull this data into Python, you can:

  • Track OI change every 3 minutes to see real-time positioning shifts
  • Calculate the PCR (Put-Call Ratio) at every strike, not just the aggregate
  • Identify max pain — the strike at which option writers lose the least
  • Flag unusual OI build-up that signals institutional activity
  • Build alerts for sudden IV spikes at specific strikes

Doing any of this manually is impractical. Doing it in Python takes 30 lines.

How NSE Serves Option Chain Data (and Why Most Scrapers Break)

NSE's website at https://www.nseindia.com/option-chain renders data client-side using JavaScript. If you try a naive requests.get() on that URL, you get an empty HTML shell — no data. This is why beginners think they need Selenium or Playwright.

They don't. NSE exposes a JSON API endpoint that the frontend itself calls:

https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY

For stock options (say RELIANCE or HDFCBANK), the endpoint is:

https://www.nseindia.com/api/option-chain-equities?symbol=RELIANCE

The catch: NSE requires a valid session cookie. You can't hit the API cold. You need to first visit the main NSE page, capture the cookies, and then use those cookies for your API call. This is why most quick scripts break — they skip the session step.

Here's the other thing to know: NSE rate-limits aggressively. Hit the API more than ~3-4 times per minute from the same IP without proper headers, and you'll get a 403 or a CAPTCHA redirect. Your code needs to respect this.

NSE Option Chain Data Python: The 30-Line Script

Below is a complete, working script. It handles session cookies, sets proper headers (mimicking a browser), fetches the NIFTY option chain, and loads it into a pandas DataFrame.

import requests
import pandas as pd

url_main = "https://www.nseindia.com"
url_oc = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language": "en-US,en;q=0.9",
    "Accept-Encoding": "gzip, deflate, br",
}

session = requests.Session()
session.headers.update(headers)
session.get(url_main, timeout=10)  # grab cookies

response = session.get(url_oc, timeout=10)
data = response.json()

records = data["records"]["data"]
current_expiry = data["records"]["expiryDates"][0]  # nearest expiry

rows = []
for rec in records:
    if rec["expiryDate"] == current_expiry:
        strike = rec["strikePrice"]
        ce = rec.get("CE", {})
        pe = rec.get("PE", {})
        rows.append({
            "strike": strike,
            "ce_oi": ce.get("openInterest", 0),
            "ce_chg_oi": ce.get("changeinOpenInterest", 0),
            "ce_ltp": ce.get("lastPrice", 0),
            "ce_iv": ce.get("impliedVolatility", 0),
            "pe_oi": pe.get("openInterest", 0),
            "pe_chg_oi": pe.get("changeinOpenInterest", 0),
            "pe_ltp": pe.get("lastPrice", 0),
            "pe_iv": pe.get("impliedVolatility", 0),
        })

df = pd.DataFrame(rows)
print(df.to_string(index=False))

That's 30 lines. Run it during market hours (9:15 AM – 3:30 PM IST) and you get a clean table with strike prices, CE/PE open interest, OI change, last traded price, and implied volatility for the nearest NIFTY expiry.

Adapting for BANKNIFTY or Stock Options

Change one line. For BANKNIFTY:

url_oc = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"

For HDFCBANK stock options:

url_oc = "https://www.nseindia.com/api/option-chain-equities?symbol=HDFCBANK"

BANKNIFTY has a lot size of 15 (revised from 25 in November 2024). NIFTY lot size is 75 (revised from 50). When you're calculating notional OI value, multiply the OI in contracts by lot size and then by the strike price. This gives you the rupee exposure at each strike — a far more useful metric than raw OI count.

Practical Analysis You Can Build on Top

Once you have the DataFrame, you're 5-10 lines away from actionable intelligence.

Max Pain Calculation

Max pain is the strike where total loss for option buyers (and therefore total profit for writers) is maximized. The formula: for each strike, calculate the total intrinsic value payable to all CE holders and all PE holders across all strikes, weighted by OI. The strike with the minimum total payout is max pain.

underlying = data["records"]["underlyingValue"]  # e.g., 24350.0
total_pain = []
for s in df["strike"]:
    ce_pain = df[df["strike"] < s].apply(lambda r: (s - r["strike"]) * r["ce_oi"], axis=1).sum()
    pe_pain = df[df["strike"] > s].apply(lambda r: (r["strike"] - s) * r["pe_oi"], axis=1).sum()
    total_pain.append({"strike": s, "pain": ce_pain + pe_pain})
max_pain_strike = pd.DataFrame(total_pain).sort_values("pain").iloc[0]["strike"]
print(f"Max Pain: {max_pain_strike}")

On a typical weekly expiry, NIFTY settles within 50-80 points of max pain roughly 60-65% of the time. That's not a guarantee — but it's a statistical edge worth knowing.

PCR at Each Strike

df["pcr"] = df["pe_oi"] / df["ce_oi"].replace(0, 1)

A PCR above 1.0 at a strike means more puts are written there than calls — typically a support zone. Below 0.7, it's a resistance zone. Watch for strikes where PCR flips from below 0.7 to above 1.0 intraday — that signals a sentiment shift institutional desks are acting on.

OI Change Heatmap

Sort by ce_chg_oi and pe_chg_oi to see where fresh positions are being built today. A large positive pe_chg_oi at a strike 200 points below the current NIFTY level, combined with rising premium, means fresh put writing — a bullish signal. The same OI build with falling premium means fresh put buying — bearish.

This distinction between writing and buying is critical and gets lost when you just look at OI numbers on the NSE website.

Scheduling and Rate Limit Best Practices

You'll want to run this script every 3-5 minutes during market hours. Use time.sleep(180) in a loop, or schedule via cron (Linux) or Task Scheduler (Windows).

Key rules to avoid getting blocked by NSE:

  • Never poll faster than once per 3 minutes. NSE's own website refreshes roughly every 3 minutes.
  • Rotate User-Agent strings if you're running multiple scripts.
  • Handle 403 errors gracefully. If you get a 403, wait 60 seconds, create a fresh session, and retry.
  • Don't run outside market hours expecting real-time data. NSE serves stale end-of-day data after 3:30 PM. The JSON structure remains the same, but values freeze.

For production use, log each pull to a local SQLite database or CSV. This gives you historical intraday OI data — something NSE doesn't provide publicly and data vendors charge ₹2,000-5,000/month for.

What SEBI's New Rules Mean for Option Chain Analysis

SEBI's October 2024 circular on derivatives reform changed several things relevant to option chain analysis:

  • Weekly expiries reduced to one benchmark per exchange. Only NIFTY weekly on NSE, SENSEX weekly on BSE. BANKNIFTY, FINNIFTY, and MIDCPNIFTY weeklies are gone. This concentrates OI into fewer expiries, making your option chain analysis more reliable since liquidity isn't fragmented.
  • Increased lot sizes. Higher lot sizes (NIFTY at 75, BANKNIFTY at 15) mean each contract represents more notional value. OI numbers will look smaller, but each unit carries more weight.
  • Upfront collection of option premium. This reduces speculative long positions, making OI data a cleaner signal of genuine positioning.

These changes actually make the nse option chain data python approach more valuable, not less. Cleaner data, more concentrated liquidity, fewer noise traders.

What to Actually Do This Week

  1. Copy the 30-line script above. Run it once. Verify you get a clean DataFrame with 20-40 strikes for the nearest NIFTY expiry.
  2. Add max pain and PCR calculations. Compare max pain to NIFTY's actual close for the next three weekly expiries. Track accuracy.
  3. Set up a 3-minute polling loop. Save each snapshot to a CSV with a timestamp column. After one week, you'll have intraday OI flow data that most retail traders never see.
  4. Watch for OI change divergence. When NIFTY is rising but call OI is increasing faster than put OI at ATM strikes, it often signals a short-term top forming. Your DataFrame makes this trivial to spot.
  5. Extend to BANKNIFTY and 2-3 stock options (RELIANCE, HDFCBANK, TATAMOTORS are the most liquid). Compare OI patterns across them for sector-level insight.

The edge isn't in having the data. Every trader can open nseindia.com. The edge is in having the data structured, timestamped, and analyzed before your next trade decision.

If you're building this kind of data pipeline yourself, you're already ahead of 90% of retail participants. But raw data still needs interpretation — knowing which OI shift matters at which market context is where real alpha lives. That's exactly the kind of AI-driven signal layering that MarketNetra is built to deliver: structured market intelligence that turns raw NSE data into actionable trading decisions, so you spend less time coding and more time executing.

Ready to trade smarter?

Get AI-powered market analysis for NIFTY, BANKNIFTY, and 200+ F&O stocks.

Start for ₹1 →