stock-bot/docs/development/backlog/tasks/R08.md

70 lines
6.2 KiB
Markdown

# R08 — Add bounded chronological and reset-segment validation
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quantitative research integrity.
Scheduling source of truth: [manifest entry R08](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177).
- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542).
## Intended behavior and implementation scope
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Aggregate segment returns as a labelled reset-segment research series, never claim one continuous tradable equity curve. Cost/parameter sensitivity reuses grid expansion. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
Persist the immutable validation manifest/report as experiment-owned JSON on the R06 experiment (or a focused child row if immutability requires it), keyed by experiment/report version and containing every contributing run ID, selection rule and segment policy. This is not R03 research-findings storage. Reopening an experiment must recover the same report; new inputs require a new experiment/report identity.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-api/src/services/ (validation recipes)
- apps/stock/orchestrator/src/backtest/
- test/integration/ (research validation tests)
- database/postgres/init/ and reviewed migration registry (only if experiment report persistence needs an additive column/table)
Write locks: validation-contract, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R06](R06.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Training/validation/test inputs and selection rule are frozen before execution. Test values cannot affect earlier parameter selection or fitted inputs.
- Every segment declares capital/reset/warmup policy; warmup has no orders/fills; OOS intervals do not overlap.
- All tried candidates and holdout accesses remain visible. Independent segment cash accounts are not summed/stitched as a continuous portfolio.
- Immutable experiment-owned reports reopen without any project/hypothesis/findings records or R03 API; conflicting attempts cannot overwrite a completed report.
- For a later declared nonzero label horizon require gap/purge >= horizon; unsupported/missing horizon/trainable fit metadata rejects rather than leaking future data.
## Mandatory tests
- chronological_selection, test_suffix_cannot_change_selection, warmup_no_trades, nonoverlapping_windows, reset_segment_accounting.
- experiment_report_without_research_metadata, immutable_report_reopen, conflicting_report_write_rejected.
- reject_uncontracted_trainable_model, horizon_gap_validation, bounded_cost_grid; fixed seeds and retained selected-parameter artifacts.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: Validation recipe and immutable report under the existing experiment API; report includes every contributing run and declared segment/warmup policy.
- Backend/data dependencies: R06 experiments/runs and experiment-owned JSON reports. No R03 analysis_artifacts dependency or separate optimization service.
- Loading/error/empty behavior: Typed invalid-window/insufficient-warmup errors; validation failures are not profitable candidates.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.