Add versioned streaming indicators and share chart calculations

This commit is contained in:
Boki 2026-10-21 22:22:42 -04:00
parent 7827220b9b
commit cca5d71e6e
20 changed files with 1470 additions and 331 deletions

View file

@ -13,6 +13,32 @@ export {
sma,
trailingMean,
trailingPopulationDeviation,
ema,
EmaIndicator,
EMA_CONTRACT,
rsi,
RsiIndicator,
RSI_CONTRACT,
atr,
AtrIndicator,
ATR_CONTRACT,
trailingSimpleRsi,
bollingerBands,
macd,
stochastic,
} from './indicators';
export type {
IndicatorSeries,
HlcBar,
EmaSnapshot,
RsiSnapshot,
AtrSnapshot,
EmaOptions,
EmaSeed,
RsiOptions,
FlatRsi,
AtrOptions,
AtrFirstRange,
} from './indicators';
export {
calculateLogReturns,

View file

@ -0,0 +1,149 @@
import {
collect,
configuration,
count,
finite,
nonnegative,
optionalNumber,
period,
snapshot,
validateBar,
type HlcBar,
type IndicatorSeries,
} from './contracts';
export const ATR_CONTRACT = 'atr-wilder/v1';
export type AtrFirstRange = 'previous-close' | 'high-low';
export interface AtrOptions {
firstRange?: AtrFirstRange;
}
export interface AtrSnapshot {
contract: typeof ATR_CONTRACT;
period: number;
firstRange: AtrFirstRange;
count: number;
previousClose: number | null;
seedSum: number;
value: number | null;
}
function firstRange(value: unknown): AtrFirstRange {
if (value !== 'previous-close' && value !== 'high-low') {
throw new Error('ATR first range must be previous-close or high-low');
}
return value;
}
function parse(input: unknown): AtrSnapshot {
const value = snapshot(input, [
'contract',
'period',
'firstRange',
'count',
'previousClose',
'seedSum',
'value',
]);
if (value.contract !== ATR_CONTRACT) {
throw new Error('Unsupported ATR snapshot contract');
}
const state: AtrSnapshot = {
contract: ATR_CONTRACT,
period: period(value.period),
firstRange: firstRange(value.firstRange),
count: count(value.count),
previousClose: optionalNumber(value.previousClose),
seedSum: nonnegative(value.seedSum),
value: optionalNumber(value.value),
};
const ranges = state.count - (state.firstRange === 'previous-close' ? 1 : 0);
const ready = ranges >= state.period;
if (
(state.previousClose !== null) !== state.count > 0 ||
(state.value !== null) !== ready ||
(state.value !== null && state.value < 0) ||
((ready || ranges <= 0) && state.seedSum !== 0)
) {
throw new Error('Inconsistent ATR snapshot phase');
}
return state;
}
/** Wilder ATR with an explicit first-bar policy; finite HLC inputs, O(1) memory. */
export class AtrIndicator {
private state: AtrSnapshot;
constructor(size = 14, options: AtrOptions = {}) {
configuration(options, ['firstRange']);
this.state = {
contract: ATR_CONTRACT,
period: period(size),
firstRange: firstRange(
options.firstRange === undefined ? 'previous-close' : options.firstRange
),
count: 0,
previousClose: null,
seedSum: 0,
value: null,
};
}
update(bar: HlcBar): number | null {
validateBar(bar);
const prior = this.state;
const next = { ...prior, count: count(prior.count + 1), previousClose: bar.close };
if (prior.previousClose !== null || prior.firstRange === 'high-low') {
const range = finite(
prior.previousClose === null
? bar.high - bar.low
: Math.max(
bar.high - bar.low,
Math.abs(bar.high - prior.previousClose),
Math.abs(bar.low - prior.previousClose)
)
);
if (prior.value === null) {
next.seedSum = nonnegative(prior.seedSum + range);
const ranges = next.count - (prior.firstRange === 'previous-close' ? 1 : 0);
if (ranges === prior.period) {
next.value = nonnegative(next.seedSum / prior.period);
next.seedSum = 0;
}
} else {
next.value = nonnegative((prior.value * (prior.period - 1) + range) / prior.period);
}
}
this.state = next;
return next.value;
}
current(): number | null {
return this.state.value;
}
snapshot(): AtrSnapshot {
return { ...this.state };
}
reset(): void {
this.state = { ...this.state, count: 0, previousClose: null, seedSum: 0, value: null };
}
restore(input: unknown): void {
const next = parse(input);
if (next.period !== this.state.period || next.firstRange !== this.state.firstRange) {
throw new Error('ATR snapshot configuration mismatch');
}
this.state = next;
}
static fromSnapshot(input: unknown): AtrIndicator {
const state = parse(input);
const stream = new AtrIndicator(state.period, { firstRange: state.firstRange });
stream.restore(state);
return stream;
}
}
export function atr(bars: readonly HlcBar[], size = 14, options: AtrOptions = {}): IndicatorSeries {
const stream = new AtrIndicator(size, options);
return collect(
bars,
stream,
ATR_CONTRACT,
size - (stream.snapshot().firstRange === 'high-low' ? 1 : 0)
);
}

View file

@ -0,0 +1,100 @@
import { at } from '@stock-bot/invariants';
import { count, finite, period, validateBar, type HlcBar, type IndicatorSeries } from './contracts';
import { ema, type EmaOptions } from './ema';
import { sma } from './sma';
/** Population bands around unrounded SMA. This is a batch composition, not streaming state. */
export function bollingerBands(values: readonly number[], size = 20, deviations = 2) {
period(size);
if (finite(deviations) < 0) {
throw new RangeError('Band deviations must be nonnegative');
}
const middle = sma(values, size);
const upper: number[] = [],
lower: number[] = [];
for (let i = 0; i < middle.length; i++) {
const mean = at(middle, i);
let squared = 0;
for (let j = i; j < i + size; j++) {
squared = finite(squared + (at(values, j) - mean) ** 2);
}
const spread = finite(Math.sqrt(squared / size) * deviations);
upper.push(finite(mean + spread));
lower.push(finite(mean - spread));
}
return { contract: 'bollinger-population/v1', startIndex: size - 1, middle, upper, lower };
}
/** EMA seeds are shared by both price EMAs and the signal EMA; offsets retain exact source alignment. */
export function macd(
values: readonly number[],
fast = 12,
slow = 26,
signal = 9,
options: EmaOptions = {}
) {
period(fast);
period(slow);
period(signal);
if (fast >= slow) {
throw new RangeError('MACD fast period must be below slow period');
}
const a = ema(values, fast, options),
b = ema(values, slow, options);
const startIndex = Math.max(a.startIndex, b.startIndex);
const difference: number[] = [];
for (let i = startIndex; i < values.length; i++) {
difference.push(finite(at(a.values, i - a.startIndex) - at(b.values, i - b.startIndex)));
}
const signalSeries = ema(difference, signal, options);
const histogram = signalSeries.values.map((value, i) =>
finite(at(difference, signalSeries.startIndex + i) - value)
);
const contract = 'macd-ema/v1';
const signalStart = count(startIndex + signalSeries.startIndex);
return {
macd: { contract, startIndex, values: difference } satisfies IndicatorSeries,
signal: {
contract,
startIndex: signalStart,
values: signalSeries.values,
} satisfies IndicatorSeries,
histogram: {
contract,
startIndex: signalStart,
values: histogram,
} satisfies IndicatorSeries,
};
}
/** SMA-smoothed stochastic. A flat high/low window is explicitly neutral (50), never NaN. */
export function stochastic(bars: readonly HlcBar[], size = 14, smoothK = 3, smoothD = 3) {
period(size);
period(smoothK);
period(smoothD);
for (const bar of bars) {
validateBar(bar);
}
const raw: number[] = [];
for (let i = size - 1; i < bars.length; i++) {
let low = at(bars, i).low,
high = at(bars, i).high;
for (let j = i - size + 1; j < i; j++) {
low = Math.min(low, at(bars, j).low);
high = Math.max(high, at(bars, j).high);
}
const range = finite(high - low);
raw.push(range === 0 ? 50 : finite(((at(bars, i).close - low) / range) * 100));
}
const k = sma(raw, smoothK),
d = sma(k, smoothD);
const startIndex = count(size - 1 + smoothK - 1);
return {
k: { contract: 'stochastic-sma/v1', startIndex, values: k } satisfies IndicatorSeries,
d: {
contract: 'stochastic-sma/v1',
startIndex: count(startIndex + smoothD - 1),
values: d,
} satisfies IndicatorSeries,
};
}

View file

@ -0,0 +1,95 @@
/** No padding: values[i] belongs to source input startIndex + i. Empty warm-up stays empty. */
export interface IndicatorSeries {
contract: string;
startIndex: number;
values: number[];
}
export interface HlcBar {
high: number;
low: number;
close: number;
}
export function finite(value: unknown): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new RangeError('Indicator values must be finite numbers');
}
return value;
}
export function period(value: unknown): number {
const result = finite(value);
if (!Number.isSafeInteger(result) || result < 1 || result >= Number.MAX_SAFE_INTEGER) {
throw new RangeError('Indicator period must be a positive safe integer below MAX_SAFE_INTEGER');
}
return result;
}
export function count(value: unknown): number {
const result = finite(value);
if (!Number.isSafeInteger(result) || result < 0) {
throw new RangeError('Indicator count must be a nonnegative safe integer');
}
return result;
}
export function nonnegative(value: unknown): number {
const result = finite(value);
if (result < 0) {
throw new RangeError('Indicator accumulator must be nonnegative');
}
return result;
}
export function optionalNumber(value: unknown): number | null {
return value === null ? null : finite(value);
}
export function snapshot(input: unknown, keys: readonly string[]): Record<string, unknown> {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
throw new Error('Invalid indicator snapshot');
}
const fields = Object.keys(input);
if (fields.length !== keys.length || fields.some(key => !keys.includes(key))) {
throw new Error('Invalid indicator snapshot fields');
}
return input as Record<string, unknown>;
}
export function configuration(input: unknown, keys: readonly string[]): void {
if (
!input ||
typeof input !== 'object' ||
Array.isArray(input) ||
Object.keys(input).some(key => !keys.includes(key))
) {
throw new Error('Invalid indicator configuration fields');
}
}
export function collect<T>(
inputs: readonly T[],
stream: { update(input: T): number | null },
contract: string,
startIndex: number
): IndicatorSeries {
const values: number[] = [];
for (const input of inputs) {
const value = stream.update(input);
if (value !== null) {
values.push(value);
}
}
return { contract, startIndex, values };
}
export function validateBar(bar: HlcBar): void {
const high = finite(bar.high);
const low = finite(bar.low);
const close = finite(bar.close);
if (high < low || close < low || close > high) {
throw new RangeError('Indicator bar requires low <= close <= high');
}
finite(high - low);
}

View file

@ -0,0 +1,122 @@
import {
collect,
configuration,
count,
finite,
optionalNumber,
period,
snapshot,
type IndicatorSeries,
} from './contracts';
export const EMA_CONTRACT = 'ema/v1';
export type EmaSeed = 'sma' | 'first';
export interface EmaOptions {
seed?: EmaSeed;
}
export interface EmaSnapshot {
contract: typeof EMA_CONTRACT;
period: number;
seed: EmaSeed;
count: number;
value: number | null;
seedSum: number;
}
function seed(value: unknown): EmaSeed {
if (value !== 'sma' && value !== 'first') {
throw new Error('EMA seed must be sma or first');
}
return value;
}
function parse(input: unknown): EmaSnapshot {
const value = snapshot(input, ['contract', 'period', 'seed', 'count', 'value', 'seedSum']);
if (value.contract !== EMA_CONTRACT) {
throw new Error('Unsupported EMA snapshot contract');
}
const state: EmaSnapshot = {
contract: EMA_CONTRACT,
period: period(value.period),
seed: seed(value.seed),
count: count(value.count),
value: optionalNumber(value.value),
seedSum: finite(value.seedSum),
};
const ready = state.count >= (state.seed === 'first' ? 1 : state.period);
if (
(state.value !== null) !== ready ||
((ready || state.count === 0 || state.seed === 'first') && state.seedSum !== 0)
) {
throw new Error('Inconsistent EMA snapshot phase');
}
return state;
}
/** O(1) memory. Rejected inputs/restores leave all prior state intact. */
export class EmaIndicator {
private state: EmaSnapshot;
constructor(size: number, options: EmaOptions = {}) {
configuration(options, ['seed']);
this.state = {
contract: EMA_CONTRACT,
period: period(size),
seed: seed(options.seed === undefined ? 'sma' : options.seed),
count: 0,
value: null,
seedSum: 0,
};
}
update(input: number): number | null {
const value = finite(input);
const next = { ...this.state, count: count(this.state.count + 1) };
if (next.value !== null) {
const alpha = 2 / (next.period + 1);
next.value = finite(alpha * value + (1 - alpha) * next.value);
} else if (next.seed === 'first') {
next.value = value;
} else {
next.seedSum = finite(next.seedSum + value);
if (next.count === next.period) {
next.value = finite(next.seedSum / next.period);
next.seedSum = 0;
}
}
this.state = next;
return next.value;
}
current(): number | null {
return this.state.value;
}
snapshot(): EmaSnapshot {
return { ...this.state };
}
reset(): void {
this.state = { ...this.state, count: 0, value: null, seedSum: 0 };
}
restore(input: unknown): void {
const next = parse(input);
if (next.period !== this.state.period || next.seed !== this.state.seed) {
throw new Error('EMA snapshot configuration mismatch');
}
this.state = next;
}
static fromSnapshot(input: unknown): EmaIndicator {
const state = parse(input);
const stream = new EmaIndicator(state.period, { seed: state.seed });
stream.restore(state);
return stream;
}
}
export function ema(
values: readonly number[],
size: number,
options: EmaOptions = {}
): IndicatorSeries {
const stream = new EmaIndicator(size, options);
return collect(values, stream, EMA_CONTRACT, stream.snapshot().seed === 'first' ? 0 : size - 1);
}

View file

@ -4,3 +4,11 @@ export {
trailingPopulationDeviation,
} from './window-statistics';
export { sma } from './sma';
export { ema, EmaIndicator, EMA_CONTRACT } from './ema';
export type { EmaOptions, EmaSeed, EmaSnapshot } from './ema';
export { rsi, RsiIndicator, RSI_CONTRACT, trailingSimpleRsi } from './rsi';
export type { FlatRsi, RsiOptions, RsiSnapshot } from './rsi';
export { atr, AtrIndicator, ATR_CONTRACT } from './atr';
export type { AtrFirstRange, AtrOptions, AtrSnapshot } from './atr';
export type { HlcBar, IndicatorSeries } from './contracts';
export { bollingerBands, macd, stochastic } from './compositions';

View file

@ -0,0 +1,175 @@
import { at } from '@stock-bot/invariants';
import {
collect,
configuration,
count,
finite,
nonnegative,
optionalNumber,
period,
snapshot,
type IndicatorSeries,
} from './contracts';
export const RSI_CONTRACT = 'rsi-wilder/v1';
export type FlatRsi = 0 | 50 | 100;
export interface RsiOptions {
flatValue?: FlatRsi;
}
export interface RsiSnapshot {
contract: typeof RSI_CONTRACT;
period: number;
flatValue: FlatRsi;
count: number;
previous: number | null;
gain: number;
loss: number;
}
function flat(value: unknown): FlatRsi {
if (value !== 0 && value !== 50 && value !== 100) {
throw new Error('Flat RSI value must be 0, 50 or 100');
}
return value;
}
function oscillator(gain: number, loss: number, flatValue: FlatRsi): number {
if (gain === 0 && loss === 0) {
return flatValue;
}
if (loss === 0) {
return 100;
}
return finite(100 - 100 / (1 + gain / loss));
}
function parse(input: unknown): RsiSnapshot {
const value = snapshot(input, [
'contract',
'period',
'flatValue',
'count',
'previous',
'gain',
'loss',
]);
if (value.contract !== RSI_CONTRACT) {
throw new Error('Unsupported RSI snapshot contract');
}
const state: RsiSnapshot = {
contract: RSI_CONTRACT,
period: period(value.period),
flatValue: flat(value.flatValue),
count: count(value.count),
previous: optionalNumber(value.previous),
gain: nonnegative(value.gain),
loss: nonnegative(value.loss),
};
if (
(state.previous !== null) !== state.count > 0 ||
(state.count <= 1 && (state.gain !== 0 || state.loss !== 0))
) {
throw new Error('Inconsistent RSI snapshot phase');
}
return state;
}
/** SMA of the first n changes, then Wilder smoothing; the seed change is consumed once. */
export class RsiIndicator {
private state: RsiSnapshot;
constructor(size = 14, options: RsiOptions = {}) {
configuration(options, ['flatValue']);
this.state = {
contract: RSI_CONTRACT,
period: period(size),
flatValue: flat(options.flatValue === undefined ? 50 : options.flatValue),
count: 0,
previous: null,
gain: 0,
loss: 0,
};
}
update(input: number): number | null {
const value = finite(input);
const prior = this.state;
const next = { ...prior, count: count(prior.count + 1), previous: value };
if (prior.previous !== null) {
const change = finite(value - prior.previous);
const gain = Math.max(0, change),
loss = Math.max(0, -change);
if (prior.count <= prior.period) {
next.gain = nonnegative(prior.gain + gain);
next.loss = nonnegative(prior.loss + loss);
if (prior.count === prior.period) {
next.gain /= prior.period;
next.loss /= prior.period;
}
} else {
next.gain = nonnegative((prior.gain * (prior.period - 1) + gain) / prior.period);
next.loss = nonnegative((prior.loss * (prior.period - 1) + loss) / prior.period);
}
}
const result =
next.count > next.period ? oscillator(next.gain, next.loss, next.flatValue) : null;
this.state = next;
return result;
}
current(): number | null {
return this.state.count > this.state.period
? oscillator(this.state.gain, this.state.loss, this.state.flatValue)
: null;
}
snapshot(): RsiSnapshot {
return { ...this.state };
}
reset(): void {
this.state = { ...this.state, count: 0, previous: null, gain: 0, loss: 0 };
}
restore(input: unknown): void {
const next = parse(input);
if (next.period !== this.state.period || next.flatValue !== this.state.flatValue) {
throw new Error('RSI snapshot configuration mismatch');
}
this.state = next;
}
static fromSnapshot(input: unknown): RsiIndicator {
const state = parse(input);
const stream = new RsiIndicator(state.period, { flatValue: state.flatValue });
stream.restore(state);
return stream;
}
}
export function rsi(
values: readonly number[],
size = 14,
options: RsiOptions = {}
): IndicatorSeries {
return collect(values, new RsiIndicator(size, options), RSI_CONTRACT, size);
}
/** Rolling simple-average RSI, NOT Wilder RSI. Reverse summation preserves mean-reversion/v2 arithmetic. */
export function trailingSimpleRsi(
values: readonly number[],
size = 14,
flatValue: FlatRsi = 50
): number | undefined {
period(size);
flat(flatValue);
if (values.length < size + 1) {
return undefined;
}
let gain = 0,
loss = 0;
for (let i = 1; i <= size; i++) {
const change = finite(
finite(at(values, values.length - i)) - finite(at(values, values.length - i - 1))
);
if (change > 0) {
gain = finite(gain + change);
} else {
loss = finite(loss + Math.abs(change));
}
}
return oscillator(gain / size, loss / size, flatValue);
}