top of page

Web Scrapping Nse Option Chain

The NSE has a website that displays the option chain in near real-time. This program retrieves this data from the NSE site and then generates a useful analysis of the Option Chain for the specified Index.


import requests
import pandas as pd
url = 'https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY'
headers = {
           'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36' ,
           'accept-encoding': 'gzip, deflate, br',
           'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8'
}

Open Chrome and go to:


https://www1.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp


Press Ctrl+U to view the source.


session = requests.Session()
request = session.get(url, headers=headers)
cookies = dict(request.cookies)
response = session.get(url, headers=headers, cookies=cookies).json()
rawdata = pd.DataFrame(response)
rawop = pd.DataFrame(rawdata['filtered']['data'])
print(rawop)
pd.set_option("display.max_rows", None)
pd.set_option('display.max_columns',20)
print(pd)

Setting up data frame:


def dataframe(ramp):
    data = []
    for i in range(0, len(rawop)):
        calloi = callcoi = cltp = putcoi = pltp = 0
        stp = rawop['strikePrice'][i]
        if(rawop['CE'][i]==0):
            calloi = callcoi = 0
        else:
            calloi = rawop['CE'][i]['openInterest']
            cltp = rawop['CE'][i]['lastPrice']
        if (rawop['PE'][i] == 0):
            putoi = putcoi = 0
        else:
            pltp = rawop['PE'][i]['lastPrice']
            putoi = rawop['PE'][i]['openInterest']

        opdata = {
            'CALL OI' : calloi, 'CALL LTP': cltp, 'STRIKE PRICE': stp,
            'PUT LTP' : pltp, 'PUT OI': putoi
        }
        data.append(opdata)
    optionchain = pd.DataFrame(data)
    
    return optionchain
optionchain = dataframe(rawop)
print(optionchain)


Output: