R/weight_ave_3ROC_strict.R

Defines functions weight_ave_3ROC_strict

Documented in weight_ave_3ROC_strict

#' 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.
#' If any of the three ROC values is zero or negative for a day,
#' then return NA for the rank for that date.
#' @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_strict(XLK,n=c(2,4,6),weights=c(.5,.3,.2))
#' tail(wa)
#' }
weight_ave_3ROC_strict <- 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)
    # wave <- ifelse(roc1 > 0 & roc2 > 0 & roc3 > 0, wave, NA)
    wave <- replace(wave,!(roc1 > 0 & roc2 > 0 & roc3 > 0), NA)
    row_rank(wave)
  }
}
greatgray/scorecard documentation built on May 17, 2019, 8:34 a.m.