-
Notifications
You must be signed in to change notification settings - Fork 534
/
ema.js
56 lines (46 loc) · 1.33 KB
/
ema.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'use strict';
module.exports = function(indicatorMixin, accessor_ohlc) { // Injected dependencies
return function() { // Closure function
var p = {}, // Container for private, direct access mixed in variables
period = 10,
previous,
alpha,
initialTotal,
initialCount;
function indicator(data) {
indicator.init();
return data.map(ma).filter(function(d) { return d.value; });
}
indicator.init = function() {
previous = null;
alpha = 2/(period+1);
initialTotal = 0;
initialCount = 0;
return indicator;
};
function ma(d, i) {
var value = indicator.average(p.accessor(d));
if (i+1 < period) {
value = null;
}
return { date: p.accessor.d(d), value: value };
}
indicator.average = function(value) {
if(initialCount < period) return (initialTotal += value)/++initialCount;
else {
if(initialCount === period) {
previous = initialTotal/initialCount++;
}
return (previous = previous + alpha*(value-previous));
}
};
indicator.period = function(_) {
if (!arguments.length) return period;
period = _;
return indicator;
};
// Mixin 'superclass' methods and variables
indicatorMixin(indicator, p, accessor_ohlc());
return indicator;
};
};