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

ALMA optimization #117

Closed ethanbsmith closed 3 years ago

ethanbsmith commented 3 years ago

Description

ALMA is a clever weighted ma. its currently implemented as a rollapply, but could be sped up by using WMA

Minimal, reproducible example

ALMA.new<- function (x, n = 9, offset = 0.85, sigma = 6, ...)
{
  if (offset < 0 || offset > 1) {
    stop("Please ensure 0 <= offset <= 1")
  }
  if (sigma <= 0)
    stop("sigma must be > 0")
  m <- floor(offset * (n - 1))
  s <- n/sigma
  wts <- exp(-((seq(0, n - 1) - m)^2)/(2 * s * s))
  sumWeights <- sum(wts)
  if (sumWeights != 0)     wts <- wts/sumWeights
  alma <- WMA(x, n, wts)
  reclass(alma, x)
}

z <- Cl(getSymbols("SPY"))

all.equal(drop(coredata(ALMA(z))), drop(coredata(ALMA.new(z))))
#[1] TRUE

microbenchmark(ALMA(z), ALMA.new(z), times = 100,unit = "ms")
#Unit: milliseconds
#        expr       min         lq      mean     median        uq     max neval
#     ALMA(z) 10.692501 11.2338510 12.426196 11.5029515 11.944251 33.3690   100
# ALMA.new(z)  0.403302  0.4692515  0.688744  0.5237505  0.575451 17.0059   100

since this is part of TTR, not sure if its better to call WMA or .Call("wma", x, wts, n, PACKAGE = "TTR")?

if agreed, i can do a pr

ethanbsmith commented 3 years ago

existing implementation allows for multi-column, input so actual solution would require an apply to be backward compatible

joshuaulrich commented 3 years ago

Awesome, thank you!

Ha, just noticed that you said you could do a PR... sorry about that!