Skip to content

Commit 5d7184d

Browse files
committed
Add method to grab FRED data
1 parent 8fcd997 commit 5d7184d

File tree

3 files changed

+66
-1
lines changed

3 files changed

+66
-1
lines changed

pit_estimates.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""
2-
Generate point-in-time estimates
2+
Generate point-in-time estimates.
3+
4+
For each date, rerun the model and save the latest estimate of expected return
5+
and term premium
36
"""
47
from tqdm import tqdm
58
import pandas as pd

pyacm/utils.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import pandas as pd
23

34

45
def vec(mat):
@@ -41,3 +42,63 @@ def commutation_matrix(shape):
4142
w = np.arange(m * n).reshape((m, n), order="F").T.ravel(order="F")
4243
k = np.eye(m * n)[w, :]
4344
return k
45+
46+
47+
class FRED(object):
48+
"""
49+
Wrapper for the data API of the FRED
50+
"""
51+
52+
def fetch(self, series_id):
53+
"""
54+
Grabs series from the FRED website and returns them in a pandas
55+
dataframe
56+
57+
Parameters
58+
----------
59+
series_id: str, list, dict
60+
string with series ID, list of strings of the series ID or
61+
dict with series ID as keys and their desired names as values
62+
"""
63+
64+
if type(series_id) is list:
65+
66+
df = pd.DataFrame()
67+
68+
for cod in series_id:
69+
single_series = self._fetch_single_code(cod)
70+
df = pd.concat([df, single_series], axis=1)
71+
72+
df.sort_index(inplace=True)
73+
74+
elif type(series_id) is dict:
75+
76+
df = pd.DataFrame()
77+
78+
for cod in series_id.keys():
79+
single_series = self._fetch_single_code(cod)
80+
df = pd.concat([df, single_series], axis=1)
81+
82+
df.columns = series_id.values()
83+
84+
else:
85+
86+
df = self._fetch_single_code(series_id)
87+
88+
return df
89+
90+
@staticmethod
91+
def _fetch_single_code(series_id):
92+
93+
url = r'https://fred.stlouisfed.org/data/' + series_id + '.txt'
94+
df = pd.read_csv(url, sep='\t')
95+
series_start = df[df[df.columns[0]].str.contains('DATE\s+VALUE')].index[0] + 1
96+
df = df.loc[series_start:]
97+
df = df[df.columns[0]].str.split('\s+', expand=True)
98+
df = df[~(df[1] == '.')]
99+
df = pd.DataFrame(data=df[1].values.astype(float),
100+
index=pd.to_datetime(df[0]),
101+
columns=[series_id])
102+
df.index.rename('Date', inplace=True)
103+
104+
return df

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
'scikit-learn',
2727
'numpy',
2828
'matplotlib',
29+
'tqdm',
2930
],
3031
keywords=[
3132
'asset pricing',

0 commit comments

Comments
 (0)