if response.status_code == 200: return response.json() else: print(f"Failed to fetch data for instrument token {instrument_token}. Status code: {response.status_code}, Response: {response.text}") return None
# Specify the date range start_date = datetime(2001, 1, 1) end_date = datetime(2023, 12, 6) instrument_token = 256265
# Calculate the number of 200-day intervals interval_days = 100 num_intervals = (end_date - start_date).days // interval_days # List to store individual instrument DataFrames with instrument_token column
nifty_df = [] instrument_data = []
for interval in range(num_intervals): # Calculate the start and end dates for each interval interval_start_date = start_date + timedelta(days=interval * interval_days) interval_end_date = interval_start_date + timedelta(days=interval_days)
# Fetch historical data for the current interval historical_data = fetch_historical_data(instrument_token, interval_start_date, interval_end_date)
# Append the data to the instrument_data list with an additional 'instrument_token' column if historical_data: candles = historical_data['data']['candles'] candles_with_token = [{'timestamp': candle[0], 'open': candle[1], 'high': candle[2], 'low': candle[3], 'close': candle[4], 'volume': candle[5], 'instrument_token': instrument_token} for candle in candles] instrument_data.extend(candles_with_token)
# Create a DataFrame from the combined data df = pd.DataFrame(instrument_data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'instrument_token'])
# Convert timestamp to datetime format df['timestamp'] = pd.to_datetime(df['timestamp'])
print(df.head()) print(df.tail())
but it is just fetching me data from 09/01/2015 to 22/09/2023. Why can I not get data from before 09/01/2015 and also after 22/09/2023. Verify from the first 5 lines & the last 5 lines of the output smile:
I just checked for 256265, and it's showing the latest 5minute data. {'date': datetime.datetime(2023, 12, 6, 10, 45, tzinfo=tzoffset(None, 19800)), 'open': 20904.25, 'high': 20921.2, 'low': 20904.25, 'close': 20920.6, 'volume': 0} Are you sure about requesting the correct to-period .... 'to': to_date.strftime('%Y-%m-%d %H:%M:%S')? Maybe print/debug it once at your end.
{'date': datetime.datetime(2023, 12, 6, 10, 45, tzinfo=tzoffset(None, 19800)),
'open': 20904.25, 'high': 20921.2, 'low': 20904.25, 'close': 20920.6, 'volume': 0}
Are you sure about requesting the correct to-period
.... 'to': to_date.strftime('%Y-%m-%d %H:%M:%S')
? Maybe print/debug it once at your end.