To fetch SmartAPI historical data in Python, log in to your AngelOne account with the SmartAPI library (API key, client code, PIN and a TOTP), then call getCandleData() with the exchange, symbol token, interval and a from/to date range. The response comes back as a list of OHLCV candles that you can load straight into a pandas DataFrame, as shown in the complete code below.
This tutorial will guide you through fetching historical stock market data using the SmartAPI Python library, specifically with an AngelOne trading account. SmartAPI is a well-structured library providing easy access to the AngelOne trading platform’s features.

Key Takeaways
- You need an AngelOne account, a SmartAPI app (API key) and TOTP enabled on your account.
- Login uses
generateSession()with your client code, PIN and a TOTP generated bypyotp. - Historical candles come from
getCandleData(); every instrument is identified by a numeric symbol token from the scrip master file. - Each request returns a limited window of data, so fetch long histories in chunks.
- The SmartAPI portals and scrip master have moved from angelbroking.com to angelone.in; update old bookmarks and URLs.
Requirements
- An active AngelOne trading account.
- API key from AngelOne.
- Python environment with SmartAPI, pyotp, pytz, and pandas libraries installed.
How to Fetch SmartAPI Historical Data in Python: Step by Step
Step 1: Install the Python Library
use the following pip commands to install the python library
pip install smartapi-python
pip install pyotp
pip install pytz
pip install pandas
2026 note: the official smartapi-python README also asks you to install logzero, websocket-client and pycryptodome. If you get an import error on a fresh machine, run pip install logzero websocket-client pycryptodome as well.
Step 2: Generate the Token
1) Visit smartapi.angelbroking.com/enable-totp
2) Enter your Angel One client id and trading terminal password or MPIN
3) Enter OTP sent to the Registered email & mobile. Once OTP is entered, you will see a QR code on the screen and a token number on the screen.
The same page is now also available on the new domain at smartapi.angelone.in/enable-totp. The token number shown under the QR code is the TOTP secret that goes into config.py. For a deeper walk-through, see how to auto-generate TOTP for AngelOne login in Python.

Step 3: Generate the API Key
1)Login to SmartAPI Developer Portal
2)Click on Create an App button
3)Select the Market Feeds APIs option and enter the app name, enter the redirect url and postback url as shown below ,enter your Angel Client ID, and click the Create App button

4)Copy the API Key and keep it seperately.

Step 4: Preparing the config.py file
apikey = '9bmmTPjj'
username = 'R464999'
pwd = '1111'
token = '4YYB6RA2LXXXEKEZZ3BS7SJ3Y'
The config.py file is a Python configuration script containing sensitive information required for authenticating and connecting to a SmartAPI
The values above are dummies. Keep the real file out of Git (add it to .gitignore) or load the values from environment variables, because anyone with your API key, PIN and TOTP secret can log in to your account.
Step 5: Fetch Historical Data (history.py)
Here is the complete python code which does the login operation (generate Auth Token and Feed Token) and the historical_data function renders the stock data in pandas dataframe format
from SmartApi import SmartConnect # or from smartapi.smartConnect import SmartConnect
import pyotp, time, pytz
from datetime import datetime, timedelta
import pandas as pd
from config import *
# Create an object of SmartConnect
obj = SmartConnect(api_key=apikey)
def login():
"""
Function to login and return AUTH and FEED tokens.
"""
data = obj.generateSession(username, pwd, pyotp.TOTP(token).now())
refreshToken = data['data']['refreshToken']
auth_token = data['data']['jwtToken']
feed_token = obj.getfeedToken()
return auth_token, feed_token
def historical_data(exchange,token,from_date, to_date,timeperiod):
"""
Function to fetch historical data and return it as a Pandas DataFrame.
"""
try:
historicParam = {
"exchange": exchange,
"symboltoken": token,
"interval": timeperiod,
"fromdate": from_date,
"todate": to_date
}
api_response = obj.getCandleData(historicParam)
data = api_response['data']
columns = ['DateTime', 'Open', 'High', 'Low', 'Close', 'Volume']
df = pd.DataFrame(data, columns=columns)
df['DateTime'] = pd.to_datetime(df['DateTime'])
df.set_index('DateTime', inplace=True)
return df
except Exception as e:
print("Historic Api failed: {}".format(e))
# Usage Example
auth_token, feed_token = login()
thirty_days_ago = datetime.now() - timedelta(days=30)
from_date = thirty_days_ago.strftime("%Y-%m-%d %H:%M")
to_date = datetime.now().strftime("%Y-%m-%d %H:%M")
exchange = "NSE"
token = 1333
timeperiod = "ONE_MINUTE"
df = historical_data(exchange, token, from_date, to_date,timeperiod)
print(df)
Output
Open High Low Close Volume
DateTime
2023-11-20 09:15:00+05:30 2348.55 2356.90 2348.55 2356.50 42667
2023-11-20 09:16:00+05:30 2355.50 2355.50 2351.45 2354.50 48520
2023-11-20 09:17:00+05:30 2354.50 2356.05 2352.15 2353.50 16859
2023-11-20 09:18:00+05:30 2353.25 2357.00 2353.05 2356.05 23204
2023-11-20 09:19:00+05:30 2356.05 2357.00 2355.00 2355.25 18030
... ... ... ... ... ...
2023-12-19 13:00:00+05:30 2568.90 2569.50 2568.50 2569.00 15111
2023-12-19 13:01:00+05:30 2568.50 2569.00 2568.50 2569.00 11000
2023-12-19 13:02:00+05:30 2569.00 2569.00 2567.70 2567.95 9303
2023-12-19 13:03:00+05:30 2568.00 2568.30 2567.35 2568.00 22261
2023-12-19 13:04:00+05:30 2568.00 2568.50 2567.15 2568.30 7064
[7730 rows x 5 columns]
Token 1333 is HDFC Bank on NSE. The 30-day, one-minute request returned 7,730 candles, indexed by IST timestamps, ready for resampling, indicators or backtesting.
Exchange Constants
| Param | Value | Description |
|---|---|---|
| exchange | NSE | NSE Stocks and Indices |
| NFO | NSE Futures and Options | |
| BSE | BSE Stocks and Indices | |
| BFO | BSE Future and Options | |
| CDS | Currency Derivatives | |
| MCX | Commodities Exchange |
Interval Constants
| Interval | Description |
|---|---|
| ONE_MINUTE | 1 Minute |
| THREE_MINUTE | 3 Minute |
| FIVE_MINUTE | 5 Minute |
| TEN_MINUTE | 10 Minute |
| FIFTEEN_MINUTE | 15 Minute |
| THIRTY_MINUTE | 30 Minute |
| ONE_HOUR | 1 Hour |
| ONE_DAY | 1 Day |
How to Get the Symbol Token Information
The symbol token is the unique ID used to identify a particular trading instrument. Token ID can be obtained from the Master Data provided by the Brokers
import pandas as pd
import requests
url = 'https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json'
d = requests.get(url).json()
token_df = pd.DataFrame.from_dict(d)
token_df['expiry'] = pd.to_datetime(token_df['expiry']).apply(lambda x: x.date())
#Get the Token id for HDFC Bank
token_df[token_df.symbol== 'HDFCBANK-EQ']
#Get the Token id for Nifty Futures
print(token_df[token_df.symbol== 'BANKNIFTY25JAN24FUT'])
Output
token symbol name expiry strike lotsize instrumenttype \
3300 1333 HDFCBANK-EQ HDFCBANK NaT -1.000000 1
exch_seg tick_size
3300 NSE 5.000000
token symbol name expiry strike lotsize \
34020 55317 BANKNIFTY25JAN24FUT BANKNIFTY 2024-01-25 -1.000000 15
instrumenttype exch_seg tick_size
34020 FUTIDX NFO 5.000000
Updated version (2026)
The scrip master URL on the old angelbroking.com domain used in the code above now returns a 404 error. The file is served from margincalculator.angelone.in. The updated code below also passes the date format for the expiry column and uses pd.DataFrame() directly, since newer pandas versions warn against from_dict() on a list. It was tested against the live scrip master in November 2026.
import pandas as pd
import requests
# The scrip master now lives on the angelone.in domain
url = 'https://margincalculator.angelone.in/OpenAPI_File/files/OpenAPIScripMaster.json'
d = requests.get(url, timeout=60).json()
token_df = pd.DataFrame(d)
# expiry is a text field like 29DEC2026; blank for cash market symbols
token_df['expiry'] = pd.to_datetime(token_df['expiry'], format='%d%b%Y', errors='coerce').dt.date
# Token id for HDFC Bank (cash market)
print(token_df[token_df.symbol == 'HDFCBANK-EQ'][['token', 'symbol', 'exch_seg']])
# All current Nifty index futures with their tokens, expiries and lot sizes
fut = token_df[(token_df.name == 'NIFTY') & (token_df.instrumenttype == 'FUTIDX')]
print(fut[['token', 'symbol', 'expiry', 'lotsize', 'exch_seg']].sort_values('expiry'))
Contract symbols such as BANKNIFTY25JAN24FUT expire, so always look up the token for the current contract rather than hard-coding it. Lot sizes also change from time to time, so read them from the lotsize column instead of assuming a number.
Fetching Longer History in Chunks
Each getCandleData() call returns a limited window of candles, and the allowed window is smaller for shorter intervals. To build a longer one-minute or five-minute database, loop over the date range in smaller chunks and join the pieces. This helper reuses the historical_data() function from Step 5:
from datetime import datetime, timedelta
import time
import pandas as pd
def historical_data_range(exchange, token, start, end, timeperiod, chunk_days=30):
"""Fetch a long date range in chunks using historical_data() and join the results."""
frames = []
chunk_start = start
while chunk_start < end:
chunk_end = min(chunk_start + timedelta(days=chunk_days), end)
df = historical_data(exchange, token,
chunk_start.strftime("%Y-%m-%d %H:%M"),
chunk_end.strftime("%Y-%m-%d %H:%M"),
timeperiod)
if df is not None and not df.empty:
frames.append(df)
chunk_start = chunk_end
time.sleep(0.5) # pause between calls to stay inside the API rate limit
if not frames:
return pd.DataFrame()
out = pd.concat(frames)
# candles on a chunk boundary can appear twice, keep the first copy
return out[~out.index.duplicated(keep='first')].sort_index()
# Usage: 90 days of 5-minute candles for HDFC Bank (token 1333)
end = datetime.now()
start = end - timedelta(days=90)
df = historical_data_range("NSE", 1333, start, end, "FIVE_MINUTE")
print(df.tail())
df.to_csv("HDFCBANK_5min.csv")
If you work with more than one broker, OpenAlgo’s historical data tutorial shows how to pull broker historical data through a single API without hitting rate limits.
Common Errors and Fixes
- Invalid TOTP: the system clock on your PC or server is out of sync. TOTP codes change every 30 seconds, so enable automatic time sync.
- Empty or None DataFrame: check that the symbol token matches the exchange (an NFO token will not work with
"NSE"), that the dates fall on trading days, and that the from/to format isYYYY-MM-DD HH:MM. - Too many requests: add a short pause between calls, as in the chunking helper above.
- Import error for SmartApi: the package installs as
smartapi-pythonbut imports asfrom SmartApi import SmartConnect; also install the extra dependencies listed in Step 1.
Once the historical data is in place, you can add live prices with realtime stock quotes using the SmartAPI Python library. If you plan to move from data to order placement, read how to get a static IP for algo trading compliance.
Frequently Asked Questions
Is AngelOne SmartAPI free?
SmartAPI is offered free to AngelOne clients. You need an active trading account to create an app and generate an API key.
How do I find the symbol token in AngelOne SmartAPI?
Download the OpenAPIScripMaster.json scrip master file, load it into pandas and filter by the symbol column, for example HDFCBANK-EQ for HDFC Bank in the cash market. The token column holds the ID that getCandleData needs.
Which intervals does SmartAPI historical data support?
ONE_MINUTE, THREE_MINUTE, FIVE_MINUTE, TEN_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR and ONE_DAY, as listed in the interval table above.
Can I get historical data for futures and options with SmartAPI?
Yes. Use the NFO exchange and the token of the specific futures or options contract from the scrip master. Expired contracts drop out of the scrip master, so save the data you need while the contract is live.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

