Fetching one minute data from 2017 from FYERS API.

Fyers provides python API using which one minute data can be fetched for more than 4 years.

This data can be used for backtesting or during live market for plotting indicators.

Login into your Account

First of all you need to login into your fyers account using v2 API.


from fyers_api import fyersModel
from fyers_api import accessToken
import login


session=accessToken.SessionModel(client_id=login.client_id,secret_key=login.secret_key,redirect_uri=login.redirect_uri, response_type="code", grant_type="authorization_code")
response = session.generate_authcode()  
auth = 'Your Auth Code'
session.set_token(auth)
response = session.generate_token()
access_token = response["access_token"]
fyers = fyersModel.FyersModel(client_id=login.client_id, token=access_token,log_path="/")

How to Download Historical Data using Fyers API V2.

data = {"symbol":symbol, "resolution":"1","date_format":"1","range_from":str(sd),"range_to":str(ed),"cont_flag":"1"}
fyers.history(data)

By keeping date_format as “1” you can input string value to date. You also need to input name of the symbol as per given in symbols list on fyers API.

Above code will give out one minute data of only 100 days and in json format with datetime value as a timestamp.

We need to convert this into a dataframe with datetime as index.

Converting data into a DataFrame

cols = ['datetime','open','high','low','close','volume']
df = pd.DataFrame.from_dict(nx['candles'])
df.columns = cols
df['datetime'] = pd.to_datetime(df['datetime'],unit = "s")
df['datetime'] = df['datetime'].dt.tz_localize('utc').dt.tz_convert('Asia/Kolkata')
df['datetime'] = df['datetime'].dt.tz_localize(None)
df = df.set_index('datetime')

Fetching data of more than 100 days at a time

For this we first need the start date and end date and then calculate the total number of days between them.

Then we need to create a loop that will go through 100 days at a time and fetch data for that. After fetching data for first 100 days the program should merge this data with the data of next 100 days.

sd = datetime.date(2017,1,1)
enddate = datetime.date(2022,1,31) #datetime.datetime.now().date()
df = pd.DataFrame()

n = abs((sd - enddate).days)
ab = None

while ab == None: 
    sd = (enddate - datetime.timedelta(days= n))
    ed = (sd + datetime.timedelta(days= 99 if n >100 else n)).strftime("%Y-%m-%d")
    sd = sd.strftime("%Y-%m-%d")
    dx = historical_bydate("NSE:NIFTY50-INDEX", sd, ed)
    df = df.append(dx)
    n = n - 100 if n > 100 else n - n 
    print(n)
    if n == 0 : 
        ab = "done"
      

This loop will stop when data of 100 days is completely fetched and saved into a single dataframe.

Saving the dataframe in csv format

df.to_csv(r"F:\backtest\NFO_Filter\nifty_new.csv")

Scroll to Top