stock-bot/test/integration/analytics-service.test.ts

295 lines
9.9 KiB
TypeScript

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);
});
});