Home > OS >  Implement EMA (exponential moving average) in R data.table
Implement EMA (exponential moving average) in R data.table

Time:11-09

Hello I am working on implementing various technical indicators to better understand the algorithms and their implementations; I do not want to use zoo or other pre-packaged algorithms.

I want to use data.table.

sample data

Here is the data we are working with:

set.seed(123)
nrows <- 10000
dt <- data.table::data.table(
    symbol = sample(LETTERS[1:2], 100, replace = TRUE),
    close = runif(nrows, 0, 100),
    open = runif(nrows, 0, 100),
    high = runif(nrows, 0, 100),
    low = runif(nrows, 0, 100),
    volume = runif(nrows, 0, 100)
)

sma (simple moving average)

I can calculate the simple moving average (sma) very easily using data.table::frollmean; this is simply the mean of the window:

# calculate simple moving average sma
dt[, sma_short := data.table::frollmean(close, n = 30L, algo = "exact"), by = symbol]

# another way to do the same thing:
dt[, sma_manual_calculation := data.table::frollapply(close, n = 30L, \(x) {
    return(mean(x))
}), by = symbol]

identical(dt$sma_short, dt$sma_manual_calculation) # TRUE

ema (exponential moving average)

The formula I have found for calculating the ema is as shown here: ema R vs ema Cpp microbenchmark

CodePudding user response:

EMA is an enter image description here

  • Related