427 lines
14 KiB
TypeScript
427 lines
14 KiB
TypeScript
import { z } from 'zod';
|
|
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
|
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import {
|
|
MAX_WALK_FORWARD_RUNS,
|
|
MAX_WALK_FORWARD_WINDOWS,
|
|
walkForwardInputSchema,
|
|
walkForwardPolicy,
|
|
type WalkForwardDetail,
|
|
type WalkForwardFinalizationInput,
|
|
type WalkForwardInput,
|
|
type WalkForwardSubmission,
|
|
type WalkForwardSummary,
|
|
} from '@stock-bot/stock-config/walk-forward';
|
|
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
|
import {
|
|
parseChronologicalValidationPreview,
|
|
type ChronologicalValidationPreviewView,
|
|
} from './chronologicalValidationApi';
|
|
import {
|
|
parseValidationDetail,
|
|
validationEvidenceSchema,
|
|
type ValidationDetailView,
|
|
} from './chronologicalValidationDurableApi';
|
|
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
|
|
|
export type WalkForwardPreviewView = {
|
|
version: 'walk-forward-preview/v1';
|
|
execution: 'preview-only';
|
|
previewHash: string;
|
|
input: WalkForwardInput;
|
|
source: ExperimentPreviewView;
|
|
policy: typeof walkForwardPolicy;
|
|
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
|
counts: {
|
|
windows: number;
|
|
trainingRuns: number;
|
|
holdoutRuns: number;
|
|
totalRuns: number;
|
|
maxRuns: number;
|
|
};
|
|
};
|
|
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
|
preview: WalkForwardPreviewView;
|
|
windows: {
|
|
index: number;
|
|
validationId: string;
|
|
status: 'admitted' | 'missing';
|
|
validation: ValidationDetailView | null;
|
|
}[];
|
|
};
|
|
export class WalkForwardApiError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly status: number | null
|
|
) {
|
|
super(message);
|
|
}
|
|
get ambiguous() {
|
|
return this.status === null || this.status >= 500;
|
|
}
|
|
}
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
|
uuid = z.string().uuid(),
|
|
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
const same = (left: unknown, right: unknown) =>
|
|
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
|
const invalid = () =>
|
|
new WalkForwardApiError(
|
|
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
|
null
|
|
);
|
|
const prepared = z.object({
|
|
version: z.literal('walk-forward-preview/v1'),
|
|
execution: z.literal('preview-only'),
|
|
previewHash: hash,
|
|
input: walkForwardInputSchema,
|
|
source: z.unknown(),
|
|
policy: z.unknown(),
|
|
windows: z
|
|
.array(z.object({ index: count, preview: z.unknown() }))
|
|
.min(2)
|
|
.max(MAX_WALK_FORWARD_WINDOWS),
|
|
counts: z.object({
|
|
windows: count,
|
|
trainingRuns: count,
|
|
holdoutRuns: count,
|
|
totalRuns: count,
|
|
maxRuns: count,
|
|
}),
|
|
});
|
|
export function parseWalkForwardPreview(
|
|
raw: unknown,
|
|
expected?: WalkForwardInput
|
|
): WalkForwardPreviewView {
|
|
const value = prepared.parse(raw),
|
|
source = parseExperimentPreview(value.source);
|
|
const { windows: recipes, ...sourceInput } = value.input;
|
|
const size = recipes.length,
|
|
candidates = source.candidates.length;
|
|
if (
|
|
(expected && !same(value.input, expected)) ||
|
|
!same(source.input, sourceInput) ||
|
|
!same(value.policy, walkForwardPolicy) ||
|
|
value.windows.length !== size ||
|
|
!same(value.counts, {
|
|
windows: size,
|
|
trainingRuns: size * candidates,
|
|
holdoutRuns: size * 2,
|
|
totalRuns: size * (candidates + 2),
|
|
maxRuns: MAX_WALK_FORWARD_RUNS,
|
|
}) ||
|
|
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
|
) {
|
|
throw invalid();
|
|
}
|
|
const windows = value.windows.map((item, index) => {
|
|
const recipe = recipes[index],
|
|
previous = recipes[index - 1];
|
|
if (
|
|
!recipe ||
|
|
item.index !== index ||
|
|
(previous &&
|
|
(recipe.train.tradeStart < previous.train.tradeStart ||
|
|
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
|
recipe.validation.tradeStart < previous.test.tradeEnd))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
const name = `${value.input.name} · window ${index + 1}`;
|
|
const preview = parseChronologicalValidationPreview(
|
|
{ preview: item.preview },
|
|
{ ...sourceInput, name, recipe }
|
|
);
|
|
const { previewHash: _windowHash, ...childSource } = preview.source;
|
|
const { previewHash: _sourceHash, ...originalSource } = source;
|
|
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
|
throw invalid();
|
|
}
|
|
return { index, preview };
|
|
});
|
|
return { ...value, source, windows, policy: walkForwardPolicy };
|
|
}
|
|
const summary = z
|
|
.object({
|
|
id: uuid,
|
|
backtestId: uuid,
|
|
name: z.string().min(1),
|
|
previewHash: hash,
|
|
createdAt: z.string().min(1),
|
|
cancelRequested: z.boolean(),
|
|
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
|
reportedWindowCount: count,
|
|
trainingRunCount: count,
|
|
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
|
stage: z.enum(['windows', 'reported']),
|
|
})
|
|
.superRefine((item, context) => {
|
|
if (
|
|
item.reportedWindowCount > item.windowCount ||
|
|
item.trainingRunCount < item.windowCount ||
|
|
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
|
) {
|
|
context.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
message: 'Inconsistent walk-forward counts',
|
|
});
|
|
}
|
|
});
|
|
const report = z.object({
|
|
version: z.literal('walk-forward-report/v1'),
|
|
id: uuid,
|
|
walkForwardId: uuid,
|
|
previewHash: hash,
|
|
reportHash: hash,
|
|
createdAt: z.string().min(1),
|
|
principal: researchActorSchema,
|
|
reset: z.literal('initial-capital-empty-positions'),
|
|
segments: z
|
|
.array(
|
|
z.object({
|
|
index: count,
|
|
validationId: uuid,
|
|
previewHash: hash,
|
|
selectionHash: hash,
|
|
reportId: uuid,
|
|
reportHash: hash,
|
|
validation: validationEvidenceSchema,
|
|
test: validationEvidenceSchema,
|
|
})
|
|
)
|
|
.min(2)
|
|
.max(MAX_WALK_FORWARD_WINDOWS),
|
|
limitations: z.array(z.string()),
|
|
});
|
|
const detail = z.object({
|
|
preview: z.unknown(),
|
|
windows: z.array(
|
|
z.object({
|
|
index: count,
|
|
validationId: uuid,
|
|
status: z.enum(['admitted', 'missing']),
|
|
validation: z.unknown(),
|
|
})
|
|
),
|
|
report: report.nullable(),
|
|
actions: z.object({
|
|
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
|
}),
|
|
});
|
|
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
|
const base = summary.parse(raw),
|
|
value = detail.parse(raw),
|
|
preview = parseWalkForwardPreview(value.preview);
|
|
if (
|
|
base.backtestId !== preview.input.backtestId ||
|
|
base.name !== preview.input.name ||
|
|
base.previewHash !== preview.previewHash ||
|
|
base.windowCount !== preview.counts.windows ||
|
|
base.trainingRunCount !== preview.counts.trainingRuns ||
|
|
base.plannedRunCount !== preview.counts.totalRuns ||
|
|
value.windows.length !== base.windowCount ||
|
|
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
|
(base.stage === 'reported') !== (value.report !== null)
|
|
) {
|
|
throw invalid();
|
|
}
|
|
const windows = value.windows.map((item, index) => {
|
|
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
|
throw invalid();
|
|
}
|
|
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
|
if (
|
|
validation &&
|
|
(validation.id !== item.validationId ||
|
|
validation.backtestId !== base.backtestId ||
|
|
!same(validation.preview, preview.windows[index]?.preview))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
return { ...item, validation };
|
|
});
|
|
if (
|
|
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
|
(value.actions.finalize.available &&
|
|
(base.cancelRequested ||
|
|
value.report ||
|
|
windows.some(
|
|
item =>
|
|
!item.validation?.report ||
|
|
item.validation.cancelRequested ||
|
|
item.validation.phases.some(
|
|
phase =>
|
|
phase.status !== 'admitted' ||
|
|
!phase.experiment ||
|
|
phase.experiment.cancelRequested ||
|
|
phase.experiment.trials.some(
|
|
trial =>
|
|
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
|
)
|
|
)
|
|
)))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
if (value.report) {
|
|
const saved = value.report;
|
|
if (
|
|
saved.walkForwardId !== base.id ||
|
|
saved.previewHash !== base.previewHash ||
|
|
saved.segments.length !== base.windowCount
|
|
) {
|
|
throw invalid();
|
|
}
|
|
for (const [index, segment] of saved.segments.entries()) {
|
|
const member = windows[index],
|
|
frozen = preview.windows[index]?.preview,
|
|
child = member?.validation?.report;
|
|
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
|
if (
|
|
!member ||
|
|
!frozen ||
|
|
!candidate ||
|
|
segment.index !== index ||
|
|
segment.validationId !== member.validationId ||
|
|
segment.previewHash !== frozen.previewHash ||
|
|
segment.validation.phase !== 'validation' ||
|
|
segment.test.phase !== 'test' ||
|
|
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
|
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
|
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
|
[segment.validation, segment.test].some(
|
|
item =>
|
|
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
|
) ||
|
|
(member.validation &&
|
|
(!child ||
|
|
segment.reportId !== child.id ||
|
|
segment.reportHash !== child.reportHash ||
|
|
segment.selectionHash !== child.selectionHash ||
|
|
!same(segment.validation, child.validation) ||
|
|
!same(segment.test, child.test)))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
}
|
|
}
|
|
return { ...base, ...value, preview, windows };
|
|
}
|
|
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
|
async function request<T>(
|
|
path: string,
|
|
init: RequestInit,
|
|
status: number,
|
|
parse: (body: unknown) => T
|
|
): Promise<T> {
|
|
let response: Response;
|
|
try {
|
|
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, init);
|
|
} catch (cause) {
|
|
if (init.signal?.aborted) {
|
|
throw cause;
|
|
}
|
|
throw new WalkForwardApiError(
|
|
'The walk-forward response was lost. Retry the same request to recover its receipt.',
|
|
null
|
|
);
|
|
}
|
|
const body: unknown = await response.json().catch(() => null);
|
|
if (!response.ok) {
|
|
const error = z.object({ error: z.string() }).safeParse(body);
|
|
throw new WalkForwardApiError(
|
|
error.success ? error.data.error : `Walk-forward request failed (${response.status})`,
|
|
response.status
|
|
);
|
|
}
|
|
try {
|
|
if (response.status !== status) {
|
|
throw invalid();
|
|
}
|
|
return parse(body);
|
|
} catch {
|
|
throw invalid();
|
|
}
|
|
}
|
|
const post = (body: unknown, key?: string): RequestInit => ({
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
|
});
|
|
export const walkForwardApi = {
|
|
preview: (input: WalkForwardInput, signal?: AbortSignal) =>
|
|
request('/preview', { ...post(input), signal }, 200, body =>
|
|
parseWalkForwardPreview(envelope(body, 'preview'), input)
|
|
),
|
|
list: (backtestId?: string, signal?: AbortSignal) =>
|
|
request(
|
|
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
|
|
{ signal },
|
|
200,
|
|
body => {
|
|
const rows = z.array(summary).parse(envelope(body, 'walkForwards'));
|
|
if (
|
|
new Set(rows.map(item => item.id)).size !== rows.length ||
|
|
(backtestId && rows.some(item => item.backtestId !== backtestId))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
return rows as WalkForwardSummary[];
|
|
}
|
|
),
|
|
get: (id: string, signal?: AbortSignal) =>
|
|
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
|
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
|
if (value.id !== id) {
|
|
throw invalid();
|
|
}
|
|
return value;
|
|
}),
|
|
submit: (input: WalkForwardSubmission, key: string) =>
|
|
request('', post(input, key), 202, body => {
|
|
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
|
const { previewHash, ...original } = input;
|
|
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
|
throw invalid();
|
|
}
|
|
return value;
|
|
}),
|
|
finalize: (id: string, input: WalkForwardFinalizationInput, key: string) =>
|
|
request(`/${encodeURIComponent(id)}/finalize`, post(input, key), 202, body => {
|
|
const accepted = z
|
|
.object({
|
|
id: uuid,
|
|
walkForwardId: uuid,
|
|
operation: z.literal('finalize-walk-forward-report'),
|
|
previewHash: hash,
|
|
reportHash: hash,
|
|
createdAt: z.string().min(1),
|
|
principal: researchActorSchema,
|
|
})
|
|
.parse(envelope(body, 'receipt'));
|
|
const value = parseWalkForwardDetail(envelope(body, 'walkForward')),
|
|
saved = value.report;
|
|
if (
|
|
value.id !== id ||
|
|
accepted.walkForwardId !== id ||
|
|
value.previewHash !== input.previewHash ||
|
|
accepted.previewHash !== input.previewHash ||
|
|
!saved ||
|
|
accepted.id !== saved.id ||
|
|
accepted.reportHash !== saved.reportHash ||
|
|
accepted.createdAt !== saved.createdAt ||
|
|
accepted.principal !== saved.principal
|
|
) {
|
|
throw invalid();
|
|
}
|
|
return { receipt: accepted, walkForward: value };
|
|
}),
|
|
cancel: (id: string) =>
|
|
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
|
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
|
if (value.id !== id || !value.cancelRequested) {
|
|
throw invalid();
|
|
}
|
|
return value;
|
|
}),
|
|
};
|