feat(research): add durable walk-forward validation workflows
This commit is contained in:
parent
abd1c5b83d
commit
3ed7b98f7c
45 changed files with 5188 additions and 199 deletions
|
|
@ -36,6 +36,10 @@
|
|||
"./chronological-validation": {
|
||||
"types": "./dist/contracts/chronological-validation.d.ts",
|
||||
"default": "./dist/contracts/chronological-validation.js"
|
||||
},
|
||||
"./walk-forward": {
|
||||
"types": "./dist/contracts/walk-forward.d.ts",
|
||||
"default": "./dist/contracts/walk-forward.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
115
apps/stock/config/src/contracts/walk-forward.ts
Normal file
115
apps/stock/config/src/contracts/walk-forward.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/** A bounded collection of existing chronological validations, not a new execution engine. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationDetail,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationActionCapability,
|
||||
type ValidationResultEvidence,
|
||||
} from './chronological-validation';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentPreview,
|
||||
} from './experiments';
|
||||
|
||||
export const MAX_WALK_FORWARD_WINDOWS = 10;
|
||||
/** Includes training and both future holdouts for every window. */
|
||||
export const MAX_WALK_FORWARD_RUNS = MAX_EXPERIMENT_TRIALS;
|
||||
export const walkForwardInputSchema = experimentInputSchema.extend({
|
||||
windows: z
|
||||
.array(chronologicalValidationInputSchema.shape.recipe)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
});
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
export const walkForwardSubmissionSchema = walkForwardInputSchema.extend({ previewHash: hash });
|
||||
export const walkForwardFinalizationSchema = z.object({ previewHash: hash }).strict();
|
||||
export type WalkForwardInput = z.infer<typeof walkForwardInputSchema>;
|
||||
export type WalkForwardSubmission = z.infer<typeof walkForwardSubmissionSchema>;
|
||||
export type WalkForwardFinalizationInput = z.infer<typeof walkForwardFinalizationSchema>;
|
||||
|
||||
export const walkForwardPolicy = {
|
||||
selection: 'independent-training-winner-per-window',
|
||||
training: 'nondecreasing-start-strictly-increasing-cutoff',
|
||||
holdouts: 'previous-test-end-at-or-before-next-validation-start',
|
||||
reset: 'initial-capital-empty-positions',
|
||||
reporting: 'ordered-independent-reset-segments',
|
||||
} as const;
|
||||
export interface WalkForwardPreview {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreview;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreview }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
}
|
||||
export interface WalkForwardSegment {
|
||||
index: number;
|
||||
validationId: string;
|
||||
previewHash: string;
|
||||
selectionHash: string;
|
||||
reportId: string;
|
||||
reportHash: string;
|
||||
/** Copied diagnostic and test results, never a compounded portfolio. */
|
||||
validation: ValidationResultEvidence;
|
||||
test: ValidationResultEvidence;
|
||||
}
|
||||
export interface WalkForwardReport {
|
||||
version: 'walk-forward-report/v1';
|
||||
id: string;
|
||||
walkForwardId: string;
|
||||
previewHash: string;
|
||||
reportHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
reset: 'initial-capital-empty-positions';
|
||||
/** Every frozen window in ascending index; absent evidence cannot be omitted. */
|
||||
segments: WalkForwardSegment[];
|
||||
limitations: string[];
|
||||
}
|
||||
export interface WalkForwardSummary {
|
||||
id: string;
|
||||
backtestId: string;
|
||||
name: string;
|
||||
previewHash: string;
|
||||
createdAt: string;
|
||||
cancelRequested: boolean;
|
||||
windowCount: number;
|
||||
reportedWindowCount: number;
|
||||
trainingRunCount: number;
|
||||
plannedRunCount: number;
|
||||
stage: 'windows' | 'reported';
|
||||
}
|
||||
export interface WalkForwardDetail extends WalkForwardSummary {
|
||||
preview: WalkForwardPreview;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ChronologicalValidationDetail | null;
|
||||
}[];
|
||||
report: WalkForwardReport | null;
|
||||
actions: { finalize: ValidationActionCapability };
|
||||
}
|
||||
export interface WalkForwardReceipt {
|
||||
id: string;
|
||||
walkForwardId: string;
|
||||
operation: 'finalize-walk-forward-report';
|
||||
previewHash: string;
|
||||
reportHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
}
|
||||
export interface WalkForwardActionResult {
|
||||
receipt: WalkForwardReceipt;
|
||||
walkForward: WalkForwardDetail;
|
||||
}
|
||||
|
|
@ -64,7 +64,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '21-run-reproduction.sql' ||
|
||||
f === '22-experiments.sql' ||
|
||||
f === '23-experiment-retries.sql' ||
|
||||
f === '24-chronological-validation.sql')
|
||||
f === '24-chronological-validation.sql' ||
|
||||
f === '25-walk-forward.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -19,12 +19,19 @@ import {
|
|||
parseValidationSubmission,
|
||||
} from '../services/validation-evidence';
|
||||
import { parseChronologicalValidation } from '../services/validation-preview';
|
||||
import {
|
||||
parseWalkForwardFinalization,
|
||||
parseWalkForwardInput,
|
||||
parseWalkForwardSubmission,
|
||||
} from '../services/walk-forward-input';
|
||||
import { WalkForwardService } from '../services/walk-forward.service';
|
||||
|
||||
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
|
||||
export function createExperimentRoutes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const service = new ExperimentsService(container);
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const walkForwards = new WalkForwardService(container);
|
||||
const logger = getLogger('experiments-api');
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
@ -50,6 +57,54 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
throw new ExperimentError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
||||
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/walk-forward', async c => {
|
||||
const input = parseWalkForwardSubmission(await body(c.req.raw));
|
||||
const walkForward = await walkForwards.submit(
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
);
|
||||
c.header('Location', `/api/v2/experiments/walk-forward/${walkForward.id}`);
|
||||
return c.json({ walkForward }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments/walk-forward', async c =>
|
||||
c.json({ walkForwards: await walkForwards.list(c.req.query('backtestId')) })
|
||||
);
|
||||
app.get('/api/v2/experiments/walk-forward/:id', async c =>
|
||||
c.json({ walkForward: await walkForwards.get(experimentId(c.req.param('id'))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/walk-forward/:id/finalize', async c => {
|
||||
const id = experimentId(c.req.param('id')),
|
||||
input = parseWalkForwardFinalization(await body(c.req.raw));
|
||||
return c.json(
|
||||
await walkForwards.finalize(
|
||||
id,
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
),
|
||||
202
|
||||
);
|
||||
});
|
||||
app.post('/api/v2/experiments/walk-forward/:id/cancel', async c => {
|
||||
const id = experimentId(c.req.param('id'));
|
||||
if (
|
||||
!z
|
||||
.object({})
|
||||
.strict()
|
||||
.safeParse(await body(c.req.raw)).success
|
||||
) {
|
||||
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
||||
}
|
||||
return c.json({ walkForward: await walkForwards.cancel(id) });
|
||||
});
|
||||
app.post('/api/v2/experiments/validation/preview', async c => {
|
||||
const input = parseChronologicalValidation(await body(c.req.raw));
|
||||
return c.json({ preview: await service.previewValidation(input) });
|
||||
|
|
|
|||
|
|
@ -126,48 +126,68 @@ export class ChronologicalValidationService {
|
|||
'Validation preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
for (const dataset of Object.values(prepared.datasets)) {
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
|
||||
[dataset.manifest.hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = (
|
||||
await client.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
dataset.manifest.hash,
|
||||
])
|
||||
).rows[0];
|
||||
if (!saved || !validationEqual(validateDatasetV2(saved.payload), dataset)) {
|
||||
throw new Error('Retained validation slice identity mismatch');
|
||||
}
|
||||
}
|
||||
const id = randomUUID(),
|
||||
train = validationPhasePreview(prepared.preview, 'train');
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'train') ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
id,
|
||||
input.backtestId,
|
||||
train.input.name,
|
||||
train,
|
||||
train.previewHash,
|
||||
identity.principal,
|
||||
identity.key,
|
||||
hash,
|
||||
prepared.preview,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const id = randomUUID();
|
||||
const inserted = await this.admitPrepared(client, prepared, { id, ...identity, hash });
|
||||
if (!inserted) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent validation receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await this.insertRuns(client, id, train);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
/** Caller owns the parent lock and transaction; no nested transaction or eligibility shortcut. */
|
||||
async admitPrepared(
|
||||
client: PoolClient,
|
||||
prepared: ReturnType<typeof prepareChronologicalValidation>,
|
||||
identity: {
|
||||
id: string;
|
||||
principal: 'operator' | 'service';
|
||||
key: string;
|
||||
hash: string;
|
||||
membership?: { id: string; index: number };
|
||||
}
|
||||
): Promise<boolean> {
|
||||
for (const dataset of Object.values(prepared.datasets)) {
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
|
||||
[dataset.manifest.hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = (
|
||||
await client.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
dataset.manifest.hash,
|
||||
])
|
||||
).rows[0];
|
||||
if (!saved || !validationEqual(validateDatasetV2(saved.payload), dataset)) {
|
||||
throw new Error('Retained validation slice identity mismatch');
|
||||
}
|
||||
}
|
||||
const train = validationPhasePreview(prepared.preview, 'train');
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase,walk_forward_id,walk_forward_index)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'train',$10,$11) ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
identity.id,
|
||||
prepared.preview.input.backtestId,
|
||||
train.input.name,
|
||||
train,
|
||||
train.previewHash,
|
||||
identity.principal,
|
||||
identity.key,
|
||||
identity.hash,
|
||||
prepared.preview,
|
||||
identity.membership?.id ?? null,
|
||||
identity.membership?.index ?? null,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
return false;
|
||||
}
|
||||
await this.insertRuns(client, identity.id, train);
|
||||
return true;
|
||||
}
|
||||
async list(backtestId?: string): Promise<ChronologicalValidationSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
|
|
@ -368,43 +388,10 @@ export class ChronologicalValidationService {
|
|||
) {
|
||||
throw new ExperimentError(409, 'Validation or selection identity changed');
|
||||
}
|
||||
for (const childId of [
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query('SELECT id FROM research_experiments WHERE id=$1 FOR UPDATE', [childId]);
|
||||
}
|
||||
for (const experimentId of [
|
||||
const { training, validation, test } = await this.verifySelectionEvidence(
|
||||
client,
|
||||
id,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query(
|
||||
'SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index FOR UPDATE',
|
||||
[experimentId]
|
||||
);
|
||||
}
|
||||
const training = await this.evidence(client, id, 'train');
|
||||
if (!validationEqual(training, selection.training)) {
|
||||
throw new ExperimentError(409, 'Training evidence differs from the frozen selection');
|
||||
}
|
||||
const validation = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
'validation',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
const test = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.test,
|
||||
'test',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
selection
|
||||
);
|
||||
const manifest = {
|
||||
version: 'chronological-validation-report/v1' as const,
|
||||
|
|
@ -442,6 +429,97 @@ export class ChronologicalValidationService {
|
|||
return { receipt: receipt(report, operation), validation: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async verifySelectionEvidence(
|
||||
client: PoolClient,
|
||||
id: string,
|
||||
selection: ChronologicalValidationSelection
|
||||
) {
|
||||
for (const childId of [
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query('SELECT id FROM research_experiments WHERE id=$1 FOR UPDATE', [childId]);
|
||||
}
|
||||
for (const experimentId of [
|
||||
id,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query(
|
||||
'SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index FOR UPDATE',
|
||||
[experimentId]
|
||||
);
|
||||
}
|
||||
const training = await this.evidence(client, id, 'train');
|
||||
if (!validationEqual(training, selection.training)) {
|
||||
throw new ExperimentError(409, 'Training evidence differs from the frozen selection');
|
||||
}
|
||||
const validation = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
'validation',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
const test = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.test,
|
||||
'test',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
return { training, validation, test };
|
||||
}
|
||||
/** Re-verifies every native result behind an immutable member report; no current execution gates. */
|
||||
async verifiedSealedReport(
|
||||
client: PoolClient,
|
||||
id: string
|
||||
): Promise<ChronologicalValidationReport> {
|
||||
const root = (
|
||||
await client.query(
|
||||
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR UPDATE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!root || root.cancel_requested || !root.validation_selection || !root.validation_report) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Every walk-forward member needs an uncancelled sealed validation report'
|
||||
);
|
||||
}
|
||||
const preview = retainedValidationPreview(root.validation_manifest);
|
||||
const selection = publicValidationDocument<ChronologicalValidationSelection>(
|
||||
root.validation_selection,
|
||||
'selectionHash'
|
||||
);
|
||||
const report = publicValidationDocument<ChronologicalValidationReport>(
|
||||
root.validation_report,
|
||||
'reportHash'
|
||||
);
|
||||
if (
|
||||
report.validationId !== id ||
|
||||
report.previewHash !== preview.previewHash ||
|
||||
report.selectionHash !== selection.selectionHash
|
||||
) {
|
||||
throw new Error('Retained member report identity mismatch');
|
||||
}
|
||||
const evidence = await this.verifySelectionEvidence(client, id, selection);
|
||||
if (
|
||||
!validationEqual(evidence.training, report.training) ||
|
||||
!validationEqual(evidence.validation, report.validation) ||
|
||||
!validationEqual(evidence.test, report.test)
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Retained member report differs from its verified financial evidence'
|
||||
);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
private async lockRoot(client: PoolClient, id: string) {
|
||||
const parent = (
|
||||
await client.query(
|
||||
|
|
@ -581,7 +659,7 @@ export class ChronologicalValidationService {
|
|||
}
|
||||
return evidence;
|
||||
}
|
||||
private async readDetail(client: PoolClient, id: string): Promise<ChronologicalValidationDetail> {
|
||||
async readDetail(client: PoolClient, id: string): Promise<ChronologicalValidationDetail> {
|
||||
const row = (
|
||||
await client.query(
|
||||
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR SHARE",
|
||||
|
|
|
|||
147
apps/stock/web-api/src/services/walk-forward-input.ts
Normal file
147
apps/stock/web-api/src/services/walk-forward-input.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
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;
|
||||
}
|
||||
398
apps/stock/web-api/src/services/walk-forward.service.ts
Normal file
398
apps/stock/web-api/src/services/walk-forward.service.ts
Normal file
|
|
@ -0,0 +1,398 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type {
|
||||
WalkForwardActionResult,
|
||||
WalkForwardDetail,
|
||||
WalkForwardReceipt,
|
||||
WalkForwardReport,
|
||||
WalkForwardSegment,
|
||||
WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import { ChronologicalValidationService } from './chronological-validation.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
} from './experiment-input';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import { validationEqual } from './validation-evidence';
|
||||
import {
|
||||
parseWalkForwardFinalization,
|
||||
parseWalkForwardInput,
|
||||
parseWalkForwardSubmission,
|
||||
prepareWalkForward,
|
||||
publicWalkForwardReport,
|
||||
retainedWalkForwardPreview,
|
||||
type StoredWalkForwardReport,
|
||||
} from './walk-forward-input';
|
||||
|
||||
type Actor = { principal: string; key: string };
|
||||
const summary = (row: QueryResultRow, reported: number): WalkForwardSummary => ({
|
||||
id: row.id,
|
||||
backtestId: row.backtest_id,
|
||||
name: row.name,
|
||||
previewHash: row.preview_hash,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
cancelRequested: row.cancel_requested,
|
||||
windowCount: row.preview.counts.windows,
|
||||
reportedWindowCount: reported,
|
||||
trainingRunCount: row.preview.counts.trainingRuns,
|
||||
plannedRunCount: row.preview.counts.totalRuns,
|
||||
stage: row.report ? 'reported' : 'windows',
|
||||
});
|
||||
function checkedHeader(row: QueryResultRow) {
|
||||
const preview = retainedWalkForwardPreview(row.preview);
|
||||
if (
|
||||
preview.previewHash !== row.preview_hash ||
|
||||
preview.input.backtestId !== row.backtest_id ||
|
||||
preview.input.name !== row.name ||
|
||||
!Array.isArray(row.member_ids) ||
|
||||
row.member_ids.length !== preview.windows.length ||
|
||||
new Set(row.member_ids).size !== row.member_ids.length
|
||||
) {
|
||||
throw new Error('Retained walk-forward header identity mismatch');
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
const receipt = (report: WalkForwardReport): WalkForwardReceipt => ({
|
||||
id: report.id,
|
||||
walkForwardId: report.walkForwardId,
|
||||
operation: 'finalize-walk-forward-report',
|
||||
previewHash: report.previewHash,
|
||||
reportHash: report.reportHash,
|
||||
createdAt: report.createdAt,
|
||||
principal: report.principal,
|
||||
});
|
||||
/** Grouped immutable validations; existing workers and per-window controls execute every run. */
|
||||
export class WalkForwardService {
|
||||
private readonly database;
|
||||
private readonly experiments;
|
||||
private readonly validations;
|
||||
constructor(container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.experiments = new ExperimentsService(container);
|
||||
this.validations = new ChronologicalValidationService(container);
|
||||
}
|
||||
async preview(raw: unknown) {
|
||||
const input = parseWalkForwardInput(raw);
|
||||
return this.database.transaction(async client => (await this.prepare(client, input)).preview);
|
||||
}
|
||||
private async prepare(client: PoolClient, input: ReturnType<typeof parseWalkForwardInput>) {
|
||||
const { windows: _windows, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
return prepareWalkForward(input, source, dataset);
|
||||
}
|
||||
async submit(raw: unknown, actor: Actor): Promise<WalkForwardDetail> {
|
||||
const submission = parseWalkForwardSubmission(raw),
|
||||
identity = experimentReceipt(actor),
|
||||
{ previewHash, ...input } = submission;
|
||||
const hash = experimentHash({ version: 1, operation: 'submit-walk-forward', submission });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'SELECT id,submission_hash FROM research_walk_forwards WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.submission_hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different walk-forward submission'
|
||||
);
|
||||
}
|
||||
return this.readDetail(client, row.id);
|
||||
};
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const prepared = await this.prepare(client, input);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Walk-forward preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
const id = randomUUID(),
|
||||
memberIds = prepared.prepared.map(() => randomUUID());
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_walk_forwards(id,backtest_id,name,preview,preview_hash,member_ids,submission_principal,submission_key,submission_hash)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
id,
|
||||
input.backtestId,
|
||||
input.name,
|
||||
prepared.preview,
|
||||
previewHash,
|
||||
memberIds,
|
||||
identity.principal,
|
||||
identity.key,
|
||||
hash,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent walk-forward receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
for (const [index, member] of prepared.prepared.entries()) {
|
||||
const memberId = at(memberIds, index);
|
||||
const accepted = await this.validations.admitPrepared(client, member, {
|
||||
id: memberId,
|
||||
principal: identity.principal,
|
||||
key: `walk-forward-member:${id}:${index}`,
|
||||
hash: experimentHash({
|
||||
version: 1,
|
||||
walkForwardId: id,
|
||||
index,
|
||||
validationId: memberId,
|
||||
previewHash: member.preview.previewHash,
|
||||
}),
|
||||
membership: { id, index },
|
||||
});
|
||||
if (!accepted) {
|
||||
throw new Error('Walk-forward member receipt unexpectedly exists');
|
||||
}
|
||||
}
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<WalkForwardSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT w.*,(SELECT count(*)::int FROM research_experiments e WHERE e.walk_forward_id=w.id AND e.validation_report IS NOT NULL) AS reported
|
||||
FROM research_walk_forwards w ${backtestId === undefined ? '' : 'WHERE w.backtest_id=$1'} ORDER BY w.created_at DESC,w.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(row => {
|
||||
checkedHeader(row);
|
||||
return summary(row, Number(row.reported));
|
||||
});
|
||||
}
|
||||
async get(id: string): Promise<WalkForwardDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(client => this.readDetail(client, id));
|
||||
}
|
||||
async cancel(id: string): Promise<WalkForwardDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
await this.lockHeader(client, id);
|
||||
await client.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [
|
||||
id,
|
||||
]);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async finalize(id: string, raw: unknown, actor: Actor): Promise<WalkForwardActionResult> {
|
||||
experimentId(id);
|
||||
const input = parseWalkForwardFinalization(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: 'finalize-walk-forward-report',
|
||||
walkForwardId: id,
|
||||
input,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
"SELECT id,report FROM research_walk_forwards WHERE report->>'principal'=$1 AND report#>>'{_receipt,key}'=$2",
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.report._receipt.hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different walk-forward finalization'
|
||||
);
|
||||
}
|
||||
const report = publicWalkForwardReport(row.report);
|
||||
return { receipt: receipt(report), walkForward: await this.readDetail(client, row.id) };
|
||||
};
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
const row = await this.lockHeader(client, id);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (row.report) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Walk-forward report is already sealed under another receipt'
|
||||
);
|
||||
}
|
||||
const preview = checkedHeader(row);
|
||||
if (input.previewHash !== preview.previewHash) {
|
||||
throw new ExperimentError(409, 'Walk-forward preparation identity changed');
|
||||
}
|
||||
if (row.cancel_requested) {
|
||||
throw new ExperimentError(409, 'Walk-forward validation is cancelled');
|
||||
}
|
||||
const members = await this.members(client, row, 'UPDATE');
|
||||
const segments: WalkForwardSegment[] = [];
|
||||
for (const [index, memberId] of (row.member_ids as string[]).entries()) {
|
||||
const member = members.find(m => m.id === memberId && m.walk_forward_index === index);
|
||||
if (!member) {
|
||||
throw new ExperimentError(409, 'Expected walk-forward member is missing');
|
||||
}
|
||||
const report = await this.validations.verifiedSealedReport(client, memberId);
|
||||
segments.push({
|
||||
index,
|
||||
validationId: memberId,
|
||||
previewHash: at(preview.windows, index).preview.previewHash,
|
||||
selectionHash: report.selectionHash,
|
||||
reportId: report.id,
|
||||
reportHash: report.reportHash,
|
||||
validation: report.validation,
|
||||
test: report.test,
|
||||
});
|
||||
}
|
||||
const manifest = {
|
||||
version: 'walk-forward-report/v1' as const,
|
||||
id: randomUUID(),
|
||||
walkForwardId: id,
|
||||
previewHash: preview.previewHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: identity.principal,
|
||||
reset: 'initial-capital-empty-positions' as const,
|
||||
segments,
|
||||
limitations: [
|
||||
'Every window and phase starts with its declared initial capital and empty positions. These are independent reset segments, not a continuous portfolio.',
|
||||
'Training may include earlier historical holdouts; each frozen selection reads only its own training evidence. This does not certify globally unseen data.',
|
||||
'No compounded return, combined equity curve or averaged risk-adjusted metric is implied. Completed execution is not proof of profitability or statistical adequacy.',
|
||||
],
|
||||
};
|
||||
const report: WalkForwardReport = { ...manifest, reportHash: experimentHash(manifest) };
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
||||
`walk-forward-finalize:${identity.principal}:${identity.key}`,
|
||||
]);
|
||||
const race = await replay();
|
||||
if (race) {
|
||||
return race;
|
||||
}
|
||||
const stored: StoredWalkForwardReport = { ...report, _receipt: { key: identity.key, hash } };
|
||||
await client.query('UPDATE research_walk_forwards SET report=$2 WHERE id=$1', [id, stored]);
|
||||
return { receipt: receipt(report), walkForward: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async lockHeader(client: PoolClient, id: string) {
|
||||
const parent = (
|
||||
await client.query(
|
||||
'SELECT id FROM backtests WHERE id=(SELECT backtest_id FROM research_walk_forwards WHERE id=$1) FOR UPDATE',
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Walk-forward validation not found');
|
||||
}
|
||||
const row = (
|
||||
await client.query('SELECT * FROM research_walk_forwards WHERE id=$1 FOR UPDATE', [id])
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Walk-forward validation not found');
|
||||
}
|
||||
return row;
|
||||
}
|
||||
private async members(client: PoolClient, row: QueryResultRow, lock: 'SHARE' | 'UPDATE') {
|
||||
const members = (
|
||||
await client.query(
|
||||
`SELECT * FROM research_experiments WHERE walk_forward_id=$1 ORDER BY walk_forward_index FOR ${lock}`,
|
||||
[row.id]
|
||||
)
|
||||
).rows;
|
||||
for (const member of members) {
|
||||
const expected = row.preview.windows[member.walk_forward_index];
|
||||
if (
|
||||
!expected ||
|
||||
member.id !== row.member_ids[member.walk_forward_index] ||
|
||||
member.backtest_id !== row.backtest_id ||
|
||||
member.validation_phase !== 'train' ||
|
||||
!validationEqual(member.validation_manifest, expected.preview)
|
||||
) {
|
||||
throw new Error('Retained walk-forward membership identity mismatch');
|
||||
}
|
||||
}
|
||||
return members;
|
||||
}
|
||||
private async readDetail(client: PoolClient, id: string): Promise<WalkForwardDetail> {
|
||||
const row = (
|
||||
await client.query('SELECT * FROM research_walk_forwards WHERE id=$1 FOR SHARE', [id])
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Walk-forward validation not found');
|
||||
}
|
||||
const preview = checkedHeader(row),
|
||||
members = await this.members(client, row, 'SHARE');
|
||||
const windows: WalkForwardDetail['windows'] = [];
|
||||
for (const [index, validationId] of (row.member_ids as string[]).entries()) {
|
||||
const member = members.find(m => m.id === validationId && m.walk_forward_index === index);
|
||||
windows.push({
|
||||
index,
|
||||
validationId,
|
||||
status: member ? 'admitted' : 'missing',
|
||||
validation: member ? await this.validations.readDetail(client, validationId) : null,
|
||||
});
|
||||
}
|
||||
const report = row.report ? publicWalkForwardReport(row.report) : null;
|
||||
const reported = windows.filter(w => w.validation?.report).length;
|
||||
const ready =
|
||||
!row.cancel_requested &&
|
||||
!report &&
|
||||
windows.every(
|
||||
w =>
|
||||
w.validation?.report &&
|
||||
!w.validation.cancelRequested &&
|
||||
w.validation.phases.every(
|
||||
p =>
|
||||
p.experiment &&
|
||||
!p.experiment.cancelRequested &&
|
||||
p.experiment.trials.every(
|
||||
t => t.status === 'completed' && t.comparable && !t.cancelRequested
|
||||
)
|
||||
)
|
||||
);
|
||||
return {
|
||||
...summary(row, reported),
|
||||
preview,
|
||||
windows,
|
||||
report,
|
||||
actions: {
|
||||
finalize: {
|
||||
available: ready,
|
||||
reason: ready
|
||||
? null
|
||||
: report
|
||||
? 'Walk-forward report is already saved'
|
||||
: row.cancel_requested
|
||||
? 'Walk-forward validation is cancelled'
|
||||
: 'Every window needs complete uncancelled verified evidence and a sealed report',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
ChronologicalValidationDetailPage,
|
||||
ExperimentDetailPage,
|
||||
ExperimentListPage,
|
||||
WalkForwardDetailPage,
|
||||
} from '@/features/experiments';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
|
|
@ -59,6 +60,7 @@ export function App() {
|
|||
path="validation/:validationId"
|
||||
element={<ChronologicalValidationDetailPage />}
|
||||
/>
|
||||
<Route path="walk-forward/:walkForwardId" element={<WalkForwardDetailPage />} />
|
||||
<Route path=":experimentId" element={<ExperimentDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Button } from '@/components/ui/Button';
|
|||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentEditor } from './components/ExperimentEditor';
|
||||
import { SavedChronologicalValidations } from './components/SavedChronologicalValidations';
|
||||
import { SavedWalkForwards } from './components/SavedWalkForwards';
|
||||
import { experimentApi } from './services/experimentApi';
|
||||
|
||||
export function ExperimentListPage() {
|
||||
|
|
@ -73,6 +74,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
</div>
|
||||
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
|
||||
<SavedChronologicalValidations backtestId={backtestId} />
|
||||
<SavedWalkForwards backtestId={backtestId} />
|
||||
<section aria-label="Saved experiments" className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved experiments</h2>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,383 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ValidationEvidence } from './components/ValidationEvidence';
|
||||
import {
|
||||
walkForwardApi,
|
||||
WalkForwardApiError,
|
||||
type WalkForwardDetailView,
|
||||
} from './services/walkForwardApi';
|
||||
|
||||
export function WalkForwardDetailPage() {
|
||||
const { walkForwardId = '' } = useParams<{ walkForwardId: string }>();
|
||||
return <WalkForwardDetail key={walkForwardId} walkForwardId={walkForwardId} />;
|
||||
}
|
||||
type Intent = { id: string; body: { previewHash: string }; key: string };
|
||||
function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
reading = useRef(true),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null),
|
||||
captured = useRef<Intent | null>(null);
|
||||
const [value, setValue] = useState<WalkForwardDetailView | null>(null),
|
||||
[intent, setIntent] = useState<Intent | null>(null),
|
||||
[receipt, setReceipt] = useState<WalkForwardReceipt | null>(null);
|
||||
const [loading, setLoading] = useState(true),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reload, setReload] = useState(0),
|
||||
[readError, setReadError] = useState(''),
|
||||
[actionError, setActionError] = useState(''),
|
||||
[ambiguous, setAmbiguous] = useState(false);
|
||||
useUnsavedWarning(Boolean(intent));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (pending.current) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
const revision = ++generation.current,
|
||||
controller = new AbortController();
|
||||
read.current = controller;
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setReadError('');
|
||||
void walkForwardApi
|
||||
.get(walkForwardId, controller.signal)
|
||||
.then(result => {
|
||||
if (current && revision === generation.current) {
|
||||
setValue(result);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current && revision === generation.current) {
|
||||
setReadError(
|
||||
cause instanceof Error ? cause.message : 'Could not load walk-forward validation'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current && revision === generation.current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [walkForwardId, reload]);
|
||||
const begin = () => {
|
||||
if (pending.current || reading.current) {
|
||||
return false;
|
||||
}
|
||||
pending.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
return true;
|
||||
};
|
||||
const finish = () => {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const finalize = async () => {
|
||||
if (pending.current || reading.current || !value) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (!value.actions.finalize.available) {
|
||||
return;
|
||||
}
|
||||
captured.current = {
|
||||
id: walkForwardId,
|
||||
body: { previewHash: value.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
};
|
||||
setIntent(captured.current);
|
||||
setReceipt(null);
|
||||
}
|
||||
const original = captured.current;
|
||||
if (!begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await walkForwardApi.finalize(original.id, original.body, original.key);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setReceipt(result.receipt);
|
||||
setValue(result.walkForward);
|
||||
setAmbiguous(false);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
cause instanceof Error ? cause.message : 'Could not save walk-forward report'
|
||||
);
|
||||
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const cancel = async () => {
|
||||
if (!value || !begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await walkForwardApi.cancel(walkForwardId);
|
||||
if (alive.current) {
|
||||
setValue(result);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
`${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
pending.current ||
|
||||
!window.confirm(
|
||||
'Discard this report request? It may already have succeeded. Refresh the saved walk-forward validation before preparing another action.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setActionError('');
|
||||
setAmbiguous(false);
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className="h-full overflow-auto p-1 space-y-4"
|
||||
onClickCapture={event => {
|
||||
if (
|
||||
(event.target as HTMLElement).closest('a') &&
|
||||
captured.current &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!window.confirm(
|
||||
'Leave this unconfirmed walk-forward report request? Its exact body and key will be discarded. You can inspect evidence in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Link to="/experiments" className="text-primary-500 text-sm">
|
||||
All experiments
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-lg font-bold">{value?.name ?? 'Walk-forward validation'}</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || busy}
|
||||
onClick={() => {
|
||||
if (!pending.current && !reading.current) {
|
||||
reading.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setReload(current => current + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Refresh walk-forward
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading walk-forward validation...</p>}
|
||||
{readError && (
|
||||
<p role="alert" className="text-error">
|
||||
{readError}
|
||||
{value && ' Showing the last loaded state.'}
|
||||
</p>
|
||||
)}
|
||||
{actionError && (
|
||||
<p role="alert" className="text-error">
|
||||
{actionError}
|
||||
</p>
|
||||
)}
|
||||
{intent && (
|
||||
<div className="space-y-2">
|
||||
<p role="status">
|
||||
{ambiguous ? 'Report acceptance is unconfirmed. ' : ''}This request retains its exact
|
||||
walk-forward identity, preview and key.
|
||||
</p>
|
||||
<Button disabled={busy || loading} onClick={() => void finalize()}>
|
||||
Retry walk-forward report request
|
||||
</Button>{' '}
|
||||
<Button variant="outline" disabled={busy} onClick={discard}>
|
||||
Discard walk-forward report request
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{receipt && (
|
||||
<p role="status">
|
||||
Walk-forward report accepted. Receipt {receipt.id} · {receipt.createdAt}
|
||||
</p>
|
||||
)}
|
||||
{value && (
|
||||
<>
|
||||
<p className="font-semibold">
|
||||
{value.report
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
: 'Window validations admitted · walk-forward report not yet saved'}
|
||||
</p>
|
||||
<p>
|
||||
{value.reportedWindowCount}/{value.windowCount} window reports saved ·{' '}
|
||||
{value.trainingRunCount} training runs · {value.plannedRunCount} total planned runs,
|
||||
including future holdouts.
|
||||
</p>
|
||||
<p>
|
||||
Each phase and window resets initial capital and positions. These are ordered
|
||||
independent reset segments, not a continuous portfolio equity curve. No returns are
|
||||
compounded and no window metrics are averaged.
|
||||
</p>
|
||||
{value.cancelRequested && (
|
||||
<p>
|
||||
Cancellation requested for all windows. Completed evidence remains retained; active
|
||||
work may still finish.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!intent && !value.report && (
|
||||
<Button
|
||||
disabled={loading || busy || !value.actions.finalize.available}
|
||||
onClick={() => void finalize()}
|
||||
>
|
||||
Save walk-forward report
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={loading || busy || value.cancelRequested}
|
||||
onClick={() => void cancel()}
|
||||
>
|
||||
Cancel remaining walk-forward work
|
||||
</Button>
|
||||
</div>
|
||||
{!value.report && value.actions.finalize.reason && <p>{value.actions.finalize.reason}</p>}
|
||||
<section aria-label="Walk-forward windows" className="space-y-3">
|
||||
<h2 className="font-semibold">Window progress and evidence</h2>
|
||||
{value.windows.map(member => (
|
||||
<article key={member.index} className="rounded border border-border p-3 space-y-2">
|
||||
<h3 className="font-medium">Window {member.index + 1}</h3>
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/experiments/validation/${encodeURIComponent(member.validationId)}`}
|
||||
>
|
||||
Open window {member.index + 1} validation
|
||||
</Link>
|
||||
{member.status === 'missing' ? (
|
||||
<p role="alert">
|
||||
Window {member.index + 1} validation is missing. Its outcome has not been
|
||||
omitted.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{member.validation?.report
|
||||
? 'Window report saved'
|
||||
: member.validation?.selection
|
||||
? 'Fixed winner selected · validation and test admitted'
|
||||
: 'Training candidates admitted · selection not yet frozen'}
|
||||
</p>
|
||||
{member.validation?.cancelRequested && (
|
||||
<p>Cancellation requested for this window.</p>
|
||||
)}
|
||||
{member.validation?.phases.map(phase => (
|
||||
<div key={phase.phase}>
|
||||
<p>
|
||||
{phase.phase}:{' '}
|
||||
{phase.status === 'not-admitted'
|
||||
? 'Not admitted'
|
||||
: phase.status === 'missing'
|
||||
? 'Experiment missing'
|
||||
: phase.experiment
|
||||
? `${phase.experiment.counts.completed} completed, ${phase.experiment.counts.failed} failed, ${phase.experiment.counts.cancelled} cancelled, ${phase.experiment.counts.pending} pending, ${phase.experiment.counts.running} running, ${phase.experiment.counts.paused} paused`
|
||||
: 'Unavailable'}
|
||||
</p>
|
||||
{phase.experiment &&
|
||||
phase.experiment.trials
|
||||
.filter(
|
||||
trial =>
|
||||
trial.status === 'missing' ||
|
||||
trial.error ||
|
||||
(trial.status === 'completed' && !trial.comparable)
|
||||
)
|
||||
.map(trial => (
|
||||
<p key={trial.index}>
|
||||
Candidate {trial.index + 1}: {trial.status};{' '}
|
||||
{trial.error ?? trial.diagnostic ?? 'Evidence unavailable'}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Frozen walk-forward inputs</summary>
|
||||
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(value.preview, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
{value.report && (
|
||||
<section aria-label="Saved walk-forward report" className="space-y-3">
|
||||
<h2 className="font-semibold">Saved walk-forward report</h2>
|
||||
<p className="break-all">
|
||||
Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}
|
||||
</p>
|
||||
{value.report.limitations.map((limitation, index) => (
|
||||
<p key={index}>{limitation}</p>
|
||||
))}
|
||||
{value.report.segments.map(segment => (
|
||||
<section key={segment.index} className="space-y-2">
|
||||
<h3 className="font-medium">Window {segment.index + 1} reset segment</h3>
|
||||
<p className="break-all">
|
||||
Window report {segment.reportId} · {segment.reportHash}
|
||||
</p>
|
||||
<p className="break-all">Selection {segment.selectionHash}</p>
|
||||
<ValidationEvidence
|
||||
title={`Window ${segment.index + 1} validation and test evidence`}
|
||||
items={[segment.validation, segment.test]}
|
||||
backtestId={value.backtestId}
|
||||
/>
|
||||
</section>
|
||||
))}
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained walk-forward report</summary>
|
||||
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(value.report, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -15,38 +15,15 @@ import {
|
|||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
} from '../services/chronologicalValidationDurableApi';
|
||||
import {
|
||||
emptyValidationWindows,
|
||||
parseValidationWindows,
|
||||
ValidationWindowFields,
|
||||
validationWindowsDirty,
|
||||
type ValidationWindows,
|
||||
} from './ValidationWindowFields';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
const labels = {
|
||||
warmupStart: 'warmup start',
|
||||
tradeStart: 'trading start',
|
||||
tradeEnd: 'trading end',
|
||||
};
|
||||
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
||||
type Windows = Record<ValidationPhase, Record<(typeof fields)[number], string>>;
|
||||
const empty = (): Windows => ({
|
||||
train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
});
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
function parseInstant(raw: string, label: string) {
|
||||
const text = raw.trim();
|
||||
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text);
|
||||
const value = Date.parse(text);
|
||||
if (
|
||||
!match ||
|
||||
!Number.isFinite(value) ||
|
||||
new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
|
|
@ -84,7 +61,7 @@ export function ChronologicalValidationPreflight({
|
|||
const [submittingTraining, setSubmittingTraining] = useState(false);
|
||||
const [trainingError, setTrainingError] = useState('');
|
||||
const [trainingAmbiguous, setTrainingAmbiguous] = useState(false);
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
const [windows, setWindows] = useState<ValidationWindows>(emptyValidationWindows);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
|
|
@ -100,8 +77,7 @@ export function ChronologicalValidationPreflight({
|
|||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty =
|
||||
hasTrainingIntent || phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
const dirty = hasTrainingIntent || validationWindowsDirty(windows);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
|
|
@ -121,7 +97,7 @@ export function ChronologicalValidationPreflight({
|
|||
setLoading(false);
|
||||
setError('');
|
||||
}, [identity]);
|
||||
const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
|
||||
const edit = (phase: ValidationPhase, field: keyof ValidationWindows['train'], value: string) => {
|
||||
if (disabled || trainingIntent.current) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -143,24 +119,11 @@ export function ChronologicalValidationPreflight({
|
|||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const bounds = (phase: ValidationPhase) =>
|
||||
Object.fromEntries(
|
||||
fields.map(field => [
|
||||
field,
|
||||
parseInstant(windows[phase][field], `${phaseLabels[phase]} ${labels[field]} (UTC)`),
|
||||
])
|
||||
);
|
||||
const input = chronologicalValidationInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
recipe: {
|
||||
version: 1,
|
||||
train: bounds('train'),
|
||||
validation: bounds('validation'),
|
||||
test: bounds('test'),
|
||||
labelHorizonMs: 0,
|
||||
},
|
||||
recipe: parseValidationWindows(windows),
|
||||
});
|
||||
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
||||
if (
|
||||
|
|
@ -264,33 +227,14 @@ export function ChronologicalValidationPreflight({
|
|||
instants ending in Z; no local-time conversion or automatic date split is applied. Trading
|
||||
windows exclude their end instant. Warmup may overlap earlier phases.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">{phaseLabels[phase]} window</legend>
|
||||
{fields.map(field => (
|
||||
<label key={field} className="block text-xs">
|
||||
{phaseLabels[phase]} {labels[field]} (UTC)
|
||||
<input
|
||||
className={fieldClass}
|
||||
type="text"
|
||||
value={windows[phase][field]}
|
||||
placeholder="2024-01-01T09:00:00Z"
|
||||
onChange={event => edit(phase, field, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
<ValidationWindowFields
|
||||
windows={windows}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
onChange={edit}
|
||||
/>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the ordinary sweep submission before preparing chronological
|
||||
inputs.
|
||||
Resolve or explicitly release the other submission before preparing chronological inputs.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
} from '../services/experimentApi';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import { WalkForwardPreflight } from './WalkForwardPreflight';
|
||||
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
|
|
@ -49,15 +50,17 @@ export function ExperimentEditor({
|
|||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | null>(null);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner === 'chronological') {
|
||||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
|
|
@ -65,7 +68,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
|
|
@ -87,9 +90,11 @@ export function ExperimentEditor({
|
|||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [validationDirty, setValidationDirty] = useState(false);
|
||||
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
|
||||
const dirty =
|
||||
hasIntent ||
|
||||
validationDirty ||
|
||||
walkForwardDirty ||
|
||||
Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
|
|
@ -349,7 +354,7 @@ export function ExperimentEditor({
|
|||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={submitting || lockedBy === 'chronological'}
|
||||
disabled={submitting || (lockedBy !== null && lockedBy !== 'ordinary')}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
|
|
@ -369,12 +374,22 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy === 'ordinary'}
|
||||
disabled={lockedBy !== null && lockedBy !== 'chronological'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'walk-forward'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { WalkForwardSummary } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { walkForwardApi } from '../services/walkForwardApi';
|
||||
|
||||
export function SavedWalkForwards({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<WalkForwardSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void walkForwardApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(
|
||||
cause instanceof Error ? cause.message : 'Could not load walk-forward validations'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<section aria-label="Saved walk-forward validations" className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved walk-forward validations</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh walk-forward validations
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading walk-forward validations...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No saved walk-forward validations.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-1">
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/walk-forward/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{item.stage === 'reported'
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
: 'Window validations admitted'}{' '}
|
||||
· {item.reportedWindowCount}/{item.windowCount} window reports saved ·{' '}
|
||||
{item.trainingRunCount} training runs · {item.plannedRunCount} planned runs
|
||||
</p>
|
||||
{item.cancelRequested && <p className="text-sm">Cancellation requested</p>}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import type {
|
||||
ChronologicalValidationInput,
|
||||
ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
const labels = {
|
||||
warmupStart: 'warmup start',
|
||||
tradeStart: 'trading start',
|
||||
tradeEnd: 'trading end',
|
||||
};
|
||||
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
||||
export type ValidationWindows = Record<ValidationPhase, Record<(typeof fields)[number], string>>;
|
||||
export const emptyValidationWindows = (): ValidationWindows => ({
|
||||
train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
});
|
||||
export const validationWindowsDirty = (windows: ValidationWindows) =>
|
||||
phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
function parseInstant(raw: string, label: string) {
|
||||
const text = raw.trim(),
|
||||
match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text),
|
||||
value = Date.parse(text);
|
||||
if (
|
||||
!match ||
|
||||
!Number.isFinite(value) ||
|
||||
new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export function parseValidationWindows(
|
||||
windows: ValidationWindows,
|
||||
prefix = ''
|
||||
): ChronologicalValidationInput['recipe'] {
|
||||
const bounds = (phase: ValidationPhase) => ({
|
||||
warmupStart: parseInstant(
|
||||
windows[phase].warmupStart,
|
||||
`${prefix}${phaseLabels[phase]} warmup start (UTC)`
|
||||
),
|
||||
tradeStart: parseInstant(
|
||||
windows[phase].tradeStart,
|
||||
`${prefix}${phaseLabels[phase]} trading start (UTC)`
|
||||
),
|
||||
tradeEnd: parseInstant(
|
||||
windows[phase].tradeEnd,
|
||||
`${prefix}${phaseLabels[phase]} trading end (UTC)`
|
||||
),
|
||||
});
|
||||
return {
|
||||
version: 1,
|
||||
train: bounds('train'),
|
||||
validation: bounds('validation'),
|
||||
test: bounds('test'),
|
||||
labelHorizonMs: 0,
|
||||
};
|
||||
}
|
||||
export function ValidationWindowFields({
|
||||
windows,
|
||||
disabled,
|
||||
prefix = '',
|
||||
onChange,
|
||||
}: {
|
||||
windows: ValidationWindows;
|
||||
disabled: boolean;
|
||||
prefix?: string;
|
||||
onChange: (phase: ValidationPhase, field: (typeof fields)[number], value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">
|
||||
{prefix}
|
||||
{phaseLabels[phase]} window
|
||||
</legend>
|
||||
{fields.map(field => (
|
||||
<label key={field} className="block text-xs">
|
||||
{prefix}
|
||||
{phaseLabels[phase]} {labels[field]} (UTC)
|
||||
<input
|
||||
className="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60"
|
||||
type="text"
|
||||
value={windows[phase][field]}
|
||||
placeholder="2024-01-01T09:00:00Z"
|
||||
onChange={event => onChange(phase, field, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,349 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
type WalkForwardSubmission,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import {
|
||||
walkForwardApi,
|
||||
WalkForwardApiError,
|
||||
type WalkForwardPreviewView,
|
||||
} from '../services/walkForwardApi';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import {
|
||||
emptyValidationWindows,
|
||||
parseValidationWindows,
|
||||
ValidationWindowFields,
|
||||
validationWindowsDirty,
|
||||
type ValidationWindows,
|
||||
} from './ValidationWindowFields';
|
||||
|
||||
type Owner = 'ordinary' | 'chronological' | 'walk-forward';
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: 'Could not prepare walk-forward validation';
|
||||
export function WalkForwardPreflight({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (value: boolean) => void;
|
||||
claimSubmission: (owner: Owner) => boolean;
|
||||
releaseSubmission: (owner: Owner) => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const [windows, setWindows] = useState<ValidationWindows[]>(() => [
|
||||
emptyValidationWindows(),
|
||||
emptyValidationWindows(),
|
||||
]);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
preview: WalkForwardPreviewView;
|
||||
} | null>(null);
|
||||
const [hasIntent, setHasIntent] = useState(false),
|
||||
[loading, setLoading] = useState(false),
|
||||
[submitting, setSubmitting] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[ambiguous, setAmbiguous] = useState(false);
|
||||
const captured = useRef<{
|
||||
body: WalkForwardSubmission;
|
||||
key: string;
|
||||
preview: WalkForwardPreviewView;
|
||||
} | null>(null);
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
posting = useRef(false),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }),
|
||||
currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
captured.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty = hasIntent || windows.length !== 2 || windows.some(validationWindowsDirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
pending.current = false;
|
||||
setPrepared(null);
|
||||
setLoading(false);
|
||||
if (!captured.current) {
|
||||
setError('');
|
||||
}
|
||||
}, [identity]);
|
||||
const edit = (change: (current: ValidationWindows[]) => ValidationWindows[]) => {
|
||||
if (disabled || captured.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setWindows(change);
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !eligible || captured.current || pending.current) {
|
||||
return;
|
||||
}
|
||||
const revision = ++generation.current,
|
||||
original = identity,
|
||||
controller = new AbortController();
|
||||
read.current?.abort();
|
||||
read.current = controller;
|
||||
pending.current = true;
|
||||
setPrepared(null);
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const input = walkForwardInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
windows: windows.map((window, index) =>
|
||||
parseValidationWindows(window, `Window ${index + 1} `)
|
||||
),
|
||||
});
|
||||
const value = await walkForwardApi.preview(input, controller.signal);
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
setPrepared({ identity: original, preview: value });
|
||||
}
|
||||
} catch (cause) {
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
pending.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (
|
||||
posting.current ||
|
||||
pending.current ||
|
||||
(!captured.current && (!preview || disabled || !eligible)) ||
|
||||
!claimSubmission('walk-forward')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
captured.current = {
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
preview,
|
||||
};
|
||||
}
|
||||
const original = captured.current;
|
||||
posting.current = true;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await walkForwardApi.submit(original.body, original.key);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('walk-forward');
|
||||
navigate(`/experiments/walk-forward/${encodeURIComponent(value.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
posting.current = false;
|
||||
if (alive.current) {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
posting.current ||
|
||||
!window.confirm(
|
||||
'Discard this walk-forward submission? It may already exist. Inspect saved walk-forward validations before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setHasIntent(false);
|
||||
setPrepared(null);
|
||||
setError('');
|
||||
setAmbiguous(false);
|
||||
releaseSubmission('walk-forward');
|
||||
};
|
||||
return (
|
||||
<details className="border-t border-border pt-4 text-sm">
|
||||
<summary className="cursor-pointer font-semibold">Walk-forward validation</summary>
|
||||
<section aria-label="Walk-forward setup" className="space-y-3 pt-3">
|
||||
<p>
|
||||
Uses the saved backtest, name and parameter grid above. Enter explicit UTC instants ending
|
||||
in Z. Preview saves nothing; submission freezes all windows and admits training together.
|
||||
Each window selects independently from training, with separate validation and test runs.
|
||||
</p>
|
||||
<p>
|
||||
Every phase resets initial capital and positions. Warmup may overlap earlier windows;
|
||||
held-out trading windows cannot overlap. Up to {MAX_WALK_FORWARD_WINDOWS} windows and{' '}
|
||||
{MAX_WALK_FORWARD_RUNS} total planned runs, including both future holdouts per window.
|
||||
</p>
|
||||
{windows.map((window, index) => (
|
||||
<section
|
||||
key={index}
|
||||
aria-label={`Walk-forward window ${index + 1}`}
|
||||
className="space-y-2"
|
||||
>
|
||||
<h4 className="font-medium">Window {index + 1}</h4>
|
||||
<ValidationWindowFields
|
||||
windows={window}
|
||||
prefix={`Window ${index + 1} `}
|
||||
disabled={disabled || hasIntent}
|
||||
onChange={(phase, field, value) =>
|
||||
edit(current =>
|
||||
current.map((item, i) =>
|
||||
i === index ? { ...item, [phase]: { ...item[phase], [field]: value } } : item
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled || hasIntent || windows.length <= 2}
|
||||
onClick={() => edit(current => current.filter((_, i) => i !== index))}
|
||||
>
|
||||
Remove window {index + 1}
|
||||
</Button>
|
||||
</section>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || hasIntent || windows.length >= MAX_WALK_FORWARD_WINDOWS}
|
||||
onClick={() => edit(current => [...current, emptyValidationWindows()])}
|
||||
>
|
||||
Add walk-forward window
|
||||
</Button>{' '}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || hasIntent || !eligible || !name.trim() || loading}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview walk-forward
|
||||
</Button>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the other submission before preparing walk-forward inputs.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Preparing walk-forward inputs...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{preview && (
|
||||
<section aria-label="Prepared walk-forward inputs" className="space-y-3">
|
||||
<p className="font-medium">
|
||||
{preview.counts.windows} windows · {preview.counts.trainingRuns} training runs ·{' '}
|
||||
{preview.counts.holdoutRuns} future holdout runs · {preview.counts.totalRuns} total
|
||||
planned runs
|
||||
</p>
|
||||
<ExperimentInputs preview={preview.source} />
|
||||
{preview.windows.map(item => (
|
||||
<details key={item.index}>
|
||||
<summary className="cursor-pointer">
|
||||
Window {item.index + 1} prepared inputs
|
||||
</summary>
|
||||
<p className="break-all">Preview {item.preview.previewHash}</p>
|
||||
{item.preview.partitions.map(part => (
|
||||
<div key={part.phase} className="py-2">
|
||||
<p>
|
||||
{part.phase}: {new Date(part.dataset.bounds.tradeStart).toISOString()} to{' '}
|
||||
{new Date(part.dataset.bounds.tradeEnd).toISOString()} (end excluded)
|
||||
</p>
|
||||
<p>
|
||||
Warmup starts {new Date(part.dataset.bounds.warmupStart).toISOString()};
|
||||
admitted warmup {part.counts.admittedWarmup}, required {part.requiredWarmup};
|
||||
evaluation observations {part.counts.availableEvaluation}; terminal-at-end
|
||||
observations {part.counts.terminalAtEnd}; completed observations unavailable
|
||||
at end {part.counts.unavailableAtEnd}.
|
||||
</p>
|
||||
<p className="break-all">Dataset {part.dataset.hash}</p>
|
||||
{part.warnings.map((warning, index) => (
|
||||
<p key={index}>{warning}</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(item.preview, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
))}
|
||||
<p className="break-all">Walk-forward preview {preview.previewHash}</p>
|
||||
</section>
|
||||
)}
|
||||
{hasIntent && (
|
||||
<p role="status">
|
||||
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission retains its exact
|
||||
windows, inputs and key. Retry to recover the same walk-forward validation.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting || (disabled && !hasIntent)} onClick={() => void submit()}>
|
||||
{hasIntent ? 'Retry walk-forward submission' : 'Submit walk-forward training'}
|
||||
</Button>
|
||||
{hasIntent && (
|
||||
<Button variant="outline" disabled={submitting} onClick={discard}>
|
||||
Discard walk-forward submission
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
|
||||
export { WalkForwardDetailPage } from './WalkForwardDetailPage';
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ const summary = z.object({
|
|||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
const evidence = z.object({
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
|
|
@ -87,7 +87,7 @@ const selection = z.object({
|
|||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
|
|
@ -100,9 +100,9 @@ const report = z.object({
|
|||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
validation: evidence,
|
||||
test: evidence,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
|
|
@ -134,7 +134,7 @@ const invalid = () =>
|
|||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
function parseDetail(raw: unknown): ValidationDetailView {
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
|
|
@ -198,7 +198,7 @@ function parseDetail(raw: unknown): ValidationDetailView {
|
|||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof evidence>,
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
|
|
@ -330,7 +330,7 @@ export const chronologicalValidationDurableApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -338,7 +338,7 @@ export const chronologicalValidationDurableApi = {
|
|||
}),
|
||||
submit: (input: ChronologicalValidationSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
|
|
@ -353,7 +353,7 @@ export const chronologicalValidationDurableApi = {
|
|||
) =>
|
||||
request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => {
|
||||
const accepted = receipt.parse(envelope(body, 'receipt'));
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
const record = operation === 'select' ? value.selection : value.report;
|
||||
if (
|
||||
accepted.validationId !== id ||
|
||||
|
|
@ -378,7 +378,7 @@ export const chronologicalValidationDurableApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,426 @@
|
|||
import { z } from 'zod';
|
||||
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: z.enum(['operator', 'service']),
|
||||
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: z.enum(['operator', 'service']),
|
||||
})
|
||||
.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;
|
||||
}),
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue