64|PYTHON – Bitcoin vs. S&P 500 with Matplotlib Basics

BYU Student Author: @Mike_Paulsin
Reviewers: @Nate, @IWillyerd, @Brett_Lowe
Estimated Time to Solve: 15 - 25 Minutes

We provide the solution to this challenge using:

  • Python

Need a program? Click here.

Overview
As part of this task, you are required to conduct a comparative analysis between the Bitcoin price data and the S&P 500 data for the first two months of 2023. The necessary data for January 2023 and February 2023 has already been provided to you, and your task is to leverage the powerful visualization capabilities of Python’s Matplotlib library to create a dual-axis graph that will enable you to effectively compare the two datasets.

The primary objective of this challenge is to help you gain a strong understanding of the fundamental concepts of Matplotlib, and to provide you with a foundation for future work with this powerful data visualization tool. To complete this task, you are encouraged to make use of available resources such as Google and ChatGPT to assist you in overcoming any challenges you may encounter. This exercise should take approximately 15-25 minutes to complete, and will be followed by further challenges that explore the intersection of cryptocurrency and stocks.

Instructions

  1. Start by using pandas to read the Bitcoin price data and the S&P 500 data from their respective Excel sheets into separate dataframes. This will allow you to easily manipulate and analyze the data in Python.
    Suggestions and Hints

    You can use the following code to achieve this:
    df = pd.read_excel(“Challenge64_Bitcoin_Price_Data.xlsx”)
    df1 = pd.read_excel(“Challenge64_S&P500_Price_Data.xlsx”)

  2. Create two axes on the graph using matplotlib.
    Suggestions and Hints

    You can use the following code to achieve this:
    fig = plt.figure()
    axis1 = plt.subplots()
    axis2 = axis1.twinx()

    This will create two y-axes on the same plot, with axis1 representing the left y-axis and axis2
    representing the right y-axis.

  3. Add the appropriate Bitcoin price data to the first axis.
    Suggestions and Hints

    You can use the following code to achieve this:
    axis1.plot(bitcoin_dataframe[‘Date’], bitcoin_dataframe[‘High’], color=‘blue’, label=‘Bitcoin Price’)

    This will plot the Bitcoin price data on the left y-axis with a blue line and a label of ‘Bitcoin Price’.

  4. Add the appropriate S&P 500 data to the second axis using axis2.plot(). For example:
    Suggestions and Hints

    You can use the following code to achieve this:
    axis2.plot(sp500_dataframe[‘Date’], sp500_dataframe[‘Price’], color=‘red’, label=‘S&P 500 Price’)

    This will plot the S&P 500 data on the right y-axis with a green line and a label of ‘S&P 500 Price’.

  5. Format both axes and the data to improve readability.
    Suggestions and Hints

    You can match the line colors and y-axis label colors of each line using axis1.set_ylabel() and
    axis2.set_ylabel(), respectively. For example:
    axis1.set_ylabel(‘Bitcoin Price’, color=‘blue’)
    axis2.set_ylabel(‘S&P 500 Price’, color=‘red’)

    This will set the y-axis label of the Bitcoin price data to blue and the y-axis label of the S&P 500 data to green. You can customize the colors by replacing ‘blue’ and ‘red’ with colors of your choice.

  6. Change the tick mark labels of the x-axis to display the date in the format “Jan 1, Jan 8, etc.”
    Suggestions and Hints

    You can do this using axis1.xaxis.set_major_formatter() and specifying the desired date format. For example:
    date_format = mpl.dates.DateFormatter(‘%b %d’)
    axis1.xaxis.set_major_formatter(date_format)

    This will format the tick mark labels on the x-axis to display the date in the desired format.

By following these instructions, you should be able to create a well-formatted dual-axis graph that effectively compares the Bitcoin price data and the S&P 500 data.

Data Files

Solution

import pandas as pd
pd.set_option(‘display.max_columns’, None)
pd.set_option(‘display.max_rows’, None)
pd.set_option(‘display.max_colwidth’, None)
pd.options.display.float_format = ‘{:,.2f}’.format
import matplotlib.pyplot as plt

df1=pd.read_excel(‘Challenge64_Bitcoin_Price_Data.xlsx’)
df2=pd.read_excel(‘Challenge64_S&P500_Price_Data.xlsx’)
Bitcoin= df1[[‘Date’, ‘High’]]
sp500 = df2[[‘Date’, ‘High’]]

fig = plt.figure(figsize=(10,6))

axis1 = fig.add_subplot()
axis2 = plt.twinx()
axis1.plot(Bitcoin[‘Date’],Bitcoin[‘High’],label=“Bitcoin”,linewidth=4,color=‘#0088cc’)
axis1.set_ylabel(“Bitcoin Price”,fontsize=14,color=‘#0088cc’)
axis1.set_xlabel(“Date”,fontsize=14)

axis2.plot(sp500[‘Date’],sp500[‘High’],label=“S&P 500”,linewidth=4,color=‘red’)
axis2.set_ylabel(“S&P 500 Price”,fontsize=14, color=‘red’)

import matplotlib.dates as mdates
date_format = mdates.DateFormatter(‘%b %d’)
axis1.xaxis.set_major_formatter(date_format)

axis1.tick_params(axis=‘x’, colors=‘black’, labelsize=14)
axis1.tick_params(axis=‘y’, colors=‘#0088cc’, labelsize=14)
axis2.tick_params(axis=‘y’, colors=‘red’, labelsize=14)

plt.title(“Bitcoin vs. S&P 500 Price Comparison”, fontsize=20)
fig.legend(fontsize=8)

plt.show()

I really enjoyed completing this challenge! I’ve attached my solution below.

import pandas as pd

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

pd.set_option(‘display.max_columns’, None)

pd.set_option(‘display.max_rows’, None)

pd.set_option(‘display.max_colwidth’, None)

df= pd.read_excel(‘Challenge64_Bitcoin_Price_Data.xlsx’)

df1= pd.read_excel(‘Challenge64_S&P500_Price_Data.xlsx’)

fig = plt.figure(figsize=(10,6))

axis1 = fig.add_subplot()

axis2 = plt.twinx()

axis1.plot(df[‘Date’],df[‘High’], label = ‘Bitcoin Price’, color = ‘Pink’)

axis1.tick_params(axis = ‘y’, labelcolor = ‘Pink’)

axis1.set_ylabel(‘Bitcoin Prices’, color = ‘Pink’, fontsize = 15)

axis1.set_xlabel(‘Date’,fontsize=15, color = ‘Black’)

axis2.plot(df1[‘Date’], df1[‘High’], label= ‘S&P 500 Price’, color= ‘Green’)

axis2.set_ylabel(‘S&P 500 Prices’, color = ‘Green’, fontsize = 15)

axis2.tick_params(axis = ‘y’, labelcolor= ‘Green’)

date_format = mdates.DateFormatter(‘%b %d’)

axis1.xaxis.set_major_formatter(date_format)

plt.title(‘Bitcoin Price vs. S&P 500 Price’, fontsize=20)

fig.legend(fontsize=8)

plt.show()

Awesome Challenge! Really helped solidify my skills of reading in excel sheets into pandas dataframes and using those data frames to create a dual-axis graph using matplotlib. Here is my code and a picture of my graph:

import pandas as pd

pd.set_option(‘display.max_columns’, None)

pd.set_option(‘display.max_rows’, None)

pd.set_option(‘display.max_colwidth’, None)

pd.options.display.float_format = ‘{:,.2f}’.format

import matplotlib.pyplot as plt

bitcoin_data = pd.read_excel(‘Challenge64_Bitcoin_Price_Data.xlsx’)

sp_data = pd.read_excel(‘Challenge64_S&P500_Price_Data.xlsx’)

display(bitcoin_data.head())

display(sp_data.head())

fig = plt.figure()

axis1 = fig.add_subplot()

axis2 = plt.twinx()

axis1.plot(bitcoin_data[‘Date’],bitcoin_data[‘High’], label = ‘Bitcoin Prices’, color = ‘Blue’)

axis1.set_ylabel(“Bitcoin Prices”,fontsize=12)

axis1.set_xlabel(“Date”,fontsize=12)

axis2.plot(sp_data[‘Date’],sp_data[‘High’], label = ‘S&P 500 Prices’, color = ‘Red’)

axis2.set_ylabel(“S&P 500 Prices”,fontsize=12)

import matplotlib.dates as mdates

date_format = mdates.DateFormatter(‘%b %d’)

axis1.xaxis.set_major_formatter(date_format)

plt.title(“Bitcoin vs. S&P 500 Price Comparison”,fontsize=20)

fig.legend(fontsize=10, loc=“lower right”)

plt.show()

image

import pandas as pd

pd.options.display.float_format = ‘{:,.2f}’.format

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

bit_df=pd.read_excel(‘Challenge64_Bitcoin_Price_Data.xlsx’)

sp_df=pd.read_excel(‘Challenge64_S&P500_Price_Data.xlsx’)

Bitcoin= bit_df[[‘Date’, ‘High’]]

sp500 = sp_df[[‘Date’, ‘High’]]

fig = plt.figure(figsize=(10,6))

axis1 = fig.add_subplot()

axis2 = plt.twinx()

axis1.plot(Bitcoin[‘Date’],Bitcoin[‘High’],label=“Bitcoin”,linewidth=4,color=‘#002E5D’)

axis1.set_ylabel(“Bitcoin Price”,fontsize=14,color=‘#FFCC00’)

axis1.set_xlabel(“Date”,fontsize=14,color=‘#FFCC00’)

axis2.plot(sp500[‘Date’],sp500[‘High’],label=“S&P 500”,linewidth=4,color=‘#0062B8’)

axis2.set_ylabel(“S&P 500 Price”,fontsize=14, color=‘#FFCC00’)

date_format = mdates.DateFormatter(‘%b %d’)

axis1.xaxis.set_major_formatter(date_format)

axis1.tick_params(axis=‘x’, colors=‘#990000’, labelsize=14)

axis1.tick_params(axis=‘y’, colors=‘#990000’, labelsize=14)

axis2.tick_params(axis=‘y’, colors=‘#990000’, labelsize=14)

plt.title(“Bitcoin vs. S&P 500 Price Comparison”, fontsize=20)

fig.legend(fontsize=8)

plt.show()

This was some great practice for me. I didn’t realize how much I forgot about matplotlib just a few months without using it. I changed the colors of the lines and axes using the hex codes of my two favorite schools, BYU and USC. Thanks for the tip on the date formatter, that’s a super useful tool.