Download data from Zerodha using python script

This is a simple script based on jugaad-trader library to download minute interval data for any instrument (stock, futures, options and indices).

Follow simple steps as below-

1. Install jugaad-trader

$ pip install jugaad-trader

2. Login zerodha using jtrader CLI

$ jtrader zerodha startsession

3. Create a file with name zdata.py and copy paste the below script

4. Execute python zdata.py --help command to get all available options

Usage: zdata.py [OPTIONS]

Options:
  -i, --instrument TEXT  Instrument name "NSE:INFY"
  -f, --from TEXT        from date yyyy-mm-dd
  -t, --to TEXT          to date yyyy-mm-dd
  -n, --interval TEXT    Data interval eg. minute, day
  -o, --output TEXT      Output file name
  --help                 Show this message and exit.

5. Download stock data-

$ python zdata.py -i "NSE:INFY" -f 2020-12-01 -t 2020-12-02 -n minute -o data.csv

6. Download index data-

$ python zdata.py -i "NSE:NIFTY 50" -f 2020-12-01 -t 2020-12-02 -n minute -o data.csv

Script

import click
import pickle as pk
import csv
from jugaad_trader import Zerodha


@click.command()
@click.option("--instrument", "-i", help='Instrument name "NSE:INFY"', type=str)
@click.option("--from", "-f", "from_", help="from date yyyy-mm-dd")
@click.option("--to", "-t", help="to date yyyy-mm-dd")
@click.option("--interval", "-n", default="day", help="Data interval eg. minute, day")
@click.option("--output", "-o", help="Output file name")
def main(instrument, from_, to, interval, output):
    #print(instrument, from_, to, interval, output)
    kite = Zerodha()

    kite.set_access_token()
    q = kite.ltp(instrument)
    token = q[instrument]['instrument_token']

    data = kite.historical_data(token, from_, to, interval)
    with open(output, 'w') as fp:
        writer = csv.DictWriter(fp, ["date", "open", "high", "low", "close", "volume"])
        writer.writeheader()
        writer.writerows(data)


if __name__ == "__main__":
    main()

This should work with official API with minimal changes