While I was working on a smoothing function, I came across the EMA (exponential moving average) which basically applies exponentially-decreasing weights to older observations. This is commonly used in finance, and can offer some protection against lags in trend movements.

As I was looking to combine this moving average with a volume-weighted version, or simply a weighted moving average, I ran across this Volume-weighted Exponential Moving Average stuff from Peter Ponzo. I gave it a try in R and here’s the code. This requires the ‘xts’ package to be loaded.

 

require(xts)

VEMA <- function(x, volumes, n = 10, wilder = F, ratio = NULL, ...)
{
    x <- try.xts(x, error = as.matrix)
    if (n < 1 || n > NROW(x))
        stop("Invalid 'n'")
    if (any(nNonNA <- n > colSums(!is.na(x))))
        stop("n > number of non-NA values in column(s) ", paste(which(nNonNA),
            collapse = ", "))
    x.na <- xts:::naCheck(x, n)
    if (missing(n) && !missing(ratio))
        n <- trunc(2/ratio - 1)
    if (is.null(ratio)) {
        if (wilder)
            ratio <- 1/n
        else ratio <- 2/(n + 1)
    }

    foo <- cbind(x[,1], volumes, VEMA.num(as.numeric(x[,1]), volumes, ratio), VEMA.den(volumes, ratio))
    (foo[,3] / foo[,4]) -> ma

    ma <- reclass(ma, x)
    if (!is.null(dim(ma))) {
        colnames(ma) <- paste(colnames(x), "VEMA", n, sep = ".")
    }
    return(ma)
}

VEMA.num <- function(x, volumes, ratio) {
    ret <- c()
    s <- 0
    for(i in 1:length(x)) { s <- ratio * s + (1-ratio) * x[i] * volumes[i]; ret <- c(ret, s); }
    ret
}

VEMA.den <- function(volumes, ratio) {
    ret <- c()
    s <- 0
    for(i in 1:length(volumes)) { s <- ratio * s + (1-ratio) * volumes[i]; ret <- c(ret, s); }
    ret
}

VEMA(1:20, 20:1, ratio=0.1)

VEMA(1:20, 20:1, ratio=0.9)