Skip to content

Instantly share code, notes, and snippets.

@karolk
Created October 24, 2012 13:46
Show Gist options
  • Save karolk/3946139 to your computer and use it in GitHub Desktop.
Save karolk/3946139 to your computer and use it in GitHub Desktop.
Moving average in JS
function movingAvg(series, len) {
var ret = [];
series.forEach(function(elem, i, ser) {
var localSeries = ser.slice(0, i+1), lsLen = localSeries.length
len && localSeries.splice( 0, Math.max(0, lsLen-len) );
ret.push(
Math.round(
localSeries.reduce(
function(a,b){return a+b;},
0
)/localSeries.length
)
);
});
return ret;
}
@karolk
Copy link
Author

karolk commented Oct 24, 2012

Moving average is used in charting to smoothen curves and show trends. If you think about a graph created form a typical data series, it tends to have spikes and dips that seem very random. MA can smoothen it and help show underlying trends. MA is used in technical analysis of share price, typical signal to buy is the price going above MA, and sell is price going below MA. See example: http://jsbin.com/asalur/1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment