Unify analytics calculations and fail closed on unavailable data
This commit is contained in:
parent
783b619846
commit
ccce401f72
31 changed files with 1978 additions and 1553 deletions
16
test/fixtures/analytics-golden.json
vendored
Normal file
16
test/fixtures/analytics-golden.json
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"drawdowns": { "equity": [100, 80, 110, 99, 120], "depths": [0.2, 0.1], "durations": [1, 1] },
|
||||
"daily": {
|
||||
"returns": [-0.01, 0.02, -0.03, 0.04],
|
||||
"annualVariance": 0.2436,
|
||||
"annualDownsideVariance": 0.063,
|
||||
"annualExcess": 1.26
|
||||
},
|
||||
"trades": {
|
||||
"pnl": [10, -4, 0, 20, -2, -3, 0, -1],
|
||||
"profitFactor": 3,
|
||||
"winRate": 0.25,
|
||||
"expectancy": 2.5,
|
||||
"maxConsecutiveLosses": 2
|
||||
}
|
||||
}
|
||||
154
test/integration/analytics-math.test.ts
Normal file
154
test/integration/analytics-math.test.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { dayMs, equityAnalysis } from '../../apps/stock/orchestrator/src/analytics/equity';
|
||||
import { performanceAnalysis } from '../../apps/stock/orchestrator/src/analytics/performance';
|
||||
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
|
||||
import {
|
||||
factorStatistics,
|
||||
returnStatistics,
|
||||
} from '../../apps/stock/orchestrator/src/analytics/return-statistics';
|
||||
import { tradeStatistics } from '../../apps/stock/orchestrator/src/analytics/trade-statistics';
|
||||
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);
|
||||
});
|
||||
});
|
||||
295
test/integration/analytics-service.test.ts
Normal file
295
test/integration/analytics-service.test.ts
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
import type { AxiosRequestConfig } from 'axios';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { createAnalyticsRoutes } from '../../apps/stock/orchestrator/src/api/rest/analytics';
|
||||
import { AnalyticsServiceError } from '../../apps/stock/orchestrator/src/services/analytics-error';
|
||||
import { AnalyticsService } from '../../apps/stock/orchestrator/src/services/AnalyticsService';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const performance = {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
totalTrades: 0,
|
||||
};
|
||||
const risk = { currentExposure: 0, dailyPnl: 0, positionCount: 0, grossExposure: 0, var95: null };
|
||||
const optimize = {
|
||||
symbols: ['A.US', 'B.US'],
|
||||
returns: [
|
||||
[0.01, -0.01],
|
||||
[-0.01, 0.02],
|
||||
],
|
||||
constraints: { minWeight: 0.1, maxWeight: 0.9 },
|
||||
};
|
||||
function fixture(initial: unknown = performance) {
|
||||
let data = initial;
|
||||
let failure = false;
|
||||
let now = 0;
|
||||
const requests: AxiosRequestConfig[] = [];
|
||||
const service = new AnalyticsService(
|
||||
{ logger },
|
||||
{
|
||||
baseUrl: 'http://analytics.fixture',
|
||||
now: () => now,
|
||||
client: {
|
||||
async request(request) {
|
||||
requests.push(structuredClone(request));
|
||||
if (failure) throw new Error('Private upstream diagnostic must never reach the client');
|
||||
return { data };
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
return {
|
||||
service,
|
||||
requests,
|
||||
routes: createAnalyticsRoutes({ logger, custom: { AnalyticsService: service } }),
|
||||
setData(value: unknown) {
|
||||
data = value;
|
||||
},
|
||||
fail(value = true) {
|
||||
failure = value;
|
||||
},
|
||||
advance(ms: number) {
|
||||
now += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
const post = (body: unknown) => ({
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const from = new Date('2024-01-01T00:00:00Z');
|
||||
const to = new Date('2024-02-01T00:00:00Z');
|
||||
|
||||
describe('analytics upstream contract and HTTP failure semantics', () => {
|
||||
test('outages never become zero metrics, equal weights, normal regimes, identity matrices or false model misses', async () => {
|
||||
const f = fixture();
|
||||
f.fail();
|
||||
for (const [path, options] of [
|
||||
[
|
||||
'/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString(),
|
||||
undefined,
|
||||
],
|
||||
['/risk/P', undefined],
|
||||
['/regime', undefined],
|
||||
['/optimize', post(optimize)],
|
||||
['/correlation', post({ symbols: ['A.US', 'B.US'] })],
|
||||
['/predict', post({ modelId: 'model', features: { x: 1 } })],
|
||||
] as const) {
|
||||
const response = await f.routes.request(path, options);
|
||||
expect(response.status).toBe(503);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Analytics service is unavailable',
|
||||
code: 'analytics_unavailable',
|
||||
});
|
||||
}
|
||||
await expect(f.service.runBacktestAnalysis('run')).rejects.toBeInstanceOf(
|
||||
AnalyticsServiceError
|
||||
);
|
||||
expect(
|
||||
f.requests.every(request => request.timeout === 5000 && request.maxContentLength === 1048576)
|
||||
).toBe(true);
|
||||
const missing = await createAnalyticsRoutes({ logger }).request('/risk/P');
|
||||
expect(missing.status).toBe(503);
|
||||
});
|
||||
test('invalid upstream values are 502, not client 400, and never enter the success cache', async () => {
|
||||
const f = fixture({ ...performance, totalReturn: '0' });
|
||||
const path =
|
||||
'/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString();
|
||||
const response = await f.routes.request(path);
|
||||
expect(response.status).toBe(502);
|
||||
expect((await response.json()).code).toBe('analytics_invalid_response');
|
||||
f.setData(performance);
|
||||
expect(await f.service.getPerformanceMetrics('P', from, to)).toEqual(performance);
|
||||
expect(f.requests).toHaveLength(2);
|
||||
const view = await f.service.getPerformanceMetrics('P', from, to);
|
||||
view.totalReturn = 100;
|
||||
expect((await f.service.getPerformanceMetrics('P', from, to)).totalReturn).toBe(0);
|
||||
f.setData({ ...performance, totalReturn: Infinity });
|
||||
f.advance(60000);
|
||||
await expect(f.service.getPerformanceMetrics('P', from, to)).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
test('cache expiration honors each entry TTL and expired failures never masquerade as fresh observations', async () => {
|
||||
const f = fixture({ regime: 'observed-bull' });
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bull');
|
||||
f.setData({ regime: 'observed-bear' });
|
||||
f.advance(60001);
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bull');
|
||||
expect(f.requests).toHaveLength(1);
|
||||
f.advance(240000);
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bear');
|
||||
f.setData(risk);
|
||||
expect(await f.service.getRiskMetrics('P')).toEqual(risk);
|
||||
f.advance(60000);
|
||||
f.fail();
|
||||
await expect(f.service.getRiskMetrics('P')).rejects.toMatchObject({ status: 503 });
|
||||
f.fail(false);
|
||||
f.setData({ ...risk, dailyPnl: -10 });
|
||||
expect((await f.service.getRiskMetrics('P')).dailyPnl).toBe(-10);
|
||||
});
|
||||
test('success cache is bounded and identifiers are encoded rather than interpreted as paths', async () => {
|
||||
const f = fixture(risk);
|
||||
for (let i = 0; i < 129; i++) await f.service.getRiskMetrics(String(i));
|
||||
await f.service.getRiskMetrics('0');
|
||||
expect(f.requests).toHaveLength(130);
|
||||
await f.service.getRiskMetrics('A/B?secret');
|
||||
expect(f.requests.at(-1)?.url).toBe('http://analytics.fixture/analytics/risk/A%2FB%3Fsecret');
|
||||
});
|
||||
test('optimization forwards real symbol identities and maps the Python wire contract without fabricating weights', async () => {
|
||||
const f = fixture({
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: null,
|
||||
});
|
||||
const result = await f.service.optimizePortfolio(optimize);
|
||||
expect(result).toEqual({
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expectedReturn: 0.1,
|
||||
expectedRisk: 0.2,
|
||||
sharpeRatio: null,
|
||||
});
|
||||
expect(f.requests[0]?.data).toMatchObject({
|
||||
symbols: optimize.symbols,
|
||||
returns: optimize.returns,
|
||||
constraints: { min_weight: 0.1, max_weight: 0.9 },
|
||||
});
|
||||
for (const data of [
|
||||
{
|
||||
symbols: ['B.US', 'A.US'],
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
{
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.4],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
{
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: NaN,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
]) {
|
||||
f.setData(data);
|
||||
await expect(f.service.optimizePortfolio(optimize)).rejects.toMatchObject({ status: 502 });
|
||||
}
|
||||
});
|
||||
test('correlations validate dimensions, ordered identities, symmetry, range and positive semidefiniteness', async () => {
|
||||
const f = fixture({
|
||||
symbols: ['A.US', 'B.US'],
|
||||
matrix: [
|
||||
[1, 0.5],
|
||||
[0.5, 1],
|
||||
],
|
||||
});
|
||||
expect(await f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).toEqual([
|
||||
[1, 0.5],
|
||||
[0.5, 1],
|
||||
]);
|
||||
expect(f.requests[0]?.data).toEqual(['A.US', 'B.US']);
|
||||
for (const matrix of [
|
||||
[[1]],
|
||||
[
|
||||
[1, 2],
|
||||
[2, 1],
|
||||
],
|
||||
[
|
||||
[1, 0.5],
|
||||
[0.2, 1],
|
||||
],
|
||||
[
|
||||
[0.9, 0],
|
||||
[0, 1],
|
||||
],
|
||||
[
|
||||
[1, NaN],
|
||||
[NaN, 1],
|
||||
],
|
||||
]) {
|
||||
f.setData({ symbols: ['A.US', 'B.US'], matrix });
|
||||
await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
}
|
||||
f.setData({
|
||||
symbols: ['A.US', 'B.US', 'C.US'],
|
||||
matrix: [
|
||||
[1, 0.9, 0.9],
|
||||
[0.9, 1, -0.9],
|
||||
[0.9, -0.9, 1],
|
||||
],
|
||||
});
|
||||
await expect(
|
||||
f.service.calculateCorrelationMatrix(['A.US', 'B.US', 'C.US'])
|
||||
).rejects.toMatchObject({ status: 502 });
|
||||
f.setData({
|
||||
symbols: ['B.US', 'A.US'],
|
||||
matrix: [
|
||||
[1, 0],
|
||||
[0, 1],
|
||||
],
|
||||
});
|
||||
await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
test('model and backtest responses validate identity, finite JSON and wire field names', async () => {
|
||||
const f = fixture({
|
||||
model_id: 'model',
|
||||
prediction: 0,
|
||||
probability: null,
|
||||
metadata: { version: 'v1' },
|
||||
});
|
||||
expect((await f.service.predictWithModel('model', { x: 1 })).prediction).toBe(0);
|
||||
expect(f.requests[0]?.data).toEqual({ model_id: 'model', features: { x: 1 } });
|
||||
f.setData({ model_id: 'wrong-model', prediction: 1 });
|
||||
await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
f.setData({ model_id: 'model', prediction: 1, metadata: { nested: { value: Infinity } } });
|
||||
await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
f.setData({
|
||||
backtest_id: 'other',
|
||||
metrics: {},
|
||||
statistics: {},
|
||||
risk_analysis: {},
|
||||
trade_analysis: {},
|
||||
});
|
||||
await expect(f.service.runBacktestAnalysis('run')).rejects.toMatchObject({ status: 502 });
|
||||
});
|
||||
test('invalid client requests return 400 before upstream access', async () => {
|
||||
const f = fixture();
|
||||
for (const [path, options] of [
|
||||
[
|
||||
'/performance/P?start_date=' + to.toISOString() + '&end_date=' + from.toISOString(),
|
||||
undefined,
|
||||
],
|
||||
['/optimize', post({ ...optimize, returns: [[1], [2]] })],
|
||||
['/optimize', post({ ...optimize, constraints: { minWeight: 0.8 } })],
|
||||
['/correlation', post({ symbols: ['A.US', 'A.US'] })],
|
||||
['/predict', post({ modelId: '', features: { x: 1 } })],
|
||||
['/predict', { method: 'POST', body: '{broken' }],
|
||||
] as const)
|
||||
expect((await f.routes.request(path, options)).status).toBe(400);
|
||||
expect(f.requests).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
90
test/integration/analytics-ui.test.tsx
Normal file
90
test/integration/analytics-ui.test.tsx
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { BacktestMetrics } from '../../apps/stock/web-app/src/features/backtest/components/BacktestMetrics';
|
||||
import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics';
|
||||
|
||||
const metrics = {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitableTrades: 0,
|
||||
profitFactor: null,
|
||||
calmarRatio: null,
|
||||
sortinoRatio: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
};
|
||||
const text = (html: string) => html.replace(/<[^>]*>/g, '');
|
||||
test('detailed metrics distinguish undefined ratios from legitimate zero return and exposure', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(BacktestMetrics, {
|
||||
isLoading: false,
|
||||
result: {
|
||||
id: 'fixture',
|
||||
config: {
|
||||
name: 'fixture',
|
||||
startDate: new Date('2024-01-01'),
|
||||
endDate: new Date('2024-02-01'),
|
||||
initialCapital: 1000,
|
||||
symbols: ['A.US'],
|
||||
strategy: 'sma',
|
||||
speedMultiplier: 0,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
},
|
||||
metrics,
|
||||
positions: [],
|
||||
trades: [],
|
||||
performanceData: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
},
|
||||
})
|
||||
);
|
||||
const rendered = text(html);
|
||||
expect(rendered).toContain('Sharpe RatioN/A');
|
||||
expect(rendered).toContain('Profit FactorN/A');
|
||||
expect(rendered).toContain('Calmar RatioN/A');
|
||||
expect(rendered).toContain('Sortino RatioN/A');
|
||||
expect(rendered).toContain('Total Return0.00%');
|
||||
expect(rendered).toContain('Exposure Time0.0%');
|
||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
test('compact metrics preserve null ratios and render a genuine zero profit', () => {
|
||||
const result: BacktestRunResult = {
|
||||
runId: 'fixture',
|
||||
backtestId: 'fixture',
|
||||
engine: 'typescript',
|
||||
status: 'completed',
|
||||
completedAt: '2024-02-01T00:00:00Z',
|
||||
config: {
|
||||
name: 'fixture',
|
||||
strategy: 'sma',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01T00:00:00Z',
|
||||
endDate: '2024-02-01T00:00:00Z',
|
||||
initialCapital: 1000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
parameters: {},
|
||||
},
|
||||
metrics,
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
positions: [],
|
||||
trades: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
executionTime: 0,
|
||||
};
|
||||
const rendered = text(
|
||||
renderToStaticMarkup(createElement(CompactPerformanceMetrics, { result, isLoading: false }))
|
||||
);
|
||||
expect(rendered).toContain('Sharpe Ratio-');
|
||||
expect(rendered).toContain('Profit Factor-');
|
||||
expect(rendered).toContain('$0.00');
|
||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
|
|
@ -311,7 +311,11 @@ describe('detached, repeatable backtest reporting', () => {
|
|||
expect(result.metrics.totalReturn).toBeCloseTo(-110);
|
||||
expect(result.metrics.maxDrawdown).toBe(1.1);
|
||||
expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110);
|
||||
expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true);
|
||||
expect(
|
||||
Object.values(result.analytics.riskMetrics).every(
|
||||
value => value === null || Number.isFinite(value)
|
||||
)
|
||||
).toBe(true);
|
||||
expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -323,8 +327,15 @@ describe('detached, repeatable backtest reporting', () => {
|
|||
expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]);
|
||||
expect(result.metrics.totalReturn).toBeCloseTo(-0.2);
|
||||
expect(result.metrics.maxDrawdown).toBeCloseTo(0.002);
|
||||
expect(result.analytics.dailyReturns).toEqual([]);
|
||||
expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true);
|
||||
expect(result.analytics.dailyReturns).toHaveLength(1);
|
||||
expect(result.analytics.dailyReturns[0]).toBeCloseTo(-0.2);
|
||||
expect(result.metrics.sharpeRatio).toBeNull();
|
||||
expect(result.metrics.annualizedReturn).toBeNull();
|
||||
expect(
|
||||
Object.values(result.analytics.riskMetrics).every(
|
||||
value => value === null || Number.isFinite(value)
|
||||
)
|
||||
).toBe(true);
|
||||
expect(Object.keys(result.ohlcData)).toEqual(config.symbols);
|
||||
expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([
|
||||
start,
|
||||
|
|
@ -364,6 +375,27 @@ describe('detached, repeatable backtest reporting', () => {
|
|||
expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 });
|
||||
});
|
||||
|
||||
test('risk analytics and summary share fraction-based math without 100x percentage scaling', () => {
|
||||
const report = new BacktestReport(config, 'risk');
|
||||
let value = config.initialCapital;
|
||||
for (let i = 1; i <= 30; i++) {
|
||||
value *= 1 + (i % 2 ? -0.01 : 0.02);
|
||||
report.record(start + i * day, value);
|
||||
}
|
||||
const result = report.complete(dataset, [], [], {});
|
||||
const returns = result.analytics.dailyReturns.map(value => value / 100);
|
||||
const average = returns.reduce((sum, value) => sum + value, 0) / returns.length;
|
||||
const expected =
|
||||
Math.sqrt(
|
||||
returns.reduce((sum, value) => sum + (value - average) ** 2, 0) / (returns.length - 1)
|
||||
) * Math.sqrt(252);
|
||||
expect(result.analytics.riskMetrics.volatility).toBeCloseTo(expected, 10);
|
||||
const summary = JSON.parse(report.export()).summary;
|
||||
expect(summary.volatility / 100).toBeCloseTo(expected, 10);
|
||||
expect(summary.var95 / 100).toBeCloseTo(result.analytics.riskMetrics.var95!, 10);
|
||||
expect(summary.cvar95 / 100).toBeCloseTo(result.analytics.riskMetrics.cvar95!, 10);
|
||||
});
|
||||
|
||||
test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => {
|
||||
const input = structuredClone(dataset);
|
||||
for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) {
|
||||
|
|
|
|||
|
|
@ -59,7 +59,8 @@ const config = BacktestConfigSchema.parse({
|
|||
|
||||
async function fixture(
|
||||
empty = false,
|
||||
engineOptions: ConstructorParameters<typeof RustBacktestAdapter>[1] = {}
|
||||
engineOptions: ConstructorParameters<typeof RustBacktestAdapter>[1] = {},
|
||||
barCount = 70
|
||||
) {
|
||||
// PostgreSQL protocol is replaced with an in-process database; SQL and transaction manager are real.
|
||||
const db = newDb();
|
||||
|
|
@ -108,7 +109,7 @@ async function fixture(
|
|||
await persistEodPrices(
|
||||
mongodb,
|
||||
{ symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' },
|
||||
Array.from({ length: 70 }, (_, index) => {
|
||||
Array.from({ length: barCount }, (_, index) => {
|
||||
const close = 100 + Math.sin((index * Math.PI) / 6) * 8 + index * 0.02;
|
||||
return {
|
||||
date: new Date(Date.parse(config.startDate) + index * 86400000)
|
||||
|
|
@ -307,6 +308,26 @@ describe('one backtest execution workflow', () => {
|
|||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('undefined one-timestamp statistics survive normalization, persistence and the public result reader as null', async () => {
|
||||
const f = await fixture(false, {}, 1);
|
||||
const services = await typescriptRuntime(f);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
await services.custom?.ModeManager?.shutdown();
|
||||
});
|
||||
const result = await runner.runBacktest(config);
|
||||
expect(result.metrics.sharpeRatio).toBeNull();
|
||||
expect(result.metrics.profitFactor).toBeNull();
|
||||
expect(result.metrics.cagr).toBeNull();
|
||||
expect(result.metrics.annualizedReturn).toBeNull();
|
||||
expect(result.analytics.riskMetrics?.volatility).toBeNull();
|
||||
const saved = await new BacktestServiceV2(services).getRunResults(result.runId);
|
||||
expect(saved?.metrics).toEqual(result.metrics);
|
||||
expect(saved?.analytics).toEqual(result.analytics);
|
||||
expect(JSON.stringify(saved)).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
|
||||
test('TypeScript cancellation is persisted without a partial success or completion event', async () => {
|
||||
const f = await fixture();
|
||||
const services = await typescriptRuntime(f);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue