Site icon R-bloggers

Volume-weighted Exponential Moving Average

[This article was first published on DataPunks.com » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

 

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(x)) { 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)

To leave a comment for the author, please follow the link and comment on their blog: DataPunks.com » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.