> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sequency.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Regime vnext rd

# Regime vNext R\&D Runbook

This runbook covers the R\&D-ready regime vNext workflow for comparing the legacy
direction x volatility grid with the vNext swing axes. It is not a production
policy rollout guide.

## Current Scope

Available for swing/daily R\&D backtests:

* `v2_risk_state`
* `v2_volatility_change`
* `v2_directional_pressure`
* combined tuple attribution from those three axes
* legacy `by_regime_grid` as shadow comparison data

Unavailable for swing/daily execution gates:

* `v2_breadth_state`
* `v2_correlation_state`
* `v2_intraday_structure`
* macro horizon as an execution gate

Macro snapshots are metadata/analysis overlays only and require
`feature_binding='prior_session'` plus provenance in `source_refs`. Intraday
snapshots require `feature_binding='prior_bar'`; if prior-bar structure inputs
are absent, the snapshot reports `intraday_structure='unavailable'`.

## Emitted vs Corrected

Use `variant='emitted'` for point-in-time checks and executable historical
backtests. Emitted rows represent what was available at the time.

Use `variant='corrected'` only for offline diagnostics, distribution studies, and
historical detector analysis. Corrected rows may include backfilled revisions and
must not be used as an executable historical gate.

## Latest Legacy vs vNext Comparison

Run from `data/api`:

```bash theme={null}
venv/bin/python -m app.services.regime_vnext.comparison \
  --from 2026-06-18 \
  --to 2026-06-22 \
  --variant emitted \
  --logic-version sp1-v1
```

This prints latest assignment, distributions, episode counts, and the legacy-grid
to vNext tuple crosswalk. Empty windows are valid output and mean no pinned
archive rows matched the requested window.

## Five-Year Corrected Diagnostic

Run from `data/api`:

```bash theme={null}
venv/bin/python -m app.services.regime_vnext.comparison \
  --from 2021-06-22 \
  --to 2026-06-21 \
  --variant corrected \
  --logic-version sp1-v1
```

Treat this as detector research only. Do not use corrected five-year output to
approve live policy or historical execution gates.

## SPY/QQQ Return Overlay

Run from `data/api`:

```bash theme={null}
venv/bin/python - <<'PY'
import asyncio
from datetime import date

from app.core.database import get_ts_client, init_clients, shutdown_clients
from app.services.regime_vnext.comparison import (
    compare_regime_vnext_return_attribution,
)


async def main() -> None:
    await init_clients()
    try:
        report = await compare_regime_vnext_return_attribution(
            get_ts_client(),
            date(2021, 6, 22),
            date(2026, 6, 21),
            variant="corrected",
            logic_version="sp1-v1",
            symbols=("SPY", "QQQ"),
        )
        print(report)
    finally:
        await shutdown_clients()


asyncio.run(main())
PY
```

The overlay attributes benchmark close-to-close returns by the latest prior
archive session. It is useful for detector diagnostics, not strategy alpha by
itself.

## vNext-Enabled Backtests

Backtest requests must carry explicit v2 pins:

* `regime_engine_version='v2'`
* `regime_logic_version`
* `evidence_logic_version`
* `regime_variant`
* `regime_horizon_profile='swing'`
* `policy_version`
* `evidence_id` or an approved `evidence_selector`

Example request body:

```json theme={null}
{
  "date_from": "2026-06-22",
  "date_to": "2026-07-22",
  "symbols": ["SPY"],
  "initial_capital": 100000,
  "regime_engine_version": "v2",
  "regime_logic_version": "sp1-v1",
  "evidence_logic_version": "v2-logic-1",
  "regime_variant": "emitted",
  "regime_horizon_profile": "swing",
  "policy_version": "policy-v1",
  "evidence_id": "ev1",
  "strategy_rules": {
    "entry_groups": [
      {
        "id": "risk-gate",
        "label": "Elevated risk gate",
        "action": "enter_long",
        "conditions": [
          {
            "source": "regime",
            "field": "v2_risk_state",
            "operator": "eq",
            "value": "elevated"
          }
        ]
      }
    ],
    "exit_groups": []
  }
}
```

Submit it with the normal authenticated backtest API:

```bash theme={null}
curl -sS -X POST "http://localhost:8000/api/graph/v1/backtest/v2/run" \
  -H "Authorization: Bearer ${SUPABASE_JWT}" \
  -H "X-Requested-With: XMLHttpRequest" \
  -H "Content-Type: application/json" \
  --data-binary @/tmp/regime-v2-backtest.json
```

Result reads add vNext attribution under `detailed_metrics` when v2 tags are
present:

* `by_regime_v2_risk_state`
* `by_regime_v2_volatility_change`
* `by_regime_v2_directional_pressure`
* `by_regime_v2_tuple`

Existing `by_regime_grid` remains unchanged.

## Strategy-Family Outcome Export

Run from `data/api` after a backtest completes:

```bash theme={null}
RUN_ID="run-id" USER_ID="user-id" venv/bin/python - <<'PY'
import asyncio
import os

from app.core.database import get_ts_client, init_clients, shutdown_clients
from app.services.regime_vnext.strategy_outcomes import (
    export_strategy_family_outcomes_for_run,
)


async def main() -> None:
    await init_clients()
    try:
        report = await export_strategy_family_outcomes_for_run(
            get_ts_client(),
            run_id=os.environ["RUN_ID"],
            user_id=os.environ["USER_ID"],
            variant="emitted",
            logic_version="sp1-v1",
        )
        print(report.to_dict())
    finally:
        await shutdown_clients()


asyncio.run(main())
PY
```

Strategy-family outcomes use realized net `pnl_dollars` when available for win
count, probability of profit, and profit factor. Rows without net P\&L are marked
with an explicit fallback note.

## Interpreting Evidence

SPY/QQQ overlays answer: how did the benchmark behave under detector states?

Strategy-family outcome exports answer: how did a strategy family perform under
detector states after the backtester's costs and fills?

Do not use benchmark overlays as proof that a strategy has edge. Use them as
context beside strategy-family outcomes.

## R\&D Readiness Checklist

* v2 swing axes are read-only rule context.
* v2 requests require explicit variant/version/evidence pins.
* historical executable reads require `variant='emitted'`.
* vNext axes derive from raw PIT substrate fields, not legacy grid labels.
* vNext attribution is additive beside `by_regime_grid`.
* macro is metadata/analysis only.
* intraday requires prior-bar structure and is unavailable until a PIT source is proven.
* diagnostics are marked as R\&D evidence unless backed by approved pinned evidence.

## Production Policy Checklist

Before treating vNext as executable policy, complete separate approval work:

* durable point-in-time evidence construction
* approved evidence aliases to immutable artifact ids
* small-sample, autocorrelation, and multiple-comparison controls
* risk multiplier composition with sleeve sizing and vol targeting
* production artifact persistence and audit review
* operator signoff on policy versions and config versions

## Historical exposure of the fabricated-`normal` defect (data#1607)

Between 2026-06-22 (`1ec06874`, `RiskState` introduced) and 2026-08-04 (fail-closed
fix), `classify_snapshot` resolved missing/non-finite risk inputs to `normal` and
`policy._risk_multiplier` would have handed that full 1.0 sizing.

**Verified realized exposure: ZERO, across all four possible vehicles** (2026-08-04):

1. **Persisted snapshots** — `regime_v2_artifacts` had 0 rows on prod; the
   `LocalRegimeArtifactStore` fallback dir was absent on compute.
2. **Research artifacts** — no producer ever called the classify path; the
   research\_loop / research\_grammar / cross-sectional / discovery pipelines have
   zero references to vNext `risk_state`, and no freeze/tape schema carries it.
3. **Sealed docs** — the only risk\_state numbers in sealed evidence
   (`2026-06-22-regime-vnext-prereg-reset-evidence.md` §2.2) are derived from
   `regime_archive` percentiles via the backtester resolver, whose non-Nullable
   `vol_pctile` makes the missing-input fallback structurally unreachable there.
4. **Live sizing** — no Go service, agent, script, or app surface consumed
   `risk_state`/`risk_multiplier_hint` during the window.

**No quarantine migration is therefore required.** The cutover marker is
`RegimeSnapshotV2.risk_classifier_version`: absent-or-`"risk-v2.0"` = pre-fix
semantics (fabricated normal possible), `"risk-v2.1"` = fail-closed. Research
slicing on vNext risk\_state MUST filter or stratify on it.

If snapshots are ever found in `regime_v2_artifacts` predating the fix
(`payload_json` lacking the `risk_classifier_version` key), they are pre-fix
records: treat **every** `normal`/`calm` row as **unassessable** unless its
complete point-in-time inputs can be reconstructed from source evidence and
re-classified under `risk-v2.1`. Do NOT filter on `unavailable_inputs` — the
pre-fix recorder itself was defective: it checked `is None` only (NaN passed
invisibly) and never recorded `drawdown_pct`/`tail_loss_z` at all, so an
empty `unavailable_inputs` on a pre-fix row proves nothing.

Policy enforces this mechanically: `evaluate_policy` zero-sizes and blocks any
snapshot whose `risk_classifier_version` is not in
`ACTIONABLE_RISK_CLASSIFIER_VERSIONS`, so a legacy payload cannot authorize
sizing regardless of what it displays.
