Skip to content

Instantly share code, notes, and snippets.

@bepitulaz
Created August 17, 2021 16:11
Show Gist options
  • Save bepitulaz/5fc2b4a2a42b5225e2ea47b098a12883 to your computer and use it in GitHub Desktop.
Save bepitulaz/5fc2b4a2a42b5225e2ea47b098a12883 to your computer and use it in GitHub Desktop.
Calculate simple moving average in JavaScript.
/**
* Calculate the simple moving average from stock prices.
* @param {Array} prices - The list of prices.
* @param {number} interval - The number of periods to calculate.
* @return {Array} The list of SMA value.
*/
exports.simpleMovingAverage = (prices, interval) => {
let index = interval - 1;
const length = prices.length + 1;
let results = [];
while (index < length) {
index = index + 1;
const intervalSlice = prices.slice(index - interval, index);
const sum = intervalSlice.reduce((prev, curr) => prev + curr, 0);
results.push(sum / interval);
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment