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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With