147 lines
5.6 KiB
TypeScript
147 lines
5.6 KiB
TypeScript
import { z } from 'zod';
|
|
import { at } from '@stock-bot/invariants';
|
|
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
|
import { assertStrategyJsonText } from '@stock-bot/stock-config/strategy';
|
|
import {
|
|
MAX_WALK_FORWARD_RUNS,
|
|
walkForwardFinalizationSchema,
|
|
walkForwardInputSchema,
|
|
walkForwardPolicy,
|
|
walkForwardSubmissionSchema,
|
|
type WalkForwardInput,
|
|
type WalkForwardPreview,
|
|
type WalkForwardReport,
|
|
} from '@stock-bot/stock-config/walk-forward';
|
|
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
|
import {
|
|
buildExperimentPreview,
|
|
ExperimentError,
|
|
experimentHash,
|
|
retainedExperimentPreview,
|
|
} from './experiment-input';
|
|
import { retainedValidationPreview, validationEqual } from './validation-evidence';
|
|
import { prepareChronologicalValidation } from './validation-preview';
|
|
|
|
function parse<T extends z.ZodTypeAny>(schema: T, raw: unknown): z.infer<T> {
|
|
try {
|
|
assertStrategyJsonText(raw);
|
|
return schema.parse(raw);
|
|
} catch {
|
|
throw new ExperimentError(400, 'Invalid walk-forward operation');
|
|
}
|
|
}
|
|
export const parseWalkForwardInput = (raw: unknown): WalkForwardInput =>
|
|
parse(walkForwardInputSchema, raw);
|
|
export const parseWalkForwardSubmission = (raw: unknown) => parse(walkForwardSubmissionSchema, raw);
|
|
export const parseWalkForwardFinalization = (raw: unknown) =>
|
|
parse(walkForwardFinalizationSchema, raw);
|
|
function countsAndChronology(input: WalkForwardInput, candidateCount: number) {
|
|
for (let index = 1; index < input.windows.length; index++) {
|
|
const previous = at(input.windows, index - 1),
|
|
next = at(input.windows, index);
|
|
if (
|
|
next.train.tradeStart < previous.train.tradeStart ||
|
|
next.train.tradeEnd <= previous.train.tradeEnd ||
|
|
previous.test.tradeEnd > next.validation.tradeStart
|
|
) {
|
|
throw new ExperimentError(
|
|
400,
|
|
'Walk-forward training starts must not decrease, cutoffs must increase, and heldout windows cannot overlap'
|
|
);
|
|
}
|
|
}
|
|
const windows = input.windows.length,
|
|
trainingRuns = windows * candidateCount,
|
|
holdoutRuns = windows * 2,
|
|
totalRuns = trainingRuns + holdoutRuns;
|
|
if (totalRuns > MAX_WALK_FORWARD_RUNS) {
|
|
throw new ExperimentError(
|
|
400,
|
|
`Walk-forward may plan at most ${MAX_WALK_FORWARD_RUNS} runs, including all future holdouts`
|
|
);
|
|
}
|
|
return { windows, trainingRuns, holdoutRuns, totalRuns, maxRuns: MAX_WALK_FORWARD_RUNS };
|
|
}
|
|
export function prepareWalkForward(
|
|
raw: WalkForwardInput,
|
|
sourcePreview: ExperimentPreview,
|
|
sourceDataset: HistoricalDatasetV2
|
|
) {
|
|
const input = parseWalkForwardInput(raw),
|
|
source = retainedExperimentPreview(sourcePreview);
|
|
const { windows: recipes, ...sourceInput } = input;
|
|
if (!validationEqual(source.input, sourceInput)) {
|
|
throw new Error('Walk-forward source identity mismatch');
|
|
}
|
|
const counts = countsAndChronology(input, source.candidates.length);
|
|
const prepared = recipes.map((recipe, index) => {
|
|
const windowInput = { ...sourceInput, name: `${input.name} · window ${index + 1}` };
|
|
const windowSource = buildExperimentPreview(windowInput, source.request, source.dataset);
|
|
return prepareChronologicalValidation({ ...windowInput, recipe }, windowSource, sourceDataset);
|
|
});
|
|
const manifest = {
|
|
version: 'walk-forward-preview/v1' as const,
|
|
execution: 'preview-only' as const,
|
|
input,
|
|
source,
|
|
policy: walkForwardPolicy,
|
|
windows: prepared.map((window, index) => ({ index, preview: window.preview })),
|
|
counts,
|
|
};
|
|
const preview: WalkForwardPreview = { ...manifest, previewHash: experimentHash(manifest) };
|
|
return { preview, prepared };
|
|
}
|
|
export function retainedWalkForwardPreview(raw: unknown): WalkForwardPreview {
|
|
const value = raw as WalkForwardPreview,
|
|
{ previewHash, ...manifest } = value;
|
|
if (
|
|
value.version !== 'walk-forward-preview/v1' ||
|
|
value.execution !== 'preview-only' ||
|
|
experimentHash(manifest) !== previewHash
|
|
) {
|
|
throw new Error('Retained walk-forward preparation integrity failure');
|
|
}
|
|
const input = walkForwardInputSchema.parse(value.input),
|
|
source = retainedExperimentPreview(value.source);
|
|
const { windows: recipes, ...sourceInput } = input;
|
|
let counts;
|
|
try {
|
|
counts = countsAndChronology(input, source.candidates.length);
|
|
} catch {
|
|
throw new Error('Retained walk-forward chronology or budget integrity failure');
|
|
}
|
|
if (
|
|
!validationEqual(sourceInput, source.input) ||
|
|
!validationEqual(value.policy, walkForwardPolicy) ||
|
|
!validationEqual(value.counts, counts) ||
|
|
value.windows.length !== recipes.length
|
|
) {
|
|
throw new Error('Retained walk-forward source or budget mismatch');
|
|
}
|
|
for (const [index, window] of value.windows.entries()) {
|
|
const child = retainedValidationPreview(window.preview),
|
|
windowInput = { ...sourceInput, name: `${input.name} · window ${index + 1}` };
|
|
if (
|
|
window.index !== index ||
|
|
!validationEqual(child.input, { ...windowInput, recipe: at(recipes, index) }) ||
|
|
!validationEqual(
|
|
child.source,
|
|
buildExperimentPreview(windowInput, source.request, source.dataset)
|
|
)
|
|
) {
|
|
throw new Error('Retained walk-forward window identity mismatch');
|
|
}
|
|
}
|
|
return value;
|
|
}
|
|
export type StoredWalkForwardReport = WalkForwardReport & {
|
|
_receipt: { key: string; hash: string };
|
|
};
|
|
export function publicWalkForwardReport(value: StoredWalkForwardReport): WalkForwardReport {
|
|
const { _receipt, ...document } = value,
|
|
{ reportHash, ...manifest } = document;
|
|
if (!_receipt || experimentHash(manifest) !== reportHash) {
|
|
throw new Error('Retained walk-forward report integrity failure');
|
|
}
|
|
return document;
|
|
}
|