Skip to content

Commit

Permalink
Improve performance of ALMA()
Browse files Browse the repository at this point in the history
Ethan Smith pointed out significant performance improvement from
replacing the rollapply() call with WMA().

   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

The rollapply() solution handled multi-column inputs. So initialize
the result and loop over the columns. Add a try.xts() at the beginning
of the function to handle cases where 'x' is a vector.

Closes #117.
  • Loading branch information
joshuaulrich committed Sep 19, 2021
1 parent e000c60 commit 01b04c6
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions R/MovingAverages.R
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ function(x, n=20, ...) {
function(x, n=9, offset=0.85, sigma=6, ...) {

# ALMA (Arnaud Legoux Moving Average)
x <- try.xts(x, error=as.matrix)

if(offset < 0 || offset > 1) {
stop("Please ensure 0 <= offset <= 1")
Expand All @@ -445,7 +446,10 @@ function(x, n=9, offset=0.85, sigma=6, ...) {
sumWeights <- sum(wts)
if(sumWeights != 0)
wts <- wts/sumWeights
alma <- rollapply(x, width=n, FUN=function(xx) sum(xx*wts),
fill=NA, align="right")

alma <- x * NA_real_
for(i in seq_len(NCOL(x))) {
alma[,i] <- WMA(x[,i], n, wts)
}
reclass(alma, x)
}

0 comments on commit 01b04c6

Please sign in to comment.