Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Visualizing Nifty 50 Market Capitalization using Plotly Treemap – Python Tutorial

5 min read

A Nifty 50 market cap treemap draws every index stock as a rectangle whose area is proportional to its free float market capitalisation, so you can see at a glance which companies dominate the index. Below is the Python code to build one with Plotly Express in about ten lines, a line-by-line explanation, and an extended version that colours each stock by its daily % change like a market heatmap.

Key Takeaways

  • Nifty 50 is computed using the free float market capitalisation method, which is why a treemap sized by free float market cap is a good picture of each stock’s influence on the index.
  • With Plotly Express, px.treemap(data, path=[...], values=...) is all you need; the rest of the code is data cleaning.
  • The sample CSV is a December 2023 snapshot. Replace it with the latest data from NSE to get a current picture.
  • Adding a color column (for example % change) turns the treemap into a heatmap of the day’s market move.

In the domain of data science, visualization is not just an aesthetic choice but a crucial aspect of analysis. It’s the process that transforms numbers and datasets into visual context, bringing clarity and insight to complex information. For financial markets, where understanding trends, patterns, and anomalies can be the difference between profit and loss, the value of visualization is unparalleled. It translates intricate market data into understandable and actionable visuals, enabling traders, analysts, and strategists to make informed decisions swiftly.

What is Treemap Visualization?

Treemap is a powerful visualization tool that portrays hierarchical data via nested rectangles. In the context of the stock market, each rectangle represents a stock entity, and its size reflects a quantitative variable, such as market capitalization. This method is particularly effective in displaying the proportionate market share of companies within an index like Nifty 50.

Python for traders, the quick way in

BEGINNER FRIENDLY · RATED 5.0

Python for traders, the quick way in

A crash course that gets you from zero to writing your own market data scripts.

  • Python basics with market examples
  • Fetch, clean and chart price data
  • Lifetime access
Start learning →by Marketcalls

Plotly Library for Treemap Visualization

Plotly, a leading library in Python for interactive data visualization offers an extensive range of plotting options, including the treemap. It excels in creating sophisticated plots that are not just visually appealing but interactive, allowing users to hover over, zoom, and click for more detailed information. For stock market data, this interactivity is invaluable, providing a dynamic way to explore and analyze the market’s composition and trends.

Below is a step-by-step guide explaining the provided Python code for creating a treemap visualization of Nifty 50 companies based on their market capitalization using Plotly.

The Data: What Is in the CSV

The script reads a small CSV hosted on the marketcalls GitHub repository (marketcap.csv). It has 50 rows and four columns:

ColumnExampleMeaning
SymbolHDFCBANKNSE trading symbol
Perchange0.23%% change on the day the snapshot was taken
Indexweight13.67%Weight of the stock in Nifty 50
Marketcap“1,274.61”Free float market cap in ₹ thousand crore

All four columns load as text, which is why the market cap column has to be cleaned of commas before it can size the rectangles. The snapshot dates from December 2023, when HDFC Bank alone was 13.67% of the index and the top ten stocks made up well over half of it.

Step-by-Step Code Explanation

Importing Libraries and Loading Data

  • The script begins by importing necessary libraries: pandas for data manipulation and plotly.express for visualization.
pip install pandas
pip install plotly
  • It loads the market capitalization data of Nifty 50 companies from a CSV file into a pandas DataFrame.
import pandas as pd
import plotly.express as px

# Load the data from a CSV file
data = pd.read_csv('https://raw.githubusercontent.com/marketcalls/data/main/marketcap.csv')

Data Cleaning and Preparation

  • The ‘Marketcap’ column is cleaned to remove any currency symbols and commas, and then converted into float values for numerical operations.
  • A ‘Company’ column is created from the ‘Symbol’ to represent company names.
  • A custom ‘Label’ is generated by combining the company symbol with its market cap, formatted for readability.
data['Marketcap'] = data['Marketcap'].replace('[\$,]', '', regex=True).astype(float)
data['Company'] = data['Symbol']
data['Label'] = data['Symbol'] + "<br>" + data['Marketcap'].apply(lambda x: f"₹{x:,.2f}")

Creating the Treemap

  • Using Plotly Express, a treemap is created with the ‘Label’ as the path and ‘Marketcap’ as the values. This designates the size of each rectangle.
  • The title provides context, indicating these are free float market cap values of Nifty 50 companies.
  • The figure’s layout is updated to specify the size, ensuring the treemap is spacious and clear.
  • Finally, fig.show() renders the plot. In an interactive Python environment, this will display a dynamic treemap where users can hover over individual stocks to see detailed information.
fig = px.treemap(data, path=['Label'], values='Marketcap', title='Market Capitalization - Nifty50 Companies - (Free float marketcap values in ₹ thousand cr.)')
fig.update_layout(width=1200, height=700)
fig.show()

Complete Python Code to Visualise the Nifty 50 Market Cap

import pandas as pd
import plotly.express as px

# Load the data from a CSV file
data = pd.read_csv('https://raw.githubusercontent.com/marketcalls/data/main/marketcap.csv')

# Clean the 'MarketCap' column and convert it to floats
data['Marketcap'] = data['Marketcap'].replace('[\$,]', '', regex=True).astype(float)

# Now that we have cleaned the 'MarketCap' column, we can proceed.
data['Company'] = data['Symbol']  # Create a column for company names if not already present


# Create a custom label that combines the company symbol with the market cap
# Format the market cap as you prefer, here it's formatted as a float with two decimal places
data['Label'] = data['Symbol'] + "<br>" + data['Marketcap'].apply(lambda x: f"₹{x:,.2f}")

# Create the treemap using Plotly Express
fig = px.treemap(data, path=['Label'], values='Marketcap',
                 title='Market Capitalization - Nifty50 Companies - (Free float marketcap values in ₹ thousand cr.)')


# Set the figure size
fig.update_layout(width=1200, height=700)

# Show the plot
fig.show()

Updated Version (2026): Treemap Coloured by % Change

The original code still runs with current pandas and Plotly versions (I tested it with pandas 3.1 and Plotly 7.1). Python 3.12 and later print a SyntaxWarning: invalid escape sequence for the '[\$,]' pattern, so the version below uses a raw string. It also uses the other two columns in the CSV: the treemap is coloured by the day’s % change on a red-to-green scale and the index weight appears in the hover box.

import pandas as pd
import plotly.express as px

data = pd.read_csv('https://raw.githubusercontent.com/marketcalls/data/main/marketcap.csv')

# Clean text columns into numbers
data['Marketcap'] = data['Marketcap'].replace(r'[\$,]', '', regex=True).astype(float)
data['Weight'] = data['Indexweight'].str.rstrip('%').astype(float)
data['Change'] = data['Perchange'].str.rstrip('%').astype(float)

fig = px.treemap(
    data,
    path=[px.Constant('Nifty 50'), 'Symbol'],
    values='Marketcap',
    color='Change',
    color_continuous_scale='RdYlGn',
    color_continuous_midpoint=0,
    hover_data={'Weight': ':.2f'},
    title='Nifty 50 - Free float market cap (₹ thousand cr.), coloured by % change',
)
fig.update_traces(texttemplate='%{label}<br>%{value:,.0f}')
fig.update_layout(width=1200, height=700)
fig.show()          # or fig.write_html('nifty50_treemap.html')

px.Constant('Nifty 50') adds a root rectangle so the whole index sits inside one parent box, and color_continuous_midpoint=0 makes 0% the neutral yellow so gainers are green and losers red. If you add a Sector column to the CSV, change the path to [px.Constant('Nifty 50'), 'Sector', 'Symbol'] and Plotly will group stocks by sector with click-to-zoom. The Plotly treemap docs list the remaining options.

Using Current Nifty 50 Weights

Index weights change every day with prices and at each semi-annual rebalance. For comparison with the 2023 snapshot, here are the top ten weights from the NSE Indices Nifty 50 factsheet dated 30 October 2026:

CompanyWeight (Oct 2026)
HDFC Bank9.95%
ICICI Bank9.39%
Reliance Industries7.30%
Bharti Airtel5.63%
Larsen & Toubro4.25%
Infosys3.92%
State Bank of India3.73%
Axis Bank3.28%
Kotak Mahindra Bank3.19%
Bajaj Finance2.40%
Source: NSE Indices, Nifty 50 factsheet

HDFC Bank has dropped from 13.67% to under 10% and Bharti Airtel has moved into the top five, which is exactly the kind of shift a treemap makes obvious. To refresh the chart, download the current constituent list with market caps from the NSE website, save it with the same four column names and point read_csv() at your file.

How to Read a Nifty 50 Treemap

  • Concentration: the few largest rectangles (banks, Reliance, Infosys, Airtel) move the index more than the other 40 stocks combined.
  • Sector tilt: grouping by sector shows how heavily the index leans on financials.
  • Breadth: with colour by % change, a green index on a day when most small rectangles are red tells you the move came from a few heavyweights.

For other ways to visualise the same index, see the TradingView-style Nifty 50 heatmap with Highcharts and the Nifty 50 heatmap Python tutorial.

Frequently Asked Questions

What is a treemap in Python?

A treemap is a chart that shows hierarchical data as nested rectangles, with each rectangle’s area proportional to a value. In Python, Plotly Express creates one with px.treemap(), and the result is interactive in a browser or notebook.

How is the Nifty 50 market cap calculated?

Nifty 50 uses the free float market capitalisation method: each stock’s market cap is multiplied by the share of its equity available for public trading, and index weights are based on these free float values. The index is rebalanced semi-annually.

Which stock has the highest weight in Nifty 50?

HDFC Bank, with a weight of 9.95% as per the NSE Indices factsheet of 30 October 2026, followed by ICICI Bank and Reliance Industries.

How do I save a Plotly treemap as an image or HTML?

Use fig.write_html('treemap.html') for an interactive file. For PNG or JPG, install the kaleido package and call fig.write_image('treemap.png').

Wrapping Up

This guide showed you how to build a treemap with Plotly and Python, giving you a live picture of the Nifty 50’s market cap. These visuals are super handy. They give real insights that help analysts, traders, and anyone into stocks get the hang of the market’s twists and turns.

If you want to go further with interactive charts, using Plotly and Pandas TA shows how to add technical indicators to Plotly charts.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More