Let’s consider you know the date, strike price, and whether it’s a put or call option for the contract NIFTY23DEC23000PE
. To programmatically find the instrument_key
(such as NSE_FO|37721
) for a given trading symbol like NIFTY23DEC23000PE
, when you have the date, strike price, and whether it’s a put or call option, you can follow these steps:
- Standardize the Date Format: Ensure the date is in a standard format that matches the format used in your dataset. For example, if your date is
23-Dec-2023
, you may need to convert it to a format like23DEC
. - Concatenate Strings for Trading Symbol: Construct the trading symbol by concatenating the index name, standardized expiry date, strike price, and option type (PE for Put, CE for Call).
- Filter the Dataset: Use the constructed trading symbol to filter your dataset and extract the
instrument_key
.
Here’s a Python function that demonstrates this:
python
import pandas as pd
def find_instrument_key(df, index, date, strike_price, option_type):
"""
Finds the instrument key in the dataframe for a given option.
:param df: DataFrame containing the data.
:param index: The index, e.g., 'NIFTY'.
:param date: Expiry date in the format 'DD-MMM-YYYY' (e.g., '23-Dec-2023').
:param strike_price: Strike price as an integer or float.
:param option_type: 'Put' or 'Call'.
:return: The instrument key or None if not found.
"""
# Convert date to the required format (e.g., '23DEC')
date_str = pd.to_datetime(date).strftime('%d%b').upper()
# Define option type abbreviation
option_abbr = 'PE' if option_type.lower() == 'put' else 'CE'
# Construct the trading symbol
trading_symbol = f"{index}{date_str}{strike_price}{option_abbr}"
# Filter the dataframe for the trading symbol
filtered_df = df[df['tradingsymbol'] == trading_symbol]
# Return the instrument key
if not filtered_df.empty:
return filtered_df.iloc[0]['instrument_key']
else:
return None
# Example usage
data = pd.read_csv('/path/to/NSE.csv', low_memory=False) # Load the dataset
instrument_key = find_instrument_key(data, 'NIFTY', '23-Dec-2023', 23000, 'Put')
instrument_key
This function will find the instrument_key
for the trading symbol constructed from the given date, strike price, and option type. If the trading symbol does not exist in the dataset, it will return None
. Make sure to adjust the date format conversion (strftime('%d%b')
) to match the format used in your dataset.
Tested it randomly for 3-4 entries and worked for me. You can give a shot and let me know.