-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathmovingStandardDeviation.ts
50 lines (40 loc) · 1.09 KB
/
movingStandardDeviation.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
import { sma } from '../trend/simpleMovingAverage';
/**
* Optional configuration of MSTD parameters.
*/
export interface MSTDConfig {
period?: number;
}
/**
* The default configuration of MSTD.
*/
export const MSTDDefaultConfig: Required<MSTDConfig> = {
period: 4,
};
/**
* Moving strandard deviation function.
*
* @param values value array.
* @param config configuration.
* @return std values.
*/
export function mstd(values: number[], config: MSTDConfig = {}): number[] {
const { period } = { ...MSTDDefaultConfig, ...config };
const result = new Array<number>(values.length);
const averages = sma(values, { period });
for (let i = 0; i < values.length; i++) {
result[i] = 0;
if (i >= period - 1) {
let sum = 0;
for (let k = i - (period - 1); k <= i; k++) {
sum += (values[k] - averages[i]) * (values[k] - averages[i]);
}
result[i] = Math.sqrt(sum / period);
}
}
return result;
}
// Export full name
export { mstd as movingStandardDeviation };