(This article was first published on

**DataPunks.com » R**, and kindly contributed to R-bloggers)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 his blog:**DataPunks.com » R**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...