stock-bot/test/integration/indicator-contracts.test.ts

173 lines
6.5 KiB
TypeScript

import { expect, test } from 'bun:test';
import { atr, ema, macd, rsi, trailingSimpleRsi } from '@stock-bot/calculations/indicators';
import { IncrementalEMA, IncrementalRSI, TechnicalIndicators } from '@stock-bot/engine';
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
import {
calculateATR,
calculateBollingerBands,
calculateEMA,
calculateMACD,
calculateRSI,
calculateSMA,
calculateStochastic,
calculateVWAP,
CHART_INDICATOR_CONTRACT,
} from '../../apps/stock/web-app/src/features/charts/utils/indicators';
import golden from '../../libs/calculations/test/fixtures/indicators.json';
function close(actual: readonly number[], expected: readonly number[]) {
expect(actual).toHaveLength(expected.length);
actual.forEach((value, i) => expect(value).toBeCloseTo(expected[i]!, 10));
}
function candles(values: number[]) {
return values.map((value, i) => ({
time: 1700000000 + i * i * 60,
open: value,
high: value + 1,
low: value - 1,
close: value,
volume: 10,
}));
}
test('shared first-seeded EMA matches real native batch and incremental output', () => {
const native = new TechnicalIndicators();
const values = Array.from({ length: 80 }, (_, i) => 100 + Math.sin(i / 2) * 7);
for (const period of [1, 3, 14]) {
const batch = ema(values, period, { seed: 'first' });
close(batch.values, native.calculateEma(values, period));
const stream = new IncrementalEMA(period);
close(
values.map(value => stream.update(value)!),
batch.values
);
}
// The SMA seed is deliberately a separate contract parameter, not a native alias.
expect(ema(values, 3).startIndex).toBe(2);
expect(ema(values, 3, { seed: 'first' }).startIndex).toBe(0);
});
test('Wilder RSI matches compatible native paths; historical zero-loss differences stay explicit', () => {
const native = new TechnicalIndicators();
const { prices, period } = golden.rsi;
close(rsi(prices, period).values, native.calculateRsi(prices, period));
const stream = new IncrementalRSI(period);
const streaming = prices
.map(value => stream.update(value))
.filter(value => value !== null && value !== undefined);
close(streaming, rsi(prices, period).values);
const rising = [1, 2, 3, 4, 5];
expect(native.calculateRsi(rising, 3)[0]).toBeCloseTo(100 - 100 / 101, 12);
expect(rsi(rising, 3).values).toEqual([100, 100]);
expect(rsi([1, 1, 1, 1], 3).values).toEqual([50]);
});
test('previous-close ATR and first-seeded MACD match their real native variants', () => {
const native = new TechnicalIndicators();
const { bars, period } = golden.atr;
close(
atr(bars, period).values,
native.calculateAtr(
bars.map(bar => bar.high),
bars.map(bar => bar.low),
bars.map(bar => bar.close),
period
)
);
const prices = Array.from({ length: 40 }, (_, i) => 10 + Math.sin(i));
const expected = JSON.parse(native.calculateMacd(prices, 3, 7, 4));
const result = macd(prices, 3, 7, 4, { seed: 'first' });
close(result.macd.values, expected.macd);
close(result.signal.values, expected.signal);
close(result.histogram.values, expected.histogram);
});
test('mean-reversion/v2 keeps exact rolling-RSI arithmetic and checkpoint identity', () => {
function priorV2(values: number[], period: number): number {
if (values.length < period + 1) {
return 50;
}
let gain = 0,
loss = 0;
for (let i = 1; i <= period; i++) {
const change = values[values.length - i]! - values[values.length - i - 1]!;
if (change > 0) {
gain += change;
} else {
loss += Math.abs(change);
}
}
const averageGain = gain / period,
averageLoss = loss / period;
if (averageLoss === 0) {
return 100;
}
return 100 - 100 / (1 + averageGain / averageLoss);
}
const values = Array.from({ length: 80 }, (_, i) => 100 + Math.sin(i / 2) * 8 + i / 10);
for (const period of [1, 2, 3, 14]) {
for (let end = 0; end <= values.length; end++) {
const prefix = values.slice(0, end);
expect(trailingSimpleRsi(prefix, period, 100) ?? 50).toBe(priorV2(prefix, period));
}
}
expect(trailingSimpleRsi([1, 1, 1, 1], 3, 100)).toBe(100);
expect(MeanReversionStrategy.prototype.getCheckpointVersion()).toBe('mean-reversion/v2');
});
test('chart adapters map real source timestamps, warm-up and final rounding only', () => {
const data = candles(golden.ema.prices);
const original = structuredClone(data);
expect(CHART_INDICATOR_CONTRACT).toBe('chart-indicators/v2');
expect(calculateSMA(data, 3).map(point => point.time)).toEqual(
data.slice(2).map(bar => bar.time)
);
expect(calculateEMA(data, 3)).toEqual(
data.slice(2).map((bar, i) => ({ time: bar.time, value: golden.ema.smaSeed[i] }))
);
const rs = candles(golden.rsi.prices);
expect(calculateRSI(rs, 3)).toEqual(
rs
.slice(3)
.map((bar, i) => ({ time: bar.time, value: Number(golden.rsi.values[i]!.toFixed(2)) }))
);
const ranges = golden.atr.bars.map((bar, i) => ({
...bar,
open: bar.close,
time: 1000 + i * 900,
}));
expect(calculateATR(ranges, 3).map(point => point.time)).toEqual(
ranges.slice(3).map(bar => bar.time)
);
expect(calculateEMA(data.slice(0, 2), 3)).toEqual([]);
expect(calculateRSI(rs.slice(0, 3), 3)).toEqual([]);
expect(calculateATR(ranges.slice(0, 3), 3)).toEqual([]);
expect(data).toEqual(original);
});
test('corrected chart RSI has no duplicated seed delta, synthetic 99 RSI, or flat NaN', () => {
expect(calculateRSI(candles([1, 2, 3, 4]), 3)[0]?.value).toBe(100);
expect(calculateRSI(candles([1, 1, 1, 1]), 3)[0]?.value).toBe(50);
expect(calculateRSI(candles(golden.rsi.prices), 3)[0]?.value).toBe(75);
expect(
calculateStochastic(
Array(4).fill({ time: 1, open: 1, high: 1, low: 1, close: 1 }),
2,
1,
1
).k.every(point => point.value === 50)
).toBe(true);
});
test('chart compositions do not round intermediates, and missing volume produces no fake VWAP', () => {
const bands = calculateBollingerBands(candles([0.011, 0.019, 0.021]), 2, 2);
expect(bands.lower[0]?.value).toBe(0.01);
const result = calculateMACD(candles([1.01, 1.03, 1.02, 1.07, 1.03]), 2, 3, 2);
expect(result.signalLine[0]?.value).toBe(0);
const data = candles([10, 11, 12]);
data[0]!.volume = 0;
expect(calculateVWAP(data)[0]?.time).toBe(data[1]?.time);
expect(calculateVWAP(data.map(bar => ({ ...bar, volume: undefined })))).toEqual([]);
expect(() => calculateEMA(candles([1, 2]), 0)).toThrow();
expect(() => calculateRSI(candles([1, NaN, 3, 4]), 3)).toThrow();
});