We shall be using Zerodha’s Kite Connect API to back test the given dataset. We’re a Zerodha Partner and if you’ve signed up with Unofficed, then You’ll get access to the raw file used to make this tutorial.
Kite Connect offers REST-like HTTP APIs with a wide range of capabilities which will suffice our needs.
As You can see from the example of KiteConnect Python API from Zerodha’s GitHub, the Step 1 is to create the Kite object
import logging
from kiteconnect import KiteConnect
logging.basicConfig(level=logging.DEBUG)
kite = KiteConnect(api_key="your_api_key")
# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.
data = kite.generate_session("request_token_here", api_secret="your_secret")
kite.set_access_token(data["access_token"])
Zerodha’s KiteConnect API gives historical data for free. As per their documentation, We need to use kite.historical_data() function.
def historical_data(self, instrument_token, from_date, to_date, interval, continuous=False, oi=False)
instrument_token
is the instrument identifier (retrieved from the instruments()) call.from_date
is the From date (datetime object or string in format of yyyy-mm-dd HH:MM:SS.to_date
is the To date (datetime object or string in format of yyyy-mm-dd HH:MM:SS).interval
is the candle interval (minute, day, 5 minute etc.).continuous
is a boolean flag to get continuous data for futures and options instruments.oi
is a boolean flag to get open interest. So We need to get the instrument_token. Now, there are two methods to get the Instrument Token of a Scrip.
In this chapter, We will proceed using the Instrument List Method.
First, let’s download the entire instrument list from Zerodha and save it as a portable database. We will use the pandas library for this task, making data manipulation seamless. The instrument list is available at https://api.kite.trade/instruments in CSV format. So, let’s declare a variable named “instrumentList” to harness the power of pandas in managing this crucial trading data.
import pandas as pd
instrumentList = pd.read_csv("https://api.kite.trade/instruments")
print(instrumentList)
The output will be –
Triggered at Count Stocks (new stocks are highlighted) Trigger Date Trigger Time
0 Fri Apr 21 2023, 10:07 am 1 APOLLOTYRE 2023-04-21 10:07:00
1 Fri Apr 21 2023, 9:58 am 1 ASIANPAINT 2023-04-21 09:58:00
2 Thu Apr 20 2023, 3:21 pm 1 TATACONSUM 2023-04-20 15:21:00
3 Thu Apr 20 2023, 2:16 pm 1 BAJAJ-AUTO 2023-04-20 14:16:00
4 Thu Apr 20 2023, 12:49 pm 1 CUB 2023-04-20 12:49:00
... ... ... ... ... ...
775 Tue Sep 13 2022, 10:03 am 3 DIXON 2022-09-13 10:03:00
776 Tue Sep 13 2022, 10:03 am 3 DRREDDY 2022-09-13 10:03:00
777 Tue Sep 13 2022, 10:03 am 3 HEROMOTOCO 2022-09-13 10:03:00
778 Tue Sep 13 2022, 10:01 am 2 DRREDDY 2022-09-13 10:01:00
779 Tue Sep 13 2022, 10:01 am 2 HEROMOTOCO 2022-09-13 10:01:00
780 rows × 5 columns
tradesymbol = "RELIANCE"
exchange = "NSE"
dataToken = instrumentList[(instrumentList['tradingsymbol'] == tradesymbol)&(instrumentList['exchange']==exchange)]
print(dataToken)
instrument_token exchange_token tradingsymbol name \
93364 738561 2885 RELIANCE RELIANCE INDUSTRIES
last_price expiry strike tick_size lot_size instrument_type segment \
93364 0 NaN 0.0 0.05 1 EQ NSE
exchange
93364 NSE
print(dataToken.instrument_token.iloc[0])
So, wrapping this procedure into a function which we can use into our future endevaours.
def get_insToken(tradesymbol,exchange="NFO"):
if(exchange=="NSE"):
if(tradesymbol=="NIFTY"):tradesymbol="NIFTY 50"
if(tradesymbol=="BANKNIFTY"):tradesymbol="NIFTY BANK"
if(tradesymbol=="FINNIFTY"):tradesymbol="NIFTY FIN SERVICE"
dataToken = instrumentList[(instrumentList['tradingsymbol'] == tradesymbol)&(instrumentList['exchange']==exchange)]
return dataToken.instrument_token.iloc[0]
symbol = "RELIANCE"
token = get_insToken(symbol,"NSE")
print(token)
738561