R/weight_ave_3ROC.R

Defines functions weight_ave_3ROC

Documented in weight_ave_3ROC

#' Provides a ranking of weighted-average rate of change (ROC)
#' of a given price history time series over three periods,
#' using only ROC values that are positive for each period.
#' Returns all ROC and weighted average results, regardless of sign.
#' @param x price history as XTS
#' @param n an array of ROC lookback periods, in same perodicity as \code{x};
#' must include exactly three elements; default 1, 3, 6.
#' @param weights an array of weights for each ROC, must be length
#' 3 and sum to 1.
#' default is 1/3 for each entry.
#' @return ranking as determined by \code{row_rank}
#' @examples
#' \dontrun{
#' library(quantmod)
#' getSymbols("XLK",auto.assign=TRUE)
#' wa <- weight_ave_3ROC(XLK,n=c(2,4,6),weights=c(.5,.3,.2))
#' tail(wa)
#' }
weight_ave_3ROC <- function(x,
                            n = c(1, 3, 6),
                            weights = c( 1 / 3, 1 / 3, 1 / 3)) {

  if ( (sum(weights) != 1) || (length(n) != 3) || (length(weights) != 3)) {
    stop("The sum of three weights must equal 1")
  } else {
    roc1 <- TTR::ROC(x, n = n[1], type = "discrete")
    roc2 <- TTR::ROC(x, n = n[2], type = "discrete")
    roc3 <- TTR::ROC(x, n = n[3], type = "discrete")
    wave <- (roc1 * weights[1] +
               roc2 * weights[2] +
               roc3 * weights[3]) / sum(weights)
    row_rank(wave)
  }
}
greatgray/scorecard documentation built on Feb. 14, 2018, 4:28 a.m.