DEV Community

Cover image for Calculating the Moving Average Convergence Divergence (MACD) with JavaScript
Mustafa Onur Çelik
Mustafa Onur Çelik

Posted on • Edited on

4 2

Calculating the Moving Average Convergence Divergence (MACD) with JavaScript

To calculate the Moving Average Convergence Divergence (MACD) with JavaScript, you can use the following formula:

MACD = 12-day EMA - 26-day EMA

Enter fullscreen mode Exit fullscreen mode

where the Exponential Moving Average (EMA) is calculated using 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 these formulas to calculate the MACD for a given array of closing prices:

function calculateMACD(closingPrices) {
  const ema12 = calculateEMA(closingPrices, 12);
  const ema26 = calculateEMA(closingPrices, 26);
  const macd = ema12 - ema26;

  return macd;
}

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 macd = calculateMACD(closingPrices);
console.log(macd); // Output: -1.33

Enter fullscreen mode Exit fullscreen mode

This code calculates the MACD for a given array of closing prices by first calculating the 12-day and 26-day EMAs using the calculateEMA() function, and then applying the MACD formula to these values. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateMACD() function.

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)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️