R/commodity.R

Defines functions fetch_commodity fetch_commodity_info

Documented in fetch_commodity fetch_commodity_info

#' Fetches commodity dataseries from DataHub
#'
#' @param code the code of the commodity
#' @param source_code the source code of the commodity
#' @param query optional, availible list(from = yyyy-mm-dd, to = yyyy-mm-dd, bridge = 'linear' or 'last')
#'
#' @return dataframe \describe{
#'   \item{code}{commodity code}
#'   \item{source_code}{source code}
#'   \item{date}{series date}
#'   \item{value}{value of the series}
#'   \item{unit}{unit of the value}
#' }
#'
#' @examples
#' fetch_commodity('BRENT', 'EIA')
#' fetch_commodity('WTI', 'EIA', query = list(from = '2019-01-01', bridge = 'last'))
#'
#' @export
fetch_commodity <- function(code, source_code, query = list()) {

  # Check input arguments
  collection <- checkmate::makeAssertCollection()
  checkmate::assertString(code, na.ok = FALSE, min.chars = 1, add = collection)
  checkmate::assertString(source_code, na.ok = FALSE, min.chars = 1, add = collection)
  checkmate::assertList(query, add = collection)
  checkmate::reportAssertions(collection)

  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/commodity/",
    toupper(code),
    "/source/",
    toupper(source_code),
    "/value")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept_json(),
    query = query)

  parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))

  #* Stop if errors
  if (httr::http_error(resp)) {
    stop(
      sprintf(
        "DataHub API request failed [%s]\n%s\n<%s>",
        httr::status_code(resp),
        parsed$message,
        parsed$errors
      ),
      call. = FALSE
    )
  }

  tryCatch({
    parsed$date = as.Date(parsed$date)
    return(parsed)
  },
    error=function(error_message) {
      return(setNames(data.frame(matrix(ncol = 5, nrow = 0)), c("code", "source_code", "date", "value", "unit")))
  })
}


#' Fetches all available commodities
#'
#' @return dataframe \describe{
#'   \item{code}{commodity code}
#'   \item{name}{commodity name}
#'   \item{source_code}{source code}
#'   \item{source_name}{source name, use this for caption}
#'   \item{description}{description of this series}
#'   \item{last_update}{date this series was last updated}
#'   \item{usage}{code example on how to call for the dataseries}
#' }
#'
#' @examples
#' fetch_commodity_info()
#' fetch_commodity_info() %>%
#'    filter(stringr::str_detect(name, stringr::fixed('brent', ignore_case = T)))
#'
#' @export
fetch_commodity_info <- function(.x = NULL) {
  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/commodity")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept_json())

  parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))

  #* Stop if errors
  if (httr::http_error(resp)) {
    stop(
      sprintf(
        "DataHub API request failed [%s]\n%s\n<%s>",
        httr::status_code(resp),
        parsed$message,
        parsed$errors
      ),
      call. = FALSE
    )
  }

  parsed <- parsed %>%
    select(code, name, source_code, source_name, description, last_update) %>%
    mutate(usage = paste0("fetch_commodity('", code, "','", source_code, "')"))

  if (is.data.frame(.x)) rbind(.x, parsed)
  else parsed
}
palmargisla/datahub-r documentation built on Sept. 18, 2019, 9:50 p.m.