rttr

Exponential moving average of just the last value of a vector in R


I have a simple vector as follows:

x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64)

I have found the EMA of this vector using

library(TTR)
y = EMA(x, 5)

and the result is

[1] NA NA NA NA 13.33400 13.22267 13.52844 14.44563 16.51042 16.88695

The next day a new value is added to the end of original vector x and the updated x vector is:

x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64, 18.09)

The expected output is -

y = [1] NA NA NA NA 13.33400 13.22267 13.52844 14.44563 16.51042 16.88695 17.28796

This output can be produced by EMA(x, 5), but this statement will calculate EMA of the entire vector again and will be time inefficient. Since we already have the previous day's EMA calculation in vector y, is there a way to calculate the EMA of just the last 5 days instead of recalculating for the entire vector and merge the new value in vector y?

Thanks!


Solution

  • As already suggested in this post, looking at C code of TTR provides a possible solution :

    x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64)
    
    n <- 5
    y = TTR::EMA(x,n)
    
    ratio <- 2 / (n+1)
    
    newx <- 18.09
    newy <- tail(y,1) * (1 - ratio) + ratio * newx
    newy
    #> [1] 17.28796
    
    y = c(y,newy)
    y
    #>  [1]       NA       NA       NA       NA 13.33400 13.22267 13.52844 14.44563
    #>  [9] 16.51042 16.88695 17.28796