|
1 | 1 | import numpy as np |
| 2 | +import pandas as pd |
2 | 3 |
|
3 | 4 |
|
4 | 5 | def vec(mat): |
@@ -41,3 +42,63 @@ def commutation_matrix(shape): |
41 | 42 | w = np.arange(m * n).reshape((m, n), order="F").T.ravel(order="F") |
42 | 43 | k = np.eye(m * n)[w, :] |
43 | 44 | 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 |
0 commit comments