How to Fetch Intraday Historical Data of Stocks for any time interval using Python
If you’re a stock market enthusiast or data analyst, you might often need intraday historical data of stocks to perform technical analysis or backtest trading strategies. While many APIs require paid subscriptions, this guide will show you how to fetch intraday historical data from Moneycontrol using a Python script.
Prerequisites
Before you begin, ensure you have:
- Basic knowledge of Python
- Python 3.8+ installed
requests
,pandas
, anddatetime
modules available (install usingpip install
if not)
Step 1: Get the Script
Copy and paste below script to a file and save it where you like:
Step 2: Understand the Script
The script works by sending requests to a Moneycontrol URL pattern that retrieves intraday data (in JSON format) for a given stock.
Key functions include:
- MControlAPI Class expose functions to fetch stock data, while initializing class stock symbol have to be present i.e. obj = MControlAPI(‘SBIN’).
- Using this obj Object we can access fetch_intraday_data function to get intraday data of provided symbol.
Note: Moneycontrol may not officially provide a public API, so this method relies on available web endpoints. The data structure may change without notice.
Step 3: Set the Parameters
You can use this MControlAPI module as:
from pprint import pprint
obj = MControlAPI('SBIN')
nd = 0
while nd > -1:
nd = obj.fetch_intraday_data()
print(nd)
if nd > 0:
pprint(obj.dataframe)
last = obj.dataframe.iloc[-1:].iloc[0]['dt']
if (last.hour + last.minute/60) > 15.5:
print('Market is closed')
break
sleep(obj.delta_time)
Step 4: Save or Analyze the Data
Once you retrieve the data, you can now use this for:
- Plotting intraday charts
- Backtesting strategies
- Feeding into ML models
Troubleshooting
- 403 Forbidden? You may need to add headers to mimic a browser.
- Empty DataFrame? The symbol may be invalid or the time range may be out of bounds.
- Data Format Changed? Moneycontrol might’ve updated its internal API. You’ll need to inspect the new format using browser DevTools.
Conclusion
This is a powerful tool to fetch stock data without relying on premium APIs. However, always respect website terms of service and use responsibly. If you want to use APIs provided by different trading platforms you can explore my YouTube Channel. Or you can view Fyers API post or PaytmMoney API post as well.