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.
Requirements
- An active AngelOne trading account.
- API key from AngelOne.
- Python environment with SmartAPI, pyotp, pytz, and pandas libraries installed.
Step1 : 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
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.
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
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]
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