stock-bot/libs/calculations/src/indicators/window-statistics.ts

74 lines
2.1 KiB
TypeScript

import { at } from '@stock-bot/invariants';
/** Scalar trailing-window math. Missing warm-up is undefined, never a synthetic zero average. */
export function trailingMean(
values: readonly number[],
period: number,
offset = 0
): number | undefined {
if (!Number.isSafeInteger(period) || period < 1 || !Number.isSafeInteger(offset) || offset < 0) {
throw new Error('Indicator period must be positive and offset nonnegative integers');
}
const end = values.length - offset;
if (end < period) {
return undefined;
}
let sum = 0;
for (let i = end - period; i < end; i++) {
const value = values[i];
if (value === undefined || !Number.isFinite(value)) {
throw new Error('Indicator prices must be finite');
}
sum += value;
}
const mean = sum / period;
if (!Number.isFinite(mean)) {
throw new Error('Indicator mean overflow');
}
return mean;
}
export function trailingPopulationDeviation(
values: readonly number[],
period: number
): number | undefined {
const mean = trailingMean(values, period);
if (mean === undefined) {
return undefined;
}
let squared = 0;
for (let i = values.length - period; i < values.length; i++) {
squared += (at(values, i) - mean) ** 2;
}
const deviation = Math.sqrt(squared / period);
if (!Number.isFinite(deviation)) {
throw new Error('Indicator deviation overflow');
}
return deviation;
}
export function movingAverageCrossover(values: readonly number[], fast: number, slow: number) {
if (fast >= slow) {
throw new Error('fastPeriod must be below slowPeriod');
}
const fastMA = trailingMean(values, fast);
const slowMA = trailingMean(values, slow);
const prevFastMA = trailingMean(values, fast, 1);
const prevSlowMA = trailingMean(values, slow, 1);
if (
fastMA === undefined ||
slowMA === undefined ||
prevFastMA === undefined ||
prevSlowMA === undefined
) {
return undefined;
}
return {
fastMA,
slowMA,
prevFastMA,
prevSlowMA,
goldenCross: prevFastMA <= prevSlowMA && fastMA > slowMA,
deathCross: prevFastMA >= prevSlowMA && fastMA < slowMA,
};
}