423 lines
16 KiB
TypeScript
423 lines
16 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import { describe, expect, test } from 'bun:test';
|
|
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
|
import type { ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
|
|
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
|
import type {
|
|
HistoricalDataset,
|
|
HistoricalDatasetInputV2,
|
|
HistoricalDatasetV2,
|
|
} from '@stock-bot/types';
|
|
import {
|
|
convertDatasetV1ToV2,
|
|
createDatasetV2,
|
|
sliceDatasetV2,
|
|
validateDatasetV2,
|
|
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
|
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
|
import {
|
|
buildExperimentPreview,
|
|
PREVIEW_RUN_ID,
|
|
} from '../../apps/stock/web-api/src/services/experiment-input';
|
|
import {
|
|
parseChronologicalValidation,
|
|
prepareChronologicalValidation,
|
|
} from '../../apps/stock/web-api/src/services/validation-preview';
|
|
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
|
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
|
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 = (): ChronologicalValidationInput => ({
|
|
backtestId,
|
|
name: 'Chronological input checks',
|
|
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
|
recipe: chronologicalDataset().recipe,
|
|
});
|
|
function source(
|
|
dataset: HistoricalDatasetV2,
|
|
raw = input(),
|
|
meanParameters?: Record<string, string | number>
|
|
) {
|
|
const { recipe: _recipe, ...experiment } = raw;
|
|
const descriptor = builtinCatalogDescriptors[meanParameters ? 1 : 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: meanParameters ?? { 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 providerInput(dataset: HistoricalDatasetV2): HistoricalDatasetInputV2 {
|
|
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
|
dataset.manifest;
|
|
return {
|
|
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
|
bars: dataset.bars.map(
|
|
({
|
|
seriesId,
|
|
intervalStart,
|
|
availableAt,
|
|
sourceSequence,
|
|
open,
|
|
high,
|
|
low,
|
|
close,
|
|
volume,
|
|
vwap,
|
|
}) => ({
|
|
seriesId,
|
|
timestamp: intervalStart,
|
|
availableAt,
|
|
sourceSequence,
|
|
open,
|
|
high,
|
|
low,
|
|
close,
|
|
volume,
|
|
vwap,
|
|
})
|
|
),
|
|
};
|
|
}
|
|
function changedAvailability(delays: Record<number, number>) {
|
|
const fixture = chronologicalDataset();
|
|
const raw = providerInput(fixture.dataset);
|
|
return createDatasetV2({
|
|
...raw,
|
|
bars: raw.bars.map((bar, index) => ({
|
|
...bar,
|
|
availableAt: fixture.start + (delays[index] ?? index + 1) * fixture.minute,
|
|
})),
|
|
});
|
|
}
|
|
|
|
describe('chronological validation input preparation', () => {
|
|
test('exact slices retain observations and all provenance without mutating the source or financial policy', () => {
|
|
const dataset = chronologicalDataset().dataset,
|
|
raw = input(),
|
|
preview = source(dataset, raw);
|
|
const before = structuredClone({ dataset, preview, raw });
|
|
const result = prepareChronologicalValidation(raw, preview, dataset);
|
|
expect(prepareChronologicalValidation(raw, preview, dataset)).toEqual(result);
|
|
expect({ dataset, preview, raw }).toEqual(before);
|
|
expect(result.preview.execution).toBe('preview-only');
|
|
expect(result.preview.policy).toMatchObject({
|
|
selection: { phase: 'train', metric: 'totalReturn', requireAllCandidates: true },
|
|
reset: 'initial-capital-empty-positions',
|
|
});
|
|
for (const phase of ['train', 'validation', 'test'] as const) {
|
|
const slice = result.datasets[phase],
|
|
partition = result.preview.partitions.find(p => p.phase === phase)!;
|
|
expect(validateDatasetV2(slice)).toEqual(slice);
|
|
expect(slice.bars).toEqual(
|
|
dataset.bars.filter(
|
|
b =>
|
|
b.intervalStart >= raw.recipe[phase].warmupStart &&
|
|
b.intervalEnd <= raw.recipe[phase].tradeEnd
|
|
)
|
|
);
|
|
expect(slice.manifest.parentDatasetHash).toBeNull();
|
|
for (const key of [
|
|
'calendars',
|
|
'series',
|
|
'executionSeries',
|
|
'universe',
|
|
'corporateActions',
|
|
] as const) {
|
|
expect(slice.manifest[key]).toEqual(dataset.manifest[key]);
|
|
}
|
|
const expected = structuredClone(preview.request),
|
|
clock = canonicalRiskSessionClock(slice);
|
|
expected.datasetHash = slice.manifest.hash;
|
|
expected.policy.matching.risk.ledger.riskSession = clock.riskSession;
|
|
expected.policy.risk_boundaries = clock.riskBoundaries;
|
|
expect(partition.request).toEqual(expected);
|
|
expect(partition.counts.terminalAtEnd).toBe(1);
|
|
const c = partition.counts;
|
|
expect(c.availableWarmup + c.availableEvaluation + c.terminalAtEnd + c.unavailableAtEnd).toBe(
|
|
c.totalBars
|
|
);
|
|
}
|
|
});
|
|
test('direct slice rejects out-of-source bounds, invalid ordering and every bar-cut boundary', () => {
|
|
const dataset = chronologicalDataset().dataset,
|
|
bounds = input().recipe.train;
|
|
for (const changed of [
|
|
{ ...bounds, warmupStart: bounds.warmupStart - 1 },
|
|
{ ...bounds, tradeStart: dataset.manifest.bounds.tradeStart - 1 },
|
|
{ ...bounds, tradeEnd: dataset.manifest.bounds.tradeEnd + 1 },
|
|
{ ...bounds, warmupStart: bounds.tradeStart + 60_000 },
|
|
{ ...bounds, tradeStart: bounds.tradeEnd },
|
|
{ ...bounds, tradeEnd: bounds.tradeStart - 60_000 },
|
|
...(['warmupStart', 'tradeStart', 'tradeEnd'] as const).map(key => ({
|
|
...bounds,
|
|
[key]: bounds[key] + 1,
|
|
})),
|
|
]) {
|
|
expect(() => sliceDatasetV2(dataset, changed)).toThrow();
|
|
}
|
|
});
|
|
test('later test suffix cannot change earlier datasets, requests or counts; full source identity still changes', () => {
|
|
const raw = input(),
|
|
first = chronologicalDataset().dataset,
|
|
changed = chronologicalDataset(900).dataset;
|
|
const before = prepareChronologicalValidation(raw, source(first, raw), first);
|
|
const after = prepareChronologicalValidation(raw, source(changed, raw), changed);
|
|
expect(after.preview.previewHash).not.toBe(before.preview.previewHash);
|
|
expect(after.datasets.train).toEqual(before.datasets.train);
|
|
expect(after.datasets.validation).toEqual(before.datasets.validation);
|
|
expect(after.preview.partitions.slice(0, 2)).toEqual(before.preview.partitions.slice(0, 2));
|
|
expect(after.datasets.test.manifest.hash).not.toBe(before.datasets.test.manifest.hash);
|
|
});
|
|
test('availability, terminal-only and ignored late warmup counts reflect arrival order without dropping delayed bars', () => {
|
|
const raw = input(),
|
|
dataset = changedAvailability({ 0: 5, 10: 13 });
|
|
const result = prepareChronologicalValidation(raw, source(dataset, raw), dataset);
|
|
expect(result.preview.partitions[0].counts).toEqual({
|
|
totalBars: 12,
|
|
availableWarmup: 5,
|
|
admittedWarmup: 4,
|
|
ignoredLateWarmup: 1,
|
|
availableEvaluation: 5,
|
|
terminalAtEnd: 1,
|
|
unavailableAtEnd: 1,
|
|
});
|
|
expect(result.datasets.train.bars).toHaveLength(12);
|
|
expect(result.preview.partitions[0].warnings).toHaveLength(2);
|
|
const insufficient = changedAvailability({ 0: 5, 1: 5 });
|
|
expect(() =>
|
|
prepareChronologicalValidation(raw, source(insufficient, raw), insufficient)
|
|
).toThrow('3 admitted warmup');
|
|
const unavailable = changedAvailability(
|
|
Object.fromEntries(Array.from({ length: 6 }, (_, i) => [i + 5, 13]))
|
|
);
|
|
expect(() =>
|
|
prepareChronologicalValidation(raw, source(unavailable, raw), unavailable)
|
|
).toThrow('no observations');
|
|
});
|
|
test('SMA readiness uses the largest candidate period and rejects warmup at the exact trading start', () => {
|
|
const dataset = chronologicalDataset().dataset;
|
|
const ready = { ...input(), grid: { fastPeriod: [1], slowPeriod: [3, 4] } };
|
|
expect(
|
|
prepareChronologicalValidation(ready, source(dataset, ready), dataset).preview.partitions[0]
|
|
.requiredWarmup
|
|
).toBe(5);
|
|
const insufficient = { ...ready, grid: { fastPeriod: [1], slowPeriod: [3, 5] } };
|
|
expect(() =>
|
|
prepareChronologicalValidation(insufficient, source(dataset, insufficient), dataset)
|
|
).toThrow('5 admitted warmup observations; 6 required');
|
|
});
|
|
test('mean reversion readiness covers trend, lookback and both return-history periods across the grid', () => {
|
|
const dataset = chronologicalDataset().dataset;
|
|
const parameters = {
|
|
lookbackPeriod: 2,
|
|
trendPeriod: 3,
|
|
momentumPeriod: 1,
|
|
volatilityPeriod: 2,
|
|
entryZScore: 2,
|
|
exitZScore: 1,
|
|
minTrendReturn: 0,
|
|
minMomentumReturn: 0,
|
|
maxVolatility: 1,
|
|
minNotionalVolume: '0',
|
|
regimeFilter: 'volatility',
|
|
};
|
|
for (const [grid, required] of [
|
|
[{ trendPeriod: [3, 5] }, 5],
|
|
[{ momentumPeriod: [1, 4] }, 5],
|
|
[{ volatilityPeriod: [2, 4] }, 5],
|
|
[{ lookbackPeriod: [2, 3], trendPeriod: [4] }, 4],
|
|
] as const) {
|
|
const raw = parseChronologicalValidation({ ...input(), grid });
|
|
expect(
|
|
prepareChronologicalValidation(raw, source(dataset, raw, parameters), dataset).preview
|
|
.partitions[0].requiredWarmup
|
|
).toBe(required);
|
|
}
|
|
for (const grid of [
|
|
{ trendPeriod: [6] },
|
|
{ momentumPeriod: [5] },
|
|
{ volatilityPeriod: [5] },
|
|
{ lookbackPeriod: [6], trendPeriod: [7] },
|
|
]) {
|
|
const raw = parseChronologicalValidation({ ...input(), grid });
|
|
expect(() =>
|
|
prepareChronologicalValidation(raw, source(dataset, raw, parameters), dataset)
|
|
).toThrow('admitted warmup');
|
|
}
|
|
});
|
|
test('sparse calendar gaps remain sparse and each segment receives the exact original clock inclusivity', () => {
|
|
const fixture = nativeReplayFixture(1208),
|
|
dataset = fixture.dataset;
|
|
const sessions = dataset.manifest.calendars[0]!.sessions;
|
|
const raw = input();
|
|
raw.recipe.train = {
|
|
warmupStart: sessions[0]!.open,
|
|
tradeStart: sessions[0]!.open + 6 * fixture.minute,
|
|
tradeEnd: sessions[1]!.open,
|
|
};
|
|
raw.recipe.validation = {
|
|
warmupStart: sessions[1]!.open,
|
|
tradeStart: sessions[1]!.open + 6 * fixture.minute,
|
|
tradeEnd: sessions[2]!.open,
|
|
};
|
|
raw.recipe.test = {
|
|
warmupStart: sessions[2]!.open,
|
|
tradeStart: sessions[2]!.open + 6 * fixture.minute,
|
|
tradeEnd: dataset.manifest.bounds.tradeEnd,
|
|
};
|
|
const result = prepareChronologicalValidation(raw, source(dataset, raw), dataset);
|
|
expect(result.datasets.train.bars).toHaveLength(600);
|
|
expect(result.datasets.validation.bars).toHaveLength(600);
|
|
expect(result.datasets.test.bars).toHaveLength(8);
|
|
const expected = (i: number) => ({
|
|
calendarId: 'fixture-calendar',
|
|
calendarRevision: '1',
|
|
sessionId: sessions[i]!.date,
|
|
startsAt: sessions[i]!.open,
|
|
});
|
|
expect(canonicalRiskSessionClock(dataset)).toEqual({
|
|
riskSession: expected(0),
|
|
riskBoundaries: [expected(1), expected(2)],
|
|
});
|
|
for (const [index, partition] of result.preview.partitions.entries()) {
|
|
expect(partition.request.policy.matching.risk.ledger.riskSession).toEqual(expected(index));
|
|
expect(partition.request.policy.risk_boundaries).toEqual(
|
|
index < 2 ? [expected(index + 1)] : []
|
|
);
|
|
}
|
|
expect(result.preview.partitions[2].warnings).toContain(
|
|
'Only 2 evaluation observations; input readiness does not establish statistical adequacy'
|
|
);
|
|
});
|
|
test('v1 conversion lineage and null VWAP provenance survive slicing without inventing v2 ancestry', () => {
|
|
const fixture = datasetInput();
|
|
const bars = fixture.bars.map(row => ({
|
|
symbol: 'A.US',
|
|
timestamp: Date.parse(String(row.timestamp)),
|
|
open: row.open,
|
|
high: row.high,
|
|
low: row.low,
|
|
close: row.close,
|
|
volume: row.volume,
|
|
vwap: 101,
|
|
}));
|
|
const manifest = {
|
|
version: 1 as const,
|
|
instruments: [{ id: 'A.US', symbol: 'A', exchange: 'US' }],
|
|
startDate: '2024-03-08T00:00:00.000Z',
|
|
endDate: '2024-11-30T00:00:00.000Z',
|
|
interval: '1d',
|
|
policy: { adjustment: 'raw' as const, timestamp: 'utc-session-date' as const },
|
|
volumePolicy: 'reported' as const,
|
|
qualityPolicy: 'reject-invalid-no-interpolation' as const,
|
|
sources: [
|
|
{ instrumentId: 'A.US', provider: 'eod' as const, revision: 'historical-normalization-v1' },
|
|
],
|
|
barCount: bars.length,
|
|
};
|
|
const legacy: HistoricalDataset = {
|
|
manifest: {
|
|
...manifest,
|
|
hash: createHash('sha256').update(JSON.stringify({ manifest, bars })).digest('hex'),
|
|
},
|
|
bars,
|
|
};
|
|
const converted = convertDatasetV1ToV2(legacy, fixture.metadata);
|
|
const bounds = {
|
|
...converted.manifest.bounds,
|
|
tradeEnd: fixture.metadata.calendars[0]!.sessions[1]!.close,
|
|
};
|
|
const slice = sliceDatasetV2(converted, bounds);
|
|
expect(slice.manifest.parentDatasetHash).toBe(legacy.manifest.hash);
|
|
expect(slice.manifest.parentDatasetHash).not.toBe(converted.manifest.hash);
|
|
expect(slice.bars.every(b => b.vwap === null)).toBe(true);
|
|
expect(slice.manifest.limitations).toEqual(converted.manifest.limitations);
|
|
expect(validateDatasetV2(slice)).toEqual(slice);
|
|
});
|
|
test('corrupt source identities fail closed and strict recipe forbids fitting, labels, overlap and unknown fields', () => {
|
|
const dataset = chronologicalDataset().dataset,
|
|
raw = input(),
|
|
preview = source(dataset, raw);
|
|
expect(() =>
|
|
prepareChronologicalValidation({ ...raw, name: 'other' }, preview, dataset)
|
|
).toThrow('identity mismatch');
|
|
const bad = structuredClone(preview);
|
|
bad.candidates[0]!.parameters = {};
|
|
expect(() => prepareChronologicalValidation(raw, bad, dataset)).toThrow('integrity');
|
|
for (const recipe of [
|
|
{ ...raw.recipe, labelHorizonMs: 1 },
|
|
{ ...raw.recipe, fit: true },
|
|
{
|
|
...raw.recipe,
|
|
validation: { ...raw.recipe.validation, tradeStart: raw.recipe.train.tradeEnd - 1 },
|
|
},
|
|
{ ...raw.recipe, train: { ...raw.recipe.train, warmupStart: raw.recipe.train.tradeStart } },
|
|
]) {
|
|
expect(() => parseChronologicalValidation({ ...raw, recipe })).toThrow(
|
|
'Invalid chronological'
|
|
);
|
|
}
|
|
expect(() => parseChronologicalValidation({ ...raw, modelArtifacts: [] })).toThrow();
|
|
const tooMany = {
|
|
...raw,
|
|
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1), slowPeriod: [199] },
|
|
};
|
|
expect(() => source(dataset, tooMany)).toThrow('at most');
|
|
});
|
|
});
|