Search code examples
rquantmod

Why is EMA not equal when comparing samples of different length?


I am struggling to understand why EMA (Exponential Moving Average) is different in these 2 cases.

options(scipen = 10)
library(quantmod)

getSymbols("AAPL", src = "google")

data1 <- EMA(AAPL[, "AAPL.Close"])
data2 <- EMA(tail(AAPL[, "AAPL.Close"], n = 10))

result <- data.frame(tail(data1, n = 1), tail(data2, n = 1))

In the first EMA call i supply as parameter the whole AAPL sample. In the second EMA call i supply only the minimum amount of data to calculate EMA for the last date. If i compare calculated value for the last day, they are different.

In concrete, result[1,1] is 152.907 and result[1,2] is 152.623. Why is this happening? I would expect both numbers to be the same, since EMA is not cumulative.


Solution

  • That is because the exponential decay has 'infinite' history: it decays, but never completely goes away.

    So the set of weights is different between your two use cases, and hence so is the result. There is a decent recent series on MAs for smoothing price series:

    It should make it clear that what you were expecting only holds for SMA which does in fact go to zero weights.