[Plotly Treemap][1]
** EDIT I got it doing what I wanted to do, code is updated below
For background this is my little crypto tracker that I'm using for keeping track of my crypto portfolio, there is a csv file with the headings.
symbol,amount,PurchasePrice
(crypto token), (amount owned), (priced of token at purchase)
MLNUSDT,1.75,1
The idea is to have a plotly treemap plotted with the labels
symbol
Value (amount * current market price)
Purchase Price (amount * PurchasePrice)
% change
I'm trying to work out how to get this script to show labels underneath the symbols. There doesn't seem to be much documentation and I'm kinda confused?
This is the code I have which is working at the moment, but there aren't labels in the treemap. I've tried a few different variations of the labels but I haven't had anything that has worked.
import requests
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
# Binance API endpoint for ticker prices (public)
binance_api_url = "https://api.binance.com/api/v3/ticker/price"
# Read the portfolio from the CSV file
portfolio_df = pd.read_csv('Crypto.csv')
# Fetch real-time prices from Binance (public API)
prices = {}
for index, row in portfolio_df.iterrows():
symbol = row['symbol']
response = requests.get(binance_api_url, params={'symbol': symbol})
try:
data = response.json()
prices[symbol] = float(data['price'])
except KeyError as e:
print(f"Error fetching price for {symbol}. Response: {response.text}")
prices[symbol] = None
# Filter out symbols with missing prices
portfolio_df = portfolio_df[portfolio_df['symbol'].isin(prices.keys())]
# Calculate the total value of each cryptocurrency in the portfolio
portfolio_df['value'] = round((portfolio_df['amount'] * portfolio_df['symbol'].map(prices)),2)
portfolio_df["PurchaseCost"] = portfolio_df['amount'] * portfolio_df['PurchasePrice']
portfolio_df["PercentageChange"] = round((portfolio_df['symbol'].map(prices)/portfolio_df["PurchasePrice"])*100-100,2)
# Calculate the total value of the portfolio
total_portfolio_value = portfolio_df['value'].sum()
portfolio_cost = (len(portfolio_df.index) + 1)*100
portfolio_percentage = round((total_portfolio_value/portfolio_cost-1)*100,2)
# Create a treemap with a dummy parent symbol
portfolio_df['parent'] = 'All Cryptocurrencies'
fig = px.treemap(
names=portfolio_df['symbol'],
parents=portfolio_df['parent'],
values=portfolio_df['value'],
#labels=portfolio_df['PurchaseCost'],
title=f"Crypto Portfolio Treemap (Current Value: {total_portfolio_value:.2f} USD {portfolio_percentage}%)", # Use double quotes for the title
color=portfolio_df['value'],
color_continuous_scale='Viridis'
)
# token label
# Value (current token price * amount of tokens owned)
# Purchase value (purchause price * amount of tokens owned)
# Percentage change of token in %
fig.data[0].customdata = np.column_stack([portfolio_df['symbol'], portfolio_df['value'], portfolio_df["PurchaseCost"], portfolio_df["PercentageChange"] ])
fig.data[0].texttemplate = "%{customdata[0]}<br>Current Value: $%{customdata[1]}<br>Purchase Value: $%{customdata[2]}<br>Percentage Change: %{customdata[3]}%"
# Show the treemapR
fig.show()