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
|
|
@ -296,6 +296,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import type {
|
|||
ChronologicalValidationActionResult,
|
||||
ChronologicalValidationDetail,
|
||||
ChronologicalValidationPreview,
|
||||
ChronologicalValidationReport,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
|
|
@ -16,10 +17,16 @@ import type {
|
|||
ExperimentRetryResult,
|
||||
ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import type {
|
||||
WalkForwardActionResult,
|
||||
WalkForwardDetail,
|
||||
WalkForwardPreview,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
import {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
|
|
@ -42,6 +49,224 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_report_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const { dataset, windows } = walkForwardDataset();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed bounded walk-forward native browser fixture',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Walk-forward native template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const backtest = await f.request('/api/v2/backtests', 'POST', {
|
||||
...definition,
|
||||
autoStart: false,
|
||||
});
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Frozen rolling windows');
|
||||
await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
|
||||
await f.page.getByText('Walk-forward validation', { exact: true }).click();
|
||||
for (const [index, recipe] of windows.entries()) {
|
||||
for (const phase of ['Train', 'Validation', 'Test'] as const) {
|
||||
const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test'];
|
||||
for (const [label, value] of [
|
||||
['warmup start', window.warmupStart],
|
||||
['trading start', window.tradeStart],
|
||||
['trading end', window.tradeEnd],
|
||||
] as const) {
|
||||
await f.page
|
||||
.getByLabel(`Window ${index + 1} ${phase} ${label} (UTC)`, { exact: true })
|
||||
.fill(new Date(value).toISOString());
|
||||
}
|
||||
}
|
||||
}
|
||||
const preparing = f.page.waitForResponse(r =>
|
||||
r.url().endsWith('/api/v2/experiments/walk-forward/preview')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview walk-forward', exact: true }).click();
|
||||
const prepared = await preparing;
|
||||
expect(prepared.status()).toBe(200);
|
||||
const { preview } = (await prepared.json()) as { preview: WalkForwardPreview };
|
||||
expect(preview.input.windows).toEqual(windows);
|
||||
expect(preview.counts).toEqual({
|
||||
windows: 2,
|
||||
trainingRuns: 4,
|
||||
holdoutRuns: 4,
|
||||
totalRuns: 8,
|
||||
maxRuns: 100,
|
||||
});
|
||||
expect((await f.pool.query('SELECT * FROM research_walk_forwards')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
const submitting = f.page.waitForResponse(
|
||||
r => r.request().method() === 'POST' && r.url().endsWith('/api/v2/experiments/walk-forward')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Submit walk-forward training', exact: true }).click();
|
||||
const accepted = await submitting;
|
||||
expect(accepted.status()).toBe(202);
|
||||
const { walkForward: initial } = (await accepted.json()) as { walkForward: WalkForwardDetail };
|
||||
const endpoint = `/api/v2/experiments/walk-forward/${initial.id}`;
|
||||
const route = `${f.origin}/experiments/walk-forward/${initial.id}`;
|
||||
expect(accepted.headers().location).toBe(endpoint);
|
||||
expect(initial.preview).toEqual(preview);
|
||||
expect(initial.windows.map(w => w.index)).toEqual([0, 1]);
|
||||
expect(
|
||||
initial.windows.every(w => w.status === 'admitted' && w.validation?.selection === null)
|
||||
).toBe(true);
|
||||
expect(initial.actions.finalize.available).toBe(false);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(4);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(4);
|
||||
await f.page.waitForURL(route);
|
||||
// Every member already owns its frozen source before any native training starts.
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Edited after frozen series',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
|
||||
'4',
|
||||
'all training windows complete'
|
||||
);
|
||||
const childReports: ChronologicalValidationReport[] = [];
|
||||
for (const member of initial.windows) {
|
||||
await f.page.getByRole('button', { name: 'Refresh walk-forward', exact: true }).click();
|
||||
await f.page
|
||||
.getByRole('link', { name: `Open window ${member.index + 1} validation`, exact: true })
|
||||
.click();
|
||||
await f.page.waitForURL(`${f.origin}/experiments/validation/${member.validationId}`);
|
||||
const selecting = f.page.waitForResponse(r =>
|
||||
r.url().endsWith(`/validation/${member.validationId}/select`)
|
||||
);
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Freeze selection and run holdouts', exact: true })
|
||||
.click();
|
||||
const selectionResponse = await selecting;
|
||||
expect(selectionResponse.status()).toBe(202);
|
||||
const selected = (await selectionResponse.json()) as ChronologicalValidationActionResult;
|
||||
const holdoutIds = selected.validation.phases
|
||||
.slice(1)
|
||||
.map(p => p.experiment!.trials[0]!.runId!);
|
||||
await until(
|
||||
async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*) FROM runs WHERE id=ANY($1::uuid[]) AND status='completed'",
|
||||
[holdoutIds]
|
||||
)
|
||||
).rows[0].count === '2',
|
||||
'member holdouts complete'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
|
||||
const finalizing = f.page.waitForResponse(r =>
|
||||
r.url().endsWith(`/validation/${member.validationId}/finalize`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save validation report', exact: true }).click();
|
||||
const memberResponse = await finalizing;
|
||||
expect(memberResponse.status()).toBe(202);
|
||||
const memberResult = (await memberResponse.json()) as ChronologicalValidationActionResult;
|
||||
childReports.push(memberResult.validation.report!);
|
||||
await visible(f.page, 'Execution complete · report saved');
|
||||
await f.page.goto(route);
|
||||
await visible(f.page, 'Frozen rolling windows');
|
||||
const state = (await f.request(endpoint)).walkForward as WalkForwardDetail;
|
||||
expect(state.reportedWindowCount).toBe(member.index + 1);
|
||||
if (member.index === 0) {
|
||||
expect(state.actions.finalize.available).toBe(false);
|
||||
expect(
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Save walk-forward report', exact: true })
|
||||
.isDisabled()
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [backtest.id]);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
|
||||
await f.page.getByRole('button', { name: 'Refresh walk-forward', exact: true }).click();
|
||||
const finalizing = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/finalize`));
|
||||
await f.page.getByRole('button', { name: 'Save walk-forward report', exact: true }).click();
|
||||
const response = await finalizing;
|
||||
expect(response.status()).toBe(202);
|
||||
const completed = (await response.json()) as WalkForwardActionResult;
|
||||
const report = completed.walkForward.report!;
|
||||
expect(completed.receipt.id).toBe(report.id);
|
||||
expect(completed.receipt.reportHash).toBe(report.reportHash);
|
||||
expect(report.reset).toBe('initial-capital-empty-positions');
|
||||
expect(report.segments).toHaveLength(2);
|
||||
for (const [index, segment] of report.segments.entries()) {
|
||||
const child = childReports[index]!;
|
||||
expect(segment.index).toBe(index);
|
||||
expect(segment.validationId).toBe(initial.windows[index]!.validationId);
|
||||
expect(segment.reportId).toBe(child.id);
|
||||
expect(segment.reportHash).toBe(child.reportHash);
|
||||
expect(segment.selectionHash).toBe(child.selectionHash);
|
||||
expect(segment.validation).toEqual(child.validation);
|
||||
expect(segment.test).toEqual(child.test);
|
||||
const result = (await f.request(
|
||||
`/api/v2/runs/${segment.test.runId}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(segment.test.metrics).toEqual(result.analytics.metrics);
|
||||
expect(segment.test.unavailable).toEqual(result.analytics.unavailable);
|
||||
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'10000.00000000'
|
||||
);
|
||||
}
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(6);
|
||||
await visible(f.page, 'Execution complete · walk-forward report saved');
|
||||
const replay = (await f.request(
|
||||
`${endpoint}/finalize`,
|
||||
'POST',
|
||||
response.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': response.request().headers()['idempotency-key']! }
|
||||
)) as WalkForwardActionResult;
|
||||
expect(replay.receipt).toEqual(completed.receipt);
|
||||
expect(replay.walkForward.report).toEqual(report);
|
||||
const submitReplay = await f.request(
|
||||
'/api/v2/experiments/walk-forward',
|
||||
'POST',
|
||||
accepted.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': accepted.request().headers()['idempotency-key']! }
|
||||
);
|
||||
expect(submitReplay.walkForward.id).toBe(initial.id);
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Execution complete · walk-forward report saved');
|
||||
expect((await f.request(endpoint)).walkForward.report).toEqual(report);
|
||||
await f.page.goto(`${f.origin}/experiments`);
|
||||
await visible(f.page, 'Saved walk-forward validations');
|
||||
await f.page.locator(`a[href="/experiments/walk-forward/${initial.id}"]`).click();
|
||||
await visible(f.page, 'Execution complete · walk-forward report saved');
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('chronological_preflight_checks_explicit_windows_without_admitting_or_saving_work_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue