Created
October 24, 2012 13:46
-
-
Save karolk/3946139 to your computer and use it in GitHub Desktop.
Moving average in JS
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 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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