How to fetch historical data from Zerodha API properly ?

Asked by Sejpalsinh Jadeja · SOLVED
1 reply 694 views Jump to solution Reply
Sejpalsinh Jadeja Original Post
AlgoDelta Team

I’m building an algo trading system and need to fetch historical data (like 1-minute candles) from Zerodha.I saw the historical\_data function but not sure what’s the correct way to use it in production.Can someone share a simple and reliable way to fetch historical candles?

Posted Apr 24
Reply

    1 Reply

    Support AlgoDelta
    Support AlgoDelta AlgoDelta Support ·

    To fetch the historical data from zerodha’s api below is the sample code that you can refer and modify it accordingg to your requirenment.

    def fetch_historical(kite, token, interval="minute", days=7):
        try:
            to_date   = datetime.now()
            from_date = to_date - timedelta(days=days)
            data = kite.historical_data(
                instrument_token=token,
                from_date=from_date,
                to_date=to_date,
                interval=interval
            )
            # FIX: strip timezone from all historical candle dates for consistent comparison
            for c in data:
                if c.get("date") and hasattr(c["date"], "tzinfo") and c["date"].tzinfo:
                    c["date"] = c["date"].replace(tzinfo=None)
            return data
        except Exception as error:
            print(f"Historical fetch failed for token {token}: {error}")
            return []
    
    fetch_historical(kite = kite,token=209604 , interval="minute", days=5)

    Since the from\_date and to\_date are necessary parameters gives the candle data between this 2 dates in format datetime.

    There are the 2 more parametrs we can pass to the kite.historical\_data that is IO ( for IO data ) and continuous ( for continuous data ), but they are optional also sees thatin offical documentation <https://www.kite.trade/docs/>.

    Verified Solution
    • Thanks a lot for the explanation and the code that you provided through this I can be able to get the historical data correctly. – Sejpalsinh Jadeja Team Jul 28
    Markdown supported · ```json for code blocks · paste or drop screenshots

    Be specific and kind. Never share API keys, passwords or personal account details.

    Welcome to the community

    Log in or create your account in under a minute.

    1. 1Mobile
    2. 2E-mail
    3. 3Password
    +91

    Have a password?

    By continuing you agree to the community guidelines. We’ll send a one-time code by SMS.