How to Visualize Time Series Financial Data with Python in 3 Easy Steps

What will we cover

  • The easy way visualize financial data with Python
  • How to fetch data from stocks in Python
  • The easy way to visualize it on a plot
  • How to enrich the data with valuable analysis

Step 1: Fetch the data on your favorite stock

As with most things in Python, somebody made an easy to use library to do all the hard work for you. This is also true if you want to visualize financial data with Python.

The Pandas datareader library lets you fetch financial data from various sources and return them in a Pandas Dataframe.

If you do not know what a Dataframe from Pandas is, do not worry. We will cover the necessary here.

The full list data sources available can be found here, but include Tiingo, IEX, Alpha Vantage, Enigma, Quandl, St.Louis FED (FRED), Kenneth French’s data library, World Bank, and many more.

import pandas_datareader as pdr
import datetime 


aapl = pdr.get_data_yahoo('AAPL', 
                          start=datetime.datetime(2010, 1, 1), 
                          end=datetime.datetime(2020, 1, 1))

print(aapl.head())

Which will result in 10 years of data from Apple. See below.

                 High        Low  ...       Volume  Adj Close
Date                              ...                        
2010-01-04  30.642857  30.340000  ...  123432400.0  26.466835
2010-01-05  30.798571  30.464285  ...  150476200.0  26.512596
2010-01-06  30.747143  30.107143  ...  138040000.0  26.090879
2010-01-07  30.285715  29.864286  ...  119282800.0  26.042646
2010-01-08  30.285715  29.865715  ...  111902700.0  26.215786

For each bank day you will be presented with the following data.

High         2.936800e+02
Low          2.895200e+02
Open         2.899300e+02
Close        2.936500e+02
Volume       2.520140e+07
Adj Close    2.921638e+02
Name: 2019-12-31 00:00:00, dtype: float64
  • High: The highest price traded during that day.
  • Low: The lowest price traded during that day.
  • Open: The opening price that day.
  • Close: The closing price that day, that is the price of the last trade that day.
  • Volume: The number of shares that exchange hands for the stock that day.
  • Adj Close: It accurately reflect the stock’s value after accounting for any corporate actions. It is considered to be the true price of that stock and is often used when examining historical returns.

As you can see, to make further infestations on the data, you should use the Adj Close.

Step 2: Visualize the data

This is where Dataframes come in handy. They integrate easy with matplotlib, which is a comprehensive library for creating static, animated, and interactive visualizations in Python.

import pandas_datareader as pdr
import datetime 
import matplotlib.pyplot as plt


aapl = pdr.get_data_yahoo('AAPL', 
                          start=datetime.datetime(2010, 1, 1), 
                          end=datetime.datetime(2020, 1, 1))

aapl['Adj Close'].plot()
plt.show()

Will result in a graph like this.

Apple stock price.

That was easy.

You can see further ways to visualize the data in the documentation here.

Step 3: Enrich the data

That is another great advantage of Dataframes, it is easy to enrich it with valuable data.

A good example is to enrich the data with running mean values of the stock price.

import pandas_datareader as pdr
import datetime 
import matplotlib.pyplot as plt


aapl = pdr.get_data_yahoo('AAPL', 
                          start=datetime.datetime(2015, 1, 1), 
                          end=datetime.datetime(2020, 1, 1))

aapl['Mean Short'] = aapl['Adj Close'].rolling(window=20).mean()
aapl['Mean Long'] = aapl['Adj Close'].rolling(window=100).mean()
aapl[['Adj Close', 'Mean Short', 'Mean Long']].plot()
plt.show()

Which will result in the following graph.

Apple stock with rolling mean values with window of 20 and 100 days.

Now that was simple. The code simple rolls the window of 20 (or 100) days and sets the average (mean) value of that. This kind of analysis is used to see the average trend of the stock. Also, to see when the short term trend (20 days) is crossing the long term trend (100 days).

A simple trading strategy is decides on to buy and sell based on when these averages crosses. This strategy is called dual moving average crossover. You can read more about it here.

A volatility analysis is used to see how “stable” the share is. The higher the volatility value is, the riskier it is.

import pandas_datareader as pdr
import datetime 
import matplotlib.pyplot as plt
import numpy as np


aapl = pdr.get_data_yahoo('AAPL', 
                          start=datetime.datetime(2015, 1, 1), 
                          end=datetime.datetime(2020, 1, 1))


daily_close = aapl['Close']
daily_pc = daily_close.pct_change()

# See the volatibility
vol = daily_pc.rolling(75).std()*np.sqrt(75)
vol.plot()
plt.show()

Which results in the following graph.

Volatility of Apple stock

This is a good indication on how risky the stock is.

Conclusion

This is just a simple introduction to how to retrieve financial stock data in Python and visualize it. Also, how easy it is to enrich it with more valuable analysis.

There are so much more to explore and learn about it.

Leave a Reply