399 lines
15 KiB
TypeScript
399 lines
15 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
canonicalRunRequestSchema,
|
|
type CanonicalRunRequest,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import type {
|
|
CostSensitivityInput,
|
|
WorkbenchExperimentDetail,
|
|
WorkbenchExperimentPreview,
|
|
} from '@stock-bot/stock-config/cost-sensitivity';
|
|
import {
|
|
experimentComparisonDimensions,
|
|
type ExperimentComparisonDimension,
|
|
} from '@stock-bot/stock-config/experiment-comparison';
|
|
import { builtinCatalogDescriptors, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import {
|
|
parseFinancialDecimal,
|
|
type CanonicalBacktestAnalytics,
|
|
type HistoricalDatasetV2,
|
|
} from '@stock-bot/types';
|
|
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
|
import { buildCostSensitivityPreview } from '../../apps/stock/web-api/src/services/cost-sensitivity-input';
|
|
import {
|
|
compareExperiments,
|
|
comparisonConditions,
|
|
parseExperimentComparison,
|
|
} from '../../apps/stock/web-api/src/services/experiment-comparison';
|
|
import {
|
|
buildExperimentPreview,
|
|
PREVIEW_RUN_ID,
|
|
} from '../../apps/stock/web-api/src/services/experiment-input';
|
|
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
const backtestId = '10000000-0000-4000-8000-000000000001';
|
|
const versionId = '20000000-0000-4000-8000-000000000001';
|
|
const owner = `strategy:${versionId}`;
|
|
const input = (): CostSensitivityInput => ({
|
|
backtestId,
|
|
name: 'Cost diagnostics',
|
|
scenarios: [
|
|
{ feeRate: '0', slippageRate: '0' },
|
|
{ feeRate: '0.02', slippageRate: '0.01' },
|
|
],
|
|
});
|
|
function source(dataset: HistoricalDatasetV2, raw = input()) {
|
|
const experiment = { backtestId: raw.backtestId, name: raw.name, grid: {} };
|
|
const descriptor = builtinCatalogDescriptors[0]!;
|
|
const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
|
|
const clock = canonicalRiskSessionClock(dataset);
|
|
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
|
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
|
policy.matching.risk.ledger.riskSession = clock.riskSession;
|
|
policy.risk_boundaries = clock.riskBoundaries;
|
|
const request = canonicalRunRequestSchema.parse({
|
|
kind: 'canonical-research/v1',
|
|
runId: PREVIEW_RUN_ID,
|
|
backtestId,
|
|
name: 'Template',
|
|
strategy: {
|
|
familyId: '30000000-0000-4000-8000-000000000001',
|
|
versionId,
|
|
origin: 'builtin',
|
|
reviewId: '40000000-0000-4000-8000-000000000001',
|
|
package: {
|
|
version: 1,
|
|
program: descriptor.program,
|
|
parameterSchema: descriptor.parameterSchema,
|
|
artifact: {
|
|
format: 'esm-bundle/v1',
|
|
entryExport: descriptor.entryExport,
|
|
content: 'fixture',
|
|
sha256: 'a'.repeat(64),
|
|
},
|
|
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
|
source: { revision: 'c'.repeat(40), dirty: false },
|
|
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
|
},
|
|
selection: {
|
|
strategyId: descriptor.program.strategyId,
|
|
strategyVersion: descriptor.program.strategyVersion,
|
|
ownerId: owner,
|
|
seed: 42,
|
|
instrumentId: 'X0.US',
|
|
seriesId: 'X0.US:1m',
|
|
ownerBudget: '40',
|
|
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
},
|
|
},
|
|
datasetHash: dataset.manifest.hash,
|
|
policy,
|
|
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
|
build: {
|
|
version: 1,
|
|
workerSha256: 'a'.repeat(64),
|
|
engineWrapperSha256: 'b'.repeat(64),
|
|
engineBinarySha256: 'c'.repeat(64),
|
|
dependencyLockSha256: 'd'.repeat(64),
|
|
runtime: 'bun',
|
|
runtimeVersion: 'fixture',
|
|
platform: 'linux',
|
|
arch: 'x64',
|
|
},
|
|
modelArtifacts: [],
|
|
});
|
|
return buildExperimentPreview(experiment, request, dataset.manifest);
|
|
}
|
|
|
|
function detail(preview: WorkbenchExperimentPreview, id = randomUUID()): WorkbenchExperimentDetail {
|
|
const metrics: CanonicalBacktestAnalytics['metrics'] = {
|
|
totalReturn: 0,
|
|
cagr: null,
|
|
maxDrawdown: null,
|
|
exposureTime: null,
|
|
volatility: null,
|
|
downsideDeviation: null,
|
|
sharpeRatio: null,
|
|
sortinoRatio: null,
|
|
var95: null,
|
|
cvar95: null,
|
|
var99: null,
|
|
alpha: null,
|
|
beta: null,
|
|
informationRatio: null,
|
|
roundTripCount: null,
|
|
winRate: null,
|
|
profitFactor: null,
|
|
avgWin: null,
|
|
avgLoss: null,
|
|
};
|
|
return {
|
|
id,
|
|
backtestId: preview.input.backtestId,
|
|
name: preview.input.name,
|
|
kind: preview.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
|
|
createdAt: '2026-01-01T00:00:00.000Z',
|
|
cancelRequested: false,
|
|
trialCount: preview.candidates.length,
|
|
counts: {
|
|
pending: 0,
|
|
running: 0,
|
|
paused: 0,
|
|
completed: preview.candidates.length,
|
|
failed: 0,
|
|
cancelled: 0,
|
|
},
|
|
datasetHash: preview.request.datasetHash,
|
|
strategyVersionId: preview.request.strategy.versionId,
|
|
previewHash: preview.previewHash,
|
|
preview,
|
|
trials: preview.candidates.map(candidate => ({
|
|
...candidate,
|
|
runId: randomUUID(),
|
|
attemptNumber: 1,
|
|
retryCount: 0,
|
|
status: 'completed' as const,
|
|
progress: 100,
|
|
cancelRequested: false,
|
|
error: null,
|
|
comparable: true,
|
|
diagnostic: null,
|
|
metrics,
|
|
unavailable: { sharpeRatio: 'insufficient-periods' as const },
|
|
limitations: ['fixture compact summary'],
|
|
})),
|
|
} as WorkbenchExperimentDetail;
|
|
}
|
|
const differences = (
|
|
first: Record<ExperimentComparisonDimension, unknown>,
|
|
second: Record<ExperimentComparisonDimension, unknown>
|
|
) =>
|
|
experimentComparisonDimensions.filter(
|
|
key => canonicalStrategyJson(first[key]) !== canonicalStrategyJson(second[key])
|
|
);
|
|
describe('retained input comparison policy', () => {
|
|
test('names/run/account/version-owner IDs and strategy/parameters may vary without mutating either input', () => {
|
|
const data = canonicalSmaFixture().dataset,
|
|
baseline = source(data),
|
|
original = structuredClone(baseline),
|
|
changed = structuredClone(baseline.request),
|
|
version = randomUUID(),
|
|
owner = `strategy:${version}`,
|
|
runId = randomUUID();
|
|
changed.name = 'Other presentation';
|
|
changed.runId = runId;
|
|
changed.backtestId = randomUUID();
|
|
changed.strategy.familyId = randomUUID();
|
|
changed.strategy.versionId = version;
|
|
changed.strategy.reviewId = randomUUID();
|
|
changed.strategy.package.artifact.content = 'Other trusted implementation';
|
|
changed.strategy.package.artifact.sha256 = 'f'.repeat(64);
|
|
changed.strategy.selection.parameters = { fastPeriod: 1, slowPeriod: 3 };
|
|
changed.strategy.selection.ownerId = owner;
|
|
changed.policy.matching.risk.ledger.sessionId = runId;
|
|
changed.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
|
changed.policy.matching.risk.ledger.ownerIds = [owner];
|
|
changed.policy.matching.owners[0]!.ownerId = owner;
|
|
changed.policy.cadence[0]!.owner_id = owner;
|
|
const before = structuredClone(changed);
|
|
expect(comparisonConditions(changed, data.manifest)).toEqual(
|
|
comparisonConditions(baseline.request, data.manifest)
|
|
);
|
|
expect(changed).toEqual(before);
|
|
expect(baseline).toEqual(original);
|
|
});
|
|
test('every mutable financial/execution/clock/analytics/seed/build condition lands in its explicit mismatch partition', () => {
|
|
const data = canonicalSmaFixture().dataset,
|
|
baseline = source(data).request,
|
|
original = comparisonConditions(baseline, data.manifest);
|
|
const cases: [ExperimentComparisonDimension, (r: CanonicalRunRequest) => void][] = [
|
|
['dataset', r => (r.datasetHash = 'f'.repeat(64))],
|
|
[
|
|
'capital',
|
|
r =>
|
|
(r.policy.matching.risk.ledger.initialCapital = parseFinancialDecimal('20000.00000000')),
|
|
],
|
|
['capital', r => (r.strategy.selection.ownerBudget = parseFinancialDecimal('50.00000000'))],
|
|
['costs', r => (r.policy.matching.risk.feeRate = parseFinancialDecimal('0.20000000'))],
|
|
['costs', r => (r.policy.matching.halfSpreadRate = parseFinancialDecimal('0.10000000'))],
|
|
['costs', r => (r.policy.matching.slippageRate = parseFinancialDecimal('0.10000000'))],
|
|
['execution', r => (r.policy.matching.latencyMs = 1)],
|
|
['execution', r => (r.policy.participation_rate = parseFinancialDecimal('0.50000000'))],
|
|
[
|
|
'execution',
|
|
r => {
|
|
r.strategy.selection.instrumentId = 'OTHER';
|
|
r.policy.matching.series[0]!.instrumentId = 'OTHER';
|
|
},
|
|
],
|
|
[
|
|
'execution',
|
|
r => {
|
|
r.strategy.selection.seriesId = 'OTHER:1m';
|
|
r.policy.matching.series[0]!.seriesId = 'OTHER:1m';
|
|
r.policy.cadence[0]!.series_ids = ['OTHER:1m'];
|
|
},
|
|
],
|
|
[
|
|
'clock',
|
|
r =>
|
|
(r.policy.matching.risk.ledger.riskSession.sessionId =
|
|
'economic-session-must-not-normalize'),
|
|
],
|
|
['clock', r => (r.policy.matching.risk.ledger.riskSession.calendarId = 'other-calendar')],
|
|
[
|
|
'clock',
|
|
r => (r.policy.matching.risk.ledger.riskSession.calendarRevision = 'other-revision'),
|
|
],
|
|
['clock', r => (r.policy.matching.risk.ledger.riskSession.startsAt += 1)],
|
|
[
|
|
'clock',
|
|
r =>
|
|
r.policy.risk_boundaries.push({
|
|
...r.policy.matching.risk.ledger.riskSession,
|
|
sessionId: 'later',
|
|
startsAt: r.policy.matching.risk.ledger.riskSession.startsAt + 1000,
|
|
}),
|
|
],
|
|
['analytics', r => (r.analyticsPolicy.periodsPerYear = 365)],
|
|
['analytics', r => (r.analyticsPolicy.annualRiskFreeRate = 0.01)],
|
|
['seed', r => (r.strategy.selection.seed = 99)],
|
|
];
|
|
for (const key of [
|
|
'maxOrderQuantity',
|
|
'maxPositionQuantity',
|
|
'maxSymbolExposure',
|
|
'maxGrossExposure',
|
|
'maxDailyLoss',
|
|
'maxDrawdownAmount',
|
|
] as const) {
|
|
cases.push([
|
|
'risk',
|
|
r => (r.policy.matching.risk[key] = parseFinancialDecimal('20000.00000000')),
|
|
]);
|
|
}
|
|
cases.push(['risk', r => (r.policy.matching.risk.maxMarkAgeMs += 1)]);
|
|
for (const key of [
|
|
'workerSha256',
|
|
'engineWrapperSha256',
|
|
'engineBinarySha256',
|
|
'dependencyLockSha256',
|
|
] as const) {
|
|
cases.push(['build', r => (r.build[key] = 'f'.repeat(64))]);
|
|
}
|
|
for (const key of ['runtimeVersion', 'platform', 'arch'] as const) {
|
|
cases.push(['build', r => (r.build[key] = 'changed')]);
|
|
}
|
|
for (const [dimension, mutate] of cases) {
|
|
const request = structuredClone(baseline);
|
|
mutate(request);
|
|
expect(differences(original, comparisonConditions(request, data.manifest))).toEqual([
|
|
dimension,
|
|
]);
|
|
}
|
|
const bounds = {
|
|
...data.manifest,
|
|
bounds: { ...data.manifest.bounds, tradeEnd: data.manifest.bounds.tradeEnd - 1 },
|
|
};
|
|
expect(differences(original, comparisonConditions(baseline, bounds))).toEqual([
|
|
'dataset',
|
|
'window',
|
|
]);
|
|
const provenance = {
|
|
...data.manifest,
|
|
calendars: data.manifest.calendars.map(calendar => ({ ...calendar, revision: 'changed' })),
|
|
};
|
|
expect(differences(original, comparisonConditions(baseline, provenance))).toEqual(['dataset']);
|
|
});
|
|
test('unsupported currency/reserve/owner modes/models reject canonical parsing instead of silently matching', () => {
|
|
const data = canonicalSmaFixture().dataset,
|
|
baseline = source(data).request;
|
|
for (const mutate of [
|
|
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.baseCurrency = 'EUR'),
|
|
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.reserveOwnerId = 'foreign'),
|
|
(r: CanonicalRunRequest) => (r.policy.matching.owners[0]!.mode = 'Orders'),
|
|
(r: CanonicalRunRequest) => (r.policy.allow_exploratory = true),
|
|
(r: CanonicalRunRequest) => Object.assign(r, { modelArtifacts: [{ id: 'unsupported' }] }),
|
|
]) {
|
|
const request = structuredClone(baseline);
|
|
mutate(request);
|
|
expect(() => comparisonConditions(request, data.manifest)).toThrow();
|
|
}
|
|
});
|
|
test('effective scenario costs compare across experiments, independently of summary availability and reference order', () => {
|
|
const baseline = source(canonicalSmaFixture().dataset),
|
|
costs = buildCostSensitivityPreview(input(), baseline),
|
|
left = detail(costs),
|
|
right = detail(
|
|
buildCostSensitivityPreview(
|
|
{ ...input(), scenarios: [...input().scenarios].reverse() },
|
|
baseline
|
|
)
|
|
);
|
|
const before = structuredClone([left, right] as [
|
|
WorkbenchExperimentDetail,
|
|
WorkbenchExperimentDetail,
|
|
]),
|
|
selected = left.trials[1]!.trialKey;
|
|
const compared = compareExperiments(
|
|
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
|
|
[left, right]
|
|
);
|
|
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
|
|
'mismatch',
|
|
'match',
|
|
'mismatch',
|
|
'mismatch',
|
|
'mismatch',
|
|
'match',
|
|
]);
|
|
expect(compared.rows.map(r => r.ready)).toEqual([false, true, false, false, false, true]);
|
|
expect(compared.experiments).toEqual(before);
|
|
expect([left, right]).toEqual(before);
|
|
left.trials[1]!.status = 'failed';
|
|
left.trials[1]!.comparable = false;
|
|
left.trials[1]!.diagnostic = 'Retained failure';
|
|
left.trials[1]!.metrics = null;
|
|
const failed = compareExperiments(
|
|
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
|
|
[left, right]
|
|
);
|
|
expect(failed.reference.summaryAvailable).toBe(false);
|
|
expect(failed.reference.diagnostic).toBe('Retained failure');
|
|
expect(failed.rows.every(r => !r.ready)).toBe(true);
|
|
expect(failed.rows[5]!.summaryAvailable).toBe(true);
|
|
expect(failed.rows[5]!.inputCompatibility).toBe('match');
|
|
});
|
|
test('missing first candidate remains the default; zero/null metrics and completed cancellation are retained', () => {
|
|
const baseline = source(canonicalSmaFixture().dataset),
|
|
left = detail(buildCostSensitivityPreview(input(), baseline)),
|
|
right = detail(baseline);
|
|
left.trials[0]!.runId = null;
|
|
left.trials[0]!.status = 'missing';
|
|
left.trials[0]!.comparable = false;
|
|
left.trials[0]!.diagnostic = 'Expected trial run is missing';
|
|
left.trials[0]!.metrics = null;
|
|
right.cancelRequested = true;
|
|
const comparison = compareExperiments({ leftId: left.id, rightId: right.id }, [left, right]);
|
|
expect(comparison.selection.referenceTrialKey).toBe(left.trials[0]!.trialKey);
|
|
expect(comparison.reference.runId).toBeNull();
|
|
expect(comparison.rows.every(r => !r.ready)).toBe(true);
|
|
expect(comparison.experiments[1].trials[0]!.metrics!.totalReturn).toBe(0);
|
|
expect(comparison.experiments[1].trials[0]!.metrics!.sharpeRatio).toBeNull();
|
|
expect(comparison.experiments[1].trials[0]!.unavailable!.sharpeRatio).toBe(
|
|
'insufficient-periods'
|
|
);
|
|
expect(comparison.experiments[1].cancelRequested).toBe(true);
|
|
expect(() =>
|
|
compareExperiments(
|
|
{ leftId: left.id, rightId: right.id, referenceTrialKey: 'f'.repeat(64) },
|
|
[left, right]
|
|
)
|
|
).toThrow('does not belong');
|
|
expect(() => parseExperimentComparison({ leftId: left.id, rightId: left.id })).toThrow(
|
|
'distinct'
|
|
);
|
|
});
|
|
});
|