A Nifty 50 heatmap in Python takes the live percentage change of all 50 index stocks, sorts them from top gainer to biggest loser and colours each cell from green to red, so you can read market breadth at a glance. In this Nifty 50 heatmap Python tutorial we fetch live quotes for all 50 stocks in one OpenAlgo multiquotes call, arrange them in a 10 x 5 grid with pandas and draw the heatmap with Plotly, then save it as a PNG.
In this tutorial, we’ll build a real-time stock market heatmap that visualize all 50 stocks from the NIFTY 50 index. The heatmap displays each stock’s daily performance using color gradients, bright green for top gainers, deep red for biggest losers, and shades in between for everything else.

By the end of this tutorial, you’ll have a script that fetches live market data, processes it into a sorted grid, and generates a publication-ready visualization like the one shown above.
- One
client.multiquotes()call fetches LTP and previous close for all 50 stocks through any OpenAlgo-supported broker. - Percentage change = (LTP – previous close) / previous close x 100.
- Integer division and modulo turn a sorted list into a 10 x 5 grid;
pivotreshapes it forpx.imshow. - Kaleido 1.x needs Chrome installed to export PNG images; run
kaleido_get_chromeif export fails. - Never hard-code a real API key in a script you share; load it from an environment variable.
See how the sorted grid from this tutorial behaves. Change the sort order, grid width and market mood, or search for a stock. Values are simulated so you can practise reading a heatmap at any time.
Simulated values for practice only, not live or historical market data. The Python script in this tutorial fetches real quotes through OpenAlgo.
Prerequisites
Before we begin, ensure you have the following installed:
pip install openalgo pandas plotly kaleido
You'll also need a running OpenAlgo server with a valid API key. OpenAlgo connects to 25+ Indian stock brokers and provides a unified API for fetching market data.
Ensure from openalgo, Goto openalgo-> click on profile icon -> Select API Key and Copy the OpenAlgo API Key and keep it secure
Understanding the Building Blocks
Our heatmap solution uses three key libraries:
OpenAlgo handles the connection to your broker and fetches live market quotes. It abstracts away broker-specific APIs, giving you a single interface to work with.
Pandas manages our data in tabular format. We'll use DataFrames to store stock symbols, calculate percentage changes, and prepare data for visualization.
Plotly Express creates the interactive heatmap. It provides the imshow function which is perfect for grid-based visualizations with color gradients.
Step 1: Initialize the OpenAlgo Client
The first step is establishing a connection to your OpenAlgo server:
from openalgo import api
import pandas as pd
import plotly.express as px
# Initialize OpenAlgo client
client = api(
api_key="your_api_key_here",
host="http://127.0.0.1:5000"
)
print("OpenAlgo Python Bot is running.")
Replace your_api_key_here with your actual API key from the OpenAlgo dashboard. The host parameter points to your local OpenAlgo server, adjust this if you're running it on a different machine or port.
Step 2: Define NIFTY 50 Symbols
Create a list containing all 50 stocks from the NIFTY 50 index:
symbols = [
"INDIGO", "TRENT", "HINDUNILVR", "HCLTECH", "WIPRO", "INFY", "TATACONSUM",
"TATASTEEL", "ITC", "ASIANPAINT", "SBILIFE", "LT", "SHRIRAMFIN", "BEL", "SBIN",
"COALINDIA", "KOTAKBANK", "TCS", "SUNPHARMA", "MAXHEALTH", "NESTLEIND",
"RELIANCE", "ETERNAL", "APOLLOHOSP", "ICICIBANK", "GRASIM", "ULTRACEMCO",
"ADANIENT", "AXISBANK", "DRREDDY", "TECHM", "TMPV", "JIOFIN", "NTPC",
"BAJFINANCE", "BHARTIARTL", "POWERGRID", "HINDALCO", "HDFCBANK", "TITAN",
"HDFCLIFE", "MARUTI", "BAJAJFINSV", "ADANIPORTS", "CIPLA", "JSWSTEEL",
"BAJAJ-AUTO", "ONGC", "EICHERMOT", "M&M"
]
Note that NIFTY 50 constituents change periodically. NSE updates the index composition based on market capitalization and liquidity. Always verify the current list from NSE India's official website.
If you need the latest constituents in code rather than a hard-coded list, see how to fetch Nifty 50 symbols using Python and pandas.
Step 3: Fetch Live Market Quotes
OpenAlgo's multiquotes function allows you to fetch data for multiple symbols in a single API call:
# Prepare symbols for API request
quote_symbols = [{"symbol": s, "exchange": "NSE"} for s in symbols]
# Fetch live quotes
response = client.multiquotes(symbols=quote_symbols)
The multiquotes function expects a list of dictionaries, each containing a symbol and exchange key. This is more efficient than making 50 separate API calls.
Step 4: Calculate Percentage Change
Extract the Last Traded Price (LTP) and previous close from each response, then calculate the percentage change:
rows = []
print("\nLive Market Data:")
for item in response["results"]:
symbol = item["symbol"]
ltp = item["data"]["ltp"]
prev_close = item["data"]["prev_close"]
# Calculate percentage change
change_pct = round(((ltp - prev_close) / prev_close) * 100, 2)
print(f"{symbol} | LTP: {ltp} | Change: {change_pct}%")
rows.append([symbol, change_pct])
The formula ((ltp - prev_close) / prev_close) * 100 gives us the percentage change from yesterday's closing price. We round to 2 decimal places for cleaner display.
Step 5: Prepare Data for Heatmap Grid
Transform the data into a grid format suitable for the heatmap:
# Create DataFrame
df = pd.DataFrame(rows, columns=["Symbol", "Change"])
# Sort by change: top gainers first, bottom losers last
df = df.sort_values("Change", ascending=False).reset_index(drop=True)
# Create 10x5 grid layout
cols = 10
df["row"] = df.index // cols
df["col"] = df.index % cols
# Pivot for heatmap
pivot_values = df.pivot(index="row", columns="col", values="Change")
pivot_labels = df.pivot(index="row", columns="col", values="Symbol")
Let's break down the grid logic:
The expression df.index // cols performs integer division to determine the row number. For indices 0-9, this gives row 0; for indices 10-19, row 1; and so on.
The expression df.index % cols uses the modulo operator to determine the column position within each row. Index 0 goes to column 0, index 11 goes to column 1, etc.
The pivot function reshapes our linear data into a 2D grid where rows and columns represent positions on the heatmap.
Step 6: Create the Heatmap Visualization
Use Plotly Express to generate the heatmap:
fig = px.imshow(
pivot_values,
color_continuous_scale="RdYlGn",
aspect="auto"
)
fig.update_traces(
text=pivot_labels.values,
texttemplate="%{text}<br>%{z:.2f}%",
hovertemplate="Symbol: %{text}<br>Change: %{z:.2f}%"
)
fig.update_layout(
title="NIFTY 50 Sorted Heatmap (%)",
xaxis=dict(type="category", title=""),
yaxis=dict(type="category", autorange="reversed", title=""),
template="plotly_dark",
height=600
)
Key configuration options explained:
color_continuous_scale="RdYlGn" uses a Red-Yellow-Green color scale. Negative values appear red, values near zero appear yellow, and positive values appear green.
texttemplate controls what appears inside each cell. The %{text} placeholder shows the symbol name, <br> adds a line break, and %{z:.2f}% displays the percentage value with 2 decimal places.
template="plotly_dark" applies a dark theme that makes the colors pop and is easier on the eyes during market hours.
Step 7: Save the Heatmap
Export the visualization as a high-resolution PNG image:
fig.write_image(
"nifty50_heatmap.png",
width=1200,
height=600,
scale=2
)
print("\nHeatmap saved as nifty50_heatmap.png")
The scale=2 parameter doubles the resolution, producing a crisp 2400x1200 pixel image. This requires the kaleido package for static image export.
Kaleido needs Chrome for PNG export
From Kaleido 1.0 onwards, Chrome is no longer bundled. Kaleido looks for an installed Chrome and, if it finds none, fig.write_image() fails. Install a compatible Chrome with the command below, and use Plotly 6.1.1 or later with Kaleido 1.x (Kaleido on PyPI).
pip install --upgrade plotly kaleido
kaleido_get_chrome
Nifty 50 heatmap Python code: handling missing quotes
The tutorial code assumes every quote comes back. During pre-open, after a symbol change or when the broker returns an error for one stock, item["data"]["ltp"] raises a KeyError and the whole script stops. This version of Step 4 skips missing quotes instead and reports how many came back. The pivot in Step 5 still works with fewer than 50 rows; empty cells are simply left blank.
rows = []
for item in response.get("results", []):
data = item.get("data") or {}
ltp = data.get("ltp")
prev_close = data.get("prev_close")
# Skip symbols with no quote (wrong symbol, broker error, pre-open)
if not ltp or not prev_close:
print(f"Skipping {item.get('symbol')}: quote not available")
continue
change_pct = round(((ltp - prev_close) / prev_close) * 100, 2)
rows.append([item["symbol"], change_pct])
print(f"Got quotes for {len(rows)} of {len(symbols)} symbols")
Save an interactive HTML heatmap
A PNG is ideal for sharing on social media, but an HTML file keeps Plotly's hover labels and zoom. Add these lines after Step 6:
# Save an interactive version you can open in any browser (hover shows values)
fig.write_html("nifty50_heatmap.html", include_plotlyjs="cdn")
# Or open it straight away in a browser window or notebook
fig.show()
Nifty 50 heatmap - full Python code
Security note: the earlier version of this script contained a real-looking OpenAlgo API key. It has been replaced with a placeholder. Keep keys out of code you share; for example use api_key=os.getenv("OPENALGO_API_KEY").
from openalgo import api
import pandas as pd
import plotly.express as px
# ---------------------------------------------------
# OpenAlgo Client
# ---------------------------------------------------
client = api(
api_key="your_api_key_here",
host="http://127.0.0.1:5000"
)
print("OpenAlgo Python Bot is running.")
# ---------------------------------------------------
# NIFTY 50 SYMBOLS
# ---------------------------------------------------
symbols = [
"INDIGO","TRENT","HINDUNILVR","HCLTECH","WIPRO","INFY","TATACONSUM",
"TATASTEEL","ITC","ASIANPAINT","SBILIFE","LT","SHRIRAMFIN","BEL","SBIN",
"COALINDIA","KOTAKBANK","TCS","SUNPHARMA","MAXHEALTH","NESTLEIND",
"RELIANCE","ETERNAL","APOLLOHOSP","ICICIBANK","GRASIM","ULTRACEMCO",
"ADANIENT","AXISBANK","DRREDDY","TECHM","TMPV","JIOFIN","NTPC",
"BAJFINANCE","BHARTIARTL","POWERGRID","HINDALCO","HDFCBANK","TITAN",
"HDFCLIFE","MARUTI","BAJAJFINSV","ADANIPORTS","CIPLA","JSWSTEEL",
"BAJAJ-AUTO","ONGC","EICHERMOT","M&M"
]
# ---------------------------------------------------
# FETCH LIVE QUOTES
# ---------------------------------------------------
quote_symbols = [{"symbol": s, "exchange": "NSE"} for s in symbols]
response = client.multiquotes(symbols=quote_symbols)
rows = []
print("\n📊 Live Market Data:")
for item in response["results"]:
symbol = item["symbol"]
ltp = item["data"]["ltp"]
prev_close = item["data"]["prev_close"]
change_pct = round(((ltp - prev_close) / prev_close) * 100, 2)
# Print immediately (rule)
print(f"{symbol} | LTP: {ltp} | Change: {change_pct}%")
rows.append([symbol, change_pct])
# ---------------------------------------------------
# PREPARE + SORT DATA
# ---------------------------------------------------
df = pd.DataFrame(rows, columns=["Symbol", "Change"])
# SORT: TOP GAINERS → BOTTOM LOSERS
df = df.sort_values("Change", ascending=False).reset_index(drop=True)
# Grid: 10 columns x 5 rows
cols = 10
df["row"] = df.index // cols
df["col"] = df.index % cols
pivot_values = df.pivot(index="row", columns="col", values="Change")
pivot_labels = df.pivot(index="row", columns="col", values="Symbol")
# ---------------------------------------------------
# HEATMAP PLOT
# ---------------------------------------------------
fig = px.imshow(
pivot_values,
color_continuous_scale="RdYlGn",
aspect="auto"
)
fig.update_traces(
text=pivot_labels.values,
texttemplate="%{text}<br>%{z:.2f}%",
hovertemplate="Symbol: %{text}<br>Change: %{z:.2f}%"
)
fig.update_layout(
title="NIFTY 50 Sorted Heatmap (%)",
xaxis=dict(type="category", title=""),
yaxis=dict(type="category", autorange="reversed", title=""),
template="plotly_dark",
height=600
)
# ---------------------------------------------------
# SAVE IMAGE (NO HTML OUTPUT)
# ---------------------------------------------------
fig.write_image(
"nifty50_heatmap.png",
width=1200,
height=600,
scale=2
)
print("\nHeatmap saved as nifty50_heatmap.png")
How to read the Nifty 50 heatmap
- Breadth: count the green and red cells. Thirty-five greens with the index flat means broad buying with a few heavyweights holding the index back.
- Clusters: if all IT names or all banks sit together at one end of the sorted grid, the move is sector-driven.
- Equal weight vs index weight: every cell here is the same size. HDFC Bank and Reliance move the index far more than smaller constituents, so for an index-weighted view use a treemap such as this Plotly treemap of Nifty 50 market cap.
- Colour scale: Plotly scales colours to the day's range. On a quiet day a +0.4% stock can look deep green; pass
range_color=[-3, 3]topx.imshowfor a fixed scale across days.
For a TradingView-style look, compare this with our TradingView-style Nifty 50 heatmap with Highcharts.
Frequently Asked Questions
What is a Nifty 50 heatmap?
It is a grid or treemap of the 50 Nifty stocks coloured by their percentage change for the day, green for gainers and red for losers, so you can see breadth and sector moves at a glance.
Do I need a broker account to run this Nifty 50 heatmap Python script?
Yes. OpenAlgo connects to your broker's API for live quotes, so you need a running OpenAlgo server linked to a supported broker and its API key.
Why does fig.write_image fail with a Chrome error?
Kaleido 1.x does not include Chrome. Install it with kaleido_get_chrome or install Google Chrome normally, and use Plotly 6.1.1 or later.
How do I make a sector-wise Nifty heatmap?
Add a sector column to the DataFrame, then use plotly.express.treemap with path=["Sector", "Symbol"] and color="Change". Sector classifications are available from NSE's index factsheets.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

