DEV Community

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

Posted on • Edited on

6 2

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()

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay