R/monthly.R

Defines functions monthly_prices monthly_returns monthly_ad

Documented in monthly_ad monthly_prices monthly_returns

#' Computes monthly periodicity of adjusted close prices.
#' Price history must include adjusted prices typically as
#' found from Yahoo and provided by the \code{quantmod} package.
#' @param x an XTS price history with adjusted column, in faster
#' than monthly periodicity
#' @param cname Column name for returned time series
#' @return an XTS price history in monthly periodicity,
#' returning adjusted column only
#' @seealso quantmod::Cl, monthly_prices
monthly_ad <- function(x, cname="Close"){
  sym <- sub("\\..*$", "", names(x)[1])
  # 20170702 changed from Ad() to Cl() for Quandl EOC
  # Assumes adjusted already moved to close column
  x <- zoo::na.locf(x)
  suppressWarnings(
    rv <- quantmod::Cl(xts::to.monthly(x,
                               # indexAt = "lastof",
                               indexAt = "endof", # 20180205
                               drop.time = TRUE,
                               name = sym))
  )
  colnames(rv) <- cname
  rv
}

#' Given a list of ticker symbols, retrieve the symbol's
#' price history from the given environment and compute
#' the monthly adjusted close price return for each symbol.
#' Returns an XTS object containing columns for each symbol.
#' @param symbols the list of ticker symbols
#' @param env the environment containing price histories,
#' default \code{.GlobalEnv}
#' @param n_roc the number of periods for return lookback,
#' default 1
#' @return merged adjusted monthly price returns for each symbol
#' @seealso TTR::ROC
monthly_returns <- function(symbols, env = .GlobalEnv, n_roc = 1) {
  TTR::ROC(x = monthly_prices(symbols, env = env),
           n = n_roc,
           type = "discrete",
           na.pad = TRUE)
}

#' Given a list of ticker symbols, retrieve the symbol's
#' price history from the given environment and compute
#' monthly adjusted prices for each, returning an XTS
#' object containing columns for each symbol.
#' @param symbols the list of ticker symbols
#' @param env the environment containing price histories,
#' default \code{.GlobalEnv}
#' @return merged adjusted monthly prices for each symbol
#' @seealso monthly_ad
monthly_prices <- function(symbols, env = .GlobalEnv) {
  list.sym <- list()
  for (i in 1:length(symbols)) {
    list.sym[[symbols[i]]] <- get(symbols[i], envir = env)
  }

  rv <- do.call(merge, lapply(list.sym, monthly_ad))
  colnames(rv) <- symbols
  rv
}
greatgray/scorecard documentation built on Feb. 14, 2018, 4:28 a.m.