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

82 lines
8.2 KiB
Markdown

# S05 — Add a small composable multi-signal regime example
Parent epic: E4. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Quant strategy research.
Scheduling source of truth: [manifest entry S05](../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
- **STR-01 — Reverified:** S01/S02 already provide an isolated owner context and trusted SMA program. `strategies/canonical-sma.ts` still contains the single-strategy factory/binding boundary; extract only that dispatch seam for a second program.
- **FIN-04 — Addressed by F02/F04/F05:** Owner basis, cash, fees and target reconciliation are already canonical Rust behavior. Verify independent MR/SMA owners against it; do not recreate those calculations in TypeScript.
- **RES-01 — Still relevant:** Experimental Python full-sample preprocessing is not research evidence. S05 uses explicit fixed per-observation thresholds and no fitting; R08 still gates validation/alpha claims.
## Intended behavior and implementation scope
Adapt the existing mean-reversion idea as a second TS strategy/example and compose trend/momentum scores plus a simple fixed/training-only volatility regime using reviewed calculations. Ordinary functions, no universal signal/regime framework. Code/decision tests can land before R08; conclusions about performance require R08 validation.
## Exclusions
No unrelated refactor, new service or broker activation.
## Likely files and ownership
- apps/stock/orchestrator/src/contracts/builtin-strategy.ts
- apps/stock/orchestrator/src/strategies/canonical-{builtins,sizing,sma,mean-reversion}.ts
- apps/stock/orchestrator/src/{container,backtest/native-worker}.ts
- test/{integration,fixtures,postgres}/canonical-regime*.ts
- Existing SMA/worker/paper test import sites and one runnable research example
Write locks: example-strategy. One program owner; root owns shared contracts/dispatch, and an independent verifier owns disjoint native fixtures/tests. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [S02](S02.md), [F08](F08.md) integrated.
No additional economic-policy approval is needed for this narrowly scoped task.
Feature activation/release gates: [R08](R08.md). These do not block implementing or integrating this component against its own tests.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Two strategy instances sharing an asset maintain independent state/basis and route fills correctly.
- Exit is not blocked by entry-only volume filters; thresholds and owner budgets are explicit.
- Regime/no-regime ablation inputs and cost-sensitivity recipe are reproducible; no alpha claim before validation release gate.
## Mandatory tests
- signal_composition_units, regime_boundary_availability, multi_strategy_ownership, no_regime_ablation_reproducibility.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests.
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.
## 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.
## Execution contract — 2026-10-23
Base `75abae2` contains accepted S04. This wave adds `mean-reversion-regime-long-only/v1` as a distinct trusted canonical strategy; it does not reinterpret legacy mean-reversion or SMA versions. The existing native worker and opt-in paper composition use one small exhaustive built-in dispatcher. Preserve all existing financial, observation-clock and recovery contracts. No Rust, legacy strategy, generic feature framework, cache, optimizer, UI/default cutover or trading activation changes.
- Explicit parameters: price lookback >=2; longer trend period; momentum lag >=1; return-volatility window >=2; positive entry z threshold; nonnegative smaller exit z threshold; fractional trend/momentum floors >-1; nonnegative volatility ceiling; nonnegative decimal notional-volume minimum; `regimeFilter: volatility|none`. Owner budget remains an explicit decimal amount.
- Pure signals reuse reviewed trailing mean/population deviation/simple returns: z=(latest-mean)/deviation (flat=0); trend=mean/longerMean-1; momentum=latest/laggedClose-1; volatility=population deviation of adjacent simple returns. Periods count observations, not elapsed time; gaps are not filled or time-normalized. Warmup is max(lookback,trend,momentum+1,volatility+1) in both ablation modes.
- Entry is the conjunction z<=-entry, trend/momentum>=floors, close*volume>=minimum and volatility<=ceiling. `none` disables only the volatility gate. These are illustrative fixed parameters, not fitted evidence. No RSI or universal score type is needed.
- Initial desired quantity is exact floor(ownerBudget/latestClose), without a forced minimum. Rust owns admission, available cash, fees, ownership, fills and all P&L. Retain a stable target while entry gates pass. If a gate fails, permanently cap the target to min(desired, actual owned quantity), abandoning unfilled buys; held fractional fills are preserved exactly. A flat owner may start a new eligible episode.
- Exit z>=-exit is evaluated before entry gates. Target zero persists until the owner is flat, even during low volume/high volatility and partial exits. Never cancel an outstanding exit by replacing zero with held quantity. Empty target lists preserve prior commitments; explicit zero/owned targets invoke native reconciliation.
- State is bounded detached JSON with exact selection/version binding, original observation identity, history and desired target. Future data rejects; duplicate/older delayed bars cannot rewrite evaluated history. Stale/missing/mismatched barriers may warm state but cannot emit a new target. Fresh decisions require the newest consumed observation to match the barrier.
- Verification covers hand calculations and threshold equality, zero variance/warmup, every-prefix state continuation, suffix causality, native partial-fill/owner/risk oracles, mixed SMA/MR worker parity, one durable restart, repeated ablation inputs and explicit fee/slippage sensitivity. No claims of profitable alpha or out-of-sample validation before R08.
## Validated handoff — 2026-10-23
Implementation and independent G1/G2 review accepted; manifest remains `review` until acceptance/commit. See [wave18 validation](../manifest.json) for exact source hashes, commands, economic oracles and limitations. Existing SMA version/selection serialization remains stable. The MR schema rejects legacy settings, unsupported versions and untrusted code fields.
Use `createBuiltinStrategy` from `strategies/canonical-builtins.ts` for either trusted canonical version. The new selection is `strategyId: mean_reversion`, `strategyVersion: mean-reversion-regime-long-only/v1`, with all parameters explicit. Both the existing native worker and opt-in canonical paper composition use that dispatcher; legacy/default APIs remain separate.
[The research example](../../../../apps/stock/orchestrator/examples/canonical-regime-research.ts) takes an existing `StrategyReplayRequest`, an existing `NativeBacktestWorker`, explicit alternative `{feeRate, slippageRate}` and an abort signal. `createRegimeComparisons` returns four detached requests for review; `runRegimeComparisons` executes them serially and returns exact requests/native reports. The caller owns worker lifecycle and artifact/result retention. This is a reproducible diagnostic recipe, not a validation/optimization or saved-experiment framework. No model or code artifact provenance guarantee replaces pending R01/R05/R06.