Market Data & Web Scraping
Advanced
Fetch Live NSE India Option Chain Data (PCR & Max Pain) in Python
Python script using requests session cookies to fetch live NSE Nifty/BankNifty Option Chain JSON, calculate Put-Call Ratio (PCR), and identify Max OI strikes.
#requests#pandas
Problem Statement
Direct `requests.get()` calls to NSE India's option chain API return 401/403 blocks unless browser session cookies are initialized first. This script establishes a valid session and parses CE/PE Open Interest.
Formula / Core Logic
Total PCR = Sum(PE_Open_Interest) / Sum(CE_Open_Interest)
Highest Call OI Strike acts as immediate statistical resistance; Highest Put OI acts as support.
Installation
pip install requests pandas
nse-india-option-chain-scraper-python-script.py
import requests
import pandas as pd
def fetch_nse_option_chain(symbol='NIFTY'):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
session = requests.Session()
session.get('https://www.nseindia.com', headers=headers, timeout=10)
url = f'https://www.nseindia.com/api/option-chain-indices?symbol={symbol}'
resp = session.get(url, headers=headers, timeout=10).json()
rows = []
for item in resp['records']['data']:
strike = item['strikePrice']
ce_oi = item.get('CE', {}).get('openInterest', 0)
pe_oi = item.get('PE', {}).get('openInterest', 0)
rows.append({'Strike': strike, 'CE_OI': ce_oi, 'PE_OI': pe_oi})
df = pd.DataFrame(rows)
pcr = round(df['PE_OI'].sum() / max(1, df['CE_OI'].sum()), 2)
return df, pcr
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: How often should I poll the NSE endpoint?
Poll no more than once every 60 to 120 seconds to avoid IP rate-limiting, as exchange OI updates every 3 minutes.