How to get stock options data?

How to get stock options data?

Options data is one of the most important aspects of algorithimic trading. It forms the basis for analysis and backtests.

How to get options data in python is pretty simple if you use python.

import pandas as pd

import requests

def get_optstk_history(inst,strike_price,opt_type,fromdate,todate):

headers = {
'Pragma': 'no-cache',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'Accept': '*/*',
'Referer': 'https://www.nseindia.com/products/content/derivatives/equities/historical_fo.htm',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
}
params = (('instrumentType', 'OPTSTK'),
('symbol', inst),
('expiryDate', 'select'),
('optionType', opt_type),
('strikePrice', strike_price),
('dateRange', 'day'),
('fromDate', fromdate),
('toDate', todate),
('segmentLink', '9'),
('symbolCount', ''),
)
response = requests.get('https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp', headers=headers, params=params)
try:
opthistdf = pd.read_html(response.text,flavor='lxml',skiprows=1,header=0)[0]
except:
opthistdf = pd.DataFrame()
return opthistdf

Test:

optdf = get_optstk_history('HDFCBANK',1000,'CE','10-04-2020','29-04-2020')

I will post a detailed explanation of the code later.

Do you need the index options data? Comment

Do you want me to help you clean up the data into a more useful form? Leave a comment.

If you need options data for another exchange leave me a comment and I will try to post that up as well.

Leave a Reply

Your email address will not be published. Required fields are marked *