stock-bot/libs/calculations/src/indicators/sma.ts

22 lines
716 B
TypeScript

import { at } from '@stock-bot/invariants';
import { finite } from '../analytics/equity';
/** Trailing-only SMA in O(n). Output 0 belongs to input period - 1; no warm-up zeros. */
export function sma(values: readonly number[], period: number): number[] {
if (!Number.isSafeInteger(period) || period < 1) {
throw new RangeError('Indicator period must be a positive integer');
}
const result: number[] = [];
let sum = 0;
for (const [index, value] of values.entries()) {
finite(value);
if (index >= period) {
sum -= finite(at(values, index - period));
}
sum = finite(sum + value);
if (index >= period - 1) {
result.push(finite(sum / period));
}
}
return result;
}