Querying FRED from R

FRED is an amazingly useful website provided by the Federal Reserve Bank of St. Louis compiling over 500k time series from 87 different sources. Here are 2 short R functions to retrieve FRED data in R. You'll need rjson (with admin privileges  : install.packages("rjson")) and a valid API key (register for free here) to run them.

iFRED returns basic information about a time series as a list. For instance, assuming you’re interested by the Russell 1000 index Total Market Index (RU1000TR):

> sid <- "RU1000TR"
> iFRED(sid)
$id
[1] "RU1000TR"

$realtime_start
[1] "2018-01-23"

$realtime_end
[1] "2018-01-23"

(...)

qFRED retrieves the time series itself as a matrix (with dates as row names). Id addition to sid, there are 6 other optional argument:

  • from: the start date as a Date object (defaults to 1776-07-04);

  • to: the end date as a Date object (defaults to Sys.Date());

  • units: one of lin (levels, the default), chg (change), ch1 (change from one year ago), pch (percent change), pc1 (percent change from one year ago), pca (compounded annual rate of change), cch (continuously compounded rate of change), cca (continuously compounded annual rate of change) or log (natural log);

  • freq: one of d (daily, the default), w (weekly), bw(bi-weekly), m (monthly), q (quarterly), sa (semiannual), a (annual), wef (weekly ending Friday), weth (weekly ending Thursday), wew (weekly ending Wednesday), wetu (weekly ending Tuesday), wem (weekly ending Monday), wesu (weekly ending Sunday), wesa (weekly ending Saturday), bwew (bi-weekly ending wednesday) or bwem (bi-weekly ending Monday).

  • aggreg: when using freq, how should data be aggregated? One of eop (end of period, the default), avg (average) or sum (sum)

  • na.rm: logical, should missing values (NAs) be removed from the output?

For instance, always with RU1000TR:

> from <- as.Date("2018-01-01")
> qFRED(sid, from)
           RU1000TR
2018-01-01       NA
2018-01-02  8346.42
2018-01-03  8398.08
2018-01-04  8431.26
2018-01-05  8487.97
2018-01-08  8504.18
(...)

Let's say you want weekly data with end-of-the-period observations:

> qFRED(sid, from, freq = "w", aggreg = "eop")
           RU1000TR
2018-01-05  8487.97
2018-01-12  8624.19
2018-01-19  8698.12
2018-01-26       NA

Same thing but with weekly averages:

> qFRED(sid, from, freq = "w", aggreg = "avg")
           RU1000TR
2018-01-05  8415.93
2018-01-12  8543.91
2018-01-19  8653.44
2018-01-26       NA

Percent change from one year ago:

> qFRED(sid, from, units = "pc1")
           RU1000TR
2018-01-01       NA
2018-01-02 21.66084
2018-01-03 21.54941
2018-01-04 22.16739
2018-01-05 22.54979
2018-01-08 23.23220
(...)

The code is on Github. Don't forget to replace .FRED_api_key with your own API key!

Aucun commentaire:

Enregistrer un commentaire

Votre mot de passe

On ne va pas épiloguer pendant 150 ans, vous avez besoin : De mots de passe très forts (à partir de 128 bits), un par site (sauf, éventuel...