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.
The method with Instrument List is the most popular one but in this chapter, We will proceed using the Kite LTP
(Last Traded Price) method to find the instrument token for RELIANCE.
# Use Kite Connect's search instruments API to find RELIANCE's instrument token
instruments = kite.ltp(['NSE:RELIANCE'])
code
, we send a request to the Kite Connect API to get the last traded price for RELIANCE, specified by its trading symbol ‘NSE:RELIANCE
‘. The response, stored in the instruments variable, contains instrument-related information, including the instrument token. The output will be –
{'NSE:RELIANCE': {'instrument_token': 738561, 'last_price': 2457.85}}
# Check if the instrument token for RELIANCE is in the instruments dictionary
if 'NSE:RELIANCE' in instruments:
instrument_token = instruments['NSE:RELIANCE']['instrument_token']
In this code snippet, we check if the trading symbol ‘NSE:RELIANCE
‘ exists in the instruments dictionary. If it does, we extract the instrument token and assign it to the instrument_token
variable for later use.