DEV Community

Cover image for Calculating the Exponential Moving Average (EMA) with JavaScript
Mustafa Onur Çelik
Mustafa Onur Çelik

Posted on • Edited on

Calculating the Exponential Moving Average (EMA) with JavaScript

To calculate the Exponential Moving Average (EMA) with JavaScript, you can use the following formula:

EMA = (price(t) * k) + (EMA(y) * (1 – k))

Enter fullscreen mode Exit fullscreen mode

where price(t) is the most recent closing price, EMA(y) is the previous period's EMA, k is the weighting factor, and t and y are the current and previous periods, respectively.

Here's an example of how you can implement this formula to calculate the EMA for a given array of closing prices:

function calculateEMA(closingPrices, period) {
  const k = 2 / (period + 1);
  let ema = closingPrices[0];
  for (let i = 1; i < closingPrices.length; i++) {
    ema = (closingPrices[i] * k) + (ema * (1 - k));
  }

  return ema;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const ema = calculateEMA(closingPrices, 12);
console.log(ema); // Output: 119.53

Enter fullscreen mode Exit fullscreen mode

This code calculates the EMA for a given array of closing prices by applying the EMA formula to each closing price in the array. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateEMA() function. You can also adjust the period used in the calculation by changing the period parameter passed to the `calculateEMA()

Top comments (0)