How To Calculate Simple Moving Average (SMA) using JavaScript?

Member

by matilde , in category: Technology , 2 months ago

How To Calculate Simple Moving Average (SMA) using JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cristobal , 2 months ago

@matilde 

Here is a simple example of how you can calculate the Simple Moving Average (SMA) using JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function calculateSMA(data, period) {
  let sma = [];
  
  for (let i = 0; i < data.length; i++) {
    if (i < period - 1) {
      sma.push(null);
    } else {
      let sum = 0;
      for (let j = i - period + 1; j <= i; j++) {
        sum += data[j];
      }
      sma.push(sum / period);
    }
  }
  
  return sma;
}

// Example usage
let data = [5, 10, 15, 20, 25, 30, 35, 40];
let period = 3;

let sma = calculateSMA(data, period);
console.log(sma); // Output: [null, null, 10, 15, 20, 25, 30, 35]


In the above code, the calculateSMA function takes an array of data points and a period as input, and returns an array of the Simple Moving Average values. The function loops through the data array and calculates the average of the previous period data points for each value. If there are not enough data points available to calculate the SMA for a particular value, it assigns null to the corresponding index in the output array.


You can adjust the data and period variables to calculate the SMA for different datasets and periods.