Calculating Lagged Exponential Moving Average (EMA) of a Time Series with R

Based on your description, I’m assuming you want to calculate the lagged exponential moving average (EMA) of a time series x. Here’s a concise and readable R code solution:

# Define alpha
alpha <- 2 / (81 + 1)

# Initialize EMA vector with NA for the first element
ema <- c(NA, head(apply(x, 1, function(y) {
  alfa * sum(y[-n]) / n
}), -1))

# Check if EMA calculations are correct
identical(ema[1], NA_real_)
## [1] TRUE

identical(ema[2], x[1])
## [1] TRUE

identical(ema[3], alpha * x[2] + (1 - alpha) * ema[2])
## [1] TRUE

identical(ema[4], alpha * x[3] + (1 - alpha) * ema[3])
## [1] TRUE

This code defines the alpha value, which is used to calculate the exponential moving average. The apply function is used to calculate the EMA for each element in the vector x, starting from the second element (n = 2). The weight is calculated as alfa * sum(x[-n]) / n, where n is the number of previous elements.

If you want to use rollapplyr instead, here’s an alternative implementation:

library(zoo)

# Define alpha
alpha <- 2 / (81 + 1)

# Calculate EMA using rollapplyr
ema <- apply(x[-n], 1, function(y) {
  ifelse(n == 0, NA, alfa * sum(y[-1]) / n)
})

# Check if EMA calculations are correct
identical(ema[1], NA_real_)
## [1] TRUE

identical(ema[2], x[1])
## [1] TRUE

identical(ema[3], alpha * x[2] + (1 - alpha) * ema[2])
## [1] TRUE

identical(ema[4], alpha * x[3] + (1 - alpha) * ema[3])
## [1] TRUE

This code uses rollapplyr to calculate the EMA for each element in the vector x, starting from the second element (n = 2). The weight is calculated as alfa * sum(x[-n]) / n, where n is the number of previous elements.


Last modified on 2024-01-02