fredpy Examples


In [1]:
import pandas as pd
import numpy as np
from fredpy import series
import matplotlib.pyplot as plt
%matplotlib inline

Preliminary example

Downloading and plotting unemployment rate data for the US is easy with fredpy:


In [2]:
u = series('UNRATE')
plt.plot_date(u.datetimes,u.data,'-',lw=3,alpha = 0.65)
plt.grid()



In [3]:
# Download quarterly real GDP data using `fredpy`. Save the data in a variable called gdp
gdp = series('gdpc1')

# Note that gdp is an instance of the `fredpy.series` class
print(type(gdp))


<class 'fredpy.series'>

In [4]:
# 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.freq)
print(gdp.daterange)
print(gdp.source)


Real Gross Domestic Product
Billions of Chained 2009 Dollars
Quarterly
Range: 1947-01-01 to 2016-04-01
US. Bureau of Economic Analysis

In [5]:
# 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:])


[ 16454.9  16490.7  16525.   16570.2] 

['2015-07-01', '2015-10-01', '2016-01-01', '2016-04-01'] 

[datetime.datetime(2015, 7, 1, 0, 0) datetime.datetime(2015, 10, 1, 0, 0)
 datetime.datetime(2016, 1, 1, 0, 0) datetime.datetime(2016, 4, 1, 0, 0)]

In [6]:
# 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[6]:
<matplotlib.text.Text at 0x11ab7e2e8>

In [7]:
# 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 [8]:
# 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 [9]:
# 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()


More examples

The following examples demonstrate some additional fredpy functionality.

Comparison of CPI and GDP deflator inflation

CPI data are released monthly by the BLS while GDP deflator data are released quarterly by the BEA. Here we'll first convert the monthly CPI data to monthly frequency compute inflation as the percentage change in the respective index since on year prior.


In [10]:
# Download CPI and GDP deflator data
cpi = series('CPIAUCSL')
deflator = 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[10]:
<matplotlib.text.Text at 0x11b1075c0>

In [11]:
# The CPI data are produced at a monthly frequency
print(cpi.freq)

# Convert CPI data to quarterly frequency to conform with the GDP deflator
cpi2 = cpi.monthtoquarter()
print(cpi2.freq)


Monthly
Quarterly

In [12]:
# 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)


Range: 1948-01-01 to 2016-04-01
Range: 1948-01-01 to 2016-04-01

In [13]:
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 [14]:
from fredpy import window_equalize

# Download unemployment and 3 month T-bill data
unemp = series('UNRATE')
tbill_3m = series('TB3MS')

# Print date ranges for series
print(unemp.daterange)
print(tbill_3m.daterange)

# Equalize the date ranges
unemp, tbill_3m = window_equalize([unemp, tbill_3m])

# Print the new date ranges for series
print()
print(unemp.daterange)
print(tbill_3m.daterange)


Range: 1948-01-01 to 2016-08-01
Range: 1934-01-01 to 2016-08-01

Range: 1948-01-01 to 2016-08-01
Range: 1948-01-01 to 2016-08-01

Filtering 1: Extracting business cycle components from quarterly data with the HP filter


In [15]:
# Download nominal GDP, the GDP deflator

gdp = series('GDP')
defl = series('GDPDEF')

# Make sure that all series have the same window of observation
gdp,defl = 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 [16]:
# 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 [17]:
# Compute the hpfilter
gdp_cycle, gdp_trend = gdp.hpfilter()

In [18]:
# 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()


Filtering 2: Extracting business cycle components from monthly data

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 [19]:
u = series('LNS14000028')
p = 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 = 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 [20]:
# 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 [21]:
# 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

Exporting data sets

Exporting data inported with fredpy to csv files is easy with Pandas.


In [22]:
# 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')


               inflation  unemployment
1954-01-01  6.330313e-01           3.6
1954-02-01  2.609508e-01           3.8
1954-03-01 -1.411834e-14           4.1
1954-04-01 -2.979518e-01           4.7
1954-05-01 -8.570949e-01           4.6