While running the below code
######## → 1_min_data ← ########
fyers = fyersModel.FyersModel(client_id=client_id, token=access_token)
Read symbols from the text file
with open(r"C:\Users\Admin\Downloads\Avi_Sunny\Data\STOCKS_DATA\BEL\April_2024\BEL_fno_April_2024.txt", “r”) as file:
symbols = file.read().splitlines()
Define the common data for API call
data = {
"resolution": "1",
"date_format": "1",
"range_from": "2024-03-01",
"range_to": "2024-04-05",
"cont_flag": "1"
}
Iterate over each symbol and make API call
for symbol in symbols:
data["symbol"] = symbol
# Modify symbol to create a valid file name
csv_file_name = f"{symbol.replace(':', '_')}.csv"
csv_file_path = os.path.join(r"C:\Users\Admin\Downloads\Avi_Sunny\Data\STOCKS_DATA\BEL\April_2024\fno_data", csv_file_name)
response = fyers.history(data=data)
print(response)
# Loop through each candle list within the 'candles' key
for candle in response['candles']:
# Access the epoch timestamp (first element)
epoch_time = candle[0]
# Convert epoch to datetime object (assuming UTC time)
dt_obj = datetime.datetime.fromtimestamp(epoch_time)
# Update the first element in the candle list with the formatted datetime string
candle[0] = dt_obj.strftime('%Y-%m-%d') # Date
candle.insert(1, dt_obj.strftime('%H:%M:%S')) # Time
# Define headers for the table
headers = ["Date", "Time", "Open", "High", "Low", "Close", "Volume"]
# Print the formatted table
#print(tabulate(response['candles'], headers=headers, tablefmt="pretty"))
print(tabulate(response['candles'][:3], headers=headers, tablefmt="pretty"))
# File path to save CSV
#csv_file = r"C:\Users\Admin\Downloads\Avi_Sunny\Data\STOCKS_DATA\BEL\Apri_2024\Options\5_min\BEL.csv"
# Write data to CSV file
with open(csv_file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headers)
writer.writerows(response['candles'])
print(f"Data has been saved to {csv_file_path}.")
I got the below issue
Data has been saved to C:\Users\Admin\Downloads\Avi_Sunny\Data\STOCKS_DATA\BEL\April_2024\fno_data\NSE_BEL24APRFUT.csv.
ERR: logEntryFunc: history : [Errno 13] Permission denied: ‘/2024-04-06.txt’
{‘s’: ‘error’, ‘code’: -99, ‘message’: ‘An unexpected error occurred. Please contact support.’}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[99], line 30
27 print(response)
29 # Loop through each candle list within the 'candles' key
---> 30 for candle in response['candles']:
31 # Access the epoch timestamp (first element)
32 epoch_time = candle[0]
34 # Convert epoch to datetime object (assuming UTC time)
KeyError: 'candles'