Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EMA computation using filter function in R

I would like to reproduce this code in vectorized notation

getEMA2<-function(x,win){
k<-2/(win+1)
v<-vector()
for (i in 1:length(x)){
    if (i==1){
        v[i]<-x[i]
    }
    else{
        v[i]<-k*x[i]+(1-k)*v[i-1]
    }
}
return (v)
}
testOutput<-getEMA2(rnorm(100,0,1),5)

I've tried using the filter function, but it doesn't appear that recursive / convolution methods can achieve this

Thanks for responses,

like image 562
Aditya Sihag Avatar asked Apr 19 '26 20:04

Aditya Sihag


1 Answers

Since filter computes

y[n] = x[n] + alpha * y[n-1]

you need to rescale the result.

f <- function(x,win) {
  alpha <- 2/(win+1)
  filter(x, 1-alpha, method="recursive", side=1, init=x[1]/alpha)*alpha
}
x <- 1:10
k <- 3
getEMA2(x,k)
f(x,k) # identical

Most of those filters are already defined in the TTR package.

like image 152
Vincent Zoonekynd Avatar answered Apr 21 '26 15:04

Vincent Zoonekynd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!