forked from cinar/indicatorts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleMovingAverage.ts
44 lines (37 loc) · 932 Bytes
/
simpleMovingAverage.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
// Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
/**
* Optional configuration of SMA parameters.
*/
export interface SMAConfig {
period?: number;
}
/**
* The default configuration of SMA.
*/
export const SMADefaultConfig: Required<SMAConfig> = {
period: 2,
};
/**
* Simple moving average (SMA).
* @param values values array.
* @param config configuration.
* @return SMA values.
*/
export function sma(values: number[], config: SMAConfig = {}): number[] {
const { period } = { ...SMADefaultConfig, ...config };
const result = new Array<number>(values.length);
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
if (i >= period) {
sum -= values[i - period];
result[i] = sum / period;
} else {
result[i] = sum / (i + 1);
}
}
return result;
}
// Export full name
export { sma as simpleMovingAverage };