Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created February 1, 2012 20:52
Show Gist options
  • Save pamelafox/1719238 to your computer and use it in GitHub Desktop.
Save pamelafox/1719238 to your computer and use it in GitHub Desktop.
Moving average calculation
// 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