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

127 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# F08 — Publish canonical metrics and versioned result projections
Parent epic: E2. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quant analytics/Rust integration.
Scheduling source of truth: [manifest entry F08](../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
- **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).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **Verified reusable analytics:** [reviewed return statistics](../../../../libs/calculations/src/analytics/return-statistics.ts#L24) already separate statistical reporting from financial execution.
## Intended behavior and implementation scope
F09 now supplies the independently deliverable compact terminal/owned-fill projection. F08 consumes it and adds historical sampling/statistical reporting; do not duplicate its native transport work. F09 is not completion of this story.
Use canonical Rust ledger postings, owned fills, occupied intervals and session-ending marks as the sole financial inputs. Reuse reviewed TypeScript statistical functions in `libs/calculations/src/analytics/` for return ratios and reports; do not port them to Rust merely for language uniformity. Add a small adapter for the engine-declared session calendar rather than blindly regrouping every venue by UTC date.
Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Add a reusable canonical analytics DTO alongside the existing result types; R05 owns persisted/public-result cutover. Do not coerce owned financial facts into incompatible legacy position/round-trip fields or rewrite old rows.
Measurable benefit: comparable, independently checked rankings without a second ledger or a needless analytics rewrite.
Before implementation, pin reporting-only conventions in the handoff: account boundaries currently execute before equal-time observations and are not automatically close-equity samples; partial final sessions must be explicit; exposure needs a declared elapsed/venue-time denominator; the reviewed statistics currently assume 252 periods and default to 2% risk-free, so the adapter must pass a supported explicit policy and diagnose omitted inputs. These choices must not alter financial event ordering or risk semantics. Fills are not round trips.
## Exclusions
No accounting/fill recomputation in TypeScript, statistical library rewrite, forced native port, new service, or silent reinterpretation of historical results. Native analytics remain an option only if measured as a bottleneck.
## Likely files and ownership
- apps/stock/engine/src/financial/result.rs and replay reporting hooks (canonical outputs; legacy simple_results.rs remains separate)
- apps/stock/orchestrator/src/backtest/native-result.ts
- apps/stock/orchestrator/src/backtest/BacktestReport.ts
- libs/calculations/src/analytics/return-statistics.ts
- libs/calculations/src/analytics/equity.ts (review existing UTC grouping; use explicit session marks)
- libs/core/types/src/backtest-run.ts
Write locks: result-contract, native-public-api, replay-reporting, canonical-analytics, calculation-statistics. One owner controls the Rust/native reporting contract. A separate analytics owner may implement disjoint shared types/calculations/adapter files after root pins the contract; consume the exact accepted schema before integration. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F06](F06.md) and [F09](F09.md) integrated.
Architecture decisions: ADR-002, ADR-003. 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
- Fees/P&L/equity/trades reconcile to Rust outputs; session returns include the final session and use the declared risk-session/calendar policy.
- Sharpe uses periodic excess-return mean/std; Sortino uses downside deviation relative to the declared target; zero-variance/undefined cases are null with reasons.
- Exposure uses the union of occupied intervals; open positions count; attribution distinguishes fills and round trips.
- Reviewed calculation functions are reused where their conventions match. Any deliberate difference has a versioned policy and independent arithmetic fixture, not an unexplained second formula.
- The additive canonical analytics DTO preserves nullable/unsupported metrics and fill ownership without invoking legacy percentage conversion. Existing result mapping and frontend fixtures remain unchanged and pass. Persisted canonical rows/public DTO conversion remain R05; this story does not enable canonical web runs.
- Preserve the sequential equal-time marking policy and its material risk limitation in result provenance: intermediate valuations may latch halts despite a recovered synchronized value. Do not report such traces as atomically marked portfolio risk. Before canonical multi-asset default cutover, apply R05's explicit owner policy-review gate; component F06 acceptance does not satisfy it.
## Mandatory tests
- two_session_marks, constant_negative_returns, zero_variance, overlapping_positions, open_position_exposure.
- Existing result mapping and frontend metric unit fixtures; documented independent arithmetic cross-check.
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
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
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
Owner instruction: commit accepted F09/P07 and continue the backlog. F09/P07 are committed in `e3bd722`; F08 is the next code/ADR-ready story. These are reporting conventions, not changes to approved financial/risk policy.
### Native financial reporting owner
- Keep `Replay.events`, event indexes/IDs, `ReplayConfig`, `ReplayCheckpoint`, all financial receipts and existing trace/projection wire output unchanged. Add a small private reporting accumulator; restore already replays the retained decisions and must rebuild identical reporting facts without a new checkpoint schema.
- Periods follow the initial account risk session plus declared risk boundaries. Clip to `[tradeStart, tradeEnd]`; never infer UTC or asset venue days. At each boundary, sample the preceding period after **all** equal-time Observation events, before Decision/Execution. Risk reset still occurs in its existing earlier phase. Initial equity comes from Rust, and terminal equity is always retained.
- First periods clipped by tradeStart have `partialStart`; final periods without a declared closing boundary at tradeEnd have `partialEnd`. An exact terminal boundary emits one preceding period, not a zero-length new period. Retain partial returns/history but exclude them from full-period statistics. Last available marks remain explicit; do not claim freshness or atomic portfolio risk.
- Exposure is the union of account occupancy intervals over elapsed calendar time, including overnight/weekends. Observe actual non-replayed committed fills, then use existing `Ledger::owned_quantities().next().is_some()`; no quantity reconstruction. Merge adjacent intervals, omit zero-length intervals, and clip open holdings at tradeEnd for measurement only. No synthetic closing fill. Encode `occupiedMs`/`elapsedMs` as canonical nonnegative integer strings to preserve durations spanning the supported timestamp domain.
- Sampling failures must not reorder or mutate financial transitions or overwrite a financial failure. Report access rejects incomplete/failed/disposed or unavailable reporting state.
- Add native `report(identityJson)` beside unchanged `finalize()`/`project()`. Wire output is `format: "report"`, `reportingVersion: 1`, `projectionVersion: 1`, `financialVersion: 1`, the existing provenance/view/limitations and financial `projection`, plus `reporting` below. Keep reporting outside strategy contexts.
```ts
reporting: {
calendarId: string;
calendarRevision: string;
tradeStart: number;
tradeEnd: number;
initialEquity: FinancialDecimal;
sampling: 'account-boundary-after-observations-v1';
exposureBasis: 'elapsed-calendar-time';
sessions: {
session: RiskSessionIdentity;
periodStart: number;
periodEnd: number;
partialStart: boolean;
partialEnd: boolean;
equity: FinancialDecimal;
}[];
occupiedIntervals: { start: number; end: number }[];
occupiedMs: string;
elapsedMs: string;
}
```
- Extend the same TS native session/conformance/worker path with explicit `resultFormat: "report"`, strict parsing and captured format/identity/policy guards. Old omitted/trace/projection behavior and hashes stay stable. Root accepts the schema before the analytics consumer integrates it.
### TypeScript analytics owner
- Add application-independent `CanonicalBacktestAnalytics`/policy types adjacent to `BacktestRunResult`, without widening/reinterpreting the legacy DTO. One orchestrator adapter composes `{ financial: ReplayReportResult, analytics: CanonicalBacktestAnalytics }`.
- Adapter input requires policy version 1, positive finite `periodsPerYear`, explicit finite `annualRiskFreeRate` or `null`, and `benchmark: null`. Benchmark-dependent metrics are unavailable in v1; reject unsupported benchmark input. Output policy also records the fixed conventions, calendar identity and units. These are recorded conventions, not new configurable switches.
- Compute ratios from authoritative equity samples only. Include every session return, including partial terminal periods, with eligibility flags. Use only complete periods with defined positive baselines for periodic statistics; do not silently discard undefined full-period returns to create a different sequence.
- Reuse reviewed `returnStatistics`, equity/drawdown helpers and primitives. Extend `returnStatistics` minimally with explicit periods/year and nullable risk-free input, preserving old defaults for existing callers. Missing risk-free input leaves volatility/tail statistics available but target-dependent ratios/downside deviation null. Sample standard deviation uses n−1; downside RMS uses all n observations relative to annualRiskFreeRate/periodsPerYear. Exactly constant finite input has zero deviation; no arbitrary epsilon.
- Drawdown is explicitly session-end/terminal-sampled, not maximum intraday drawdown. Total return uses initial-to-terminal equity; CAGR may use actual elapsed calendar time with the fixed 365-day-year convention, including partial endpoints. This does not treat a partial period as a complete session. Zero/nonpositive baselines and nonfinite/undefined results produce null with reasons.
- Reuse a narrowly extracted drawdown-only helper instead of invoking unused UTC Date grouping, since native safe-integer timestamps exceed JavaScript Date's range. Positive initial equity and elapsed time with terminal equity zero has CAGR −1; negative terminal equity remains unsupported. Pin both edge cases with independent tests. Policy must state that marks are last available and per-session freshness is not certified.
- Report `fillCount` separately. Round-trip count/win rate/profit factor/average win/loss are unsupported/null; no inferred trade grouping, position marks, average cost or financial postings. Preserve exact Rust financial facts in the composed report.
- Keep legacy `BacktestReport`, normalization, stored-row mapping and UI unchanged. R05 will consume this additive contract during its separately gated persistence/public-result migration. Existing compatibility tests must pass.
### Required additional validation
- Rust: boundary sample after observations versus unchanged earlier risk reset; equal-time sequential risk halt still latched; first/final partial periods and exact terminal-boundary deduplication; exposure overlap/open positions/same-time owner handoff; no trade/stale marks; restore after every event including within observation groups; unchanged financial checkpoint/trace/project results.
- TS/native: report format/identity/calendar/terminal-value validation; worker format/cancellation/failure guards; two sessions 100 → 110 → 99 yield +10%/−10%; partial returns retained but not annualized as full sessions; missing rates/benchmark; constant negative and nonbinary constant returns; unsupported round trips remain null; genuine zero exposure survives the additive adapter.
- Run existing calculation, mapping and frontend metric/provenance fixtures, full repository checks and scoped strict test TypeScript. Worker changes require disposable PostgreSQL/Redis recovery gates. Measure reporting overhead against the accepted compact path with identical economic hashes; no timing assertions, new cache/DSL, journal deletion, or unrelated hot-loop optimization.