-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
rollingMovingAverage.ts
50 lines (42 loc) · 1.04 KB
/
rollingMovingAverage.ts
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
// Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
/**
* Optional configuration of RMA parameters.
*/
export interface RMAConfig {
period?: number;
}
/**
* The default configuration of RMA.
*/
export const RMADefaultConfig: Required<RMAConfig> = {
period: 4,
};
/**
* Rolling moving average (RMA).
*
* R[0] to R[p-1] is SMA(values)
* R[p] and after is R[i] = ((R[i-1]*(p-1)) + v[i]) / p
*
* @param values values array.
* @param config configuration.
* @returns RMA values.
*/
export function rma(values: number[], config: RMAConfig = {}): number[] {
const { period } = { ...RMADefaultConfig, ...config };
const result = new Array<number>(values.length);
let sum = 0;
for (let i = 0; i < values.length; i++) {
let count = i + 1;
if (i < period) {
sum += values[i];
} else {
sum = result[i - 1] * (period - 1) + values[i];
count = period;
}
result[i] = sum / count;
}
return result;
}
// Export full name
export { rma as rollingMovingAverage };