How to fetch historical data using kite connect
Algo Trading is a method of trading in the stock market where computer programs automatically place buy and sell orders based on pre-defined rules. These rules are created using mathematical models, technical indicators, or market conditions.

from kiteconnect import KiteConnect
import os
import datetime as dt
import pandas as pd
import numpy as np
import time
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
#generate trading session
#generate trading session
access_token = open("access_token.txt",'r').read()
key_secret = open("api_key.txt",'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
kite.set_access_token(access_token)
#get dump of all NSE instruments
instrument_dump = kite.instruments("NSE")
instrument_df = pd.DataFrame(instrument_dump)
def fetchInstrument(instrument_df,symbol):
try:
return instrument_df[instrument_df.tradingsymbol==symbol].instrument_token.values[0]
except:
return -1
def fetchOHLC(ticker,interval,duration):
instrument = fetchInstrument(instrument_df,ticker)
data = pd.DataFrame(kite.historical_data(instrument,dt.date.today()-dt.timedelta(duration), dt.date.today(),interval))
data.set_index("date",inplace=True)
return data
tickers = ["TATAMOTORS","INFY","HINDALCO","ADANIENT","TCS","BHARTIARTL",
"INDUSINDBK","TECHM","VEDL","SHRIRAMFIN","HCLTECH","LT","MARUTI",
"WIPRO","ONGC","NTPC","ICICIBANK","BEL","HDFCBANK","BAJFINANCE","HDFCLIFE",
"ADANIPORTS","TITAN","ASIANPAINT","POWERGRID","TRENT","TATASTEEL",
"HINDUNILVR","JIOFIN","EICHERMOT","AXISBANK","HEROMOTOCO","CIPLA","ITC",
"COALINDIA","SBIN","KOTAKBANK","ULTRACEMCO","BAJAJ-AUTO","SUNPHARMA","GRASIM",
"JSWSTEEL","SBILIFE","DRREDDY","RELIANCE","M&M","TATACONSUM","NESTLEIND",
"APOLLOHOSP","BAJAJFINSV","ETERNAL"]
capital = 3000
for ticker in tickers:
starttime=time.time()
timeout = time.time() + 60*60*1 # 60 seconds times 360 meaning 6 hrs
while time.time() <= timeout:
try:
df = fetchOHLC(ticker,"day",2*365)
time.sleep(300))
except KeyboardInterrupt:
print('\n\nKeyboard exception received. Exiting.')
exit()
Explanation
Learn how to use the Zerodha Kite Connect API in Python to fetch historical stock data. This step-by-step guide explains each line of code
Importing Required Libraries
from kiteconnect import KiteConnect
import os
import datetime as dt
import pandas as pd
import numpy as np
import time
kiteconnect: The official Zerodha Kite Connect API Python client — used to connect to Zerodha for fetching live and historical market data.datetime as dt: Helps work with dates and times (used to fetch data for a specific date range).pandas as pd: Data analysis library — used here to store and manipulate tabular data (like OHLC — Open, High, Low, Close).
Change Working Directory
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
os.chdir()changes the current working directory to the specified path.- This ensures that when you open files (like
access_token.txt), Python looks for them in this directory.
Generate Trading Session
access_token = open("access_token.txt",'r').read()
key_secret = open("api_key.txt",'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
kite.set_access_token(access_token)
open("access_token.txt",'r').read()
→ Opens the file containing your access token (login session token from Zerodha).open("api_key.txt",'r').read().split()
→ Reads your API key and secret from a text file and splits them (usually separated by space or newline).- Example: file content may look like
your_api_key your_api_secret
Thenkey_secret[0]= API key,key_secret[1]= API secret. kite = KiteConnect(api_key=key_secret[0])
→ Creates a KiteConnect API session using your API key.kite.set_access_token(access_token)
→ Sets your access token to authenticate requests for market data.
Fetch All NSE Instruments
instrument_dump = kite.instruments("NSE")
instrument_df = pd.DataFrame(instrument_dump)
kite.instruments("NSE")→ Fetches the complete list of tradable instruments (stocks, indices, etc.) from NSE.- Each instrument contains details like:
tradingsymbolinstrument_tokenexchangenamepd.DataFrame(instrument_dump)converts that list into a Pandas DataFrame, which makes it easier to search/filter.
Helper Function: Fetch Instrument Token
def fetchInstrument(instrument_df, symbol):
try:
return instrument_df[instrument_df.tradingsymbol == symbol].instrument_token.values[0]
except:
return -1
- Every symbol (like
TCS,INFY,RELIANCE) has a unique instrument token — required for API calls. - This function:
- Filters the
instrument_dffor the givensymbol. - Extracts the corresponding
instrument_token. - If not found (or any error), it returns
-1.
Fetch Historical OHLC Data
def fetchOHLC(ticker, interval, duration):
instrument = fetchInstrument(instrument_df, ticker)
data = pd.DataFrame(kite.historical_data(
instrument,
dt.date.today() - dt.timedelta(duration),
dt.date.today(),
interval
))
data.set_index("date", inplace=True)
return data
1.instrument = fetchInstrument(instrument_df, ticker)
→ Finds the instrument token for the stock.
2. kite.historical_data(...)
- Fetches OHLC (Open, High, Low, Close) + Volume data between two dates:
interval: Time interval like'day','5minute','15minute', etc.from_date: Today minusdurationdays.to_date: Today
3. Converts the returned JSON data into a Pandas DataFrame.
4. data.set_index("date", inplace=True)
→ Sets the date column as the DataFrame index (for easy time-series analysis).
5.return data
→ Returns a clean DataFrame containing OHLC data.
df = fetchOHLC("INFY", "day", 30)
print(df.tail())