Created
February 1, 2012 20:52
-
-
Save pamelafox/1719238 to your computer and use it in GitHub Desktop.
Moving average calculation
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 moving average | |
var averageData = []; | |
var lastValue = null; | |
var movingAverage = null; | |
for (var i = 0; i < dates.length; i++) { | |
var value = measurementData[i] || missingData[i]; | |
if (!movingAverage) { | |
movingAverage = value; | |
} else { | |
movingAverage = ((value - movingAverage)/7) + movingAverage; | |
} | |
if (isNaN(movingAverage)) { | |
averageData.push(null); | |
} else { | |
averageData.push(movingAverage); | |
} | |
} | |
// Calculate trend if there is more than 3 data points | |
var oldestAverage = null; | |
var numAveragePoints = 0; | |
ED.util.each(dates, function(date, dateIndex) { | |
if (averageData[dateIndex] && !oldestAverage) { | |
oldestAverage = averageData[dateIndex]; | |
} | |
if (averageData[dateIndex]) { | |
numAveragePoints++; | |
newestAverage = averageData[dateIndex]; | |
} | |
}); | |
var averageChange = null; | |
if (numAveragePoints > 3) { | |
averageChange = (newestAverage - oldestAverage)/numAveragePoints; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment