# 96|PYTHON – Investment Visualizations

**URL:** <https://www.techhub.training/t/96-python-investment-visualizations/649>\
**Category:** Challenges\
**Tags:** intermediate, python, visualization\
**Created:** [May 13, 2023, 6:41pm UTC](https://www.techhub.training/t/96-python-investment-visualizations/649 "2023-05-13T18:41:08Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hyrum](https://sea2.discourse-cdn.com/flex016/user_avatar/www.techhub.training/hyrum/32/90_2.png) [@Hyrum](https://www.techhub.training/u/Hyrum)\
**Post date:** [May 13, 2023, 6:41pm UTC](https://www.techhub.training/t/96-python-investment-visualizations/649/1 "2023-05-13T18:41:08Z")

</div>

_BYU Student Author_: @Hyrum  
_Reviewers_: @Donovon, @Erick_Sizilio  
_Estimated Time to Solve:_ 20 Minutes

We provide the solution to this challenge using:

- Python

Need a program? Click [here](https://www.techhub.training/t/information-about-software-used-on-techhub-training/138).

**Overview**  
You and your friend just returned from a game-changing talk about smart investing, and you’re feeling invigorated and ready to start your investment journey. But you’re not going to settle for just any kind of investing - you want to do it the smart way.

You and your friend decide to take on the ultimate challenge and investigate some companies. Your goal? To find the best investment opportunities and earn passive income like a boss!

You come across a spreadsheet filled with data about different companies, and you’re eager to start analyzing. But there’s a catch, you don’t have the fancy software like Tableau or Alteryx to make the kind of graphs you want. But don’t worry, you’ve got a secret weapon: your top-notch python skills!

With determination and a can-do attitude, you start creating some seriously impressive tables in Python. You’re not going to let a lack of resources hold you back - you’re going to make this happen no matter what.

As you work, you can feel your excitement growing. You’re learning new things, honing your skills, and taking control of your financial future like a pro. And when you’re finished, you’ve got some seriously impressive visualizations that are going to take your investment game to the next level.

**Instructions**  
Upload the datasheet from the link as a DataFrame and fill all the null values with 0. Then make the following graphs.

1. Make a bar graph that shows the top ten revenue growth companies with their revenue growths shown as percentages, like the graph below:  

2. After considering the matter, you may wonder if pursuing revenue growth is the optimal course of action. While revenue growth is typically an indicator of a company’s expansion, it does not guarantee a positive return for investors. As such, it may be beneficial to assess the return on equity, which is a traditional metric used to gauge investor returns. To evaluate the relationship between revenue growth and return on equity, a regression analysis can be conducted. Conduct that regression analysis by making a scatterplot and making a regression line through it.

3. You have decided to gather additional information and have concluded that return on equity is more critical than revenue growth information. While revenue growth can provide insight into a company’s future, it may not have a direct impact on you as an investor. Therefore, you have chosen to focus on evaluating return on equity, enterprise value, and debt-to-equity measures. You plan to analyze all three measures simultaneously by creating a 3D graph with these metrics as the different axes. Additionally, you plan to use the short name of the company as a color-coding mechanism to differentiate them on the graph.

**Data Files**

- [Challenge96\_Data.xlsx](https://byu.box.com/shared/static/00sz8md0q9uay2hh319k4j2fxn89l1ca)
- [Challenge96\_Data\_Dictionary.docx](https://byu.box.com/shared/static/h45axynhgyihcopum1ibgekqqr0y50zw)

> **Suggestions and Hints**
>
> Use matplotlib, pandas, seaborn, numpy, scipy.stats, plotly.express
> 
> Here are some resources that can help with the application of these codes:
> 
> - [How to Create a Bar Chart in Python using Matplotlib – Data to Fish](https://datatofish.com/bar-chart-python-matplotlib/)
> - [Learn how to create beautiful and insightful charts with Python — the Quick, the Pretty, and the Awesome | by Fabian Bosler | Towards Data Science](https://towardsdatascience.com/plotting-with-python-c2561b8c0f1f)
> - [3d scatter plots in Python](https://plotly.com/python/3d-scatter-plots/)
> 
> For the bar graph, follow these steps:
> 
> - Filter the DataFrame to show only the top 10 companies with the highest revenue growth.
> - Sort the top 10 companies by the revenueGrowth column in descending order.
> - Plot a bar graph of the top 10 companies with the highest revenue growth, sorted by value.
> - Get the largest revenueGrowth amount.
> - Add a text message to the side of the graph with the largest revenueGrowth amount.
> - Add a y-label.
> - Display the y-axis labels as percentages.
> - Display the graph.
> 
> For the regression analysis, follow these steps:
> 
> - Create the scatter plot with seaborn.
> - Add axis labels and title.
> - Calculate the linear regression line using scipy.stats.linregress.
> - Plot the linear regression line.
> - Plot the r value, p-value, r square value, and linear regression equation on the image as text.
> - Show the plot.
> 
> For the 3-D graph, follow these steps:
> 
> - Select the relevant columns for the 3D scatter plot.
> - Create the 3D scatter plot.
> - Display the graph.
> 
> For further hints, here is what the second two graphs are meant to look like:  
> ![Challenge96_Image_2](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/1X/6af546e3330d2112b73928503e5af331db7bded1.png)
> 
> ![Challenge96_Image_3](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/1X/fc020017d9d26be780420181332dfe0cfff5bc27.png)

**Solution**

Upload the datasheet as a DataFrame and fill all the null values with 0.

![Challenge96_Solution_Image_1](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/1X/98423bde0ed63b4d5da528f93ac52feca14073e4.png)

> **Bar Graph**
>
> ![Challenge96_Solution_Image_2](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/1X/2e63af64fad3dc882d3389b06bc133669afddf8b.png)

> **Regression Analysis**
>
> ![Challenge96_Solution_Image_3](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/1X/ff14465dd052ff7ab1cae90aa4b38a00bcfe15ae.png)

> **3-D Graph**
>
> ![Challenge96_Solution_Image_4](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/1X/06c4b3a4fa985551773e0db23228772f1cd815af.png)

_Solution Video:_ [Challenge 96|PYTHON – Investment Visualization](https://youtu.be/hDTfDuzbit8)

---

<div class="post-metadata">

**Author:** ![Gage\_Smith](https://avatars.discourse-cdn.com/v4/letter/g/7feea3/32.png) [@Gage\_Smith](https://www.techhub.training/u/Gage_Smith)\
**Post date:** [December 14, 2023, 8:26pm UTC](https://www.techhub.training/t/96-python-investment-visualizations/649/2 "2023-12-14T20:26:03Z")

</div>

I really liked this challenge! It was especially cool to use a 3-D graph!  
Here is my solution!

 ![Screenshot 2023-12-14 at 1.16.39 PM](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/1/1f157637bf4a46982bdf97c720133f6329910427.jpeg)  
 ![Tech1](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/3/374e264394c4b624d72238fb84b12881271a03a3.jpeg)  
 ![Tech2](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/8/810657015ccee62f452f021922f89635637be75c.png)

Here is my code!

import matplotlib.pyplot as plt  
import pandas as pd  
from scipy.stats.mstats import winsorize, trim  
import numpy as np  
import math  
from glob import glob  
import warnings  
import seaborn as sns  
warnings.filterwarnings(“ignore”)

df=pd.read\_excel(‘Challenge96\_Data.xlsx’)  
df.fillna(0, inplace=True)  
df.sort\_values(by=‘revenueGrowth’, ascending=False,inplace=True)  
df\_10=df.head(10)  
df\_10.head(10)

plt.bar(df\_10[‘shortName’],df\_10[‘revenueGrowth’], label=‘revenueGrowth’)  
plt.ylabel(‘Revenue Growth’)  
plt.xlabel(‘Short Name’)  
plt.xticks(rotation=90)  
plt.legend(loc=‘upper right’)  
plt.yticks([5,10,15,20,25,30],[‘5%’,‘10%’,‘15%’,‘20%’,‘25%’,‘30%’])  
multiline\_text = “Largest revenue Growth amount:\n30.65%”  
plt.text(2.5, 15, multiline\_text, ha=‘left’, va=‘center’, fontsize=14) ## adds text  
plt.show()

import matplotlib.pyplot as plt  
import numpy as np  
from scipy.stats import linregress  
##Generate some example data  
##Perform linear regression  
slope, intercept, r\_value, p\_value, std\_err = linregress(df[‘revenueGrowth’], df[‘returnOnEquity’])  
##Print the regression parameters  
print(f"Slope: {slope}“)  
print(f"Intercept: {intercept}”)  
print(f"R-squared value: {r\_value**2}“)  
print(f"P-value: {p\_value}”)  
print(f"Standard error: {std\_err}")  
##Calculate the regression line  
slope, intercept = np.polyfit(df[‘revenueGrowth’], df[‘returnOnEquity’], 1)  
regression\_line = slope \* df[‘revenueGrowth’] + intercept  
##Create a scatter plot  
plt.scatter(df[‘revenueGrowth’], df[‘returnOnEquity’], label=‘Data Points’)  
slope=slope.round(3)  
r\_value=r\_value.round(3)  
p\_value=p\_value.round(3)  
multiline\_text = f"slope:{slope}\nr-squared:{(r\_value**2).round(3)} \nP-value: {p\_value}\nregression equation: {slope}x + {intercept.round(2)}"  
plt.text(5, 10, multiline\_text, ha=‘left’, va=‘center’, fontsize=14) ## adds text  
##Plot the regression line  
plt.plot(df[‘revenueGrowth’], regression\_line, color=‘red’, label=‘Regression Line’)  
##Add labels and legend  
plt.xlabel(‘Revenue Growth’)  
plt.ylabel(‘Return on Equity’)  
plt.legend()  
##Show the plot  
plt.show()

import matplotlib.pyplot as plt  
from mpl\_toolkits.mplot3d import Axes3D  
import seaborn as sns  
import random  
##Sample data  
##Create a figure and a 3D axis  
fig = plt.figure()  
plt.figure(figsize=(40,20))  
ax = fig.add\_subplot(111, projection=‘3d’)  
##Plot a 3D line  
##ax.scatter(df[‘enterpriseValue’],df[‘returnOnEquity’], df[‘debtToEquity’], label=‘3D Line’)  
##Set axis labels  
ax.set\_ylabel(‘Return On Equity’)  
ax.set\_zlabel(‘Debt to Equity’)  
ax.set\_xlabel(‘Enterprise Value’)  
##Generate random colors for each point  
num\_points = len(df[‘shortName’])  
colors = sns.color\_palette(“husl”, n\_colors=num\_points)  
##Plot 3D points with names and random colors  
for name, xi, yi, zi, color in zip(df[‘shortName’],df[‘enterpriseValue’],df[‘returnOnEquity’], df[‘debtToEquity’], colors):  
ax.scatter(xi, yi, zi, c=[color], marker=‘o’, label=name)  
ax.invert\_yaxis()  
##Add a legend  
legend = ax.legend(loc=‘upper left’, bbox\_to\_anchor=(1.25, 1), prop={‘size’: 8})  
##Show the plot  
plt.show()

---

<div class="post-metadata">

**Author:** ![Hadley\_Olsen](https://avatars.discourse-cdn.com/v4/letter/h/76d3ee/32.png) [@Hadley\_Olsen](https://www.techhub.training/u/Hadley_Olsen)\
**Post date:** [December 14, 2023, 9:26pm UTC](https://www.techhub.training/t/96-python-investment-visualizations/649/3 "2023-12-14T21:26:32Z")

</div>

This was great! Here is my solution

import matplotlib.pyplot as plt

import pandas as pd

import matplotlib.ticker as mtick

import seaborn as sms

import numpy as np

from scipy.stats import linregress

import plotly.express as px

df = pd.read\_excel(“Challenge96\_Data.xlsx”)

df = df.fillna(0)

top\_10 = df.nlargest(10, ‘revenueGrowth’)

top\_10 = top\_10.sort\_values(‘revenueGrowth’, ascending = False)

top\_10.head()

max\_revenueg = top\_10[‘revenueGrowth’].max()

fig, ax = plt.subplots(figsize=(10, 6))

bars = ax.bar(top\_10[‘shortName’], top\_10[‘revenueGrowth’])

ax.set\_ylabel(‘Revenue Growth’)

ax.set\_xlabel(‘Short Name’)

# Rotate x-tick labels for better readability

ax.set\_xticklabels(top\_10[‘shortName’], rotation=45, ha=‘right’)

# Adjust layout to prevent clipping of tick-labels

fig.tight\_layout()

ax.set\_ylim(0, max\_revenueg)

ax.text(.4, 0.5, f’Largest revenueGrowth amount:\n{(max\_revenueg/100):.2%}', transform=ax.transAxes, fontsize=12, va=‘center’)

fmt = ‘%.0f%%’

yticks = mtick.FormatStrFormatter(fmt)

ax.yaxis.set\_major\_formatter(yticks)

ax.legend(loc=‘upper right’)

plt.show()

plt.scatter(df[‘revenueGrowth’], df[‘returnOnEquity’])

plt.xlabel(‘Revenue Growth’)

plt.ylabel(‘Return on Equity’)

plt.title(‘Scatter Plot of Revenue Growth vs. Return on Equity’)

x = df[‘revenueGrowth’]

y = df[‘returnOnEquity’]

slope, intercept, r\_value, p\_value, std\_err = linregress(x,y)

plt.plot(x, intercept + slope \* x, color=‘lightblue’)

plt.show()

three\_df = df[[‘shortName’, ‘returnOnEquity’, ‘enterpriseValue’, ‘debtToEquity’]]

all\_fig = px.scatter\_3d(three\_df, x = ‘returnOnEquity’, y = ‘enterpriseValue’, z=‘debtToEquity’, color = ‘shortName’)

all\_fig.show()

 ![Screenshot 2023-12-14 142458](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/7/7f935d54b8f97dfe59633cb050e0d911d66ff360.png)

 ![image](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/c/c18321f3ffa3f608fef47850c56c6bd7e5942959.png)

 ![Screenshot 2023-12-14 142449](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/f/f3c0b14f191265edd962f5a47abcae4b77a8ac16.png)

---

<div class="post-metadata">

**Author:** ![Kiya\_Smith](https://sea2.discourse-cdn.com/flex016/user_avatar/www.techhub.training/kiya_smith/32/7349_2.png) [@Kiya\_Smith](https://www.techhub.training/u/Kiya_Smith)\
**Post date:** [February 4, 2025, 7:48pm UTC](https://www.techhub.training/t/96-python-investment-visualizations/649/4 "2025-02-04T19:48:38Z")

</div>

Time to complete: 2 1/2 hrs (I had to majorly trouble shoot this challenge and still its not 100% perfect.)  
Difficulty: difficut

My code:  
import pandas as pd  
import matplotlib.pyplot as plt  
import seaborn as sns  
from mpl\_toolkits.mplot3d import Axes3D  
import numpy as np  
from sklearn.linear\_model import LinearRegression

# Load the data

file\_path = “Challenge96\_Data.xlsx” # Replace with the correct file path  
data = pd.read\_excel(file\_path)

# Fill null values with 0

data.fillna(0, inplace=True)

# Extract relevant columns for analysis

revenue\_growth\_col = “revenueGrowth”  
return\_on\_equity\_col = “returnOnEquity”  
enterprise\_value\_col = “enterpriseValue”  
debt\_to\_equity\_col = “debtToEquity”  
short\_name\_col = “shortName”

# Step 1: Bar Graph - Top 10 Companies by Revenue Growth

top\_revenue\_growth = data.nlargest(10, revenue\_growth\_col)[[short\_name\_col, revenue\_growth\_col]]  
plt.figure(figsize=(10, 6))  
sns.barplot(data=top\_revenue\_growth, x=revenue\_growth\_col, y=short\_name\_col, palette=“viridis”)  
plt.title(“Top 10 Companies by Revenue Growth (%)”, fontsize=14)  
plt.xlabel(“Revenue Growth (%)”, fontsize=12)  
plt.ylabel(“Company”, fontsize=12)  
plt.tight\_layout()  
plt.show()

# Step 2: Regression Analysis - Revenue Growth vs. Return on Equity

revenue\_growth = data[revenue\_growth\_col]  
return\_on\_equity = data[return\_on\_equity\_col]

# Remove rows where either value is zero for regression analysis

filtered\_data = data[(revenue\_growth \> 0) & (return\_on\_equity \> 0)]

x = filtered\_data[revenue\_growth\_col].values.reshape(-1, 1)  
y = filtered\_data[return\_on\_equity\_col].values

model = LinearRegression()  
model.fit(x, y)  
y\_pred = model.predict(x)

plt.figure(figsize=(10, 6))  
plt.scatter(x, y, label=“Data points”, color=“blue”, alpha=0.6)  
plt.plot(x, y\_pred, label=“Regression Line”, color=“red”)  
plt.title(“Revenue Growth vs. Return on Equity”, fontsize=14)  
plt.xlabel(“Revenue Growth (%)”, fontsize=12)  
plt.ylabel(“Return on Equity (%)”, fontsize=12)  
plt.legend()  
plt.tight\_layout()  
plt.show()

# Step 3: 3D Graph - Return on Equity, Enterprise Value, Debt-to-Equity

fig = plt.figure(figsize=(10, 8))  
ax = fig.add\_subplot(111, projection=“3d”)

scatter = ax.scatter(filtered\_data[return\_on\_equity\_col],  
filtered\_data[enterprise\_value\_col],  
filtered\_data[debt\_to\_equity\_col],  
c=filtered\_data.index, cmap=“viridis”, s=50, alpha=0.8)

ax.set\_title(“3D Analysis: ROE, Enterprise Value, Debt-to-Equity”, fontsize=14)  
ax.set\_xlabel(“Return on Equity (%)”, fontsize=12)  
ax.set\_ylabel(“Enterprise Value”, fontsize=12)  
ax.set\_zlabel(“Debt-to-Equity Ratio”, fontsize=12)

plt.colorbar(scatter, ax=ax, label=“Company Index”)  
plt.tight\_layout()  
plt.show()

The plots were not exactly what were in the solution but are close to it. I wanted to do my own code before trying other peoples results.

My graphs looked like this:

 ![image](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/4/42b447cc051ddb5e735e2bdc29d622bceee43187.png)  
 ![image](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/5/53f8d6a46be9209fc20febd4bb1e872a81d64ec3.png)  
 ![image](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/8/8273834c9c89614560a15ae0ccd1b7b56a253c76.png)

For some reason some of my packages werent installing or didnt work so I had to figure out a lot of those things. Thats why it took me so long.
