feat(research): add canonical session reporting and analytics
This commit is contained in:
parent
1e164450c3
commit
3838295eec
28 changed files with 2402 additions and 47 deletions
121
test/integration/canonical-native-report.test.ts
Normal file
121
test/integration/canonical-native-report.test.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import {
|
||||
parseReplayReportResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-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');
|
||||
});
|
||||
353
test/integration/canonical-result.test.ts
Normal file
353
test/integration/canonical-result.test.ts
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import {
|
||||
parseReplayReportValue,
|
||||
type ReplayConfig,
|
||||
type ReplayReportResult,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
|
||||
const policy: CanonicalMetricsInput = {
|
||||
version: 1,
|
||||
periodsPerYear: 252,
|
||||
annualRiskFreeRate: 0,
|
||||
benchmark: null,
|
||||
};
|
||||
const money = (value: number | string) => parseFinancialDecimal(String(value));
|
||||
|
||||
/** Hand-authored statistical input fixtures validated by the accepted wire schema.
|
||||
* Native reporting tests, not these fixtures, establish financial transition validity. */
|
||||
function fixture(
|
||||
equities = [110, 99],
|
||||
options: {
|
||||
initial?: number;
|
||||
times?: number[];
|
||||
partialStart?: boolean;
|
||||
partialEnd?: boolean;
|
||||
occupiedIntervals?: { start: number; end: number }[];
|
||||
} = {}
|
||||
): ReplayReportResult {
|
||||
const initial = options.initial ?? 100;
|
||||
// Two sessions can end on the same UTC date; UTC grouping would lose a return.
|
||||
const start = Date.parse('2024-01-01T23:30:00Z');
|
||||
const times =
|
||||
options.times ?? Array.from({ length: equities.length + 1 }, (_, i) => start + i * 3600000);
|
||||
const tradeStart = times[0]!,
|
||||
tradeEnd = times.at(-1)!;
|
||||
const identity = {
|
||||
version: 1 as const,
|
||||
sessionId: 'analytics-fixture',
|
||||
datasetHash: 'a'.repeat(64),
|
||||
};
|
||||
const riskSession = (index: number) => ({
|
||||
calendarId: 'account-test',
|
||||
calendarRevision: 'revision-7',
|
||||
sessionId: `session-${index}`,
|
||||
startsAt: index === 0 && options.partialStart ? tradeStart - 1000 : times[index]!,
|
||||
});
|
||||
const config: ReplayConfig = {
|
||||
matching: {
|
||||
risk: {
|
||||
ledger: {
|
||||
version: 1,
|
||||
sessionId: identity.sessionId,
|
||||
accountId: 'account',
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
ownerIds: ['A'],
|
||||
initialCapital: money(initial),
|
||||
riskSession: riskSession(0),
|
||||
},
|
||||
feeRate: '0',
|
||||
maxOrderQuantity: '1000',
|
||||
maxPositionQuantity: '1000',
|
||||
maxSymbolExposure: '1000000',
|
||||
maxGrossExposure: '1000000',
|
||||
maxDailyLoss: '1000000',
|
||||
maxDrawdownAmount: '1000000',
|
||||
maxMarkAgeMs: 86400000,
|
||||
},
|
||||
owners: [{ ownerId: 'A', mode: 'Target' }],
|
||||
series: [{ instrumentId: 'X.US', seriesId: 'X.US:1m', mode: 'Open' }],
|
||||
halfSpreadRate: '0',
|
||||
slippageRate: '0',
|
||||
latencyMs: 0,
|
||||
},
|
||||
participation_rate: '1',
|
||||
cadence: [{ owner_id: 'A', series_ids: ['X.US:1m'] }],
|
||||
allow_exploratory: false,
|
||||
risk_boundaries: [],
|
||||
};
|
||||
const ledger = config.matching.risk.ledger;
|
||||
config.risk_boundaries = times
|
||||
.slice(1, options.partialEnd ? -1 : undefined)
|
||||
.map((_, index) => riskSession(index + 1));
|
||||
const final = money(equities.at(-1)!);
|
||||
const occupiedIntervals = options.occupiedIntervals ?? [];
|
||||
const lastRisk = config.risk_boundaries.at(-1) ?? ledger.riskSession;
|
||||
return parseReplayReportValue(
|
||||
{
|
||||
identity,
|
||||
status: 'complete',
|
||||
format: 'report',
|
||||
reportingVersion: 1,
|
||||
projectionVersion: 1,
|
||||
financialVersion: 1,
|
||||
manifest: { version: 2, hash: identity.datasetHash, bounds: { tradeStart, tradeEnd } },
|
||||
policy: config,
|
||||
view: {
|
||||
admissionRevision: 0,
|
||||
portfolio: {
|
||||
version: 1,
|
||||
sessionId: identity.sessionId,
|
||||
accountId: ledger.accountId,
|
||||
revision: 0,
|
||||
baseCurrency: ledger.baseCurrency,
|
||||
reserveOwnerId: ledger.reserveOwnerId,
|
||||
cash: final,
|
||||
positions: [],
|
||||
fees: [],
|
||||
riskSession: lastRisk,
|
||||
},
|
||||
equity: final,
|
||||
availableCash: final,
|
||||
orders: [],
|
||||
reservations: [],
|
||||
risk: {
|
||||
dailyBaseline: money(initial),
|
||||
peakEquity: money(initial),
|
||||
dailyHalted: false,
|
||||
drawdownHalted: false,
|
||||
riskSession: lastRisk,
|
||||
lastEventTime: tradeEnd,
|
||||
},
|
||||
},
|
||||
projection: {
|
||||
valuation: {
|
||||
cash: final,
|
||||
markedHoldings: '0',
|
||||
equity: final,
|
||||
remainingCost: '0',
|
||||
realizedGrossPnl: '0',
|
||||
unrealizedPnl: '0',
|
||||
fees: '0',
|
||||
owners: [],
|
||||
},
|
||||
fills: [],
|
||||
},
|
||||
reporting: {
|
||||
calendarId: ledger.riskSession.calendarId,
|
||||
calendarRevision: ledger.riskSession.calendarRevision,
|
||||
tradeStart,
|
||||
tradeEnd,
|
||||
initialEquity: money(initial),
|
||||
sampling: 'account-boundary-after-observations-v1',
|
||||
exposureBasis: 'elapsed-calendar-time',
|
||||
sessions: equities.map((equity, index) => ({
|
||||
session: riskSession(index),
|
||||
periodStart: times[index],
|
||||
periodEnd: times[index + 1],
|
||||
partialStart: index === 0 && !!options.partialStart,
|
||||
partialEnd: index === equities.length - 1 && !!options.partialEnd,
|
||||
equity: money(equity),
|
||||
})),
|
||||
occupiedIntervals,
|
||||
occupiedMs: String(
|
||||
occupiedIntervals.reduce((sum, i) => sum + BigInt(i.end) - BigInt(i.start), 0n)
|
||||
),
|
||||
elapsedMs: String(BigInt(tradeEnd) - BigInt(tradeStart)),
|
||||
},
|
||||
limitations: ['fixture availability'],
|
||||
modelLimitations: ['Equal-time asset marks are sequential; portfolio risk is not atomic.'],
|
||||
},
|
||||
identity
|
||||
);
|
||||
}
|
||||
|
||||
function analytics(financial = fixture(), selectedPolicy = policy) {
|
||||
const output = buildCanonicalBacktestReport(financial, selectedPolicy).analytics;
|
||||
for (const [key, value] of Object.entries(output.metrics)) {
|
||||
if (value === null) {
|
||||
expect(output.unavailable[key as keyof typeof output.metrics]).toBeDefined();
|
||||
} else {
|
||||
expect(Number.isFinite(value)).toBe(true);
|
||||
expect(output.unavailable[key as keyof typeof output.metrics]).toBeUndefined();
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
describe('canonical statistical reporting', () => {
|
||||
test('two_session_marks retain final session, fractional units and explicit calendar conventions', () => {
|
||||
const output = analytics();
|
||||
expect(output.sessionReturns).toHaveLength(2);
|
||||
expect(output.sessionReturns[0]?.value).toBeCloseTo(0.1);
|
||||
expect(output.sessionReturns[1]?.value).toBeCloseTo(-0.1);
|
||||
expect(output.metrics.totalReturn).toBeCloseTo(-0.01);
|
||||
expect(output.metrics.maxDrawdown).toBeCloseTo(0.1);
|
||||
expect(output.metrics.volatility).toBeCloseTo(Math.sqrt(0.02 * 252));
|
||||
expect(output.metrics.downsideDeviation).toBeCloseTo(Math.sqrt(0.005 * 252));
|
||||
expect(output.metrics.sharpeRatio).toBeCloseTo(0);
|
||||
expect(output.metrics.sortinoRatio).toBeCloseTo(0);
|
||||
expect(output.periodicSampleCount).toBe(2);
|
||||
expect(output.policy).toMatchObject({
|
||||
calendarId: 'account-test',
|
||||
calendarRevision: 'revision-7',
|
||||
sampling: 'account-boundary-after-observations-v1',
|
||||
drawdown: 'session-end-and-terminal-sampled',
|
||||
exposureBasis: 'elapsed-calendar-time',
|
||||
cagrBasis: 'elapsed-calendar-days-365',
|
||||
returnUnit: 'fraction',
|
||||
marks: 'last-available-no-per-session-freshness-certification',
|
||||
});
|
||||
});
|
||||
|
||||
test('partial initial and final returns remain visible but do not become complete statistical periods', () => {
|
||||
const output = analytics(fixture([110, 99, 198, 99], { partialStart: true, partialEnd: true }));
|
||||
expect(output.sessionReturns.map(s => s.eligible)).toEqual([false, true, true, false]);
|
||||
expect(output.sessionReturns.map(s => s.partialStart)).toEqual([true, false, false, false]);
|
||||
expect(output.sessionReturns.at(-1)?.value).toBeCloseTo(-0.5);
|
||||
expect(output.completePeriodCount).toBe(2);
|
||||
expect(output.periodicSampleCount).toBe(2);
|
||||
// Only -.1 and +1: mean .45, sample variance .605.
|
||||
expect(output.metrics.volatility).toBeCloseTo(Math.sqrt(0.605 * 252));
|
||||
expect(output.metrics.sharpeRatio).toBeCloseTo((0.45 * 252) / Math.sqrt(0.605 * 252));
|
||||
expect(output.metrics.totalReturn).toBeCloseTo(-0.01);
|
||||
});
|
||||
|
||||
test('undefined complete return invalidates the entire periodic sequence without dropping history', () => {
|
||||
const output = analytics(fixture([0, 0, 0]));
|
||||
expect(output.sessionReturns.map(s => s.value)).toEqual([-1, null, null]);
|
||||
expect(output.sessionReturns[1]?.reason).toBe('nonpositive-baseline');
|
||||
expect(output.completePeriodCount).toBe(3);
|
||||
expect(output.periodicSampleCount).toBe(0);
|
||||
for (const key of [
|
||||
'volatility',
|
||||
'downsideDeviation',
|
||||
'sharpeRatio',
|
||||
'sortinoRatio',
|
||||
'var95',
|
||||
'cvar95',
|
||||
'var99',
|
||||
] as const) {
|
||||
expect(output.metrics[key]).toBeNull();
|
||||
expect(output.unavailable[key]).toBe('undefined-period-return');
|
||||
}
|
||||
expect(output.metrics.totalReturn).toBe(-1);
|
||||
expect(output.metrics.cagr).toBe(-1);
|
||||
});
|
||||
|
||||
test('constant_negative_returns and zero_variance distinguish Sharpe from Sortino', () => {
|
||||
const negative = analytics(fixture([90, 81]));
|
||||
expect(negative.metrics.volatility).toBe(0);
|
||||
expect(negative.metrics.sharpeRatio).toBeNull();
|
||||
expect(negative.unavailable.sharpeRatio).toBe('zero-variance');
|
||||
expect(negative.metrics.sortinoRatio).toBeCloseTo(-Math.sqrt(252));
|
||||
const zero = analytics(fixture([100, 100]));
|
||||
expect(zero.metrics.totalReturn).toBe(0);
|
||||
expect(zero.metrics.volatility).toBe(0);
|
||||
expect(zero.metrics.downsideDeviation).toBe(0);
|
||||
expect(zero.metrics.sortinoRatio).toBeNull();
|
||||
expect(zero.unavailable.sortinoRatio).toBe('zero-downside-deviation');
|
||||
});
|
||||
|
||||
test('missing rate and benchmark remain unavailable; explicit zero is not missing', () => {
|
||||
const missing = analytics(fixture(), { ...policy, annualRiskFreeRate: null });
|
||||
for (const key of ['sharpeRatio', 'sortinoRatio', 'downsideDeviation'] as const) {
|
||||
expect(missing.metrics[key]).toBeNull();
|
||||
expect(missing.unavailable[key]).toBe('missing-risk-free');
|
||||
}
|
||||
expect(missing.metrics.volatility).not.toBeNull();
|
||||
expect(missing.unavailable.beta).toBe('missing-benchmark');
|
||||
expect(analytics().metrics.sharpeRatio).not.toBeNull();
|
||||
for (const input of [
|
||||
{ ...policy, benchmark: 'SPY' },
|
||||
{ ...policy, annualRiskFreeRate: undefined },
|
||||
{ ...policy, periodsPerYear: 0 },
|
||||
{ ...policy, periodsPerYear: Infinity },
|
||||
{ ...policy, version: 2 },
|
||||
{ ...policy, extra: true },
|
||||
]) {
|
||||
expect(() =>
|
||||
buildCanonicalBacktestReport(fixture(), input as CanonicalMetricsInput)
|
||||
).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('exposure consumes the canonical union and includes terminal open-position occupancy', () => {
|
||||
// Rust supplies the union [1,7) of overlapping positions [1,5),[3,7).
|
||||
const financial = fixture([100], {
|
||||
times: [0, 10],
|
||||
occupiedIntervals: [
|
||||
{ start: 1, end: 7 },
|
||||
{ start: 8, end: 10 },
|
||||
],
|
||||
});
|
||||
expect(analytics(financial).metrics.exposureTime).toBe(0.8);
|
||||
expect(analytics(fixture([100], { times: [0, 10] })).metrics.exposureTime).toBe(0);
|
||||
expect(
|
||||
analytics(fixture([100], { times: [0, 10], occupiedIntervals: [{ start: 0, end: 10 }] }))
|
||||
.metrics.exposureTime
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test('financial facts and limitations are preserved; fill count is not round-trip count', () => {
|
||||
const financial = fixture();
|
||||
financial.projection.fills.push({
|
||||
commandId: 'command',
|
||||
eventTime: financial.reporting.tradeStart,
|
||||
ownerId: 'A',
|
||||
decision: { ownerId: 'A', decisionId: 'decision', sequence: 0 },
|
||||
orderId: 'order',
|
||||
fillId: 'fill',
|
||||
instrumentId: 'X0.US',
|
||||
side: 'buy',
|
||||
quantity: money(1),
|
||||
price: money(10),
|
||||
fee: { feeId: 'fee', amount: money(1) },
|
||||
cashDelta: money(-10),
|
||||
quantityDelta: money(1),
|
||||
releasedBasis: money(0),
|
||||
realizedGrossPnl: money(0),
|
||||
});
|
||||
const before = structuredClone(financial);
|
||||
const result = buildCanonicalBacktestReport(financial, policy);
|
||||
expect(result.financial).toBe(financial);
|
||||
expect(result.financial).toEqual(before);
|
||||
expect(result.analytics.fillCount).toBe(1);
|
||||
for (const key of ['roundTripCount', 'winRate', 'profitFactor', 'avgWin', 'avgLoss'] as const) {
|
||||
expect(result.analytics.metrics[key]).toBeNull();
|
||||
expect(result.analytics.unavailable[key]).toBe('unsupported-round-trips');
|
||||
}
|
||||
expect(result.analytics).not.toHaveProperty('positions');
|
||||
});
|
||||
|
||||
test('extreme supported timestamps preserve integer durations without Date coercion', () => {
|
||||
const min = -Number.MAX_SAFE_INTEGER,
|
||||
max = Number.MAX_SAFE_INTEGER;
|
||||
const financial = fixture([110, 99], {
|
||||
times: [min, 0, max],
|
||||
occupiedIntervals: [{ start: min, end: max }],
|
||||
});
|
||||
expect(financial.reporting.elapsedMs).toBe('18014398509481982');
|
||||
const output = analytics(financial);
|
||||
expect(output.metrics.exposureTime).toBe(1);
|
||||
expect(output.metrics.maxDrawdown).toBeCloseTo(0.1);
|
||||
expect(output.metrics.cagr).not.toBeNull();
|
||||
});
|
||||
|
||||
test('insufficient complete periods and nonpositive initial baseline have explicit reasons', () => {
|
||||
const partial = analytics(fixture([110], { partialEnd: true }));
|
||||
expect(partial.sessionReturns[0]?.value).toBeCloseTo(0.1);
|
||||
expect(partial.completePeriodCount).toBe(0);
|
||||
expect(partial.unavailable.volatility).toBe('insufficient-periods');
|
||||
const zero = analytics(fixture([0], { initial: 0 }));
|
||||
expect(zero.unavailable.totalReturn).toBe('nonpositive-baseline');
|
||||
expect(zero.unavailable.cagr).toBe('nonpositive-baseline');
|
||||
expect(zero.unavailable.maxDrawdown).toBe('nonpositive-baseline');
|
||||
const overflow = analytics(fixture([200], { times: [0, 1] }));
|
||||
expect(overflow.metrics.totalReturn).toBe(1);
|
||||
expect(overflow.metrics.cagr).toBeNull();
|
||||
expect(overflow.unavailable.cagr).toBe('nonfinite-result');
|
||||
});
|
||||
});
|
||||
311
test/integration/native-replay-report.test.ts
Normal file
311
test/integration/native-replay-report.test.ts
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
import type { ChildProcess } from 'node:child_process';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { FinancialReplaySession } from '@stock-bot/engine';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
executeReplayTrace,
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplayConformance,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import {
|
||||
parseReplayProjectionResult,
|
||||
parseReplayReportResult,
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const hold = () => ({ mode: 'target' as const, targets: [] });
|
||||
const buy = () => ({
|
||||
mode: 'target' as const,
|
||||
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
|
||||
});
|
||||
function request(twoSessions = false) {
|
||||
const f = nativeReplayFixture();
|
||||
if (twoSessions) {
|
||||
f.config.risk_boundaries = [2, 3].map(n => ({
|
||||
...f.config.matching.risk.ledger.riskSession,
|
||||
sessionId: `risk-${n}`,
|
||||
startsAt: f.start + n * f.minute,
|
||||
}));
|
||||
}
|
||||
return {
|
||||
type: 'runReplayTrace' as const,
|
||||
version: 1 as const,
|
||||
dataset: f.dataset,
|
||||
config: replayConfigSchema.parse(f.config),
|
||||
eventBudget: 1,
|
||||
trace: [
|
||||
{ at: f.start + f.minute, ownerId: 'A', intent: buy() },
|
||||
{ at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('authoritative replay reporting', () => {
|
||||
test('two_session_marks and occupancy preserve compact financial facts and earlier reset', () => {
|
||||
const input = request(true),
|
||||
f = nativeReplayFixture();
|
||||
const projected = executeReplayTrace({ ...input, resultFormat: 'projection' }).result;
|
||||
let reset: string | undefined;
|
||||
const output = runReplayConformance(
|
||||
new NativeReplaySession(prepareReplayLoad(input.dataset, input.config)),
|
||||
(_owner, context) => (context.barrier.at === f.start + f.minute ? buy() : hold()),
|
||||
{
|
||||
resultFormat: 'report',
|
||||
eventBudget: 1,
|
||||
onProgress: step => {
|
||||
if (
|
||||
step.step.type === 'decisionBatch' &&
|
||||
step.step.barrier.at === f.start + 2 * f.minute
|
||||
) {
|
||||
reset = step.step.view.risk.dailyBaseline;
|
||||
}
|
||||
},
|
||||
}
|
||||
).result;
|
||||
expect(output.projection).toEqual(projected.projection);
|
||||
expect(output.view).toEqual(projected.view);
|
||||
expect(output.policy).toEqual(projected.policy);
|
||||
expect(output.modelLimitations).toEqual(projected.modelLimitations);
|
||||
expect(reset).toBe('9999.76000000');
|
||||
expect(output.reporting).toEqual({
|
||||
calendarId: 'account',
|
||||
calendarRevision: '1',
|
||||
tradeStart: f.start + f.minute,
|
||||
tradeEnd: f.start + 3 * f.minute,
|
||||
initialEquity: parseFinancialDecimal('10000.00000000'),
|
||||
sampling: 'account-boundary-after-observations-v1',
|
||||
exposureBasis: 'elapsed-calendar-time',
|
||||
sessions: [
|
||||
{
|
||||
session: input.config.matching.risk.ledger.riskSession,
|
||||
periodStart: f.start + f.minute,
|
||||
periodEnd: f.start + 2 * f.minute,
|
||||
partialStart: true,
|
||||
partialEnd: false,
|
||||
equity: parseFinancialDecimal('10001.76000000'),
|
||||
},
|
||||
{
|
||||
session: input.config.risk_boundaries[0]!,
|
||||
periodStart: f.start + 2 * f.minute,
|
||||
periodEnd: f.start + 3 * f.minute,
|
||||
partialStart: false,
|
||||
partialEnd: false,
|
||||
equity: parseFinancialDecimal('10005.76000000'),
|
||||
},
|
||||
],
|
||||
occupiedIntervals: [{ start: f.start + f.minute, end: f.start + 3 * f.minute }],
|
||||
occupiedMs: '120000',
|
||||
elapsedMs: '120000',
|
||||
});
|
||||
expect(output).not.toHaveProperty('receipts');
|
||||
expect(executeReplayTrace({ ...input, resultFormat: 'report' }).result).toEqual(output);
|
||||
});
|
||||
|
||||
test('native report is read-only and rejects incomplete, failed, wrong identity and disposed states', () => {
|
||||
const f = nativeReplayFixture(),
|
||||
load = prepareReplayLoad(f.dataset, f.config);
|
||||
const native = new FinancialReplaySession(JSON.stringify(load)),
|
||||
identity = JSON.stringify(load.identity);
|
||||
expect(() => native.report(identity)).toThrow('complete');
|
||||
expect(() => native.report(JSON.stringify({ ...load.identity, version: 2 }))).toThrow();
|
||||
expect(() => native.report(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow(
|
||||
'identity'
|
||||
);
|
||||
let sequence = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const step = JSON.parse(
|
||||
native.advance(JSON.stringify({ identity: load.identity, eventBudget: 1 }))
|
||||
).step;
|
||||
if (step.type === 'complete') {
|
||||
break;
|
||||
}
|
||||
if (step.type === 'failed') {
|
||||
throw new Error(step.diagnostic);
|
||||
}
|
||||
if (step.type === 'decisionBatch') {
|
||||
native.submit(
|
||||
JSON.stringify({
|
||||
identity: load.identity,
|
||||
barrierId: step.barrier.barrier_id,
|
||||
decisions: [
|
||||
{
|
||||
version: 1,
|
||||
sessionId: load.identity.sessionId,
|
||||
barrierId: step.barrier.barrier_id,
|
||||
revision: step.barrier.revision,
|
||||
decision: {
|
||||
ownerId: 'A',
|
||||
decisionId: `direct-${sequence}`,
|
||||
sequence: sequence++,
|
||||
},
|
||||
intent: hold(),
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
const trace = native.finalize(identity),
|
||||
projection = native.project(identity),
|
||||
report = native.report(identity);
|
||||
expect(native.report(identity)).toBe(report);
|
||||
expect(native.finalize(identity)).toBe(trace);
|
||||
expect(native.project(identity)).toBe(projection);
|
||||
const parsed = parseReplayReportResult(report, load.identity);
|
||||
expect(parsed.reporting.occupiedMs).toBe('0');
|
||||
expect(parsed.reporting.sessions).toHaveLength(1);
|
||||
expect(parsed.reporting.sessions[0]?.partialEnd).toBe(true);
|
||||
} finally {
|
||||
native.dispose();
|
||||
}
|
||||
expect(() => native.report(identity)).toThrow('disposed');
|
||||
load.prepared.bars[0]!.high = '792281625142643375935.43950335';
|
||||
load.prepared.bars[0]!.close = '792281625142643375935.43950335';
|
||||
const failed = new FinancialReplaySession(JSON.stringify(load));
|
||||
try {
|
||||
const step = JSON.parse(
|
||||
failed.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 }))
|
||||
).step;
|
||||
const submission = JSON.parse(
|
||||
failed.submit(
|
||||
JSON.stringify({
|
||||
identity: load.identity,
|
||||
barrierId: step.barrier.barrier_id,
|
||||
decisions: [
|
||||
{
|
||||
version: 1,
|
||||
sessionId: load.identity.sessionId,
|
||||
barrierId: step.barrier.barrier_id,
|
||||
revision: step.barrier.revision,
|
||||
decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 },
|
||||
intent: buy(),
|
||||
},
|
||||
],
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(submission.outcome.status).toHaveProperty('Failed');
|
||||
expect(() => failed.report(identity)).toThrow('complete');
|
||||
} finally {
|
||||
failed.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('strict reporting format, identity, calendar, partition, terminal and union validation', () => {
|
||||
const input = request(true),
|
||||
result = executeReplayTrace({ ...input, resultFormat: 'report' }).result;
|
||||
expect(() => parseReplayProjectionResult(JSON.stringify(result), result.identity)).toThrow();
|
||||
expect(() => parseReplayResult(JSON.stringify(result), result.identity)).toThrow();
|
||||
for (const mutate of [
|
||||
(r: any) => (r.format = 'projection'),
|
||||
(r: any) => (r.reportingVersion = 2),
|
||||
(r: any) => (r.projectionVersion = 2),
|
||||
(r: any) => (r.financialVersion = 2),
|
||||
(r: any) => (r.receipts = []),
|
||||
(r: any) => (r.identity.sessionId = 'wrong'),
|
||||
(r: any) => (r.reporting.calendarId = 'wrong'),
|
||||
(r: any) => (r.reporting.calendarRevision = 'wrong'),
|
||||
(r: any) => r.reporting.tradeStart++,
|
||||
(r: any) => (r.reporting.initialEquity = '9999'),
|
||||
(r: any) => (r.reporting.sessions.at(-1).equity = '1'),
|
||||
(r: any) => r.reporting.sessions[0].periodEnd++,
|
||||
(r: any) => (r.reporting.sessions[0].partialStart = false),
|
||||
(r: any) => (r.reporting.sessions.at(-1).partialEnd = true),
|
||||
(r: any) => r.reporting.sessions.push(r.reporting.sessions[0]),
|
||||
(r: any) => (r.reporting.occupiedMs = '0120000'),
|
||||
(r: any) => (r.reporting.occupiedMs = '120001'),
|
||||
(r: any) => (r.reporting.elapsedMs = '120001'),
|
||||
(r: any) => r.reporting.occupiedIntervals[0].start--,
|
||||
(r: any) => r.reporting.occupiedIntervals.push(r.reporting.occupiedIntervals[0]),
|
||||
(r: any) => (r.policy.matching.risk.feeRate = '0.5'),
|
||||
]) {
|
||||
const changed = structuredClone(result);
|
||||
mutate(changed);
|
||||
expect(() =>
|
||||
parseReplayReportResult(JSON.stringify(changed), result.identity, input.config)
|
||||
).toThrow();
|
||||
}
|
||||
const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result;
|
||||
expect(() => parseReplayReportResult(JSON.stringify(projection), result.identity)).toThrow();
|
||||
});
|
||||
|
||||
test('report duration validation uses exact integers before subtracting timestamps', () => {
|
||||
const input = request();
|
||||
input.trace = input.trace.map(row => ({ ...row, intent: hold() }));
|
||||
const result = executeReplayTrace({ ...input, resultFormat: 'report' }).result;
|
||||
const start = -Number.MAX_SAFE_INTEGER,
|
||||
end = Number.MAX_SAFE_INTEGER - 1;
|
||||
const session = { ...result.policy.matching.risk.ledger.riskSession, startsAt: start };
|
||||
result.policy.matching.risk.ledger.riskSession = session;
|
||||
Object.assign(result.manifest.bounds as object, { tradeStart: start, tradeEnd: end });
|
||||
Object.assign(result.reporting, {
|
||||
tradeStart: start,
|
||||
tradeEnd: end,
|
||||
elapsedMs: '18014398509481981',
|
||||
sessions: [
|
||||
{
|
||||
session,
|
||||
periodStart: start,
|
||||
periodEnd: end,
|
||||
partialStart: false,
|
||||
partialEnd: true,
|
||||
equity: result.view.equity,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
parseReplayReportResult(JSON.stringify(result), result.identity).reporting.elapsedMs
|
||||
).toBe('18014398509481981');
|
||||
result.reporting.elapsedMs = String(end - start);
|
||||
expect(() => parseReplayReportResult(JSON.stringify(result), result.identity)).toThrow(
|
||||
'duration'
|
||||
);
|
||||
});
|
||||
|
||||
test('worker captures report format and preserves failure and post-result cancellation guards', async () => {
|
||||
const input = { ...request(), resultFormat: 'report' as const },
|
||||
worker = new NativeBacktestWorker();
|
||||
const expected = executeReplayTrace(input).result;
|
||||
const mutable = { ...input };
|
||||
const raw = await worker.execute(mutable, new AbortController().signal, () => {
|
||||
(mutable as { resultFormat: string }).resultFormat = 'projection';
|
||||
});
|
||||
expect(parseReplayReportResult(raw, expected.identity, input.config)).toEqual(expected);
|
||||
const fixture = new NativeBacktestWorker(
|
||||
new URL('../fixtures/native-replay-worker.ts', import.meta.url)
|
||||
);
|
||||
for (const mode of [
|
||||
'wrong-format',
|
||||
'wrong-policy',
|
||||
'wrong-account',
|
||||
'wrong-session',
|
||||
'crash',
|
||||
]) {
|
||||
const bad = { ...request(), resultFormat: 'report' as const };
|
||||
bad.config.matching.risk.ledger.accountId = mode;
|
||||
await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow();
|
||||
}
|
||||
const blocked = { ...request(), resultFormat: 'report' as const };
|
||||
blocked.config.matching.risk.ledger.accountId = 'result-then-block';
|
||||
const cancellation = new AbortController();
|
||||
let observed = false;
|
||||
const running = fixture.execute(blocked, cancellation.signal, () => {});
|
||||
const child = (fixture as unknown as { active: ChildProcess }).active;
|
||||
child.on('message', (message: any) => {
|
||||
if (message.type === 'result') {
|
||||
observed = true;
|
||||
cancellation.abort(new Error('report cancelled'));
|
||||
}
|
||||
});
|
||||
await expect(running).rejects.toThrow('report cancelled');
|
||||
expect(observed).toBe(true);
|
||||
expect(
|
||||
JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format
|
||||
).toBe('report');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue