forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request elastic#35 from polyfractal/feature/movingstd
Add naive moving standard deviation function
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
var alter = require('../lib/alter.js'); | ||
var _ = require('lodash'); | ||
var Chainable = require('../lib/classes/chainable'); | ||
module.exports = new Chainable('movingstd', { | ||
args: [ | ||
{ | ||
name: 'inputSeries', | ||
types: ['seriesList'] | ||
}, | ||
{ | ||
name: 'window', | ||
types: ['number'], | ||
help: 'Number of points to compute the standard deviation over' | ||
} | ||
], | ||
aliases: ['mvstd'], | ||
help: 'Calculate the moving standard deviation over a given window. Uses naive two-pass algorithm. Rounding errors may become more noticeable with very long series, or series with very large numbers.', | ||
fn: function movingaverageFn(args) { | ||
return alter(args, function (eachSeries, _window) { | ||
|
||
var pairs = eachSeries.data; | ||
|
||
eachSeries.data = _.map(pairs, function (point, i) { | ||
if (i < _window) { return [point[0], null]; } | ||
|
||
var average = _.chain(pairs.slice(i - _window, i)) | ||
.map(function (point) { | ||
return point[1]; | ||
}).reduce(function (memo, num) { | ||
return (memo + num); | ||
}).value() / _window; | ||
|
||
var variance = _.chain(pairs.slice(i - _window, i)) | ||
.map(function (point) { | ||
return point[1]; | ||
}).reduce(function (memo, num) { | ||
return memo + Math.pow(num - average, 2); | ||
}).value() / (_window - 1); | ||
|
||
return [point[0], Math.sqrt(variance)]; | ||
}); | ||
return eachSeries; | ||
}); | ||
} | ||
}); |