-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEMA.ts
More file actions
68 lines (53 loc) · 1.5 KB
/
Copy pathEMA.ts
File metadata and controls
68 lines (53 loc) · 1.5 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
import { SMA, SMAInput, SMAOutput } from 'src/overlap/SMA';
import { Indicator } from '@/indicator';
export interface EMAInput extends SMAInput {
/**
* Specify smoothing factor.
* @default 2 / (period + 1)
*/
alpha?: number;
}
export type EMAOutput = SMAOutput;
export type EMATick = number;
/**
* Exponential Moving Average (EMA)
*
* Calculation:
*
* EMA = (current_price - previous_ema) × alpha + previous_ema
* alpha = 2 / (period + 1)
*/
export class EMA extends Indicator<EMAOutput, EMATick> {
period: number;
alpha: number;
private readonly sma: SMA;
protected override result: EMAOutput[] = [];
protected override generator;
constructor(input: EMAInput) {
super(input);
this.period = input.period || 10;
this.alpha = input.alpha || 2 / (this.period + 1);
this.sma = new SMA({ period: this.period, values: [] });
this.generator = this.emaGenerator();
this.generator.next();
this.generator.next();
input.values.forEach((t) => this.nextValue(t));
}
private *emaGenerator(): IterableIterator<EMAOutput, never, EMATick> {
let tick = yield;
let prev;
while (true) {
if (prev !== undefined && tick !== undefined) {
prev = (tick - prev) * this.alpha + prev;
tick = yield prev;
} else {
tick = yield;
prev = this.sma.nextValue(tick);
if (prev !== undefined) tick = yield prev;
}
}
}
static calculate(input: EMAInput): EMAOutput[] {
return new EMA(input).getResult();
}
}