stock-bot/libs/calculations/test/reporting-primitives.test.ts

45 lines
1.7 KiB
TypeScript

import { expect, test } from 'bun:test';
import { drawdownAnalysis, equityAnalysis } from '../src/analytics/equity';
import { cagr } from '../src/returns';
test('sampled drawdown handles safe-integer timestamps beyond JavaScript Date range', () => {
const points = [
{ timestamp: -Number.MAX_SAFE_INTEGER, value: 100 },
{ timestamp: 0, value: 80 },
{ timestamp: Number.MAX_SAFE_INTEGER, value: 90 },
];
expect(drawdownAnalysis(points, 100).maxDrawdown).toBeCloseTo(0.2);
expect(drawdownAnalysis(points, 100).currentDrawdown).toBeCloseTo(0.1);
expect(() => drawdownAnalysis([...points].reverse(), 100)).toThrow('ordered');
expect(() => drawdownAnalysis(points, 0)).toThrow('positive');
});
test('extracted drawdowns preserve the legacy equity analysis values and recovery periods', () => {
const points = [100, 110, 80, 90, 120, 100].map((value, i) => ({
timestamp: i * 86400000,
value,
}));
const sampled = drawdownAnalysis(points, 100);
const legacy = equityAnalysis(points, 100);
expect(legacy).toMatchObject(sampled);
expect(sampled.periods).toHaveLength(2);
expect(sampled.periods[0]?.recovery).toBe(4);
expect(sampled.periods[1]?.recovery).toBeNull();
});
test('CAGR zero terminal is total loss for positive elapsed time while negative terminal is unsupported', () => {
expect(cagr(100, 0, 0.5)).toBe(-1);
expect(cagr(100, 0, 0)).toBeNull();
expect(cagr(100, -1, 1)).toBeNull();
expect(cagr(100, 121, 2)).toBeCloseTo(0.1);
// Legacy UTC equity reporting retains its historical zero-terminal convention.
expect(
equityAnalysis(
[
{ timestamp: 0, value: 100 },
{ timestamp: 86400000, value: 0 },
],
100
).annualizedReturn
).toBeNull();
});