Created
August 17, 2021 16:11
-
-
Save bepitulaz/5fc2b4a2a42b5225e2ea47b098a12883 to your computer and use it in GitHub Desktop.
Calculate simple moving average in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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