Import Nifty Option Chain With Python

Import Nifty Option Chain With Python



To import Nifty option chain data with Python using an API call, you can utilize the NSE (National Stock Exchange) website's official API. This method eliminates the need for web scraping and simplifies the data retrieval process. Here's a step-by-step guide:

1. Install the required libraries: Ensure you have the necessary Python libraries installed. You will need requests and pandas for making API requests and handling data, respectively. Use the following command to install them:

pip install requests pandas

2. Import the required libraries in your Python script:

import requests import pandas as pd


3. Define the API endpoint: Set the URL for the NSE option chain API. The API endpoint provides structured data in JSON format.python

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

4. Set the headers: To mimic a web browser, set the necessary headers for the API request. This can help bypass any restrictions or security measures.

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' }


5. Send a GET request to the API and retrieve the JSON data:

response = requests.get(url, headers=headers) data = response.json()


6. Extract the relevant data: The API response will contain a variety of information. Extract the desired option chain data from the JSON response based on your requirements. Typically, you would be interested in the 'records' or 'data' section of the response

option_chain_data = data['records']


7. Convert the data to a Pandas DataFrame: Transform the extracted data into a structured DataFrame using the pd.DataFrame() constructor:

df = pd.DataFrame(option_chain_data)


8. Perform data cleaning and preprocessing: Depending on your specific needs, you may need to clean the data, handle missing values, convert data types, or apply any necessary transformations to prepare the DataFrame for analysis.


9. Analyze and process the data: With the option chain data in the DataFrame df, you can perform various analyses, calculations, or visualizations to gain insights and make informed decisions related to Nifty options.

By utilizing the official API, you can access reliable and up-to-date data directly from the NSE, eliminating the need for web scraping and ensuring compliance with data usage policies. Make sure to review and adhere to the terms of service and guidelines provided by the NSE API documentation to use the data appropriately.


Complete Code: 

import requests
import pandas as pd
import time

url = '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 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37','accept-encoding': 'gzip, deflate, br','accept-language': 'en-GB,en;q=0.9,en-US;q=0.8'}

session = requests.Session()
request = session.get(url,headers=headers)
cookies = dict(request.cookies)


def dataframe():
response = session.get(url,headers=headers,cookies=cookies).json()
rawdata = pd.DataFrame(response)
rawop = pd.DataFrame(rawdata['filtered']['data']).fillna(0)
data = []
for i in range(0,len(rawop)):
calloi = callcoi = cltp = putoi = putcoi = pltp = 0
stp = rawop['strikePrice'][i]
if(rawop['CE'][i]==0):
calloi = callcoi = 0
else:
calloi = rawop['CE'][i]['openInterest']
callcoi = rawop['CE'][i]['changeinOpenInterest']
cltp = rawop['CE'][i]['lastPrice']
if(rawop['PE'][i] == 0):
putoi = putcoi = 0
else:
putoi = rawop['PE'][i]['openInterest']
putcoi = rawop['PE'][i]['changeinOpenInterest']
pltp = rawop['PE'][i]['lastPrice']
opdata = {
'CALL OI': calloi, 'CALL CHNG OI': callcoi, 'CALL LTP': cltp, 'STRIKE PRICE': stp,
'PUT OI': putoi, 'PUT CHNG OI': putcoi, 'PUT LTP': pltp
}

data.append(opdata)
optionchain = pd.DataFrame(data)
return optionchain

optionchain = dataframe()
print(optionchain)
Video Tutorial :-


Comments

  1. sir how to save this in excel as this output is of no use

    ReplyDelete

Post a Comment

Popular posts from this blog

How to develop Screener in Pine Script TradingView

Import Chartink data into Python