The Federal Bank of St. Louis (FRED) has one of the largest free databases of economic data. It’s an excellent and trusted data source to use for financial analysis. The Pandas Datareader package makes it so easy to start analyzing the data with a few lines of code in Python.
Plot a Single Data Series
To start, here are the packages I’ll be using.
import pandas_datareader as web
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
Next, set the date range for the data.
start = datetime(2010,1,1)
end = datetime(2030,1,1)
To pull the data, we will use the web.DataReader function. It takes three arguents:
- The name of the series you want
- ‘fred’ because we are using the FRED database. More data sources can be found here
- The start date
- The end date
SP500 = web.DataReader('SP500','fred',start,end)
Now that the data is loaded in, here is some code to quickly chart the data
sns.set() #run this to overide matplotlib
SP500['SP500'].plot(title='S&P 500 Price',figsize=(20, 6))
#Use the below to save the chart as an image file
plt.savefig('s&p500.png')
How to Find the Name of any FRED Series
Easily find the API name of the any data series by searching for it in FRED and taking the last part of the URL
Plotting Multiple Data Series
To plot more than one series on the same chart, simply pass in a list of the data series
SP500_10yrtreasury = web.DataReader(['SP500',"DGS10"],'fred',start,end)
SP500_10yrtreasury.plot(title = 'S&P 500 compared to 10yr Treasury Yield', secondary_y = "DGS10", figsize=(20, 6))
plt.tight_layout()
plt.savefig('s&p500and10yr.png')
plt.show()
Calculate Daily Change
If you want to calculate the daily change from yesterday’s close, you will need to have the previous day’s numbers on the same row as the current days. To do that, you have to create a new column where the rows are all shifted up by one. This code creates a new column that does the following:
- Moves the rows up one to have yesterday’s close and the current days close in the same row.
- Then calculates the percentage change between the current days close and yesterdays close
SP500['daily_return'] = (SP500['SP500']/ SP500['SP500'].shift(1)) -1
You can then use the following code to sort and view the data:
SP500.sort_index(ascending=False, inplace=True)
print(SP500)
You can download the entire Jypter Notebook by clicking on the link.
I hope I’ve given you enough to get started and to start analyzing any FRED data series in Python!