Plot Finance Data With Python

Thomas
3 min readJan 5, 2021

This article will follow up from the accessing price data with python piece.

We will go through an introduction to MatplotLib (charting package for Python) and combine this with real financial market data.

The initial step is to install the necessary packages….

Command-Linepip install pandas                           # Data Analysis
pip install yfinance # API
pip install matplotlib # Graphs

….and then subsequently import the correct dependencies.

Text-Editorimport pandas as pd
import yfinance as yf
from datetime import date, timedelta
from matplotlib import pyplot as plt

As per the previous tutorial we will create a datetime clamp to standardise the variables (can execute it any anytime without the hassle of manually updating the dates).

Start = date.today() - timedelta(365)
Start.strftime('%Y-%m-%d')

End = date.today() + timedelta(2)
End.strftime('%Y-%m-%d')

…..and create a function that extracts the adjusted closing price over the previous 1yr. This incorporates utilising pandas and yfinance.

def closing_price(ticker):
Asset = pd.DataFrame(yf.download(ticker, start=Start,
end=End)['Adj Close'])
return Asset

TESLA = closing_price('TSLA') # CALL THE FUNCTION
AMAZON = closing_price('AMZN')

The final 2 lines simply ‘call’ or activate the function for each ticker. The given arguments (‘TSLA’/ ‘AMZN’) need to be precisely what Yahoo Finance states as the financial instrument code.

We will create graphs in this tutorial for Tesla and Amazon. This is where we use MatPlotLib which we installed and imported at the beginning.

MatplotLib has a vast array of options and functionality. Further information can be found in the official documentation here.

Below our called function we will write the following:

plt.plot(TESLA)
plt.show()

plt.plot(AMAZON)
plt.show()

This is enough to generate simple line plots. The TESLA and AMAZON objects refer to dataframes. Remember, they contain all of the data (date and price variables).

2 Lines Of Code To Generate A Simple Plot

We can now add several more features such as color, line-width, title and axis labels. You can get very creative here!

plt.plot(TESLA, color='red', linewidth=2)
plt.title('TESLA Performance')
plt.ylabel('Price ($)')
plt.xlabel('Date')
plt.show()

plt.plot(AMAZON, color='purple', linewidth=2)
plt.title('AMAZON Performance')
plt.ylabel('Price ($)')
plt.xlabel('Date')
plt.show()

Writing this twice immediately appears inefficient. If you wish to create several individual plots, we can write a function similar to the dataframe one (cleans everything up and makes duplication easy). The utility is made more obvious if we had 6 plots (vs. 2) for instance.

def plot_price(ticker, color, head):
plt.plot(ticker, color=color, linewidth=2)
plt.title(head)
plt.ylabel('Price ($)')
plt.xlabel('Date')
plt.show()

TESLA_Plot = plot_price(TESLA, 'red', 'TESLA Performance')
AMAZON_Plot = plot_price(AMAZON, 'purple', 'AMAZON Performance')

If you’re unfamiliar, the arguments in bold refer to the variables that are unique between the plots. These are then defined when we call the function in the final 2 lines. The colors and titles need to be strings (‘ ’).

Once executed close a plot to enable the next in the chain to pop-up.

Again, once you’ve written the back-end code you can get creative and experiment with the MatplotLib features.

You could create a figure with multiple plots, use log scales and completely amend color schemes. Learn more here.

--

--