OHLC data for Option Chain Instrument Like 'NSE_FO|49483'

Hello, I am not getting OHLC data for instrument ‘NSE_FO|49483’ which has expiry on next week. The code am using is

import pandas as pd
import requests
from datetime import datetime

Function to fetch OHLC data from Upstox API

def fetch_ohlc_data(access_token, instrument_key):

#print('TEST: instrument_key::', instrument_key.strip(), '__')

url = 'https://api.upstox.com/v2/market-quote/ohlc'
headers = {
    'Accept': 'application/json',
    'Authorization': 'Bearer ' + access_token,  # Replace with your actual access token
}
data = {
    "instrument_key": instrument_key,
    "interval": "I1"  # Interval set to 1-minute
}

try:
    response = requests.get(url, headers=headers, params=data)
    response.raise_for_status()
    response_json = response.json()
    

    # ## Print the raw JSON response for debugging
    # print("Response JSON:", response_json)
    # print(response_json)

    current_time = datetime.now()
    current_time = current_time.strftime('%Y%m%d %H:%M:%S')
    print('Current Time:', current_time)

    # Extract OHLC data
    data_value = response_json.get('data')
    if data_value:
        # Accessing OHLC data from the specific instrument key
        instrument_key_value = data_value.get(instrument_key.replace('|', ':'))
        if instrument_key_value:
            ohlc_data = instrument_key_value.get('ohlc')
            
            # Ensure the data is present
            if ohlc_data:
                timestamp = current_time # Using current UTC time for the record
                open_value = ohlc_data.get('open')
                high_value = ohlc_data.get('high')
                low_value = ohlc_data.get('low')
                close_value = ohlc_data.get('close')

                # Prepare the data for the DataFrame
                ohlc_list = [{
                    'Time': timestamp,
                    'Open': open_value,
                    'High': high_value,
                    'Low': low_value,
                    'Close': close_value
                }]
                
                # Convert to DataFrame
                ohlc_df = pd.DataFrame(ohlc_list)
                print(ohlc_df)
                return ohlc_df
    return None
except requests.exceptions.RequestException as e:
    print(f"Exception during request: {e}")
    return None

#_____________________________________________________________

Example usage

instrument_key = ‘NSE_INDEX|Nifty 50’ # Replace with your instrument key

instrument_key = ‘NSE_FO|49483’ # Replace with your instrument key
access_token = at # Replace with your actual access token

ohlc_df = fetch_ohlc_data(access_token, instrument_key)

Print the resulting DataFrame

if ohlc_df is not None:
print(ohlc_df)
else:
print(“No data returned.”)

Out put is

Current Time: 20250718 18:30:26
No data returned.

1 Like