Import the fredapi module. Note that I have set my api key to the environment variable FRED_API_KEY. You can also pass your key explicitly.
In [1]:
from fredapi import Fred
fred = Fred()
Import pandas and several display and plotting options
In [2]:
import pandas as pd
pd.options.display.max_colwidth = 60
In [3]:
%matplotlib inline
import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize
figsize(20, 5)
If you already know the series ID you want (say by searching on the FRED website), you can fetch data easily into a pandas Series
In [4]:
s = fred.get_series('SP500', observation_start='2014-09-02', observation_end='2014-09-05')
s.tail()
Out[4]:
In [5]:
s = fred.get_series('SP500', observation_start='1/31/2014')
s.tail()
Out[5]:
You can also easily fetch the meta data about any series
In [6]:
info = fred.get_series_info('PAYEMS')
info['title']
Out[6]:
You can also get a set of series IDs programmatically by release or category IDs. Several sorting options are also available. On the FRED website I know that the release ID 175 contains some personal income data. Let's fetch 5 most popular series in that set.
In [7]:
personal_income_series = fred.search_by_release(175, limit=5, order_by='popularity', sort_order='desc')
In [8]:
personal_income_series['title']
Out[8]:
In [9]:
df = {}
df['SF'] = fred.get_series('PCPI06075')
df['NY'] = fred.get_series('PCPI36061')
df['DC'] = fred.get_series('PCPI11001')
df = pd.DataFrame(df)
df.plot()
Out[9]:
You can also search by categories. On the FRED website I see that category 101 contains data about Consumer Credit.
In [10]:
df = fred.search_by_category(101, limit=10, order_by='popularity', sort_order='desc')
df['title']
Out[10]:
As a example let's fetch the personal income data. Release 151 looks quite intersting
In [11]:
df = fred.search_by_release(151)
df['title'].head(10)
Out[11]:
I noticed that the data is mostly organized by state, except for a few that are by BEA region. We can use pandas to easily select the seires we want
In [12]:
state_df = df[~df['title'].str.startswith('Per Capita Personal Income in the')]
In [13]:
len(state_df)
Out[13]:
In [14]:
state_df.id.str[:2]
Out[14]:
looks good, we got the data series for all 50 states here
In [15]:
income_by_state = {}
for series_id in state_df.index:
income_by_state[series_id[:2]] = fred.get_series(series_id)
In [16]:
income_by_state = pd.DataFrame(income_by_state)
In [17]:
income_by_state.ix[-1].plot(kind='bar')
plt.title('Per Capita Personal Income by State')
Out[17]: