Hello all , i am building and wanted to automate some stuff so my question is i am trying to download the historical intraday data of index option but cant able to do it ending up with the error can anyone show the snippet of how to grab those data and select the atm otm automatically
So i managed to do make a move so it is the response from the code can any one debug ,is it due to the market holiday or error someone guide me
here is the code i am using
from dhanhq import dhanhq
import pandas as pd
from datetime import datetime
import time
def load_master_data():
"""Load and parse the master CSV file"""
try:
# Load the master file with low_memory=False to handle mixed types
df = pd.read_csv('api-scrip-master-detailed.csv', low_memory=False)
# Filter for NIFTY and BANKNIFTY options only
nifty_options = df[
(df['INSTRUMENT'] == 'OPTIDX') &
(df['UNDERLYING_SYMBOL'].isin(['NIFTY', 'BANKNIFTY'])) &
(~df['UNDERLYING_SYMBOL'].str.contains('MIDCPNIFTY', na=False))
].copy()
# Convert expiry date
nifty_options['SM_EXPIRY_DATE'] = pd.to_datetime(nifty_options['SM_EXPIRY_DATE'])
# Sort by expiry date
nifty_options = nifty_options.sort_values('SM_EXPIRY_DATE')
# Print summary by underlying
print("\nMaster Data Summary:")
for underlying in ['NIFTY', 'BANKNIFTY']:
count = len(nifty_options[nifty_options['UNDERLYING_SYMBOL'] == underlying])
print(f"\n{underlying} Options: {count}")
# Print expiry dates for this underlying
underlying_data = nifty_options[nifty_options['UNDERLYING_SYMBOL'] == underlying]
print("Available expiry dates:")
for date in underlying_data['SM_EXPIRY_DATE'].unique():
count = len(underlying_data[underlying_data['SM_EXPIRY_DATE'] == date])
print(f"{date.strftime('%Y-%m-%d')}: {count} options")
# Show sample data for both
print("\nSample NIFTY options:")
nifty_sample = nifty_options[nifty_options['UNDERLYING_SYMBOL'] == 'NIFTY'][
['UNDERLYING_SYMBOL', 'SYMBOL_NAME', 'SM_EXPIRY_DATE', 'STRIKE_PRICE', 'OPTION_TYPE']
].head()
print(nifty_sample.to_string())
print("\nSample BANKNIFTY options:")
banknifty_sample = nifty_options[nifty_options['UNDERLYING_SYMBOL'] == 'BANKNIFTY'][
['UNDERLYING_SYMBOL', 'SYMBOL_NAME', 'SM_EXPIRY_DATE', 'STRIKE_PRICE', 'OPTION_TYPE']
].head()
print(banknifty_sample.to_string())
# Print security IDs
print("\nSecurity IDs:")
for underlying in ['NIFTY', 'BANKNIFTY']:
underlying_id = int(nifty_options[nifty_options['UNDERLYING_SYMBOL'] == underlying]['UNDERLYING_SECURITY_ID'].iloc[0])
print(f"{underlying}: {underlying_id}")
return nifty_options
except Exception as e:
print(f"Error loading master data: {str(e)}")
import traceback
traceback.print_exc()
return None
def get_option_chain(master_data, underlying='NIFTY'):
"""Get option chain using correct security IDs"""
try:
# Initialize Dhan
client_id = ""
access_token = ""
dhan = dhanhq(client_id, access_token)
# Get data for specific underlying
underlying_data = master_data[master_data['UNDERLYING_SYMBOL'] == underlying]
# Get nearest expiry from master data
current_date = pd.Timestamp.now()
valid_expiries = underlying_data[underlying_data['SM_EXPIRY_DATE'] > current_date]['SM_EXPIRY_DATE'].unique()
if len(valid_expiries) > 0:
nearest_expiry = min(valid_expiries)
print(f"\nFetching {underlying} option chain:")
print(f"Expiry date: {nearest_expiry.strftime('%Y-%m-%d')}")
# Get underlying security ID
underlying_id = int(underlying_data['UNDERLYING_SECURITY_ID'].iloc[0])
print(f"Underlying Security ID: {underlying_id}")
# Adding delay to avoid rate limiting
time.sleep(2)
# Get option chain
chain_response = dhan.option_chain(
under_security_id=str(underlying_id), # Ensure no decimal points
under_exchange_segment="IDX_I",
expiry=nearest_expiry.strftime('%Y-%m-%d')
)
# Log the request and response for debugging
print(f"Request: under_security_id={underlying_id}, under_exchange_segment='IDX_I', expiry={nearest_expiry.strftime('%Y-%m-%d')}")
print(f"Response: {chain_response}")
return chain_response
except Exception as e:
print(f"Error getting option chain: {str(e)}")
import traceback
traceback.print_exc()
return None
def main():
# Load master data
print("Loading master data...")
master_data = load_master_data()
if master_data is not None:
# Get option chains for both NIFTY and BANKNIFTY
for underlying in ['NIFTY', 'BANKNIFTY']:
chain_data = get_option_chain(master_data, underlying)
if chain_data and chain_data.get('status') == 'success':
filename = f"{underlying.lower()}_option_chain_{datetime.now().strftime('%Y%m%d')}.csv"
pd.DataFrame(chain_data['data']).to_csv(filename)
print(f"\nData saved to {filename}")
else:
print(f"\nFailed to get {underlying} option chain data")
if chain_data:
print("Response:", chain_data)
if __name__ == "__main__":
main()