In [1]:
import pandas as pd
import numpy as np
import fredpy as fp
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
First apply for an API key for FRED here: https://research.stlouisfed.org/docs/api/api_key.html. The API key is a 32 character string that is required for making requests from FRED. Save your API key in the fp
namespace by either setting the fp.api_key
directly:
In [2]:
fp.api_key = '################################'
or by reading from a text file containing only the text of the API key in the first line:
In [3]:
fp.api_key = fp.load_api_key('fred_api_key.txt')
If fred_api_key.txt
is not in the same directory as your program file, then you must supply the full path of the file.
In [4]:
u = fp.series('UNRATE')
plt.plot_date(u.datetimes,u.data,'-',lw=3,alpha = 0.65)
plt.grid()
In [5]:
# Download quarterly real GDP data using `fredpy`. Save the data in a variable called gdp
gdp = fp.series('gdpc1')
# Note that gdp is an instance of the `fredpy.series` class
print(type(gdp))
In [6]:
# Print the title, the units, the frequency, the date range, and the source of the gdp data
print(gdp.title)
print(gdp.units)
print(gdp.frequency)
print(gdp.daterange)
print(gdp.source)
In [7]:
# Print the last 4 values of the gdp data
print(gdp.data[-4:],'\n')
# Print the last 4 values of the gdp series dates
print(gdp.dates[-4:],'\n')
# Print the last 4 values of the gdp series datetimes
print(gdp.datetimes[-4:])
In [8]:
# Plot real GDP data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(gdp.datetimes,gdp.data,'-',lw=3,alpha = 0.65)
ax.grid()
ax.set_title(gdp.title)
ax.set_ylabel(gdp.units)
Out[8]:
In [9]:
# Restrict GDP to observations from January 1, 1990 to present
win = ['01-01-1990','01-01-2200']
gdp_win = gdp.window(win)
# Plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(gdp_win.datetimes,gdp_win.data,'-',lw=3,alpha = 0.65)
ax.grid()
ax.set_title(gdp_win.title)
ax.set_ylabel(gdp_win.units)
# Plot recession bars
gdp_win.recessions()
In [10]:
# Compute and plot the (annualized) quarterly growth rate of real GDP
gdp_pc = gdp.pc(annualized=True)
# Plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(gdp_pc.datetimes,gdp_pc.data,'-',lw=3,alpha = 0.65)
ax.grid()
ax.set_title(gdp_pc.title)
ax.set_ylabel(gdp_pc.units)
# Plot recession bars
gdp_pc.recessions()
In [11]:
# Compute and plot the log of real GDP
gdp_log = gdp.log()
# Plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(gdp_log.datetimes,gdp_log.data,'-',lw=3,alpha = 0.65)
ax.set_title(gdp_log.title)
ax.set_ylabel(gdp_log.units)
ax.grid()
In [12]:
# Download CPI and GDP deflator data
cpi = fp.series('CPIAUCSL')
deflator = fp.series('GDPDEF')
fig = plt.figure(figsize=(12,4))
ax = fig.add_subplot(1,2,1)
ax.plot_date(cpi.datetimes,cpi.data,'-',lw=3,alpha = 0.65)
ax.grid()
ax.set_title(cpi.title)
ax.set_ylabel(cpi.units)
ax = fig.add_subplot(1,2,2)
ax.plot_date(deflator.datetimes,deflator.data,'-m',lw=3,alpha = 0.65)
ax.grid()
ax.set_title(deflator.title)
ax.set_ylabel(deflator.units)
Out[12]:
In [13]:
# The CPI data are produced at a monthly frequency
print(cpi.frequency)
# Convert CPI data to quarterly frequency to conform with the GDP deflator
cpi2 = cpi.monthtoquarter()
print(cpi2.frequency)
In [14]:
# Compute the inflation rate based on each index
cpi_pi = cpi2.apc()
def_pi = deflator.apc()
# Print date ranges for new inflation series
print(cpi_pi.daterange)
print(def_pi.daterange)
In [15]:
fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(1,1,1)
ax.plot_date(cpi_pi.datetimes,cpi_pi.data,'-',lw=3,alpha = 0.65,label='cpi')
ax.plot_date(def_pi.datetimes,def_pi.data,'-',lw=3,alpha = 0.65,label='def')
ax.legend(loc='upper right')
ax.set_title('US inflation')
ax.set_ylabel('Percent')
ax.grid()
Even though the CPI inflation rate is on average about .3% higher the GDP deflator inflation rate, the CPI and the GDP deflator produce comparable measures of US inflation.
In [16]:
# Download unemployment and 3 month T-bill data
unemp = fp.series('UNRATE')
tbill_3m = fp.series('TB3MS')
# Print date ranges for series
print(unemp.daterange)
print(tbill_3m.daterange)
# Equalize the date ranges
unemp, tbill_3m = fp.window_equalize([unemp, tbill_3m])
# Print the new date ranges for series
print()
print(unemp.daterange)
print(tbill_3m.daterange)
In [17]:
# Download nominal GDP, the GDP deflator
gdp = fp.series('GDP')
defl = fp.series('GDPDEF')
# Make sure that all series have the same window of observation
gdp,defl = fp.window_equalize([gdp,defl])
# Deflate GDP series
gdp = gdp.divide(defl)
# Convert GDP to per capita terms
gdp = gdp.percapita()
# Take log of GDP
gdp = gdp.log()
In [18]:
# Plot log data
fig = plt.figure(figsize=(6,4))
ax1 = fig.add_subplot(1,1,1)
ax1.plot_date(gdp.datetimes,gdp.data,'-',lw=3,alpha = 0.65)
ax1.grid()
ax1.set_title('log real GDP per capita')
# ax1.set_ylabel(gdp.units)
gdp.recessions()
fig.tight_layout()
The post-Great Recession slowdown in US real GDP growth is apparent in the figure.
In [19]:
# Compute the hpfilter
gdp_cycle, gdp_trend = gdp.hpfilter()
In [20]:
# Plot log data
fig = plt.figure(figsize=(6,8))
ax1 = fig.add_subplot(2,1,1)
ax1.plot_date(gdp.datetimes,gdp.data,'-',lw=3,alpha = 0.7,label='actual')
ax1.plot_date(gdp_trend.datetimes,gdp_trend.data,'r-',lw=3,alpha = 0.65,label='HP trend')
ax1.grid()
ax1.set_title('log real GDP per capita')
gdp.recessions()
ax1.legend(loc='lower right')
fig.tight_layout()
ax1 = fig.add_subplot(2,1,2)
ax1.plot_date(gdp_cycle.datetimes,gdp_cycle.data,'b-',lw=3,alpha = 0.65,label='HP cycle')
ax1.grid()
ax1.set_title('log real GDP per capita - dev from trend')
gdp.recessions()
ax1.legend(loc='lower right')
fig.tight_layout()
In Figure 1.5 from The Conquest of American Inflation, Thomas Sargent compares the business cycle componenets (BP filtered) of monthly inflation and unemployment data for the US from 1960-1982. Here we replicate Figure 1.5 to include the most recently available data and we also consturct the figure using HP filtered data.
In [21]:
u = fp.series('LNS14000028')
p = fp.series('CPIAUCSL')
# Construct the inflation series
p = p.pc(annualized=True)
p = p.ma2side(length=6)
# Make sure that the data inflation and unemployment series cver the same time interval
p,u = fp.window_equalize([p,u])
# Data
fig = plt.figure()
ax = fig.add_subplot(2,1,1)
ax.plot_date(u.datetimes,u.data,'b-',lw=2)
ax.grid(True)
ax.set_title('Inflation')
ax = fig.add_subplot(2,1,2)
ax.plot_date(p.datetimes,p.data,'r-',lw=2)
ax.grid(True)
ax.set_title('Unemployment')
fig.autofmt_xdate()
In [22]:
# Filter the data
p_bpcycle,p_bptrend = p.bpfilter(low=24,high=84,K=84)
u_bpcycle,u_bptrend = u.bpfilter(low=24,high=84,K=84)
# Scatter plot of BP-filtered inflation and unemployment data (Sargent's Figure 1.5)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
t = np.arange(len(u_bpcycle.data))
ax.scatter(u_bpcycle.data,p_bpcycle.data,facecolors='none',alpha=0.75,s=20,c=t, linewidths=1.5)
ax.set_xlabel('unemployment rate (%)')
ax.set_ylabel('inflation rate (%)')
ax.set_title('Inflation and unemployment: BP-filtered data')
ax.grid(True)
In [23]:
# HP filter
p_hpcycle,p_hptrend = p.hpfilter(lamb=129600)
u_hpcycle,u_hptrend = u.hpfilter(lamb=129600)
# Scatter plot of BP-filtered inflation and unemployment data (Sargent's Figure 1.5)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
t = np.arange(len(u_hpcycle.data))
ax.scatter(u_hpcycle.data,p_hpcycle.data,facecolors='none',alpha=0.75,s=20,c=t, linewidths=1.5)
ax.set_xlabel('unemployment rate (%)')
ax.set_ylabel('inflation rate (%)')
ax.set_title('Inflation and unemployment: HP-filtered data')
ax.grid(True)
The choice of filterning method appears to strongly influence the results. While both filtering methods
In [24]:
# create a Pandas DataFrame
df = pd.DataFrame({'inflation':p.data,
'unemployment':u.data})
# Set the index of the DataFrame
df = df.set_index(pd.to_datetime(p.dates))
print(df.head())
# Export to csv
df.to_csv('data.csv')