stock market

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.

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
  • 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
  • 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
    Then key_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
  • kite.instruments("NSE") → Fetches the complete list of tradable instruments (stocks, indices, etc.) from NSE.
  • Each instrument contains details like:
  • tradingsymbol
  • instrument_token
  • exchange
  • name
  • pd.DataFrame(instrument_dump) converts that list into a Pandas DataFrame, which makes it easier to search/filter.
Helper Function: Fetch Instrument Token
  • Every symbol (like TCS, INFY, RELIANCE) has a unique instrument token — required for API calls.
  • This function:
  • Filters the instrument_df for the given symbol.
  • Extracts the corresponding instrument_token.
  • If not found (or any error), it returns -1.
Fetch Historical OHLC 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 minus duration days.
  • 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.

Leave a Reply

Your email address will not be published. Required fields are marked *