Implement Technical Indicators on Realtime Intraday Data using Python
In modern algorithmic trading and market analytics, applying technical indicators on real-time intraday data is crucial for making fast, informed decisions. In this step-by-step guide we explain how to implement technical indicators on realtime intraday data and at the end you’ll be able to:
- Fetch real-time intraday stock data
- Apply indicators like EMA, MACD, and VWAP
- Detect crossover conditions for trade signals
- Print alerts when trade conditions are met
We’ll walk through the Python script, explain each part, and show how it works together to analyze live data using the pandas_ta
library.
Prerequisites
Before we begin, please make sure you have installed Python 3.8+ with the required libraries:
pip install pandas pandas_ta
Also ensure you have access to a module (or class) named MControlAPI
for fetching intraday data. You can learn make this module or get this from my post “Fetch Intraday Data of Stocks for Any Interval Period using Python“.
Overview of the Script
This script does the following:
- Fetches real-time intraday data for a given stock (e.g.,
SBIN
) - Renames and formats the columns for compatibility with indicators
- Applies a strategy with indicators using
pandas_ta
- Evaluates signal conditions for MACD and EMA crossovers
- Prints alerts when a trade signal is detected
Step-by-Step Breakdown
Step 1: Import Required Libraries
import pandas_ta as ta
import pandas as pd
from time import sleep
from intraday import MControlAPI
pandas_ta
: For technical indicators like EMA, MACD, VWAPpandas
: For working with tabular datasleep
: To create a delay between data fetchesMControlAPI
: Custom class to fetch intraday data
Step 2: Initialize Flags and the Data Fetcher
macd_ok = False
ema_ok = False
obj = MControlAPI('SBIN')
nd = 0
macd_ok
,ema_ok
: Track if trade conditions are metMControlAPI('SBIN')
: Initializes the data fetcher for SBIN
Step 3: Fetch Real-Time Data in a Loop
while nd > -1:
nd = obj.fetch_intraday_data()
...
sleep(obj.delta_time)
- Continuously fetches new intraday data
sleep(obj.delta_time)
: Ensures polling interval isn’t too aggressive
Step 4: Format the DataFrame
df = obj.dataframe.copy()
df.rename({'h': 'high', 'l': 'low', 'c': 'close', ...}, axis=1, inplace=True)
df.set_index(pd.DatetimeIndex(df['dt']), inplace=True)
- Renames columns to match
pandas_ta
requirements - Sets the datetime as index for proper time-series behavior
Step 5: Define and Apply a Custom Strategy
customStrategy = ta.Strategy(
name='My Custom Strategy',
description='EMA 9, 29, cross over with MACD and vwap support',
ta=[
{'kind': 'ema', 'length': 9},
{'kind': 'ema', 'length': 26},
{'kind': 'vwap'},
{'kind': 'macd', 'fast': 12, 'slow': 26, 'col_names': ('MACD', 'MACD_H', 'MACD_S')}
]
)
df.ta.strategy(customStrategy, timed=True)
- Combines EMA (Exponential Moving Average), MACD, and VWAP into one strategy
- Applies the strategy to the dataframe using
pandas_ta
Step 6: Analyze the Indicators
prev = df.iloc[-2]
curr = df.iloc[-1]
- Grabs the latest and previous data points to compare values for crossovers
Step 7: Signal Detection Logic
if macd_ok == False and prev['MACD'] < curr['MACD'] and prev['MACD_S'] < curr['MACD_S']:
macd_ok = True
...
if ema_ok and macd_ok and curr['VWAP_D']/curr['close'] < 1.02 and curr['MACD_S'] > curr['MACD']:
print('It is high time to make a position')
- Detects MACD and EMA crossovers
- Checks if the price is close to VWAP
- Triggers a buy signal if all conditions are met
Step 8: Market Close Check
last = obj.dataframe.iloc[-1]['dt']
if (last.hour + last.minute/60) > 15.5:
print('Market is closed')
break
- Stops execution if the current time is after 3:30 PM
The Complete Source Code
Output Example
When run, the script prints the most recent row with the calculated indicators and may show:
It is high time to make a position
This helps automate signal detection without manual chart checking.
Ideas to Extend This Script
- Add more indicators like RSI, Bollinger Bands
- Send alerts via email or Telegram
- Execute simulated or real trades via broker APIs
- Log signals to a CSV or database
Conclusion
Implementing technical indicators on real-time intraday data using Python is a game-changer for any trader or developer looking to build intelligent trading systems.
This guide demonstrated how to:
- Fetch live stock data
- Apply powerful technical indicators using
pandas_ta
- Detect and act on crossover conditions like EMA and MACD
- Trigger alerts when a trade setup is formed
With just a bit of customization, you can adapt this to any stock or strategy. Start experimenting and take your intraday analysis to the next level!
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.