stock-bot/test/integration/canonical-native-report.test.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

121 lines
5.3 KiB
TypeScript

import { expect, test } from 'bun:test';
import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types';
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import {
parseReplayReportResult,
replayConfigSchema,
} from '@stock-bot/stock-config/canonical-replay';
import { nativeReplayFixture } from '../fixtures/native-replay';
const policy: CanonicalMetricsInput = {
version: 1,
periodsPerYear: 252,
annualRiskFreeRate: 0,
benchmark: null,
};
test('real native facts, worker transport and canonical analytics compose without changing finances', async () => {
const fixture = nativeReplayFixture();
fixture.config.risk_boundaries = [1, 2, 3].map(index => ({
...fixture.config.matching.risk.ledger.riskSession,
sessionId: `report-session-${index}`,
startsAt: fixture.start + index * fixture.minute,
}));
const input = {
type: 'runReplayTrace' as const,
version: 1 as const,
dataset: fixture.dataset,
config: replayConfigSchema.parse(fixture.config),
eventBudget: 1,
trace: [
{
at: fixture.start + fixture.minute,
ownerId: 'A',
intent: {
mode: 'target' as const,
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
},
},
{
at: fixture.start + 2 * fixture.minute,
ownerId: 'A',
intent: { mode: 'target' as const, targets: [] },
},
],
};
const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result;
const financial = executeReplayTrace({ ...input, resultFormat: 'report' }).result;
const before = JSON.stringify(financial);
const report = buildCanonicalBacktestReport(financial, policy);
expect(financial.projection).toEqual(projection.projection);
expect(financial.view).toEqual(projection.view);
expect(report.financial).toBe(financial);
expect(JSON.stringify(financial)).toBe(before);
expect<string>(financial.projection.valuation.cash).toBe('9975.76000000');
expect<string>(financial.projection.valuation.equity).toBe('10005.76000000');
expect<string>(financial.projection.valuation.fees).toBe('0.24000000');
expect<string[]>(financial.reporting.sessions.map(session => session.equity)).toEqual([
'10001.76000000',
'10005.76000000',
]);
expect(report.analytics.sessionReturns.map(session => session.eligible)).toEqual([true, true]);
expect(report.analytics.sessionReturns[0]?.value).toBeCloseTo(1.76 / 10000, 12);
expect(report.analytics.sessionReturns[1]?.value).toBeCloseTo(4 / 10001.76, 12);
expect(report.analytics.metrics.totalReturn).toBeCloseTo(5.76 / 10000, 12);
expect(report.analytics.metrics.exposureTime).toBe(1);
expect(report.analytics.metrics.maxDrawdown).toBe(0);
expect(report.analytics.metrics.sharpeRatio).not.toBeNull();
expect(report.analytics.metrics.sortinoRatio).toBeNull();
expect(report.analytics.unavailable.sortinoRatio).toBe('zero-downside-deviation');
expect(report.analytics.fillCount).toBe(1);
expect(report.analytics.metrics.roundTripCount).toBeNull();
expect(report.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips');
expect<string | undefined>(financial.view.portfolio.positions[0]?.quantity).toBe('2.00000000');
const worker = new NativeBacktestWorker();
const raw = await worker.execute(
{ ...input, resultFormat: 'report', eventBudget: 64 },
new AbortController().signal,
() => {}
);
const transported = parseReplayReportResult(raw, financial.identity, input.config);
expect(buildCanonicalBacktestReport(transported, policy)).toEqual(report);
const missingRate = buildCanonicalBacktestReport(financial, {
...policy,
annualRiskFreeRate: null,
});
expect(missingRate.financial).toBe(financial);
expect(missingRate.analytics.metrics.sharpeRatio).toBeNull();
expect(missingRate.analytics.unavailable.sharpeRatio).toBe('missing-risk-free');
expect(missingRate.analytics.metrics.volatility).toBe(report.analytics.metrics.volatility);
});
test('real no-trade native reporting retains genuine zero metrics through the canonical adapter', () => {
const fixture = nativeReplayFixture();
const financial = executeReplayTrace({
type: 'runReplayTrace',
version: 1,
dataset: fixture.dataset,
config: fixture.config,
eventBudget: 64,
trace: [1, 2].map(index => ({
at: fixture.start + index * fixture.minute,
ownerId: 'A',
intent: { mode: 'target' as const, targets: [] },
})),
resultFormat: 'report',
}).result;
const report = buildCanonicalBacktestReport(financial, policy);
expect(report.analytics.metrics.totalReturn).toBe(0);
expect(report.analytics.metrics.exposureTime).toBe(0);
expect(report.analytics.metrics.cagr).toBe(0);
expect(report.analytics.fillCount).toBe(0);
expect(report.analytics.sessionReturns[0]?.value).toBe(0);
expect(report.analytics.sessionReturns[0]?.partialEnd).toBe(true);
expect(report.analytics.periodicSampleCount).toBe(0);
expect(report.analytics.metrics.volatility).toBeNull();
expect(report.analytics.unavailable.volatility).toBe('insufficient-periods');
});