R/get_data.R

#' Set api key
set_api_key <- function(api_key) {
  message("Writing api key to '.api-key' file.")
  con <- file(".api-key", "w")
  writeLines(api_key, con = con)
  close(con)
}

#' Get api key
get_api_key <- function() {
  message("Retrieved api key from '.api-key' file.")
  read.csv(".api-key", header = F, stringsAsFactors = F)[,1]
}

#' Get Index Data
#'
#' Sends GET request to Alpha Advantage API and returns data frame.
#'
#' @param symbol Ticker for index fund
#' @param api_key Valid Alpha Advantage API key
#'
#' @import magrittr
#'
#' @export
get_index_data <- function(symbol, api_key) {
  # Request data from api
  base_url <- "https://www.alphavantage.co/query?"
  query <- paste0("function=TIME_SERIES_WEEKLY_ADJUSTED",
                  "&symbol=", symbol,
                  "&apikey=", api_key,
                  "&datatype=json")
  resp <- httr::GET(paste0(base_url, query))

  # Check to see if request was successful
  if (httr::http_error(resp))
    message(paste("The requested ticker:", symbol, "is unavailable."))

  # Extract JSON data
  text <- httr::content(resp, as="text", encoding="utf8")
  json <- jsonlite::fromJSON(text)[2][[1]]

  # Convert JSON to data frame and extract adjusted closing price
  if (!is.null(json)) {
    tibble::tibble(
      date = as.Date(names(json)),
      symbol = symbol,
      price = json %>% purrr::map_chr(~ .[[5]]) %>% as.double
    )
  } else {
      message(paste("Unable to retrive", symbol, "data."))
    }
}

#' Get Data for Multiple Index Funds
#'
#' Sends GET request to Alpha Advantage API and returns data frame.
#'
#' @param symbols A vector of index funds to retrieve
#' @param api_key Valid Alpha Advantage API key
#'
#' @import magrittr
#'
#' @export
get_data <- function(symbols, api_key) {
  df_list <- purrr::map(symbols, get_index_data, api_key)
  df_list %>% dplyr::bind_rows() %>% tidyr::spread(symbol, price)
}
logan-connolly/fireguard documentation built on May 31, 2019, 10:35 a.m.