Home Backend Development Python Tutorial NSE Option Chain Data using Python - Part II | Shah Stavan

NSE Option Chain Data using Python - Part II | Shah Stavan

Aug 08, 2024 pm 06:35 PM

In a previous article, we discussed how to fetch Nifty and Bank Nifty data using Python. The response to that article was great, so due to popular demand, here’s an extended version. In this article, we'll learn how to fetch option chain data from the NSE website every 30 seconds. This is for learning purposes only.

In Python, we'll use asyncio to make an API request to NSE data every 30 seconds.

Install required libraries in Python

pip install aiohttp asyncio

Code

import aiohttp
import asyncio
import requests
import json
import math
import time


def strRed(skk):         return "\033[91m {}\033[00m".format(skk)
def strGreen(skk):       return "\033[92m {}\033[00m".format(skk)
def strYellow(skk):      return "\033[93m {}\033[00m".format(skk)
def strLightPurple(skk): return "\033[94m {}\033[00m".format(skk)
def strPurple(skk):      return "\033[95m {}\033[00m".format(skk)
def strCyan(skk):        return "\033[96m {}\033[00m".format(skk)
def strLightGray(skk):   return "\033[97m {}\033[00m".format(skk)
def strBlack(skk):       return "\033[98m {}\033[00m".format(skk)
def strBold(skk):        return "\033[1m {}\033[00m".format(skk)

def round_nearest(x, num=50): return int(math.ceil(float(x)/num)*num)
def nearest_strike_bnf(x): return round_nearest(x, 100)
def nearest_strike_nf(x): return round_nearest(x, 50)

url_oc      = "https://www.nseindia.com/option-chain"
url_bnf     = 'https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY'
url_nf      = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'
url_indices = "https://www.nseindia.com/api/allIndices"

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
            'accept-language': 'en,gu;q=0.9,hi;q=0.8',
            'accept-encoding': 'gzip, deflate, br'}

cookies = dict()

def set_cookie():
    sess = requests.Session()
    request = sess.get(url_oc, headers=headers, timeout=5)
    return dict(request.cookies)

async def get_data(url, session):
    global cookies
    async with session.get(url, headers=headers, timeout=5, cookies=cookies) as response:
        if response.status == 401:
            cookies = set_cookie()
            async with session.get(url, headers=headers, timeout=5, cookies=cookies) as response:
                return await response.text()
        elif response.status == 200:
            return await response.text()
        return ""

async def fetch_all_data():
    async with aiohttp.ClientSession() as session:
        indices_data = await get_data(url_indices, session)
        bnf_data = await get_data(url_bnf, session)
        nf_data = await get_data(url_nf, session)
    return indices_data, bnf_data, nf_data

# Process the fetched data
def process_indices_data(data):
    global bnf_ul, nf_ul, bnf_nearest, nf_nearest
    data = json.loads(data)
    for index in data["data"]:
        if index["index"] == "NIFTY 50":
            nf_ul = index["last"]
        if index["index"] == "NIFTY BANK":
            bnf_ul = index["last"]
    bnf_nearest = nearest_strike_bnf(bnf_ul)
    nf_nearest = nearest_strike_nf(nf_ul)

def process_oi_data(data, nearest, step, num):
    data = json.loads(data)
    currExpiryDate = data["records"]["expiryDates"][0]
    oi_data = []
    for item in data['records']['data']:
        if item["expiryDate"] == currExpiryDate:
            if nearest - step*num <= item["strikePrice"] <= nearest + step*num:
                oi_data.append((item["strikePrice"], item["CE"]["openInterest"], item["PE"]["openInterest"]))
    return oi_data

def print_oi_data(nifty_data, bank_nifty_data, prev_nifty_data, prev_bank_nifty_data):
    print(strBold(strLightPurple("Nifty Open Interest:")))
    for i, (strike, ce_oi, pe_oi) in enumerate(nifty_data):
        ce_change = ce_oi - prev_nifty_data[i][1] if prev_nifty_data else 0
        pe_change = pe_oi - prev_nifty_data[i][2] if prev_nifty_data else 0
        ce_color = strGreen(ce_oi) if ce_change > 0 else strRed(ce_oi)
        pe_color = strGreen(pe_oi) if pe_change > 0 else strRed(pe_oi)
        print(f"Strike Price: {strike}, Call OI: {ce_color} ({strBold(f'+{ce_change}') if ce_change > 0 else strBold(ce_change) if ce_change < 0 else ce_change}), Put OI: {pe_color} ({strBold(f'+{pe_change}') if pe_change > 0 else strBold(pe_change) if pe_change < 0 else pe_change})")

    print(strBold(strLightPurple("\nBank Nifty Open Interest:")))
    for i, (strike, ce_oi, pe_oi) in enumerate(bank_nifty_data):
        ce_change = ce_oi - prev_bank_nifty_data[i][1] if prev_bank_nifty_data else 0
        pe_change = pe_oi - prev_bank_nifty_data[i][2] if prev_bank_nifty_data else 0
        ce_color = strGreen(ce_oi) if ce_change > 0 else strRed(ce_oi)
        pe_color = strGreen(pe_oi) if pe_change > 0 else strRed(pe_oi)
        print(f"Strike Price: {strike}, Call OI: {ce_color} ({strBold(f'+{ce_change}') if ce_change > 0 else strBold(ce_change) if ce_change < 0 else ce_change}), Put OI: {pe_color} ({strBold(f'+{pe_change}') if pe_change > 0 else strBold(pe_change) if pe_change < 0 else pe_change})")

def calculate_support_resistance(oi_data):
    highest_oi_ce = max(oi_data, key=lambda x: x[1])
    highest_oi_pe = max(oi_data, key=lambda x: x[2])
    return highest_oi_ce[0], highest_oi_pe[0]

async def update_data():
    global cookies
    prev_nifty_data = prev_bank_nifty_data = None
    while True:
        cookies = set_cookie()
        indices_data, bnf_data, nf_data = await fetch_all_data()

        process_indices_data(indices_data)

        nifty_oi_data = process_oi_data(nf_data, nf_nearest, 50, 10)
        bank_nifty_oi_data = process_oi_data(bnf_data, bnf_nearest, 100, 10)

        support_nifty, resistance_nifty = calculate_support_resistance(nifty_oi_data)
        support_bank_nifty, resistance_bank_nifty = calculate_support_resistance(bank_nifty_oi_data)

        print(strBold(strCyan(f"\nMajor Support and Resistance Levels:")))
        print(f"Nifty Support: {strYellow(support_nifty)}, Nifty Resistance: {strYellow(resistance_nifty)}")
        print(f"Bank Nifty Support: {strYellow(support_bank_nifty)}, Bank Nifty Resistance: {strYellow(resistance_bank_nifty)}")

        print_oi_data(nifty_oi_data, bank_nifty_oi_data, prev_nifty_data, prev_bank_nifty_data)

        prev_nifty_data = nifty_oi_data
        prev_bank_nifty_data = bank_nifty_oi_data

        for i in range(30, 0, -1):
            print(strBold(strLightGray(f"\rFetching data in {i} seconds...")), end="")
            time.sleep(1)
        print(strBold(strCyan("\nFetching new data... Please wait.")))
        await asyncio.sleep(1)

async def main():
    await update_data()

asyncio.run(main())
Copy after login

Output:

NSE Option Chain Data using Python - Part II | Shah Stavan

NSE Option Chain Data using Python - Part II | Shah Stavan

You can even watch the demo video following this link

Thank you!!
See you in the next insightful blog.

The above is the detailed content of NSE Option Chain Data using Python - Part II | Shah Stavan. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles