joshuaulrich / TTR

Technical analysis and other functions to construct technical trading rules with R
GNU General Public License v2.0
330 stars 103 forks source link

Ultimate Oscillator on monthly data error #30

Closed debsush closed 8 years ago

debsush commented 8 years ago

Hi,

Using the Ultimate Oscillator function on monthly data was throwing an error

require(quantmod)
getSymbols("AAPL")
AAPLm<-to.monthly(AAPL)[,1:5]
colnames(AAPLm)<-c("Open","High","Low","Close","Volume")
res<-ultimateOscillator(HLC=AAPLm[,c('High','Low','Close')],n=c(7,14,28), wts=c(4,2,1))

Error in avgs[, 1] : incorrect number of dimensions

So I changed the sapply to lapply in the function and it worked fine. Am I doing the right thing here?

ultimateOscillatorNew <-
  function(HLC, n=c(7,14,28), wts=c(4,2,1)) {

    # Ultimate Oscillator

    if(length(n) != 3 || length(wts) != 3)
      stop("length(n) and length(wts) must both be 3")

    HLC <- try.xts(HLC, error=as.matrix)

    # avoid reclassing in ATR and runSum
    HLC.RECLASS <- attr(HLC, ".RECLASS")
    attr(HLC, ".RECLASS") <- FALSE

    # only need 'tr' and 'trueLow'
    atr <- ATR(HLC, n=1)

    buyPressure <- HLC[,3] - atr[,'trueLow']

    avgs <- lapply(n, function(i) runSum(buyPressure, n=i)/runSum(atr[,'tr'], n=i))

    # restore HLC .RECLASS attribute
    attr(HLC, ".RECLASS") <- HLC.RECLASS

    osc <- 100.0*(wts[1]*avgs[[1]] + wts[2]*avgs[[2]] + wts[3]*avgs[[3]]) / sum(wts)

    reclass(osc, HLC)
  }

Regards, SD

joshuaulrich commented 8 years ago

Thanks for the report! Your patch does fix the problem, but I'm going to use a slightly different solution.