# Volume-weighted Exponential Moving Average

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)
```

Hi!

I run all your script and I have a error

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

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

could not find function “try.xts”

I need add some library?

Thanks

You’re right. I forgot to add the ‘xts’ library. thanks!

It will be more efficient in the VEMA functions to create ‘ret’ to be the same length as ‘x’ and then modify it. See Circle 2 of The R Inferno.

Also, in VEMA.den, should for(i in 1:length(x)) should be for(i in 1:length(volumes))?

another mistake from me. Thanks for the corrections.

Great site! Is it possible in R to plot the same graphs made by Peter Ponzo in Excel.

Thanks.