Logo

dev-resources.site

for different kinds of informations.

Calculating the Moving Average Convergence Divergence (MACD) with JavaScript

Published at
12/11/2022
Categories
javascript
movingaverage
macd
trading
Author
onurcelik
Author
9 person written this
onurcelik
open
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.

Featured ones: