stock-bot/libs/calculations/test/core.test.ts

125 lines
5.4 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import { equityAnalysis, mean, returnStatistics } from '@stock-bot/calculations/analytics';
import {
movingAverageCrossover,
sma,
trailingMean,
trailingPopulationDeviation,
} from '@stock-bot/calculations/indicators';
import {
calculateReturns,
calculateTrueRange,
calculateVWAP,
convertTimestamps,
extractCloses,
filterByTimeRange,
groupBySymbol,
} from '@stock-bot/calculations/market-data';
import {
annualizeReturn,
annualizeVolatility,
cagr,
logReturn,
logReturns,
percentageChange,
simpleReturn,
simpleReturns,
} from '@stock-bot/calculations/returns';
const bar = { open: 10, high: 12, low: 8, close: 10, volume: 10, symbol: 'ABC.US', timestamp: 0 };
describe('reviewed shared calculation contracts', () => {
test('returns keep fractions distinct from percentage points and reject fabricated baselines', () => {
expect(simpleReturn(100, 110)).toBeCloseTo(0.1);
expect(percentageChange(100, 110)).toBeCloseTo(10);
expect(simpleReturn(100, -10)).toBeCloseTo(-1.1);
expect(logReturn(100, 110)).toBeCloseTo(Math.log(1.1));
expect(simpleReturns([100, 110, 99])).toEqual([simpleReturn(100, 110), simpleReturn(110, 99)]);
expect(logReturns([100, 110])).toEqual([logReturn(100, 110)]);
expect(simpleReturns([])).toEqual([]);
expect(logReturns([100])).toEqual([]);
for (const value of [0, -1, NaN, Infinity]) {
expect(() => simpleReturn(value, 10)).toThrow();
expect(() => logReturn(10, value)).toThrow();
}
expect(() => simpleReturns([100, 0, 110])).toThrow('baseline');
expect(() => calculateReturns([{ close: 100 }, { close: 0 }, { close: 110 }])).toThrow();
expect(() => simpleReturns(Array(2))).toThrow('finite');
expect(Number.isFinite(logReturn(Number.MIN_VALUE, Number.MAX_VALUE))).toBe(true);
});
test('annualization has explicit undefined CAGR and validates sampling units', () => {
expect(cagr(100, 121, 2)).toBeCloseTo(0.1);
expect(cagr(100, 110, 0)).toBeNull();
expect(cagr(100, 0, 1)).toBe(-1);
expect(cagr(100, -10, 1)).toBeNull();
expect(cagr(1, 2, Number.MIN_VALUE)).toBeNull();
expect(() => cagr(0, 10, 1)).toThrow();
expect(() => cagr(100, 110, -1)).toThrow();
expect(() => cagr(100, NaN, 1)).toThrow();
expect(annualizeReturn(0.01, 12)).toBeCloseTo(1.01 ** 12 - 1);
expect(annualizeReturn(-1, 252)).toBe(-1);
expect(annualizeVolatility(0.1, 4)).toBeCloseTo(0.2);
for (const periods of [0, -1, NaN, Infinity]) {
expect(() => annualizeReturn(0.01, periods)).toThrow();
expect(() => annualizeVolatility(0.1, periods)).toThrow();
}
expect(() => annualizeReturn(-1.1, 12)).toThrow();
expect(() => annualizeVolatility(-0.1, 12)).toThrow();
const curve = equityAnalysis(
[
{ timestamp: 0, value: 100 },
{ timestamp: 365 * 86400000, value: 110 },
],
100
);
expect(curve.annualizedReturn).toBeCloseTo(cagr(100, 110, 1)!);
});
test('trailing features have explicit offsets and never read future bars', () => {
const prices = [3, 2, 1, 4, 6, 5, 7, 8];
expect(sma(prices, 3)).toEqual([2, 7 / 3, 11 / 3, 5, 6, 20 / 3]);
expect(sma([1, 2], 3)).toEqual([]);
expect(trailingMean([1, 2], 3)).toBeUndefined();
expect(trailingPopulationDeviation([1, 2, 3], 3)).toBeCloseTo(Math.sqrt(2 / 3));
for (let end = 1; end <= prices.length; end++) {
const prefix = prices.slice(0, end);
expect(sma(prices, 3).slice(0, Math.max(0, end - 2))).toEqual(sma(prefix, 3));
expect<number | undefined>(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1));
}
expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)?.goldenCross).toBe(true);
expect(() => sma([1, 2], 0)).toThrow();
expect(() => sma([1, NaN], 2)).toThrow('finite');
expect(() => sma(Array(3), 2)).toThrow('finite');
expect(() => sma([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('finite');
expect(() => movingAverageCrossover(prices, 3, 2)).toThrow();
});
test('OHLCV features preserve alignment without inventing volume or prices', () => {
expect(calculateVWAP([{ ...bar, volume: 0 }, bar])).toEqual([null, 10]);
expect(calculateVWAP([bar, { ...bar, close: 12, volume: 30 }])[1]).toBeCloseTo(10.5);
expect(calculateTrueRange([bar, { ...bar, low: 11, high: 15, close: 12 }])).toEqual([4, 5]);
expect(() => calculateVWAP([{ ...bar, volume: -1 }])).toThrow();
expect(() => calculateVWAP([{ ...bar, high: 7 }])).toThrow();
expect(() => calculateTrueRange([{ ...bar, close: 20 }])).toThrow();
expect(() => extractCloses([{ close: Infinity }])).toThrow();
expect(() => convertTimestamps([{ ...bar, timestamp: Infinity }])).toThrow();
expect(() => convertTimestamps([{ ...bar, timestamp: 1e30 }])).toThrow();
expect(filterByTimeRange([bar], 0, 0)).toEqual([bar]);
expect(() => filterByTimeRange([bar], 1, 0)).toThrow();
const grouped = groupBySymbol([
{ ...bar, symbol: '__proto__' },
{ ...bar, symbol: 'constructor' },
]);
expect(grouped['__proto__']).toHaveLength(1);
expect(grouped['constructor']).toHaveLength(1);
expect(Object.getPrototypeOf(grouped)).toBeNull();
});
test('analytics remains reusable without an application/native runtime', () => {
expect(mean([1, 2, 3])).toBe(2);
expect(mean([])).toBeNull();
expect(returnStatistics([0, 0]).sharpeRatio).toBeNull();
expect(() => returnStatistics([NaN])).toThrow('finite');
});
});