Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for NSE Option Chain Data using Python
Mr.Shah
Mr.Shah

Posted on • Edited on

     

NSE Option Chain Data using Python

In Today's Article we are going to learn how to fetch Nifty and Bank Nifty Data using Python and it's going to be amazing.

From where we will Fetch Data?

Ofcourse it's Going to beNSE Website from here we will fetch data such as Strike Price, Call and Put Option Data and based on Call and Put option data we will discover at which level more people are interested in Call and Put Option.

Let's Get into Coding

# Librariesimportrequestsimportjsonimportmath# Python program to print# colored text and backgrounddefstrRed(skk):return"\033[91m {}\033[00m".format(skk)defstrGreen(skk):return"\033[92m {}\033[00m".format(skk)defstrYellow(skk):return"\033[93m {}\033[00m".format(skk)defstrLightPurple(skk):return"\033[94m {}\033[00m".format(skk)defstrPurple(skk):return"\033[95m {}\033[00m".format(skk)defstrCyan(skk):return"\033[96m {}\033[00m".format(skk)defstrLightGray(skk):return"\033[97m {}\033[00m".format(skk)defstrBlack(skk):return"\033[98m {}\033[00m".format(skk)defstrBold(skk):return"\033[1m {}\033[0m".format(skk)# Method to get nearest strikesdefround_nearest(x,num=50):returnint(math.ceil(float(x)/num)*num)defnearest_strike_bnf(x):returnround_nearest(x,100)defnearest_strike_nf(x):returnround_nearest(x,50)# Urls for fetching Dataurl_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"# Headersheaders={'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'}sess=requests.Session()cookies=dict()# Local methodsdefset_cookie():request=sess.get(url_oc,headers=headers,timeout=5)cookies=dict(request.cookies)defget_data(url):set_cookie()response=sess.get(url,headers=headers,timeout=5,cookies=cookies)if(response.status_code==401):set_cookie()response=sess.get(url_nf,headers=headers,timeout=5,cookies=cookies)if(response.status_code==200):returnresponse.textreturn""defset_header():globalbnf_ulglobalnf_ulglobalbnf_nearestglobalnf_nearestresponse_text=get_data(url_indices)data=json.loads(response_text)forindexindata["data"]:ifindex["index"]=="NIFTY 50":nf_ul=index["last"]print("nifty")ifindex["index"]=="NIFTY BANK":bnf_ul=index["last"]print("banknifty")bnf_nearest=nearest_strike_bnf(bnf_ul)nf_nearest=nearest_strike_nf(nf_ul)# Showing Header in structured format with Last Price and Nearest Strikedefprint_header(index="",ul=0,nearest=0):print(strPurple(index.ljust(12,"")+" =>")+strLightPurple(" Last Price:")+strBold(str(ul))+strLightPurple(" Nearest Strike:")+strBold(str(nearest)))defprint_hr():print(strYellow("|".rjust(70,"-")))# Fetching CE and PE data based on Nearest Expiry Datedefprint_oi(num,step,nearest,url):strike=nearest-(step*num)start_strike=nearest-(step*num)response_text=get_data(url)data=json.loads(response_text)currExpiryDate=data["records"]["expiryDates"][0]foritemindata['records']['data']:ifitem["expiryDate"]==currExpiryDate:ifitem["strikePrice"]==strikeanditem["strikePrice"]<start_strike+(step*num*2):#print(strCyan(str(item["strikePrice"])) + strGreen(" CE ") + "[ " + strBold(str(item["CE"]["openInterest"]).rjust(10," ")) + " ]" + strRed(" PE ")+"[ " + strBold(str(item["PE"]["openInterest"]).rjust(10," ")) + " ]")print(data["records"]["expiryDates"][0]+""+str(item["strikePrice"])+" CE"+"["+strBold(str(item["CE"]["openInterest"]).rjust(10,""))+" ]"+" PE"+"["+strBold(str(item["PE"]["openInterest"]).rjust(10,""))+" ]")strike=strike+step# Finding highest Open Interest of People's in CE based on CE datadefhighest_oi_CE(num,step,nearest,url):strike=nearest-(step*num)start_strike=nearest-(step*num)response_text=get_data(url)data=json.loads(response_text)currExpiryDate=data["records"]["expiryDates"][0]max_oi=0max_oi_strike=0foritemindata['records']['data']:ifitem["expiryDate"]==currExpiryDate:ifitem["strikePrice"]==strikeanditem["strikePrice"]<start_strike+(step*num*2):ifitem["CE"]["openInterest"]>max_oi:max_oi=item["CE"]["openInterest"]max_oi_strike=item["strikePrice"]strike=strike+stepreturnmax_oi_strike# Finding highest Open Interest of People's in PE based on PE datadefhighest_oi_PE(num,step,nearest,url):strike=nearest-(step*num)start_strike=nearest-(step*num)response_text=get_data(url)data=json.loads(response_text)currExpiryDate=data["records"]["expiryDates"][0]max_oi=0max_oi_strike=0foritemindata['records']['data']:ifitem["expiryDate"]==currExpiryDate:ifitem["strikePrice"]==strikeanditem["strikePrice"]<start_strike+(step*num*2):ifitem["PE"]["openInterest"]>max_oi:max_oi=item["PE"]["openInterest"]max_oi_strike=item["strikePrice"]strike=strike+stepreturnmax_oi_strikeset_header()print('\033c')print_hr()print_header("Nifty",nf_ul,nf_nearest)print_hr()print_oi(10,50,nf_nearest,url_nf)print_hr()print_header("Bank Nifty",bnf_ul,bnf_nearest)print_hr()print_oi(10,100,bnf_nearest,url_bnf)print_hr()# Finding Highest OI in Call Option In Niftynf_highestoi_CE=highest_oi_CE(10,50,nf_nearest,url_nf)# Finding Highet OI in Put Option In Niftynf_highestoi_PE=highest_oi_PE(10,50,nf_nearest,url_nf)# Finding Highest OI in Call Option In Bank Niftybnf_highestoi_CE=highest_oi_CE(10,100,bnf_nearest,url_bnf)# Finding Highest OI in Put Option In Bank Niftybnf_highestoi_PE=highest_oi_PE(10,100,bnf_nearest,url_bnf)print(strCyan(str("Major Support in Nifty:"))+str(nf_highestoi_CE))print(strCyan(str("Major Resistance in Nifty:"))+str(nf_highestoi_PE))print(strPurple(str("Major Support in Bank Nifty:"))+str(bnf_highestoi_CE))print(strPurple(str("Major Resistance in Bank Nifty:"))+str(bnf_highestoi_PE))
Enter fullscreen modeExit fullscreen mode

Output

NIFTY


BANKNIFTY

Part-2:Website

If you guys want me to Fetch Call and Put Option Data for Global Stocks and Indices let me know in Comment Section🙂✌️

GoodBye👋

Top comments(26)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
arjunhack profile image
Salai Arjun
IIT-M/ Math & Coding enthusiastic/ Loves Poker & Chess/ an INTJ personality
  • Joined

Hi bro, very good code.. I am automating my trading strategy into python code. Need some guidance. How can I contact u?

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

You can contact me through LinkedIn.

CollapseExpand
 
kaurav1108 profile image
kaurav1108
  • Joined

Hi@shahstavan : Thank you for python program, I want to customise output as below
as in output i want to print the extra coloum as CENT and PENT and value inside those new 2 coloum based on total open interest number leangth.
eg. CE Open interest for 17400 strike = 12345678 then --> in CENT Coloum is should print first 3 digit of number : 123
eg. PE Open interest for 17400 strike = 456789 then --> in PENT Coloum is should print first 3 digit of number : 45
and leangth condition as :
if leangth is 6 digit then show 1st digit of number
if leangth is 7 digit then show 2st digit of number
if leangth is 8 digit then show 3st digit of number
if leangth is 9 digit then show 4st digit of number
can you help me with code.

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

Just format the output in Python code.

CollapseExpand
 
kaurav1108 profile image
kaurav1108
  • Joined
• Edited on• Edited

@shahstavan : Hi, I have updated code my self and its working fine as per my requirement.
Now i can you help me to run this code every 5 min and updated on some html page

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

Learn Flask or any other Framework and what you can do is reload the page every 5 minute automatically 🌛🙌

Thread Thread
 
thecodingsage profile image
Sivayogeith Umamaheswaran
  • Pronouns
    he / him
  • Work
    CTO at Ulagellam
  • Joined

lol, reloading the page is soooo wrong in 2023.

CollapseExpand
 
arnavdas profile image
Arnav-Das
  • Joined

TYVM

CollapseExpand
 
pradip_ profile image
Pradip Mukhopadhyay
Coder and Money Enthusiast.
  • Education
    Jadavpur University Kolkata
  • Work
    Coder
  • Joined

Hi,

Is the data reported by Bandl is correct?
E.g. I am seeing OI data is much lower scale compared to that of say reported by other Options tools (e.g. Opstra or SensiBull).
Like this shows data as lots? E.g.
03-Nov-2022 17550 CE ( 294.8) [ 1167 ] { 250 } | PE ( 44.5) [ 17693 ] { 8428 }

It's actually 17693 lots?

CollapseExpand
 
anirudh12 profile image
Anirudh-12
  • Joined

yes, it's actually 17693 lots. If you what the data per lot you have to multiply the data by lot_size

CollapseExpand
 
vegaonline profile image
Abhijit Bhattacharyya
  • Work
    BARC, Mumbai
  • Joined

This is nice example. How can one plot banknifty converting thejson.loads data from this code to the dataframe?

CollapseExpand
 
taniksood profile image
taniksood
  • Joined

Hello dear, can you help me out with python code to fetch live data for NSE Top 20 Contracts pl ?

nseindia.com/market-data/equity-de...

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

Hey, you can read my new blog on this topic -
Track NSE Derivatives Top Contracts Easily

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

Sure, will fetch the data and will inform you once done.

CollapseExpand
 
bharat_kumar profile image
Bharat Thatte
Enthusiat python learner
  • Joined

Dear Mr. Shah,
The code is not working.
"def set_header()" ( data = json.loads(response_text)" )
shows error. NSE website may have changed. Please update all URLs.
Thanks

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

Hii Bharat,
The NSE is no more providing the data I'm looking other sources and will post the blog very soon. For more information or query you can contact me on LinkedIn.

CollapseExpand
 
chandra6011 profile image
C P Patel 🇮🇳
Engineer of Discreet component time...learning python
  • Education
    BE Electronics
  • Work
    Retired
  • Joined

Thats great code... From where should one pick up Current time and date of Exchange and whether the "today" is an Expiry day or not..?

CollapseExpand
 
chintu35395015 profile image
Chintu
  • Joined

is it possible to add difference (CE,PE) column also for each strike price and total CE and PE

CollapseExpand
 
anbu222 profile image
Anbarasu A
  • Joined

Hello,

Is it possible to scan options price OHLC values as well and creating a scanner based on the OHLC values. Please share your thoughts.

Thank you in advance.

CollapseExpand
 
shahstavan profile image
Mr.Shah
Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

Yes, it can be possible.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Developer Intern @ D360 Tech || Content Writer || React Developer || Building Cool Products leveraging LLM's capabilities.
  • Location
    Gujarat,India
  • Education
    Institute of Technology, Nirma University
  • Work
    Summer Intern
  • Joined

More fromMr.Shah

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp