155 lines
7.5 KiB
TypeScript
155 lines
7.5 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
dayMs,
|
|
equityAnalysis,
|
|
factorStatistics,
|
|
performanceAnalysis,
|
|
returnStatistics,
|
|
tradeStatistics,
|
|
} from '@stock-bot/calculations/analytics';
|
|
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
|
|
import golden from '../fixtures/analytics-golden.json';
|
|
|
|
const start = Date.parse('2024-01-01T00:00:00Z');
|
|
const points = (values: number[]) =>
|
|
values.map((value, i) => ({ timestamp: start + i * dayMs, value }));
|
|
|
|
describe('pure, fraction-based analytics golden fixtures', () => {
|
|
test('drawdown depths belong to each period, equal peaks recover, and ongoing periods use observed time', () => {
|
|
const result = equityAnalysis(points(golden.drawdowns.equity), 100);
|
|
result.periods.forEach((period, i) => {
|
|
expect(period.depth).toBeCloseTo(golden.drawdowns.depths[i]!);
|
|
expect(period.duration).toBe(golden.drawdowns.durations[i]!);
|
|
});
|
|
expect(result.maxDrawdown).toBeCloseTo(0.2);
|
|
expect(result.currentDrawdown).toBe(0);
|
|
const recovered = equityAnalysis(points([100, 90, 100, 80]), 100);
|
|
expect(recovered.periods[0]?.recovery).toBe(2);
|
|
expect(recovered.periods[1]?.recovery).toBeNull();
|
|
expect(recovered.periods[1]?.depth).toBeCloseTo(0.2);
|
|
expect(recovered.maxDrawdownDuration).toBe(1);
|
|
const facade = new PerformanceAnalyzer(100);
|
|
points(golden.drawdowns.equity).forEach(point =>
|
|
facade.addEquityPoint(new Date(point.timestamp), point.value)
|
|
);
|
|
expect(facade.analyzeDrawdowns().drawdownPeriods.map(period => period.depth)).toEqual(
|
|
result.periods.map(period => period.depth)
|
|
);
|
|
});
|
|
test('CAGR requires positive capital, positive ending equity and positive elapsed time', () => {
|
|
expect(equityAnalysis([], 100).annualizedReturn).toBeNull();
|
|
const growth = equityAnalysis(
|
|
[
|
|
{ timestamp: start, value: 100 },
|
|
{ timestamp: start + 730 * dayMs, value: 121 },
|
|
],
|
|
100
|
|
);
|
|
expect(growth.totalReturn).toBeCloseTo(0.21);
|
|
expect(growth.annualizedReturn).toBeCloseTo(0.1);
|
|
for (const end of [0, -10])
|
|
expect(equityAnalysis(points([100, end]), 100).annualizedReturn).toBeNull();
|
|
expect(() => equityAnalysis(points([100]), 0)).toThrow();
|
|
expect(() => equityAnalysis(points([100, NaN]), 100)).toThrow('finite');
|
|
expect(() => equityAnalysis(points([100, 110]).reverse(), 100)).toThrow('ordered');
|
|
const sameTime = new PerformanceAnalyzer(100);
|
|
sameTime.addEquityPoint(new Date(start), 100);
|
|
sameTime.addEquityPoint(new Date(start), 101);
|
|
expect(sameTime.analyze().cagr).toBeNull();
|
|
expect(sameTime.analyze().annualizedReturn).toBeNull();
|
|
expect(sameTime.exportReport()).toContain('CAGR: N/A');
|
|
expect(sameTime.exportReport()).not.toMatch(/Infinity|NaN/);
|
|
});
|
|
test('UTC grouping keeps first-period returns and never associates a skipped denominator with another month', () => {
|
|
const result = equityAnalysis(
|
|
[
|
|
{ timestamp: Date.parse('2024-01-31T23:30:00Z'), value: 110 },
|
|
{ timestamp: Date.parse('2024-02-01T00:30:00Z'), value: 0 },
|
|
{ timestamp: Date.parse('2024-03-01T00:30:00Z'), value: 50 },
|
|
{ timestamp: Date.parse('2024-04-01T00:30:00Z'), value: 75 },
|
|
],
|
|
100
|
|
);
|
|
expect(result.dailyReturns[0]).toBeCloseTo(0.1);
|
|
expect(result.monthlyReturns['2024-01']).toBeCloseTo(0.1);
|
|
expect(result.monthlyReturns['2024-02']).toBe(-1);
|
|
expect(result.monthlyReturns['2024-03']).toBeUndefined();
|
|
expect(result.monthlyReturns['2024-04']).toBe(0.5);
|
|
});
|
|
test('sample volatility and full-series downside RMS use daily fractions, not percentage points', () => {
|
|
const result = returnStatistics(golden.daily.returns, 0);
|
|
expect(result.volatility! ** 2).toBeCloseTo(golden.daily.annualVariance, 10);
|
|
expect(result.downsideDeviation! ** 2).toBeCloseTo(golden.daily.annualDownsideVariance, 10);
|
|
expect(result.sharpeRatio).toBeCloseTo(
|
|
golden.daily.annualExcess / Math.sqrt(golden.daily.annualVariance)
|
|
);
|
|
expect(result.sortinoRatio).toBeCloseTo(
|
|
golden.daily.annualExcess / Math.sqrt(golden.daily.annualDownsideVariance)
|
|
);
|
|
expect(returnStatistics([], 0).volatility).toBeNull();
|
|
expect(returnStatistics([0.1], 0).sharpeRatio).toBeNull();
|
|
expect(returnStatistics([0, 0, 0], 0).sharpeRatio).toBeNull();
|
|
expect(returnStatistics([0, 0, 0], 0).volatility).toBe(0);
|
|
expect(returnStatistics([0.1, 0.2], 0).sortinoRatio).toBeNull();
|
|
expect(() => returnStatistics([Infinity])).toThrow('finite');
|
|
expect(() => returnStatistics(Array<number>(3))).toThrow('finite');
|
|
});
|
|
test('historical loss tails require enough samples and have one shared positive-loss sign convention', () => {
|
|
expect(returnStatistics(Array(19).fill(-0.01)).var95).toBeNull();
|
|
const risk = returnStatistics(Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05));
|
|
expect(risk.var95).toBeCloseTo(0.046);
|
|
expect(risk.cvar95).toBeCloseTo(0.048);
|
|
expect(risk.var99).toBeCloseTo(0.05);
|
|
expect(returnStatistics(Array(100).fill(0.01)).var95).toBe(0);
|
|
});
|
|
test('trade statistics count completed trades, break streaks on breakeven and preserve undefined ratios', () => {
|
|
const result = tradeStatistics(
|
|
golden.trades.pnl.map(pnl => ({ pnl, holdingPeriod: 60 })),
|
|
365
|
|
);
|
|
const { pnl: _pnl, ...expected } = golden.trades;
|
|
expect(result).toMatchObject(expected);
|
|
expect(result.avgWin).toBe(15);
|
|
expect(result.avgLoss).toBe(2.5);
|
|
expect(result.avgHoldingPeriod).toBe(60);
|
|
expect(result.avgTradesPerDay).toBeCloseTo(8 / 252);
|
|
expect(tradeStatistics([], 0).profitFactor).toBeNull();
|
|
expect(tradeStatistics([{ pnl: 10, holdingPeriod: 0 }], 1).profitFactor).toBeNull();
|
|
expect(tradeStatistics([{ pnl: -10, holdingPeriod: 0 }], 1).profitFactor).toBe(0);
|
|
expect(() => tradeStatistics([{ pnl: NaN, holdingPeriod: 0 }], 1)).toThrow();
|
|
});
|
|
test('benchmark math validates alignment and uses the same fraction-based excess-return convention', () => {
|
|
const benchmark = [-0.01, 0.02, -0.02, 0.03];
|
|
const result = factorStatistics(
|
|
benchmark.map(value => 2 * value),
|
|
benchmark,
|
|
0
|
|
);
|
|
expect(result.beta).toBeCloseTo(2);
|
|
expect(result.alpha).toBeCloseTo(0);
|
|
expect(result.correlation).toBeCloseTo(1);
|
|
expect(factorStatistics([0, 0], [0, 0]).beta).toBeNull();
|
|
expect(() => factorStatistics([0], [0, 0])).toThrow('same length');
|
|
expect(() => factorStatistics([0, NaN], [0, 0])).toThrow('finite');
|
|
});
|
|
test('facade input/output detachment, cache invalidation and legacy report percentages are explicit', () => {
|
|
const analyzer = new PerformanceAnalyzer(100);
|
|
const date = new Date(start);
|
|
analyzer.addEquityPoint(date, 100);
|
|
date.setUTCFullYear(2030);
|
|
analyzer.addEquityPoint(new Date(start + 365 * dayMs), 110);
|
|
expect(analyzer.analyze().totalReturn).toBeCloseTo(10);
|
|
expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1);
|
|
const view = analyzer.getAnalysis();
|
|
view.metrics.totalReturn = 999;
|
|
expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1);
|
|
analyzer.addEquityPoint(new Date(start + 366 * dayMs), 120);
|
|
expect(analyzer.analyze().totalReturn).toBeCloseTo(20);
|
|
const bankrupt = performanceAnalysis(points([100, 0, -10]), [], 100);
|
|
expect(bankrupt.metrics.totalReturn).toBeCloseTo(-1.1);
|
|
expect(bankrupt.metrics.cagr).toBeNull();
|
|
expect(
|
|
Object.values(bankrupt.metrics).every(value => value === null || Number.isFinite(value))
|
|
).toBe(true);
|
|
});
|
|
});
|