Hi Team,
I'm trying to fetch 1min data for stocks but getting empty dataframe
Empty DataFrame
Columns: [time, open, high, low, close, volume]
Index: []
Here is my code:
import os
import subprocess
import pandas as pd
from fyers_api import fyersModel
# Read access token from file
with open("accesstoken.txt", 'r') as accesstoken:
access_token = accesstoken.read().strip()
client_id = 'XXXXX'
fyers = fyersModel.FyersModel(client_id=client_id, token=access_token, log_path=os.getcwd())
# Define the date range
start_date = pd.Timestamp('2018-01-01')
end_date = pd.Timestamp('2023-07-09')
#Read symbols from file
with open(r'symbols2.txt') as file:
symbols = file.read().splitlines()
for symbol in symbols:
# Fetch data from Fyers API
data = {
"symbol": symbol,
"resolution": "1m",
"date_format": "1",
"cont_flag": "1"
}
df = pd.DataFrame(columns=['symbol', 'date', 'open', 'high', 'low', 'close', 'volume'])
current_date = start_date
while current_date <= end_date:
range_from = current_date.strftime('%Y-%m-%d')
range_to = (current_date + pd.DateOffset(days=60)).strftime('%Y-%m-%d')
data['range_from'] = range_from
data['range_to'] = range_to
sdata = fyers.history(data)
#print(sdata)
if sdata['s'] == 'ok' and len(sdata['candles']) <= 0:
# Define the command to execute
command = ['python', 'C:\\Users\\user-PC\\Documents\\NSE_BSE_DATA\\login_api_generate_accesstoken.py']
# Execute the command
process = subprocess.Popen(command)
# Wait for the command to finish
process.wait()
if sdata['s'] == 'ok' and len(sdata['candles']) > 0:
sdata = pd.DataFrame(sdata['candles'], columns=['date', 'open', 'high', 'low', 'close', 'volume'])
sdata['symbol'] = symbol
df = pd.concat([df, sdata], ignore_index=True)
current_date += pd.DateOffset(days=60)
# Convert 'date' column to datetime in UTC
df['date'] = pd.to_datetime(df['date'], unit='s').dt.tz_localize('UTC')
# Convert 'date' column from UTC to IST and remove timezone information
df['date'] = df['date'].dt.tz_convert('Asia/Kolkata').dt.tz_localize(None)
# Split 'date' column into separate 'date' and 'time' columns
df['time'] = df['date'].dt.strftime('%H:%M:%S')
# Reorder columns
df = df[['symbol', 'date', 'time', 'open', 'high', 'low', 'close', 'volume']]
# Set 'symbol' and 'date' columns as the index
df.set_index(['symbol', 'date'], inplace=True)
# Save data to CSV
filename = symbol.replace(':', '_').replace('NSE_', '') # Replace ':' with '_' and remove 'NSE' from the symbol for the filename
filepath = r"C:\Users\user-PC\Documents\NSE_BSE_DATA\NSE_BSE_FYERS_DATA\1_min_stock_data"
os.makedirs(filepath, exist_ok=True) # Create the directory if it doesn't exist
df.to_csv(os.path.join(filepath, f'{filename}.csv'))
# Print the modified DataFrame
print(df.head(5))
Though from the above code I'm able to fetch 1Day data but now I want 1min data which I'm not able to fetch.
Thanks and Regards
Avinash Baldi