Plot Stock Price Time-series Data

This tutorial will show you how to plot stock time-series data using Python. Stock prices vary in different trading days, and thus it would be of interest to the overall trends by plotting it.

Needed Packages

  • yfinance — A python library that offers a threaded and Pythonic way to download market data from Yahoo! Finance.
  • matplotlib — A python library for creating static, animated, and interactive visualizations.

Part 1: Download Data

The following code is to download data and then print out the result.

import yfinance as yf
import matplotlib.pyplot as plt

price_history_MSFT = yf.Ticker('MSFT').history(period='max',
                                    interval='1d', 
                                    actions=False)
print(price_history_MSFT)
                Open        High         Low       Close      Volume
Date                                                                  
1986-03-13    0.055949    0.064177    0.055949    0.061434  1031788800
1986-03-14    0.061434    0.064725    0.061434    0.063628   308160000
1986-03-17    0.063628    0.065274    0.063628    0.064725   133171200
1986-03-18    0.064725    0.065274    0.062531    0.063079    67766400
1986-03-19    0.063079    0.063628    0.061434    0.061982    47894400
...                ...         ...         ...         ...         ...
2022-03-28  304.329987  310.799988  304.329987  310.700012    29578200
2022-03-29  313.910004  315.820007  309.049988  315.410004    30393400
2022-03-30  313.760010  315.950012  311.579987  313.859985    28163600
2022-03-31  313.899994  315.140015  307.890015  308.309998    33422100
2022-04-01  309.369995  310.130005  305.540009  309.420013    27085100

[9089 rows x 5 columns]

Part 2: Plot Data

The following code is to plot the data.

plt.plot(price_history_MSFT.Close,label='MSFT')
plt.title('Stock Prices of Microsoft (MSFT)')
Plot Microsoft MSFT Stock Prices

Part 3: Add Another Stock to Compare

We can add another stock to do comparision, which makes the figure more interesting.

price_history_GOOG = yf.Ticker('GOOG').history(period='max', 
                                    interval='1d', 
                                    actions=False)

plt.legend(loc="upper left")
plt.show()
Plot Microsoft and Google Stock Prices

Leave a Comment