Building A Stock Market Treemap in 10 Steps

Ulas Yilmaz
3 min readMay 29, 2023

--

Hi.

I follow stock markets almost daily for investments. During the process, I have come accross a treemap visual that gives me an idea about stocks’ market cap, daily changes and sectors. It is available in TradingView and finviz.com. So I started to search how to make my own.

This is not a professional treemap, and definitely not to be used for commercialization or as an investment suggestion but a very good visual to follow your portfolio. And please note that it comes with delay as Google finance data.

Instead of receiving market data from a paid stock market data provider, my workaround is to use google sheets and google finance formulas to build data source for treemap.

So lets start:

In Wikipedia, treemapping described as :

“ In information visualization and computing, treemapping is a method for displaying hierarchical data using nested figures, usually rectangles.”

plotly — world population vs life expectatncy

It has many use cases, however, visualizing sectors and tickers, their market cap and daily performance is useful for someone who follows the markets.

Here is a shot from finviz.com:

finviz.com

What does it tell:

  • Technology is the biggest sector in S&P500
  • Microsoft and Apple are the biggest (in terms of market cap)companies in S&P 500.
  • The most green companies are highest positive change in the day by stock price
  • Red ones are the companies with stock price decreasing vs. previous day

It is simple chart that gives a quick understanding of market and sectors performance.

So lets start to build our own.

STEP 1: Create google sheet, insert tickers and google finance formulas

  • Go to google sheets and create your ticker list with below formulas
Google sheets with tickers and finnace formulast

STEP 2: Share the sheet

We need to make the document available to anyone with the link so our code will be able to read.

Select «Anyone with the link» from General access tab. Click on Done

Then copy the link of the document for later use

make it availabe to anyone with the link

Now go to your terminal , and install below libraries:

STEP 3: install libraries

pip install plotly
pip install numpy
pip install pandas
pip install matplotlib

STEP 4: Open Jupyter Notebook install libraries

import matplotlib.pyplot as plt
import os
import pandas as pd
import numpy as np
import plotly.express as px

STEP 5: Read Google Sheets document and format to link to read it as csv

sheet_url = your google sheet document link here
url_1 = sheet_url.replace('/edit#gid=', '/export?format=csv&gid=')
df=pd.read_csv(url_1)

STEP 7: Dataframe column adjustments

df['marketcap']=df['marketcap'].astype('float')
df2=df[['ticker','sector','delta','marketcap']].copy()

STEP 8: Set up color scale

color_group = [-1,-0.02,-0.01,0, 0.01, 0.02,1]
df2['colors'] = pd.cut(df['delta'], bins=color_group, labels=['red','indianred','gray','lightgreen','lime','green'])

STEP 9: Create treemap

fig = px.treemap(df2, path=[px.Constant("all"), 'sector','ticker'], values = 'marketcap', color='colors', height=700,
color_discrete_map ={'(?)':'#262931', 'red':'red', 'indianred':'indianred','gray':'gray', 'lightgreen':'lightgreen','lime':'lime','green':'green'},
hover_data = {'delta':':.2p'},
custom_data=['delta','sector']

STEP 10: Update chart elements and display the graph

fig.update_traces(
hovertemplate="<br>".join([
"Stock: %{label}",
"Market Cap(M): %{value}",
"Delta: %{customdata[0]:.2p}",
"Sector: %{customdata[1]}",
])
)
fig.data[0].texttemplate = "<b>%{label}</b><br>%{customdata[0]:.2p}«
fig.show()

And here it is :

a stock market treemap with selected sectors

Please note that I have used 4 sectors in S&P 500 for visual simplicity: Communication services, Consumer staples, Energy and Utilities

However, you can choose your ticker and sector and fi,ll Google Sheets accordingly.

References:

1- www.finviz.com

2- Create A Stock Market Heat Map Using Python

3- Plotly: treemaps

4- Read Data from Google Sheets into Pandas without the Google Sheets API

--

--