Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Visualizing Nifty 50 Market Capitalization using Plotly Treemap – Python Tutorial

2 min read

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.

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.

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()

Here is the Complete Python Code to Visualze the Nifty 50 Marketcap

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()

This guide showed you how to build a cool treemap with Plotly and Python, giving you a live picture of the Nifty 50’s market cap. These visuals are super handy – they’re not just pretty pictures, but real-deal insights that help analysts, traders, and anyone into stocks get the hang of the market’s twists and turns.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Voice Commands to Trade on OpenAlgo Platform Using Google…

Trading platforms are always getting better by using the newest technologies to make things easier and more efficient for users. A great example of...
Rajandran R
5 min read

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

How to Place Orders Concurrently using ThreadPoolExecutor – Python…

Creating concurrent orders is essential for active traders, especially those handling large funds, as it allows for executing multiple trade orders simultaneously, thereby maximizing...
Rajandran R
2 min read

Leave a Reply

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