How to Install Python on Windows 10

Do you want to learn how to install Python 3.10 on Windows 10 Computer in depth so you can install it in any computer without help. Then, you are at the right place, just keep reading till the end and you will be able to do it yourself. What is Python? Python is a powerful, […]

Continue reading...

Recent Post

31 May 2025

How to Create a Virtual Machine in VirtualBox and Install Ubuntu

Continue reading

Featured Post

25 May 2023

How to Fetch Stock’s Historical Data From NSE India in Python

Continue reading

If you’re working with real-time trading strategies, backtesting, or data visualization, having access to flexible intraday stock data is essential. In this tutorial, you’ll learn how to fetch intraday data of stocks for any interval period from Moneycontrol for any time interval (1-min, 5-min, 15-min, etc.) using Python.

We’ll walk through a complete Python script that:

  • Pulls intraday data via an API
  • Supports multiple intervals (resolutions)
  • Converts data into a Pandas DataFrame
  • Continuously updates until the market closes

Prerequisites

Before you begin, ensure you have:

  • Basic knowledge of Python
  • Python 3.8+ installed
  • requests, pandas, and datetime modules available (install using pip install pandas requests datetime)

What This Script Does

The script leverages Moneycontrol’s charting API to fetch and update stock data for any given interval. It creates a class MControlAPI which:

  • Accepts a stock symbol (e.g., SBIN, NIFTY50)
  • Fetches intraday data in your preferred resolution (e.g., 1-minute, 15-minute)
  • Stores it in a Pandas DataFrame
  • Automatically continues fetching data as time progresses

Step-by-Step Guide with Script Explanation

Step 1: Import Required Libraries

import requests 
from datetime import datetime
from time import sleep
import pandas as pd
  • HTTP requests (requests)
  • Timestamps and delays (datetime, sleep)
  • Data manipulation (pandas)

Step 2: Define the MControlAPI Class

class MControlAPI:
    ...

This class manages everything — from building URLs to handling sessions and storing data.

Step 3: Initialize Class Parameters

def __init__(self, symbol, resolution=1, data_from=None, data_to=datetime.now()) -> None:
    ...

Key arguments:

  • symbol: Stock symbol (like NIFTY50, SBIN, RELIANCE)
  • resolution: Interval in minutes (1, 5, 15, 60, etc.)
  • data_from: Optional start date (timestamp)
  • data_to: Default is the current time

A resolution-to-seconds map is stored in self.resolution_dt, allowing flexible intervals like 1, 5, 15, 60 minutes, or even daily/weekly/monthly.

self.resolution_dt = {
  '1': 60, '3': 180, '5': 300, '15': 900, '30': 1800, 
  '60': 3600, '300': 18000, 'D': 86400, 'W': 604800, 
  'M': 2592000, '45': 3888000, '120': 10368000, '240': 20736000
}

Step 4: Set up the Session

self.session = requests.sessions.Session()
self.session.headers['User-Agent'] = 'Mozilla/5.0 ...'
self.session.get('https://www.moneycontrol.com/stocksmarketsindia/')
  • A custom User-Agent ensures the API doesn’t block the request.
  • The session keeps cookies and headers consistent.

Step 5: Fetch Intraday Data

def fetch_intraday_data(self, countback=None):

This function:

  • Calls the Moneycontrol intraday data API.
  • Calculates how many candles (data points) to fetch.
  • Converts UNIX timestamps to datetime (df['dt']).
  • Appends new data to the DataFrame, removing duplicates.

Key logic:

df['dt'] = pd.to_datetime(df['t']+19800, unit='s')  # Add 5.5 hrs for IST

It intelligently handles:

  • First-time load (empty DataFrame)
  • Subsequent fetches (merging only new timestamps)

Step 6: Run the Script in Real-Time

if __name__ == "__main__":
    mc = MControlAPI('NIFTY50')
    nd = 0
    while nd > -1:
        nd = mc.fetch_intraday_data()
        ...
        sleep(mc.delta_time)
  • Creates an object to fetch data for NIFTY50
  • Keeps fetching and printing new data
  • Stops fetching once the market closes (after 3:30 PM IST)

The Complete Source Code

Output Sample

The output will be a continuously growing DataFrame with columns like:

  • c: close price
  • h: high
  • l: low
  • o: open
  • t: timestamp
  • v: volume
  • dt: human-readable datetime

Example:

             c     h     l     o         dt
0  523.10  525.5  522.8  524.0 2024-06-01 11:15:00
...

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.

Customize It

You can customize this for your needs:

  • Change resolution to '5', '15', or '60' for different intervals
  • Log data to a CSV: mc.dataframe.to_csv(‘intraday_data.csv’)
  • Analyze patterns or apply indicators using libraries like pandas_ta

Conclusion

Fetching intraday stock data at custom intervals using Python provides traders, analysts, and developers with immense flexibility to perform real-time analysis or build powerful trading tools. In this guide, we leveraged the Moneycontrol API and a custom Python class to retrieve and update stock data dynamically. Whether you’re monitoring price movements on a 1-minute chart or analyzing patterns over several hours, this solution can be tailored to your needs. With this approach, you can automate data collection, run technical strategies, and stay ahead in today’s fast-moving markets — all with just a few lines of code. If you want to implement technical indicators using this script here is the post for you “Implement Technical Indicators on Realtime Intraday Data using Python“.

If you are interest in more guides related to trading, you can visit here trading.

And for more python guides visit here Python.

You can explore more informative videos at my YouTube Channel.



About

In TutLogic, we want to share our knowledge with all of the Internet community and welcome your feedback as well. Whether you want to learn with videos or textual articles, it is all available for everyone at tutlogic.com and at our YouTube Channel.