Skip to content

Commit

Permalink
switch to xts
Browse files Browse the repository at this point in the history
  • Loading branch information
sboysel committed May 30, 2017
1 parent 1335951 commit 691ca81
Show file tree
Hide file tree
Showing 21 changed files with 154 additions and 262 deletions.
10 changes: 6 additions & 4 deletions DESCRIPTION
@@ -1,6 +1,6 @@
Package: fredr
Title: Interact with the FRED API in the R workspace
Version: 0.2.0.0
Version: 0.3.0.0
Authors@R: person("Sam", "Boysel", email = "sboysel@gmail.com", role = c("aut", "cre"))
Description: Wrap the FRED API with httr and dplyr to quickly bring data from
FRED into the R workspace.
Expand All @@ -10,10 +10,12 @@ Depends:
R (>= 3.2.2)
Imports:
httr,
dplyr
dplyr,
xts
Suggests:
ggfortify,
testthat
testthat,
zoo
License: MIT + file LICENSE
LazyData: true
RoxygenNote: 5.0.1
RoxygenNote: 6.0.1
2 changes: 1 addition & 1 deletion Makefile
@@ -1,4 +1,4 @@
R=/usr/bin/R
R=/usr/local/bin/R

all: knit

Expand Down
1 change: 0 additions & 1 deletion NAMESPACE
Expand Up @@ -5,4 +5,3 @@ export(fredr_docs)
export(fredr_key)
export(fredr_search)
export(fredr_series)
export(get_freq)
14 changes: 10 additions & 4 deletions R/fredr.R
Expand Up @@ -9,7 +9,7 @@
#' should be parsed and formatted as a tbl_df. Default is TRUE.
#' @param print_req A boolean value indicating whether or not the request
#' should be printed as well. Useful for debugging.
#' @return A tbl_df. If to_frame is TRUE, return is a reponse object from
#' @return A tbl_df. If to_frame is TRUE, return is a reponse object from
#' httr::GET().
#' @examples
#' fredr("series/observations",
Expand All @@ -18,23 +18,29 @@
#' observation_end = "2000-01-01")
#' @export
fredr <- function(endpoint, ..., to_frame = TRUE, print_req = FALSE) {
params <- list(...)

if (identical(Sys.getenv("FRED_API_KEY"), "")) {
stop("FRED API key must be set. Use fredr_key()")
}

params <- list(...)
params$api_key <- Sys.getenv("FRED_API_KEY")
params$file_type <- "json"

resp <- httr::GET(url = "https://api.stlouisfed.org/",
path = paste0("fred/", endpoint),
query = params)
if (print_req == TRUE) {

if (print_req) {
message(resp$url)
}

if (resp$status_code != 200) {
err <- httr::content(resp)
stop(paste0(err$error_code, ": ", err$error_message))
}
if (to_frame == TRUE) {

if (to_frame) {
parsed <- httr::content(resp)
if (endpoint %in% c("category",
"category/children",
Expand Down
6 changes: 3 additions & 3 deletions R/fredr_docs.R
@@ -1,13 +1,13 @@
#' Open the web documentation for a certain FRED API topic.
#'
#' @param endpoint A string representing the desired documentation for the exact
#' @param endpoint A string representing the desired documentation for the exact
#' FRED API endpoint. Default is 'base' and will open a link to
#' https://api.stlouisfed.org/docs/fred/.
#' @param params A boolean value. If TRUE, the documentation will be opened at
#' the 'Paramters' section. Default is FALSE.
#' @param debug A boolean value. If TRUE, the documentation is not opened in a
#' browser. Default is FALSE.
#' @examples
#' @examples
#' fredr_docs()
#' fredr_docs('category')
#' fredr_docs('series/observations')
Expand Down Expand Up @@ -54,6 +54,6 @@ fredr_docs <- function(endpoint = "base", params = FALSE, debug = FALSE) {
doc <- paste0(doc, "#Parameters")
}
if (!debug) {
browseURL(url = doc)
utils::browseURL(url = doc)
}
}
10 changes: 5 additions & 5 deletions R/fredr_search.R
@@ -1,13 +1,13 @@
#' Search for a FRED series.
#'
#' @param ... A series of paramters to be used in the query. Of the form
#' param_key = 'param_value'. The parameter \code{search_text} is required for
#' \code{series/search} and \code{series_search_text} is required for
#' @param ... A series of paramters to be used in the query. Of the form
#' param_key = 'param_value'. The parameter \code{search_text} is required for
#' \code{series/search} and \code{series_search_text} is required for
#' \code{series/search/tags} or \code{series/search/related_tags}.
#' @param search_field A string indicating to search for a series, series tags,
#' @param search_field A string indicating to search for a series, series tags,
#' or related series tags. Default is "series" to search for a series. Use
#' "tags" to search tags and "related_tags" to search related tags.
#' @return A \code{ts} object.
#' @return A \code{data.frame} object.
#' @examples
#' fredr_search(search_text = "oil", order_by = "popularity")
#' @export
Expand Down
63 changes: 16 additions & 47 deletions R/fredr_series.R
@@ -1,9 +1,9 @@
#' Return a FRED dataset as a time series object.
#' Return a FRED dataset as an \code{xts} object.
#'
#' @param ... A series of paramters to be used in the query. Of the form
#' param_key = 'param_value'. The parameter \code{series_id} is
#' required.
#' @return A \code{ts} object.
#' @return An \code{xts} object.
#' @examples
#' fredr_series(series_id = "UNRATE",
#' observation_start = "1980-01-01",
Expand All @@ -15,58 +15,27 @@
#' unit = "log")
#' @export
fredr_series <- function(...) {

params <- list(...)

if (!("series_id" %in% names(params))) {
stop("Missing 'series_id' parameter.")
}
if ("frequency" %in% names(params)) {
freq <- switch(params[["frequency"]],
"d" = 365,
"w" = 52,
"bw" = 26,
"m" = 12,
"q" = 4,
"sq" = 2,
"a" = 1)
if (is.null(freq)) {
stop("Invalid 'frequency' value supplied.")
}
} else {
freq <- switch(fredr::get_freq(params[["series_id"]]),
"Daily" = 365,
"Weekly" = 52,
"Bi-Weekly" = 26,
"Monthly" = 12,
"Quarterly" = 4,
"Semiannual" = 2,
"Annual" = 1)
}

frame <- fredr::fredr(endpoint = "series/observations", ...)

frame$value[frame$value == "."] <- NA
frame$value <- as.numeric(frame$value)
frame$date <- as.Date(frame$date, "%Y-%m-%d")
y <- as.numeric(format(frame$date[1], "%Y"))
m <- as.numeric(format(frame$date[1], "%m"))
d <- as.numeric(format(frame$date[1], "%d"))
series <- ts(data = frame$value,
start = c(y, m, d),
frequency = freq)
return(series)
}

#' Check the default frequency of a series with a call to the FRED API
#'
#' @param series_id A string
#' @return An integer representing the number of series observations in a unit
#' of time. Used in creating a \code{ts} object with the appropriate
#' temporal frequency.
#' @examples
#' get_freq(series_id = "GNPCA")
#' @export
get_freq <- function(series_id){
if (is.null(series_id)) {
stop("series_id parameter not present.")
}
freq <- fredr::fredr("series", series_id = series_id)$frequency
return(freq)
frame <- frame[order(frame$date), ]

series <- xts::xts(
x = frame$value,
order.by = frame$date
)

names(series) <- params[["series_id"]]

return(series)
}
46 changes: 19 additions & 27 deletions README.Rmd
Expand Up @@ -22,9 +22,9 @@ Reserve Bank of St. Louis. Essentially a simple wrapper of
[`httr`](https://github.com/hadley/httr),
[`dplyr`](https://github.com/hadley/dplyr), and the FRED API itself, `fredr` is
designed with simplicity and flexibility in mind. In addition a generic query
function `fredr` to return any query as a `tbl_df`, the package also provides
function `fredr` to return any query as a `data.frame`, the package also provides
convenience functions `fredr_search` and `fredr_series` to simplify the process
to finding and importing FRED series as `R` objects. As nearly all optional
to finding and importing FRED data series as `R` objects. As nearly all optional
parameters supplied to these functions are relayed verbatim to the API, the
user is strongly encouraged to read the full [FRED
API](https://research.stlouisfed.org/docs/api/fred/) to leverage the full power
Expand All @@ -36,7 +36,7 @@ examples.
# install.packages("devtools")
devtools::install_github("sboysel/fredr")
```
## Quickstart
## Usage
Load `fredr`
```{r load_libi, eval=FALSE}
library(fredr)
Expand All @@ -52,47 +52,38 @@ Search for FRED series
```{r fredr_search, message=FALSE, warning=FALSE}
fredr_search(search_text = "housing")
```
Get a FRED series. Returns a `ts` object.
Get a FRED series. Returns an `xts` object.
```{r fredr_series1, message=FALSE, warning=FALSE}
fredr_series(series_id = "HOUST",
observation_start = "1990-01-01",
observation_end = "1995-01-01")
library(dplyr)
library(xts)
fredr_series(series_id = "UNRATE",
observation_start = "1990-01-01") %>%
window(., start = "1990-01-01", end = "1991-01-01")
```
Leverage the native features of the FRED API
Leverage the native features of the FRED API:
```{r fredr_series2, message=FALSE, warning=FALSE}
fredr_series(series_id = "UNRATE",
observation_start = "1990-01-01",
frequency = "q",
units = "chg")
```
Combine with other packages for a slick workflow
```{r fredr_series3, message=FALSE, warning=FALSE}
library(dplyr)
library(ggfortify)
fredr_series(series_id = "GNPCA",
units = "log") %>%
autoplot()
```
```{r fredr_series4, message=FALSE, warning=FALSE}
fredr_series(series_id = "GNPCA",
units = "log") %>%
diff() %>%
autoplot()
units = "chg") %>%
window(., start = "1990-01-01", end = "1991-01-01")
```

```{r fredr_series5, message=FALSE, warning=FALSE}
fredr_series(series_id = "GNPCA",
units = "log") %>%
diff() %>%
na.omit() %>%
StructTS() %>%
residuals() %>%
acf(., main = "ACF for First Differenced real US GNP, log")
```
```{r fredr_series6, message=FALSE, warning=FALSE}
fredr_search(search_text = "federal funds",
order_by = "popularity") %>%
slice(1) %>%
fredr_series(series_id = .$id) %>%
window(., start = 2000, end = c(2000, 120))
order_by = "popularity",
limit = 1)$id %>%
fredr_series(series_id = .) %>%
plot(., main = "Federal Funds Rate")
```

Quickly access the FRED API web documentation for any endpoint
Expand All @@ -116,6 +107,7 @@ fredr(endpoint = "tags/series", tag_names = "population;south africa")
The primary goal in creating `fredr` was educational. I also suggest you check
out several other `R` packages designed for the FRED API:

* [business-science/tidyquant](https://github.com/business-science/tidyquant)
* [jcizel/FredR](https://github.com/jcizel/FredR)
* [joshuaulrich/quantmod](https://github.com/joshuaulrich/quantmod)
* [quandl/quandl-r](https://github.com/quandl/quandl-r)
Expand Down

0 comments on commit 691ca81

Please sign in to comment.