Created
January 8, 2021 08:30
-
-
Save oliverjumpertz/596d3d56bf305f20de3f4d8d912aab89 to your computer and use it in GitHub Desktop.
Calculating the simple and exponential moving average in JavaScript
This file contains hidden or 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
function simpleMovingAverage(prices, window = 5, n = Infinity) { | |
if (!prices || prices.length < window) { | |
return []; | |
} | |
let index = window - 1; | |
const length = prices.length + 1; | |
const simpleMovingAverages = []; | |
let numberOfSMAsCalculated = 0; | |
while (++index < length && numberOfSMAsCalculated++ < n) { | |
const windowSlice = prices.slice(index - window, index); | |
const sum = windowSlice.reduce((prev, curr) => prev + curr, 0); | |
simpleMovingAverages.push(sum / window); | |
} | |
return simpleMovingAverages; | |
} | |
function exponentialMovingAverage(prices, window = 5) { | |
if (!prices || prices.length < window) { | |
return []; | |
} | |
let index = window - 1; | |
let previousEmaIndex = 0; | |
const length = prices.length; | |
const smoothingFactor = 2 / (window + 1); | |
const exponentialMovingAverages = []; | |
const [sma] = simpleMovingAverage(prices, window, 1); | |
exponentialMovingAverages.push(sma); | |
while (++index < length) { | |
const value = prices[index]; | |
const previousEma = exponentialMovingAverages[previousEmaIndex++]; | |
const currentEma = (value - previousEma) * smoothingFactor + previousEma; | |
exponentialMovingAverages.push(currentEma); | |
} | |
return exponentialMovingAverages; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment