R/downloadFundData.R

#' Download fund data.
#'
#' \code{downloadFundData} downloads the most recent fund data into the
#' specified directory and file.
#'
#' @export
#'
#' @param file String, file name. Default is generated based on today's date.
#' @param dir String, directory of the file. Default is generated temporary
#'   directory.
#'
#' @return String, file path where the downloaded data is stored.
#'
#' @source Data comes from \url{http://manapensija.lv}.
#'
#' @seealso \code{\link{getFundData}}, \code{\link{downloadRfData}}.
downloadFundData <- function(file = paste0("fund-data-", Sys.Date(), ".RData"),
                             dir = tempdir()) {
  # Error handling
  if (!all(is.character(file),
           is.character(dir),
           length(file) == 1,
           length(dir) == 1)) {
    stop("file and dir should be strings")
  }


  filePathCsv <- paste0(tempfile(), ".csv")
  filePathRdata <- paste0(dir, "/", file)

  # Create folders if does not exist
  if (!dir.exists(dir)) {
    dir.create(dir)
  }

  url <- "http://www.manapensija.lv/lv/wp-content/uploads/hist_lv.csv"
  utils::download.file(url, filePathCsv, mode = "wb")

  fundData <- utils::read.csv2(filePathCsv,
                               fileEncoding = "UTF-16",
                               sep = "\t",
                               colClasses = c("character", "factor", "Date",
                                              "Date", "numeric", "numeric",
                                              "numeric", "numeric", "numeric",
                                              "numeric"),
                               dec = ".")

  # Remove preceding zeros
  fundData$ID <- stringr::str_extract(fundData$ID, "[1-9][0-9]*")
  # Convert ID to numeric
  fundData$ID <- as.numeric(fundData$ID)

  save(fundData, file = filePathRdata)

  return(filePathRdata)
}
nickto/PensionFundsLv documentation built on May 23, 2019, 5:08 p.m.