From e0c8bf320df636de70711a41323a3b9521400063 Mon Sep 17 00:00:00 2001 From: Tomasz Wilczega <90728533+tomlupo@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:17:04 +0200 Subject: [PATCH] chore(kit): retire the research skills qute-research now owns (TOM-1221 slice 6) Moving means moving: each skill below is released in qute-research 0.5.0 (tomlupo/qute-plugins, plugins/qute-research) and deleted here. - research/research-refute -> qute-research skills/research-refute - research/research-reproduce -> qute-research skills/research-reproduce - research/research-robustness -> qute-research skills/research-robustness - research/research-sweep -> qute-research skills/research-sweep - research/research-bakeoff -> qute-research skills/research-bakeoff - quant/acceptance-gates -> qute-research skills/acceptance-gates + scripts/acceptance_gates.py (engine-neutral; every kit CLI flag is present there) - quant/investment-research -> qute-research skills/research/references/ method-investment.md + method-signal.md Kept, because the plugin does not yet carry all of it: - quant/investment-research-formal: the METHODOLOGY.md skeleton, literature note and MiFID II mapping have no home in qute-research. Repointed at qute-research /research. - quant/investment-research-dashboard: /finding-report covers only a single finding's one-pager; general dashboards, research_story, multi-profile and weight-evolution views are the kit's (the plugin's own "Out of scope" list). The ci.yml reporting-contract job stays with it. References fixed: INVENTORY.md (counts 19 -> 12, rows, moved-to note), README.md count, CLAUDE.md layout, docs/playbooks/investment-research-workflow.md. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_014DiJ2ntXKfq49HAE1Jrfdz --- CLAUDE.md | 2 +- INVENTORY.md | 29 +- README.md | 9 +- claude/skills/quant/acceptance-gates/SKILL.md | 174 ------- .../acceptance-gates/scripts/dsr-gate.py | 352 -------------- .../scripts/factor-decomp-gate.py | 239 ---------- .../acceptance-gates/scripts/nw-tstat-gate.py | 207 --------- .../scripts/tests/test_dsr_gate.py | 287 ------------ .../scripts/tests/test_factor_decomp_gate.py | 124 ----- .../scripts/tests/test_nw_tstat_gate.py | 229 --------- .../quant/investment-research-formal/SKILL.md | 14 +- .../skills/quant/investment-research/SKILL.md | 438 ------------------ .../references/signal-research-lifecycle.md | 208 --------- .../skills/research/research-bakeoff/SKILL.md | 46 -- .../skills/research/research-refute/SKILL.md | 62 --- .../research/research-reproduce/SKILL.md | 47 -- .../research/research-robustness/SKILL.md | 46 -- .../skills/research/research-sweep/SKILL.md | 55 --- .../playbooks/investment-research-workflow.md | 17 +- 19 files changed, 28 insertions(+), 2557 deletions(-) delete mode 100644 claude/skills/quant/acceptance-gates/SKILL.md delete mode 100644 claude/skills/quant/acceptance-gates/scripts/dsr-gate.py delete mode 100644 claude/skills/quant/acceptance-gates/scripts/factor-decomp-gate.py delete mode 100644 claude/skills/quant/acceptance-gates/scripts/nw-tstat-gate.py delete mode 100644 claude/skills/quant/acceptance-gates/scripts/tests/test_dsr_gate.py delete mode 100644 claude/skills/quant/acceptance-gates/scripts/tests/test_factor_decomp_gate.py delete mode 100644 claude/skills/quant/acceptance-gates/scripts/tests/test_nw_tstat_gate.py delete mode 100644 claude/skills/quant/investment-research/SKILL.md delete mode 100644 claude/skills/quant/investment-research/references/signal-research-lifecycle.md delete mode 100644 claude/skills/research/research-bakeoff/SKILL.md delete mode 100644 claude/skills/research/research-refute/SKILL.md delete mode 100644 claude/skills/research/research-reproduce/SKILL.md delete mode 100644 claude/skills/research/research-robustness/SKILL.md delete mode 100644 claude/skills/research/research-sweep/SKILL.md diff --git a/CLAUDE.md b/CLAUDE.md index f882e3a1..7cf53a25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,7 @@ guards, hooks, review/release regime, or plugin skills belong in qute-plugins. | Path | Contents | |---|---| -| `claude/skills/` | Generic kit skills, grouped: `quant/`, `engineering/`, `research/`, `visual/` (`/SKILL.md` + assets) | +| `claude/skills/` | Generic kit skills, grouped: `quant/`, `engineering/`, `visual/` (`/SKILL.md` + assets) | | `claude/agents/` | Personal-kit subagents | | `claude/settings/` | Claude Code project settings profiles | | `claude/root-files/` | Root-level CLAUDE.md / AGENTS.md starters | diff --git a/INVENTORY.md b/INVENTORY.md index 4edea570..9f47e282 100644 --- a/INVENTORY.md +++ b/INVENTORY.md @@ -18,35 +18,20 @@ A repo that copies a kit skill stamps it with `PROVENANCE.yaml` (source path, source commit, each file `tracked` or `forked from , reason: …`) so the copy's drift can be checked. -## Skills (19, grouped by directory under `claude/skills/`) +## Skills (12, grouped by directory under `claude/skills/`) -### Quant / data (`quant/`, 9) +### Quant / data (`quant/`, 7) | Name | Description | |---|---| -| `acceptance-gates` | Statistical acceptance gates — deflated Sharpe (DSR), Newey-West HAC t-stat, factor decomposition. Moving to qute-research as engine-neutral gates (TOM-1221) | | `analizy-pl-data` | Programmatic access to Polish investment fund data from analizy.pl | | `atlasetf-scraper` | Scrape ETF data from atlasetf.pl (screener of ~13k funds, per-ISIN detail, prices) via its JSON API | | `gpw-benchmark-scraper` | Scrape gpwbenchmark.pl (WIBID/WIBOR reference rates, index list with ISINs, per-index OHLC history) | -| `investment-research` | Iterative investment research from question to deliverable. Moving to qute-research as a method protocol (TOM-1221) | -| `investment-research-formal` | Structured, auditable research with hypotheses + evidence chain. Moving to qute-research (TOM-1221) | -| `investment-research-dashboard` | Self-contained (offline, no CDN) Plotly HTML dashboards for finance; bundles the canonical `reporting/` lib (`base`/`backtest_dashboard`/`research_story`), reuse-first | +| `investment-research-formal` | Structured, auditable research with hypotheses + evidence chain. Its research regime is qute-research's; stays until its METHODOLOGY.md skeleton and MiFID II mapping have a home there (TOM-1221) | +| `investment-research-dashboard` | Self-contained (offline, no CDN) Plotly HTML dashboards for finance; bundles the canonical `reporting/` lib (`base`/`backtest_dashboard`/`research_story`), reuse-first. A single finding's one-pager is qute-research's `/finding-report` | | `market-datasets` | Fetch market data from Stooq, NBP, Yahoo, FRED, Tiingo, CCXT, FinancialData | | `pipeline-docs` | 4-doc pattern (instruction / dataset / methodology / reference) | -### Multi-agent research workflows (`research/`, 5) - -Each fans out a multi-agent Workflow. Moving to qute-research with agent types -that exist where they run (TOM-1221 slice 3). - -| Name | Description | -|---|---| -| `research-bakeoff` | Tournament: implement + evaluate N candidate approaches in parallel worktrees, pick a winner | -| `research-refute` | Adversarial panel of skeptics, each attacking a finding via a different failure mode | -| `research-reproduce` | Reproduce a result via independent paths (implementation / inputs / library), cross-check | -| `research-robustness` | Stress a method across windows × regimes × parameters; collect a robustness grid | -| `research-sweep` | Multi-modal evidence sweep (own data, benchmarks, atlas notes, literature, code) + cited synthesis | - ### Engineering (`engineering/`, 1) | Name | Description | @@ -71,6 +56,12 @@ Unused, broken, or covered elsewhere; in git history if ever needed: (`grill`, `tdd`, `triage`, `to-prd`, `to-slices`; Matt Pocock's plugin owns them, and qute-essentials depends on it), `brand-sonte` (archived project). +### Moved to qute-research 2026-09-28 (TOM-1221) + +`acceptance-gates`, `investment-research` (now its method protocols), +`research-refute`, `-reproduce`, `-robustness`, `-sweep`, `-bakeoff` — see the +qute-research README in `tomlupo/qute-plugins`. + ## Agents (2) | Name | Description | diff --git a/README.md b/README.md index 09c97b68..109e55bb 100644 --- a/README.md +++ b/README.md @@ -14,11 +14,10 @@ releases, or self-updates. ## The kit: `claude/` -19 generic skills (quant/data, multi-agent research workflows, engineering, -visual/UX), 2 agents, 3 settings profiles, 2 root-file -starters. Browse [`INVENTORY.md`](INVENTORY.md) for the full map. A skill bound -to one project does not live here: its master is that project's repo -(TOM-1235, 2026-09-28). +12 generic skills (quant/data, engineering, visual/UX), 2 agents, 3 settings +profiles, 2 root-file starters. Browse [`INVENTORY.md`](INVENTORY.md) for the +full map. A skill bound to one project does not live here: its master is that +project's repo (TOM-1235, 2026-09-28). **New generic skills start here** — the kit is the incubator; the rule and the promotion path are in [`CLAUDE.md`](CLAUDE.md). diff --git a/claude/skills/quant/acceptance-gates/SKILL.md b/claude/skills/quant/acceptance-gates/SKILL.md deleted file mode 100644 index 68649605..00000000 --- a/claude/skills/quant/acceptance-gates/SKILL.md +++ /dev/null @@ -1,174 +0,0 @@ ---- -name: acceptance-gates -description: "Deterministic robustness/acceptance gates for a quant backtest finding — Deflated Sharpe Ratio (DSR, Bailey/López de Prado), Newey-West HAC t-stat + min-OOS-window, and factor-decomposition (Jensen's alpha). Thin CLIs over the quantbox framework's tested statistics (quantbox.analysis); requires quantbox installed. Triggers: DSR gate, deflated sharpe, is this overfit, multiple-testing correction, Newey-West t-stat, HAC standard errors, factor decomposition, Jensen's alpha, is this just beta, acceptance gate, robustness gate before promotion." ---- - -# acceptance-gates — DSR / Newey-West / factor-decomposition robustness gates - -Three deterministic, thin CLI gates that answer three DIFFERENT questions about a -candidate strategy's backtest result, before it's trusted enough to promote: - -| Gate | Question | Script | -|---|---|---| -| **DSR** | Is the Sharpe ratio real once you deflate for the return distribution's actual skew/kurtosis AND how many trials were tried? | `scripts/dsr-gate.py` | -| **Newey-West** | Is the mean OOS return significant once autocorrelation is corrected for, AND was the OOS window long enough to trust at all? | `scripts/nw-tstat-gate.py` | -| **Factor decomposition** | Is the return NOVEL, or just paid-for exposure to a known factor (beta, momentum, carry)? | `scripts/factor-decomp-gate.py` | - -Each takes a return series (CSV/Parquet) and prints a JSON verdict. None of them -know anything about a specific harness, config format, or dataset — they consume -an already-built return/factor series. - -**The statistics themselves are NOT in this skill.** They live in the quantbox -framework (`quantbox.analysis`), which is tested there (parity proof against the -retired hand-rolled implementations, plus the pinned DSR false-PASS-band -regression). Each script here is a THIN wrapper: it loads the data, calls the -framework, applies the gate's threshold/policy, and prints JSON. This is -deliberate — three independent hand-rolled copies of the DSR math once co-existed -and drifted (one silently passed overfit strategies with a naive normal null), -which is exactly what centralising the math into one tested home prevents. - -**What stays OUT of the gates on purpose:** anything that knows how to BUILD the -input series from harness-specific data (e.g. a point-in-time crypto factor panel -from a specific dataset/universe) belongs to the consuming research repo, not -here. These gates only consume an already-built return/factor series. - -## Runtime dependencies (state them before you run) - -These gates import the framework: - -```python -from quantbox.analysis import deflated_sharpe_ratio_from_returns # dsr-gate.py -from quantbox.analysis import newey_west_tstat # nw-tstat-gate.py -from quantbox.analysis import factor_regression # factor-decomp-gate.py -``` - -- **`quantbox`** (with `quantbox.analysis`, i.e. a version that carries the - `analysis.dsr` + `analysis.hac` modules — statsmodels-backed HAC landed - alongside DSR). This is the ONE hard dependency; everything else - (`numpy`, `scipy`, `pandas`, `patsy`, `statsmodels`) comes transitively with - it. If `import quantbox.analysis` fails, install quantbox in the environment - you run these from — do not reintroduce a local copy of the math. -- **`pytest`** additionally, to run this skill's own CLI test suite. - -Because the gates now depend on quantbox, "portable to any quant repo" narrows to -"portable to any repo that has quantbox installed" — the trade for never -hand-rolling (and re-bugging) the statistics again. - -## Ethos — assume overfit until proven - -Run ALL THREE gates before trusting a backtest headline. Each catches a different -failure mode a single Sharpe number hides: - -- **DSR catches**: multiple-testing overfit (you tried 50 configs and cherry-picked - the best) and fat-tail distortion (skew/kurtosis inflate the variance of the Sharpe - estimator, so a naive normal-null test overstates confidence). -- **Newey-West catches**: autocorrelation-inflated significance (overlapping signals - make a naive t-test look more confident than it is) and a too-short OOS window - hiding behind an otherwise-clean Sharpe. -- **Factor decomposition catches**: an edge that's actually just leveraged beta or a - well-known factor re-packaged as a "novel" strategy. - -A strategy passing DSR + Newey-West but failing factor decomposition is not -worthless — it may be a legitimate, honest factor bet — but it is NOT a novel edge -and should not be promoted as one. - -## The DSR range convention (read this before running dsr-gate.py) - -`n_trials` — how many configs/hypotheses were tried before landing on this one — is -almost never an honest, uncontested single number. It depends on how you bound "the -search" (this exact sweep? every variant ever tried? every hypothesis filed in the -vault?). **Do not report DSR at one n_trials value and let the verdict hinge on that -judgment call.** Instead: - -``` -dsr-gate.py --returns oos_returns.csv --n-trials 1,5,10,20,50,100 --periods 365 -``` - -The gate's `dsr_pass` is decided from the **conservative end** (the highest n_trials -in the range — most deflation, lowest DSR), never from whichever n_trials value -happens to pass. Default range: `1,5,10,20,50,100`. Default threshold: **0.95**, -one-sided (Bailey/López de Prado standard — do not lower it to make a result pass). -`--threshold` must be finite and strictly between 0 and 1. - -**Kurtosis convention (load-bearing, easy to get wrong):** `--kurtosis` and the -return-series path both use **PEARSON (non-excess) kurtosis**, where 3.0 = normal -distribution — NOT excess kurtosis (0.0 = normal). `scipy.stats.kurtosis()` returns -EXCESS kurtosis by **default** (`fisher=True`); you must pass `fisher=False` to get -the convention this gate expects. Passing excess kurtosis silently understates the -Mertens variance term and can flip a FAIL to a PASS. `quantbox.analysis.dsr` rejects -any skew/kurtosis pair that is mathematically impossible under the Pearson convention -(`kurtosis < skew**2 + 1` — an algebraic identity), which catches the most common -form of this mixup, e.g. `skew=0, kurtosis=0`. - -**IID assumption:** the annualisation (`sqrt(periods)` scaling between per-period and -annualised Sharpe) assumes returns are i.i.d. — no serial autocorrelation. If the -return series is autocorrelated (overlapping windows, slow-moving positions), the -annualisation is biased and the gate's threshold comparison is not reliable as stated -(use the Newey-West gate for an autocorrelation-robust t-stat). - -## Quick start - -```bash -# 1. DSR — from a raw OOS return series (recommended: real skew/kurtosis, not assumed) -python3 scripts/dsr-gate.py --returns oos_returns.csv --n-trials 1,5,10,20,50,100 --periods 365 - -# 2. Newey-West + min-OOS-window -python3 scripts/nw-tstat-gate.py --returns oos_returns.csv --t-threshold 2.0 --min-oos-periods 252 - -# 3. Factor decomposition (needs a factor panel built by the consuming repo) -python3 scripts/factor-decomp-gate.py --returns oos_returns.csv --factors factor_panel.csv \ - --factor-columns mkt,mom,carry --t-threshold 2.0 -``` - -All three print JSON with a `gate_pass: bool` field. All three exit non-zero and -print `{"error": "..."}` on degenerate input — **never treat a non-zero exit as "the -gate didn't run, ignore it" — it means the input itself is broken and needs fixing, -not bypassing.** - -## Degenerate input — every gate fails loudly, never silently passes - -The load-bearing invariant, enforced in the framework so every caller inherits it: - -- **DSR** (`quantbox.analysis.dsr`): rejects inf/NaN Sharpe, `n_trials<=0`, - `periods<=0`, `n_obs<=1`, negative SR-estimator variance (garbage - skew/kurtosis), zero-variance returns, and impossible Pearson moments. - `--sharpe` without `--skew`/`--kurtosis`/`--n-obs` is refused outright — there - is no default skew=0/kurtosis=3 (that WAS the original normal-null bug). -- **Newey-West** (`quantbox.analysis.hac.newey_west_tstat` + - `nw-tstat-gate.py`): NaN/Inf return observations RAISE by default - (`--allow-nonfinite-drop` opts back in explicitly, and the output records - `n_obs_raw` / `n_nonfinite_dropped`). `--oos-periods` can only narrow the - recorded window, never claim more than the actual finite-return count. -- **Factor decomposition** (`quantbox.analysis.hac.factor_regression` + - `factor-decomp-gate.py`): an empty factor-column list raises rather than - silently running an intercept-only "regression" that can PASS on raw mean - return alone. - -## Files - -``` -scripts/ - dsr-gate.py DSR CLI gate (n_trials range, conservative-end decision) - nw-tstat-gate.py Newey-West HAC t-stat + min-OOS-window CLI gate - factor-decomp-gate.py factor-decomposition (Jensen's alpha) CLI gate - tests/ - test_dsr_gate.py CLI-level tests (the math regression lives in quantbox) - test_nw_tstat_gate.py - test_factor_decomp_gate.py -``` - -The DSR / Newey-West / factor-regression math and its regression suite live in the -`quantbox` framework (`quantbox.analysis.dsr`, `quantbox.analysis.hac`), not here. -Do NOT reimplement skew/kurtosis/expected-max-SR or a HAC sandwich in this repo — -import from `quantbox.analysis`. - -## Provenance - -The gates originally hand-rolled their statistics inside these scripts (and, in -quantbox-lab, in a `scripts/lib/dsr.py` and in `carver_prelive_gauntlet.py`). -2026-07-19 those statistics were consolidated into the quantbox framework -(`quantbox.analysis`), where they are packaged, typed, and tested — including a -numeric-parity proof that the statsmodels-backed HAC reproduces the retired -hand-rolled estimator to machine precision. These scripts became thin wrappers. -The framework-usage linter (`scripts/lint/check_framework_usage.py`) now hard-gates -re-introducing a hand-rolled DSR / Newey-West / OLS in the lab. diff --git a/claude/skills/quant/acceptance-gates/scripts/dsr-gate.py b/claude/skills/quant/acceptance-gates/scripts/dsr-gate.py deleted file mode 100644 index 3202a74f..00000000 --- a/claude/skills/quant/acceptance-gates/scripts/dsr-gate.py +++ /dev/null @@ -1,352 +0,0 @@ -#!/usr/bin/env python3 -"""Genuine Deflated Sharpe Ratio (DSR) gate — reports across a RANGE of n_trials. - -DSR (Bailey & López de Prado, 2014) tests whether an observed Sharpe ratio -still looks skillful once you deflate for (a) the shape of the actual return -distribution — skew and kurtosis inflate/deflate the variance of the Sharpe -estimator (Mertens correction) — and (b) how many trials/configs were tried -before this one was picked (the expected-max-Sharpe benchmark over -``n_trials``). Both terms are load-bearing; omitting either is not DSR, it is -a plain Sharpe-significance test wearing a DSR label. - - PROVENANCE: ported verbatim from quantbox-lab's corrected dsr-gate.py - (branch quark/fix-dsr-gate, commit b392073, 2026-07-19). That fix replaced - a prior version which computed t = sharpe * sqrt(n_years) against a - Bonferroni-corrected NORMAL null — i.e. silently assumed zero skew/kurtosis - and used leading-order (not exact) deflation. Verified false-PASS band at - N=20 trials: an old-style z-stat in [3.1, 3.6] passed the old gate while - the true DSR sat at 0.88-0.95 — BELOW the 0.95 acceptance bar. - - RANGE CONVENTION (adopted here, not present in the original single-N gate): - a single n_trials count is almost never an honest, uncontested number — the - true trial count depends on how you bound "the search" (this exact config - sweep? every variant ever tried? every hypothesis in the vault?). Reporting - DSR at ONE n_trials lets the number hinge entirely on that judgment call. - Instead this gate reports DSR across a RANGE (default 1,5,10,20,50,100 — - quantbox-lab's scripts/analysis/carver_prelive_gauntlet.py convention) and - takes the gate PASS/FAIL decision from the CONSERVATIVE (highest n_trials, - i.e. most-deflated, lowest-DSR) end of that range. A strategy that only - clears the gate at n_trials=1 is not a strategy that clears the gate. - -The math itself lives in the framework — ``quantbox.analysis.dsr`` (imported -here as ``quantbox.analysis``) — this file is CLI plumbing only: parse args, -load returns, call the shared function once per n_trials in the range, apply -the acceptance threshold at the conservative end, print JSON. This repo owns -ZERO of the DSR statistics; if you need to change the math, change it in -quantbox, not here. - -KURTOSIS CONVENTION: --kurtosis (summary-stats path) and the return-series -path both use PEARSON (non-excess) kurtosis, where 3.0 = normal distribution -— NOT excess kurtosis (0.0 = normal). scipy.stats.kurtosis() returns EXCESS -kurtosis by DEFAULT (fisher=True); you must pass fisher=False to get the -convention this gate expects. Passing excess kurtosis here silently -understates the Mertens variance term and can flip a FAIL to a PASS. -quantbox.analysis.dsr rejects any skew/kurtosis pair that is mathematically -impossible under the Pearson convention (kurtosis < skew**2 + 1) — this is the -most common way the excess/Pearson mixup surfaces. - -IID ASSUMPTION: the annualisation (sqrt(periods) scaling between per-period -and annualised Sharpe, both directions) assumes returns are i.i.d. — no -serial autocorrelation. If the return series is autocorrelated (e.g. from -overlapping windows or slow-moving positions), sqrt(T) annualisation is -biased and this gate's threshold comparison is not reliable as stated. - -Two ways to provide input — pick ONE: - - 1. --returns (RECOMMENDED, the only way to get genuine DSR) - A CSV or Parquet file with a single numeric column of PER-PERIOD - returns (e.g. daily). Skew, kurtosis, T, and the per-period Sharpe are - all computed from the actual data — no assumptions. - - dsr-gate.py --returns returns.csv --n-trials 1,5,10,20,50,100 --periods 365 - - 2. --sharpe/--skew/--kurtosis/--n-obs (summary-stats path) - For when you don't have the raw return series but DO have its moments - (e.g. from a report). ALL FOUR are required together — there is no - silent default for skew/kurtosis. Passing --sharpe alone without - --skew/--kurtosis is refused: a Sharpe number alone cannot produce a - real DSR, and defaulting skew=0/kurtosis=3 would silently degrade this - back into the old normal-null bug. - - dsr-gate.py --sharpe 0.42 --skew -0.3 --kurtosis 5.1 --n-obs 1278 \\ - --n-trials 1,5,10,20,50,100 --periods 365 - -In both paths, --sharpe/--sr-annualized in the JSON output are ANNUALISED -for readability; the DSR test itself runs on per-period units internally -(quantbox.analysis.dsr). - -Prints JSON: {sr_period, sr_annualized, T, n_years, skew, kurtosis, -by_n_trials: {n_trials: {sr_std, sr0_annualized, z, psr_vs_zero, dsr}, ...}, -n_trials_conservative, dsr_conservative, threshold, dsr_pass}. -``dsr_pass`` is decided ONLY from the conservative (max n_trials) entry. -""" - -from __future__ import annotations - -import argparse -import json -import math -import sys -from pathlib import Path - -from quantbox.analysis import deflated_sharpe_ratio, deflated_sharpe_ratio_from_returns - -DEFAULT_N_TRIALS_RANGE = "1,5,10,20,50,100" - - -def _parse_n_trials_range(raw: str) -> list[int]: - """Parse a comma-separated n_trials range; every entry must be a positive int.""" - parts = [p.strip() for p in raw.split(",") if p.strip()] - if not parts: - raise ValueError(f"--n-trials must not be empty, got {raw!r}") - out: list[int] = [] - for p in parts: - try: - n = int(p) - except ValueError as e: - raise ValueError( - f"--n-trials entries must be integers, got {p!r} in {raw!r}" - ) from e - if n <= 0: - raise ValueError( - f"--n-trials entries must be positive, got {n!r} in {raw!r} (no multiple-testing penalty removal)" - ) - out.append(n) - return out - - -def _load_returns_column(path: str): - import pandas as pd - - p = Path(path) - if not p.exists(): - raise FileNotFoundError(f"returns file not found: {path}") - if p.suffix.lower() == ".parquet": - df = pd.read_parquet(p) - else: - df = pd.read_csv(p) - - if df.shape[1] == 1: - col = df.iloc[:, 0] - else: - candidates = [ - c for c in df.columns if str(c).lower() in ("return", "returns", "ret", "r") - ] - if not candidates: - raise ValueError( - f"returns file has {df.shape[1]} columns and none is named " - f"'return'/'returns'/'ret'/'r' — ambiguous, refusing to guess: {list(df.columns)}" - ) - col = df[candidates[0]] - return col.astype(float) - - -def _by_n_trials( - *, - n_trials_range: list[int], - sr_period_of, - T: int, - skew: float, - kurtosis: float, - periods: int, -): - """Compute the DSR result at each n_trials in the range. sr_period_of is a callable - T -> sr for the summary path parity, but here sr_period is fixed — kept simple: - caller passes the already-computed per-period sr via sr_period_of() returning it. - """ - ann = math.sqrt(periods) - sr_period = sr_period_of - by_n: dict[int, dict] = {} - for n in n_trials_range: - res = deflated_sharpe_ratio( - sr=sr_period, T=T, skew=skew, kurtosis=kurtosis, n_trials=n - ) - by_n[n] = { - "sr_std": round(res.sr_std, 6), - "sr0_annualized": round(res.sr0_period * ann, 4), - "z": round(res.z, 4), - "psr_vs_zero": round(res.psr_vs_zero, 6), - "dsr": round(res.dsr, 6), - } - return by_n - - -def run_from_returns(args) -> dict: - if args.periods <= 0: - raise ValueError(f"--periods must be positive, got {args.periods!r}") - n_trials_range = _parse_n_trials_range(args.n_trials) - - returns = _load_returns_column(args.returns) - # Compute T/skew/kurtosis/sr_period once from the data (n_trials-independent), - # then sweep n_trials through the shared deflated_sharpe_ratio() function. - seed = deflated_sharpe_ratio_from_returns(returns, n_trials=n_trials_range[0]) - n_years = seed.T / args.periods - by_n = _by_n_trials( - n_trials_range=n_trials_range, - sr_period_of=seed.sr_period, - T=seed.T, - skew=seed.skew, - kurtosis=seed.kurtosis, - periods=args.periods, - ) - return _to_output( - seed, by_n=by_n, n_years=n_years, periods=args.periods, threshold=args.threshold - ) - - -def run_from_summary(args) -> dict: - if args.periods <= 0: - raise ValueError(f"--periods must be positive, got {args.periods!r}") - n_trials_range = _parse_n_trials_range(args.n_trials) - if args.n_obs <= 1: - raise ValueError(f"--n-obs must be > 1, got {args.n_obs!r}") - if not math.isfinite(args.sharpe): - raise ValueError(f"--sharpe must be finite, got {args.sharpe!r}") - - sr_period = args.sharpe / math.sqrt(args.periods) # annualised -> per-period - seed = deflated_sharpe_ratio( - sr=sr_period, - T=args.n_obs, - skew=args.skew, - kurtosis=args.kurtosis, - n_trials=n_trials_range[0], - ) - n_years = args.n_obs / args.periods - by_n = _by_n_trials( - n_trials_range=n_trials_range, - sr_period_of=sr_period, - T=args.n_obs, - skew=args.skew, - kurtosis=args.kurtosis, - periods=args.periods, - ) - return _to_output( - seed, by_n=by_n, n_years=n_years, periods=args.periods, threshold=args.threshold - ) - - -def _to_output( - seed, *, by_n: dict, n_years: float, periods: int, threshold: float -) -> dict: - ann = math.sqrt(periods) - n_conservative = max(by_n.keys()) # highest n_trials = most deflated = conservative - dsr_conservative = by_n[n_conservative]["dsr"] - return { - "sr_period": round(seed.sr_period, 6), - "sr_annualized": round(seed.sr_period * ann, 4), - "T": seed.T, - "n_years": round(n_years, 4), - "skew": round(seed.skew, 4), - "kurtosis": round(seed.kurtosis, 4), - "by_n_trials": {str(n): v for n, v in sorted(by_n.items())}, - "n_trials_conservative": n_conservative, - "dsr_conservative": dsr_conservative, - "threshold": threshold, - # Gate decision is taken ONLY from the conservative (max n_trials) end. - "dsr_pass": bool(dsr_conservative >= threshold), - } - - -def main(argv: list[str]) -> int: - ap = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - ap.add_argument( - "--returns", - type=str, - default=None, - help="path to a CSV/Parquet file of per-period returns", - ) - ap.add_argument( - "--sharpe", - type=float, - default=None, - help="ANNUALISED Sharpe (summary-stats path only)", - ) - ap.add_argument( - "--skew", - type=float, - default=None, - help="per-period return skew (summary-stats path only, REQUIRED with --sharpe)", - ) - ap.add_argument( - "--kurtosis", - type=float, - default=None, - help=( - "per-period PEARSON (non-excess) kurtosis, i.e. 3.0=normal — NOT excess kurtosis " - "(0.0=normal). scipy.stats.kurtosis() defaults to excess (fisher=True); pass " - "fisher=False to get this convention. (summary-stats path only, REQUIRED with --sharpe)" - ), - ) - ap.add_argument( - "--n-obs", - type=int, - default=None, - help="number of return observations (summary-stats path only, REQUIRED with --sharpe)", - ) - ap.add_argument( - "--n-trials", - type=str, - default=DEFAULT_N_TRIALS_RANGE, - help=( - "comma-separated n_trials range to report DSR across (default " - f"'{DEFAULT_N_TRIALS_RANGE}', carver_prelive_gauntlet.py convention). " - "The gate decision is taken from the MAX (most conservative) value." - ), - ) - ap.add_argument( - "--periods", - type=int, - default=365, - help="periods per year (quantbox uses 365); annualisation assumes i.i.d. returns (no autocorrelation)", - ) - ap.add_argument( - "--threshold", - type=float, - default=0.95, - help="DSR acceptance threshold, strictly between 0 and 1 (default 0.95, Bailey/López de Prado)", - ) - args = ap.parse_args(argv) - - if not math.isfinite(args.threshold) or not (0 < args.threshold < 1): - ap.error( - f"--threshold must be finite and strictly between 0 and 1, got {args.threshold!r} " - "(e.g. --threshold 0 or a negative value would make almost any DSR pass)" - ) - - if args.returns is not None: - extra = [ - n - for n in ("sharpe", "skew", "kurtosis", "n_obs") - if getattr(args, n) is not None - ] - if extra: - ap.error( - f"--returns is mutually exclusive with summary-stats args: {extra}" - ) - out = run_from_returns(args) - elif args.sharpe is not None: - missing = [n for n in ("skew", "kurtosis", "n_obs") if getattr(args, n) is None] - if missing: - ap.error( - f"--sharpe requires --{', --'.join(missing)} too — DSR needs the return " - "distribution's actual moments; there is no default skew/kurtosis " - "(that was the old bug). Provide them explicitly, or use --returns instead." - ) - out = run_from_summary(args) - else: - ap.error( - "provide either --returns , or --sharpe together with --skew/--kurtosis/--n-obs" - ) - - print(json.dumps(out, indent=2)) - return 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main(sys.argv[1:])) - except (ValueError, FileNotFoundError) as e: - print(json.dumps({"error": str(e)}), file=sys.stderr) - raise SystemExit(2) from e diff --git a/claude/skills/quant/acceptance-gates/scripts/factor-decomp-gate.py b/claude/skills/quant/acceptance-gates/scripts/factor-decomp-gate.py deleted file mode 100644 index b411c42c..00000000 --- a/claude/skills/quant/acceptance-gates/scripts/factor-decomp-gate.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 -"""Deterministic factor-decomposition (Jensen's-alpha) gate for dev-loop Step 3. - -Sibling to ``dsr-gate.py`` and ``nw-tstat-gate.py``. Those two gates ask *is the -return real and significant?* This gate asks a different, harder question: *is the -return NOVEL, or is it just paid-for factor exposure?* A strategy can clear the DSR -and Newey-West gates with a perfectly honest, significant positive mean return and -still be worthless as a *new* edge — because that return is nothing more than a -levered bet on BTC-beta, cross-sectional momentum, or carry, all of which are -already-known, already-harvestable factors. Promoting such a strategy adds no -diversification and no skill; it just re-packages a factor the book already owns. - -The gate regresses the candidate's return series on a set of KNOWN factor return -series: - - r_strategy(t) = alpha + sum_j beta_j * f_j(t) + e(t) - -- ``beta_j`` = the strategy's loading on factor j (how much of its return is that - factor's exposure). -- ``alpha`` = Jensen's alpha: the average return LEFT OVER after controlling for - every factor. This residual is the only part that could plausibly be skill / a - novel edge. - -GATE (null hypothesis H0: alpha <= 0 — "no residual edge beyond factors"): - PASS when alpha is significantly > 0 (one-sided HAC t-stat >= --t-threshold). - FLAG/FAIL otherwise — the return is explained by factor exposure, not skill. - -Standard errors on the coefficients are Newey-West HAC (Bartlett kernel), exactly -as in ``nw-tstat-gate.py``: strategy returns are autocorrelated (overlapping -signals, trend overlap), and OLS/White SEs would understate the alpha's SE and -rubber-stamp a spurious edge. HAC corrects the SE of the intercept specifically. - - The regression + HAC math lives in the framework — - ``quantbox.analysis.hac.factor_regression`` (statsmodels-backed). This repo owns - ZERO of the regression statistics: this file is CLI plumbing only — load the two - frames, resolve/inner-join the columns, guard against an empty factor list, call - the framework, apply the alpha t-stat + min-obs gate policy, print JSON. - -Point-in-time factors: the regression math is agnostic to how the factor series -were built, but the GATE IS ONLY AS HONEST AS ITS FACTORS. Factor series MUST be -constructed point-in-time (weights formed from information available at t-1, -realised at t) or a look-ahead-contaminated factor will absorb genuine alpha and -produce a false FAIL — or a look-ahead-leaking strategy will masquerade as alpha. -Building the point-in-time crypto factor panel is a harness-specific, -data-aware job that belongs to the consuming research repo (NOT this portable -gate) — feed an already-built factor series in via ``--factors``. - - HARDENING (2026-07-19): codex's adversarial review found a hole where an EMPTY - factor list (e.g. ``--factor-columns ","``, which parses to ``[]``) produced a - valid, intercept-only regression that could PASS purely on the raw mean return — - exactly the "is this just beta in disguise" failure this gate exists to catch. - Guarded here: an explicitly empty (post-parse) factor-column list raises, whether - it came from ``--factor-columns`` or an empty auto-detected numeric-column set. - The framework's ``factor_regression`` also refuses an empty ``factor_names``. - -Usage: - factor-decomp-gate.py --returns strat_returns.parquet \\ - --factors factors.parquet [--column returns] [--factor-columns mkt,mom,carry] \\ - [--t-threshold 2.0] [--lags N] [--min-obs 60] - -Both files are indexed by date; the strategy and factor series are inner-joined on -their common dates before regressing (so a factor panel that starts later just -trims the sample — recorded in ``n_obs``). - -Prints JSON: {n_obs, n_factors, factors, betas, alpha, alpha_se, alpha_tstat, - alpha_pvalue_onesided, r_squared, hac_lags, t_threshold, alpha_pass, - min_obs, obs_pass, gate_pass, note}. -""" - -from __future__ import annotations - -import argparse -import json -import sys - -from quantbox.analysis import factor_regression - - -def _read_frame(path: str): - """Load a date-indexed frame from parquet / csv (first column = index).""" - lower = path.lower() - if lower.endswith(".parquet"): - import pandas as pd - - return pd.read_parquet(path) - if lower.endswith(".csv"): - import pandas as pd - - return pd.read_csv(path, index_col=0, parse_dates=True) - raise SystemExit(f"unsupported file type (need .parquet/.csv): {path}") - - -_RETURN_COL_CANDIDATES = ("returns", "return", "ret", "rets", "pnl", "r") - - -def _pick_return_column(df, column: str | None): - """Resolve the strategy return column (mirrors nw-tstat-gate's auto-pick).""" - if column is not None: - if column not in df.columns: - raise SystemExit(f"column {column!r} not in {list(df.columns)}") - return column - numeric = df.select_dtypes("number") - if numeric.shape[1] == 1: - return numeric.columns[0] - for cand in _RETURN_COL_CANDIDATES: - if cand in df.columns: - return cand - raise SystemExit( - f"could not infer return column from {list(df.columns)}; pass --column" - ) - - -def _round_reg(reg: dict) -> dict: - """Round the framework's full-precision regression stats for JSON display.""" - out = dict(reg) - if out.get("betas") is not None: - out["betas"] = {name: round(b, 8) for name, b in out["betas"].items()} - for key, ndigits in ( - ("alpha", 8), - ("alpha_se", 8), - ("alpha_tstat", 4), - ("alpha_pvalue_onesided", 6), - ("r_squared", 6), - ): - if out.get(key) is not None: - out[key] = round(out[key], ndigits) - return out - - -def main(argv: list[str]) -> int: - ap = argparse.ArgumentParser() - ap.add_argument( - "--returns", required=True, help="strategy return series (parquet/csv)" - ) - ap.add_argument( - "--factors", required=True, help="factor return panel (parquet/csv)" - ) - ap.add_argument("--column", default=None, help="strategy return column (else auto)") - ap.add_argument( - "--factor-columns", - default=None, - help="comma-separated factor columns to use (else all numeric columns)", - ) - ap.add_argument( - "--t-threshold", - type=float, - default=2.0, - help="min one-sided HAC t-stat on alpha to PASS (default 2.0)", - ) - ap.add_argument( - "--lags", - type=int, - default=None, - help="HAC lags (default: Newey-West auto, floor(4*(n/100)^(2/9)))", - ) - ap.add_argument( - "--min-obs", - type=int, - default=60, - help="minimum overlapping observations to trust the regression", - ) - args = ap.parse_args(argv) - - import pandas as pd - - sdf = _read_frame(args.returns) - fdf = _read_frame(args.factors) - scol = _pick_return_column(sdf, args.column) - - if args.factor_columns is not None: - fcols = [c.strip() for c in args.factor_columns.split(",") if c.strip()] - missing = [c for c in fcols if c not in fdf.columns] - if missing: - raise SystemExit(f"factor columns {missing} not in {list(fdf.columns)}") - else: - fcols = list(fdf.select_dtypes("number").columns) - - # An empty factor list — whether explicitly passed ("--factor-columns ,") or the - # (unlikely) auto-detect fallback finding zero numeric columns — is NOT a valid - # "no factors" case for THIS gate: an intercept-only fit can pass on raw mean - # return alone, which is exactly the beta-in-disguise failure the gate exists - # to catch. Refuse it outright rather than silently running a degenerate fit. - if not fcols: - raise SystemExit( - "no factor columns resolved (empty --factor-columns, or the factor file has no " - "numeric columns) — a factor decomposition needs at least one named factor; an " - "intercept-only regression is not a decomposition and would rubber-stamp raw beta" - ) - - # Inner-join strategy + factors on their common dates, then drop any row with a - # missing value so the design matrix is complete. This trims (never pads) the - # sample — a factor panel that starts later just shortens n_obs. - joined = pd.concat( - [sdf[[scol]].rename(columns={scol: "__y__"}), fdf[fcols]], axis=1 - ) - joined = joined.dropna() - - y = joined["__y__"].to_numpy(dtype=float) - F = joined[fcols].to_numpy(dtype=float) - - reg = _round_reg(factor_regression(y, F, fcols, lags=args.lags)) - - # Gate 1 — residual (Jensen's) alpha significantly > 0. - alpha_pass = bool( - reg["alpha"] is not None - and reg["alpha_tstat"] is not None - and reg["alpha"] > 0 - and reg["alpha_tstat"] >= args.t_threshold - ) - # Gate 2 — enough overlapping data to trust the decomposition at all. - obs_pass = bool(reg["n_obs"] >= args.min_obs) - - if reg["alpha_tstat"] is None: - note = "degenerate regression (too few obs or collinear factors) — cannot decompose" - elif not obs_pass: - note = f"too few overlapping obs ({reg['n_obs']} < {args.min_obs})" - elif alpha_pass: - note = "residual alpha significant > 0 after factor controls — plausibly novel edge" - else: - note = ( - "no significant residual alpha — return explained by factor exposure (FLAG)" - ) - - out = { - **reg, - "t_threshold": args.t_threshold, - "alpha_pass": alpha_pass, - "min_obs": args.min_obs, - "obs_pass": obs_pass, - # Gate passes only when there is a significant residual edge on enough data. - "gate_pass": bool(alpha_pass and obs_pass), - "note": note, - } - print(json.dumps(out, indent=2)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main(sys.argv[1:])) diff --git a/claude/skills/quant/acceptance-gates/scripts/nw-tstat-gate.py b/claude/skills/quant/acceptance-gates/scripts/nw-tstat-gate.py deleted file mode 100644 index 7c41691c..00000000 --- a/claude/skills/quant/acceptance-gates/scripts/nw-tstat-gate.py +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/env python3 -"""Deterministic Newey-West (HAC) t-stat + min-OOS-window gate for dev-loop Step 3. - -Sibling to ``dsr-gate.py``. Two robustness checks the DSR gate does NOT cover -(obsidian-vaults#38): - -1. **Newey-West t-stat on mean return.** The DSR gate works off the annualised - Sharpe and a trial count; it assumes i.i.d. returns. Real strategy returns are - autocorrelated (momentum/trend overlap, overlapping windows), which INFLATES a - naive t-stat. The HAC (heteroskedasticity-and-autocorrelation-consistent) - Newey-West standard error corrects for that serial correlation, so the t-stat - on the mean return is honest. Gate: ``nw_tstat >= --t-threshold`` AND mean > 0. - -2. **Named minimum OOS-window length.** A passing t-stat over a 30-day sample is - not the same as one over 3 years. This records the OOS window length as a HARD - frontmatter field and fails the gate when it is shorter than ``--min-oos-periods`` - — so "tested out-of-sample on too little data" can never hide behind a Sharpe. - -Pure math — keep it out of the model's turns so the verdict is reproducible. - - The HAC statistic itself lives in the framework — - ``quantbox.analysis.hac.newey_west_tstat`` (statsmodels-backed, see that - module's parity note). This repo owns ZERO of the HAC statistics: this file is - CLI plumbing only — load the return series, call the framework, apply the - min-OOS-window and t-stat gate policy, print JSON. The non-finite - fail-loudly invariant (NaN/Inf RAISE unless ``--allow-nonfinite-drop``) and - the Newey-West lag rule also live in the framework; the CLI adds only the - ``--oos-periods`` cap (a window claim can only SHRINK the finite-observation - count, never inflate it) and the pass/fail thresholds. - -Usage: - nw-tstat-gate.py --returns oos_returns.parquet [--column returns] \\ - [--t-threshold 2.0] [--min-oos-periods 252] [--lags N] [--oos-periods N] - -The ``--returns`` file should be the OOS return series (one return per period). -Pass ``--oos-periods`` to record a window length other than ``len(returns)`` (e.g. -when the file mixes IS+OOS and you only want the OOS span counted) — it can only -SHRINK the recorded window relative to the finite-observation count, never inflate it. - -Prints JSON: {n_obs, n_obs_raw, n_nonfinite_dropped, nw_lags, mean_return, nw_se, - nw_tstat, nw_pvalue, nw_pass, oos_window_periods, min_oos_periods, - oos_window_pass, gate_pass}. -""" - -from __future__ import annotations - -import argparse -import json -import sys - -import numpy as np -from quantbox.analysis import newey_west_tstat - -# Columns to try, in order, when --column is not given and the frame has >1 col. -_RETURN_COL_CANDIDATES = ("returns", "return", "ret", "rets", "pnl", "r") - - -def _read_returns(path: str, column: str | None) -> np.ndarray: - """Load a raw return series from parquet / csv / whitespace-delimited text. - - Does NOT filter NaN/Inf — that is the framework's ``require_finite`` job (via - ``newey_west_tstat``), so the caller controls (and the output records) - whether/how many were dropped. - """ - lower = path.lower() - if lower.endswith(".parquet"): - import pandas as pd - - df = pd.read_parquet(path) - elif lower.endswith(".csv"): - import pandas as pd - - df = pd.read_csv(path) - else: # plain text: one number per line - return np.loadtxt(path, dtype=float).ravel() - - if column is not None: - if column not in df.columns: - raise SystemExit(f"column {column!r} not in {list(df.columns)}") - return df[column].to_numpy(dtype=float) - # Auto-pick: a single column, else a known return-column name. - numeric = df.select_dtypes("number") - if numeric.shape[1] == 1: - return numeric.iloc[:, 0].to_numpy(dtype=float) - for cand in _RETURN_COL_CANDIDATES: - if cand in df.columns: - return df[cand].to_numpy(dtype=float) - raise SystemExit( - f"could not infer return column from {list(df.columns)}; pass --column" - ) - - -def _round_nw(nw: dict) -> dict: - """Round the framework's full-precision stats for JSON display (presentation only).""" - out = dict(nw) - for key, ndigits in ( - ("mean_return", 8), - ("nw_se", 8), - ("nw_tstat", 4), - ("nw_pvalue", 6), - ): - if out.get(key) is not None: - out[key] = round(out[key], ndigits) - return out - - -def main(argv: list[str]) -> int: - ap = argparse.ArgumentParser() - ap.add_argument( - "--returns", required=True, help="OOS return series (parquet/csv/txt)" - ) - ap.add_argument("--column", default=None, help="return column name (else auto)") - ap.add_argument( - "--t-threshold", type=float, default=2.0, help="min |Newey-West t| to pass" - ) - ap.add_argument( - "--min-oos-periods", - type=int, - default=252, - help="named minimum OOS-window length (periods); recorded + gated", - ) - ap.add_argument( - "--lags", - type=int, - default=None, - help="HAC lags (default: Newey-West auto, floor(4*(n/100)^(2/9)))", - ) - ap.add_argument( - "--oos-periods", - type=int, - default=None, - help=( - "override the recorded OOS window length (default: finite-return count). " - "Can only be <= the finite-return count — it may narrow the claimed window " - "(e.g. an IS+OOS mixed file) but never inflate it beyond what the data supports." - ), - ) - ap.add_argument( - "--allow-nonfinite-drop", - action="store_true", - help=( - "explicitly opt into silently dropping NaN/Inf return observations before " - "counting n_obs (default: refuse and raise on any non-finite value)" - ), - ) - args = ap.parse_args(argv) - - if args.min_oos_periods <= 0: - raise ValueError( - f"--min-oos-periods must be positive, got {args.min_oos_periods!r}" - ) - - raw = _read_returns(args.returns, args.column) - # The framework validates finiteness (raise-by-default / opt-in drop) and - # computes the HAC t-stat. This CLI owns none of that math. - nw = _round_nw( - newey_west_tstat( - raw, lags=args.lags, allow_nonfinite_drop=args.allow_nonfinite_drop - ) - ) - - # Gate 1 — honest t-stat: positive mean AND |t| over the threshold. - nw_pass = bool( - nw["nw_tstat"] is not None - and nw["mean_return"] is not None - and nw["mean_return"] > 0 - and nw["nw_tstat"] >= args.t_threshold - ) - - # Gate 2 — named minimum OOS window, capped to (never exceeding) the actual - # finite-observation count. A claimed window longer than the real data is a - # bug/lie, not a legitimate override — it must raise, not be recorded as-is. - n_finite = nw["n_obs"] - if args.oos_periods is not None: - if args.oos_periods > n_finite: - raise ValueError( - f"--oos-periods={args.oos_periods} exceeds the actual finite-return count " - f"({n_finite}) — cannot claim a longer OOS window than the data supports" - ) - if args.oos_periods <= 0: - raise ValueError( - f"--oos-periods must be positive, got {args.oos_periods!r}" - ) - oos_window = args.oos_periods - else: - oos_window = n_finite - oos_window_pass = bool(oos_window >= args.min_oos_periods) - - out = { - **nw, - "nw_pass": nw_pass, - "oos_window_periods": oos_window, - "min_oos_periods": args.min_oos_periods, - "oos_window_pass": oos_window_pass, - # The robustness gate passes only when BOTH checks clear. - "gate_pass": bool(nw_pass and oos_window_pass), - } - print(json.dumps(out, indent=2)) - return 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main(sys.argv[1:])) - except ValueError as e: - print(json.dumps({"error": str(e)}), file=sys.stderr) - raise SystemExit(2) from e diff --git a/claude/skills/quant/acceptance-gates/scripts/tests/test_dsr_gate.py b/claude/skills/quant/acceptance-gates/scripts/tests/test_dsr_gate.py deleted file mode 100644 index 83e9a2a3..00000000 --- a/claude/skills/quant/acceptance-gates/scripts/tests/test_dsr_gate.py +++ /dev/null @@ -1,287 +0,0 @@ -"""CLI tests for the Deflated Sharpe Ratio (DSR) gate. - -The DSR math itself now lives in the framework (``quantbox.analysis.dsr``) and its -regression suite — including the pinned false-PASS band, the impossible-Pearson- -moments identity, and the non-finite handling — lives in -``quantbox/tests/test_analysis_dsr.py``. This suite covers only what the thin CLI -owns: the n_trials-range policy, the conservative-end gate decision, threshold -validation, the mutually-exclusive input paths, and end-to-end JSON shape. The -false-PASS band is re-pinned here at the CLI boundary. - -Run: pytest scripts/tests/test_dsr_gate.py -q -""" - -from __future__ import annotations - -import importlib.util -import json -import math -import subprocess -import sys -from pathlib import Path - -import numpy as np -import pandas as pd -import pytest - -SCRIPTS = Path(__file__).resolve().parent.parent - -# scripts/dsr-gate.py is hyphenated (CLI convention) -> load it explicitly. Importing -# it exercises the thin CLI's `from quantbox.analysis import ...`. -_SPEC = importlib.util.spec_from_file_location("dsr_gate_cli", SCRIPTS / "dsr-gate.py") -dsr_gate_cli = importlib.util.module_from_spec(_SPEC) -_SPEC.loader.exec_module(dsr_gate_cli) - - -# --------------------------------------------------------------------------- -# CLI policy + validation (main() directly) -# --------------------------------------------------------------------------- - - -def test_cli_periods_zero_rejected_not_coerced_to_one(): - """The old CLI silently coerced --periods 0 to 1, turning N obs into N years.""" - with pytest.raises(ValueError): - dsr_gate_cli.main( - [ - "--sharpe", - "0.4", - "--skew", - "0.0", - "--kurtosis", - "3.0", - "--n-obs", - "500", - "--n-trials", - "10", - "--periods", - "0", - ] - ) - - -def test_cli_requires_skew_kurtosis_with_sharpe(): - """--sharpe alone (no --skew/--kurtosis/--n-obs) must be refused, not defaulted.""" - with pytest.raises(SystemExit): - dsr_gate_cli.main(["--sharpe", "0.4", "--n-trials", "10"]) - - -def test_cli_rejects_zero_n_trials_in_range(): - with pytest.raises(ValueError): - dsr_gate_cli.main( - [ - "--sharpe", - "0.4", - "--skew", - "0.0", - "--kurtosis", - "3.0", - "--n-obs", - "500", - "--n-trials", - "0", - ] - ) - - -def test_cli_rejects_zero_n_trials_mixed_into_range(): - """A single bad entry anywhere in the range invalidates the whole call.""" - with pytest.raises(ValueError): - dsr_gate_cli.main( - [ - "--sharpe", - "0.4", - "--skew", - "0.0", - "--kurtosis", - "3.0", - "--n-obs", - "500", - "--n-trials", - "5,10,0,50", - ] - ) - - -def test_cli_rejects_empty_n_trials_range(): - with pytest.raises(ValueError): - dsr_gate_cli.main( - [ - "--sharpe", - "0.4", - "--skew", - "0.0", - "--kurtosis", - "3.0", - "--n-obs", - "500", - "--n-trials", - "", - ] - ) - - -@pytest.mark.parametrize( - "bad_threshold", [0, -1, 1, 1.5, math.inf, -math.inf, math.nan] -) -def test_cli_rejects_invalid_threshold(bad_threshold): - """--threshold 0/negative/>=1/non-finite would make nearly any DSR pass -- refuse them.""" - with pytest.raises((ValueError, SystemExit)): - dsr_gate_cli.main( - [ - "--sharpe", - "0.4", - "--skew", - "0.0", - "--kurtosis", - "3.0", - "--n-obs", - "500", - "--n-trials", - "10", - "--threshold", - str(bad_threshold), - ] - ) - - -def test_cli_rejects_impossible_pearson_moments(): - """skew=2, kurtosis=1 is impossible (min at skew=2 is 5) -- the CLI must propagate - the same rejection quantbox.analysis.dsr enforces, not swallow it.""" - with pytest.raises(ValueError, match="impossible moments"): - dsr_gate_cli.main( - [ - "--sharpe", - "0.4", - "--skew", - "2.0", - "--kurtosis", - "1.0", - "--n-obs", - "500", - "--n-trials", - "10", - ] - ) - - -def test_cli_returns_and_summary_mutually_exclusive(tmp_path): - returns_file = tmp_path / "returns.csv" - pd.Series(np.random.default_rng(1).normal(0.001, 0.01, 300), name="return").to_csv( - returns_file, index=False - ) - with pytest.raises(SystemExit): - dsr_gate_cli.main( - ["--returns", str(returns_file), "--sharpe", "0.4", "--n-trials", "10"] - ) - - -# --------------------------------------------------------------------------- -# CLI end-to-end (subprocess, exercises the actual entry point) -# --------------------------------------------------------------------------- - - -def _run_cli(args: list[str]) -> dict: - proc = subprocess.run( - [sys.executable, str(SCRIPTS / "dsr-gate.py"), *args], - capture_output=True, - text=True, - ) - assert proc.returncode == 0, f"stderr: {proc.stderr}" - return json.loads(proc.stdout) - - -def test_cli_returns_path_end_to_end(tmp_path): - rng = np.random.default_rng(7) - r = rng.normal(0.0015, 0.012, 1000) - returns_file = tmp_path / "returns.csv" - pd.Series(r, name="return").to_csv(returns_file, index=False) - out = _run_cli( - ["--returns", str(returns_file), "--n-trials", "1,5,20", "--periods", "365"] - ) - assert out["T"] == 1000 - assert set(out["by_n_trials"].keys()) == {"1", "5", "20"} - assert out["n_trials_conservative"] == 20 - assert "dsr_conservative" in out and 0.0 <= out["dsr_conservative"] <= 1.0 - assert out["dsr_pass"] == (out["dsr_conservative"] >= out["threshold"]) - - -def test_cli_reports_range_and_gates_on_max_n_trials(): - """DSR at n_trials=1 can pass while the conservative (max) end fails — the gate - must decide from the conservative end, not the most flattering one.""" - out = _run_cli( - [ - "--sharpe", - "1.5", - "--skew", - "-0.1", - "--kurtosis", - "4.0", - "--n-obs", - "1000", - "--n-trials", - "1,5,20,100", - "--periods", - "365", - ] - ) - dsrs = {int(n): v["dsr"] for n, v in out["by_n_trials"].items()} - assert dsrs[1] >= dsrs[5] >= dsrs[20] >= dsrs[100] - assert out["n_trials_conservative"] == 100 - assert out["dsr_conservative"] == pytest.approx(dsrs[100]) - assert out["dsr_pass"] == (dsrs[100] >= out["threshold"]) - - -def test_cli_default_n_trials_range_matches_carver_convention(): - """Default range mirrors carver_prelive_gauntlet.py's sensitivity sweep.""" - out = _run_cli( - ["--sharpe", "1.0", "--skew", "0.0", "--kurtosis", "3.0", "--n-obs", "500"] - ) - assert {int(n) for n in out["by_n_trials"]} == {1, 5, 10, 20, 50, 100} - assert out["n_trials_conservative"] == 100 - - -def test_cli_summary_path_end_to_end(): - out = _run_cli( - [ - "--sharpe", - "1.5", - "--skew", - "-0.1", - "--kurtosis", - "4.0", - "--n-obs", - "1000", - "--n-trials", - "5", - "--periods", - "365", - ] - ) - assert out["n_trials_conservative"] == 5 - assert out["T"] == 1000 - - -def test_false_pass_band_cli_end_to_end_fails_gate(): - """The verified false-PASS band, driven through the actual CLI (conservative end, - n_trials=20) with the default 0.95 threshold — must FAIL.""" - z_naive = 3.3 - T = 365 - sr_ann = z_naive # periods=365, T=365 -> n_years=1 -> sr_ann == z_naive - out = _run_cli( - [ - "--sharpe", - str(sr_ann), - "--skew", - "0.0", - "--kurtosis", - "3.0", - "--n-obs", - str(T), - "--n-trials", - "20", - "--periods", - "365", - ] - ) - assert out["dsr_conservative"] == pytest.approx(0.9147, abs=5e-3) - assert out["dsr_pass"] is False diff --git a/claude/skills/quant/acceptance-gates/scripts/tests/test_factor_decomp_gate.py b/claude/skills/quant/acceptance-gates/scripts/tests/test_factor_decomp_gate.py deleted file mode 100644 index 579483ab..00000000 --- a/claude/skills/quant/acceptance-gates/scripts/tests/test_factor_decomp_gate.py +++ /dev/null @@ -1,124 +0,0 @@ -"""CLI tests for the factor-decomposition (Jensen's-alpha) gate. - -The regression + HAC math now lives in the framework -(``quantbox.analysis.hac.factor_regression``) and is regression-tested there. -This suite covers only what the thin CLI owns: column resolution, the empty -factor-list guard (the codex-found "beta-in-disguise" hole), and the end-to-end -gate decision. - -Run: pytest scripts/tests/test_factor_decomp_gate.py -q -""" - -from __future__ import annotations - -import importlib.util -import json -import subprocess -import sys -from pathlib import Path - -import numpy as np -import pandas as pd - -SCRIPTS = Path(__file__).resolve().parent.parent - -_SPEC = importlib.util.spec_from_file_location( - "factor_decomp_gate_cli", SCRIPTS / "factor-decomp-gate.py" -) -fd_gate_cli = importlib.util.module_from_spec(_SPEC) -_SPEC.loader.exec_module(fd_gate_cli) - - -def test_cli_rejects_empty_factor_columns_flag(tmp_path): - """The exact codex scenario: --factor-columns "," parses to [] and must not - silently fall through to an intercept-only regression.""" - rng = np.random.default_rng(2) - n = 300 - idx = pd.date_range("2020-01-01", periods=n, freq="D") - ret = pd.DataFrame({"returns": rng.normal(0.002, 0.01, n)}, index=idx) - factors = pd.DataFrame({"mkt": rng.normal(0.0, 0.01, n)}, index=idx) - rf = tmp_path / "returns.csv" - ff = tmp_path / "factors.csv" - ret.to_csv(rf) - factors.to_csv(ff) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "factor-decomp-gate.py"), - "--returns", - str(rf), - "--factors", - str(ff), - "--factor-columns", - ",", - ], - capture_output=True, - text=True, - ) - assert proc.returncode != 0 - assert "at least one named factor" in proc.stderr - - -def test_cli_intercept_only_would_have_passed_on_raw_mean_pre_fix(tmp_path): - """Regression-proof of the actual failure mode: a strong positive-mean return - series with NO real factor control must not be gate-passable at all — the CLI - must refuse rather than run degenerate math that happens to look significant.""" - rng = np.random.default_rng(6) - n = 300 - idx = pd.date_range("2020-01-01", periods=n, freq="D") - ret = pd.DataFrame({"returns": rng.normal(0.01, 0.005, n)}, index=idx) - factors = pd.DataFrame({"mkt": rng.normal(0.0, 0.01, n)}, index=idx) - rf = tmp_path / "returns.csv" - ff = tmp_path / "factors.csv" - ret.to_csv(rf) - factors.to_csv(ff) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "factor-decomp-gate.py"), - "--returns", - str(rf), - "--factors", - str(ff), - "--factor-columns", - "", - ], - capture_output=True, - text=True, - ) - assert proc.returncode != 0 - - -def test_cli_named_factor_end_to_end(tmp_path): - rng = np.random.default_rng(8) - n = 500 - idx = pd.date_range("2020-01-01", periods=n, freq="D") - factor = rng.normal(0.0, 0.01, n) - y = 0.0004 + 0.5 * factor + rng.normal(0, 0.002, n) - ret = pd.DataFrame({"returns": y}, index=idx) - factors = pd.DataFrame({"mkt": factor}, index=idx) - rf = tmp_path / "returns.csv" - ff = tmp_path / "factors.csv" - ret.to_csv(rf) - factors.to_csv(ff) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "factor-decomp-gate.py"), - "--returns", - str(rf), - "--factors", - str(ff), - "--factor-columns", - "mkt", - ], - capture_output=True, - text=True, - ) - assert proc.returncode == 0, proc.stderr - out = json.loads(proc.stdout) - assert out["n_factors"] == 1 - assert out["gate_pass"] == (out["alpha_pass"] and out["obs_pass"]) diff --git a/claude/skills/quant/acceptance-gates/scripts/tests/test_nw_tstat_gate.py b/claude/skills/quant/acceptance-gates/scripts/tests/test_nw_tstat_gate.py deleted file mode 100644 index 5557b418..00000000 --- a/claude/skills/quant/acceptance-gates/scripts/tests/test_nw_tstat_gate.py +++ /dev/null @@ -1,229 +0,0 @@ -"""CLI tests for the Newey-West (HAC) t-stat + min-OOS-window gate. - -The HAC math itself now lives in the framework (``quantbox.analysis.hac``) and is -regression-tested there (``quantbox/tests/test_analysis_hac.py`` + -``test_hac_parity.py``). This suite covers only what the thin CLI owns: loading, -the fail-loud non-finite policy surfaced end-to-end, the ``--oos-periods`` cap, -and the two-part gate decision. Both codex-found holes stay pinned as CLI -regressions: - -1. A file with 200 legit + 500 corrupt (NaN) rows must NOT quietly pass - --min-oos-periods on the surviving 200 — it must refuse outright. -2. --oos-periods must never be trusted beyond the actual finite return count. - -Run: pytest scripts/tests/test_nw_tstat_gate.py -q -""" - -from __future__ import annotations - -import importlib.util -import json -import subprocess -import sys -from pathlib import Path - -import numpy as np -import pandas as pd - -SCRIPTS = Path(__file__).resolve().parent.parent - -# nw-tstat-gate.py is hyphenated (CLI convention) -> load it explicitly. Importing -# it exercises the thin CLI's `from quantbox.analysis import newey_west_tstat`. -_SPEC = importlib.util.spec_from_file_location( - "nw_tstat_gate_cli", SCRIPTS / "nw-tstat-gate.py" -) -nw_gate_cli = importlib.util.module_from_spec(_SPEC) -_SPEC.loader.exec_module(nw_gate_cli) - - -# --------------------------------------------------------------------------- -# HOLE 1: silent NaN/Inf drop before counting n_obs — must FAIL LOUDLY (CLI) -# --------------------------------------------------------------------------- - - -def test_cli_corrupt_file_raises_instead_of_silently_shrinking_sample(tmp_path): - """The exact codex scenario: 200 legit + 500 NaN rows must NOT quietly report - n_obs=200 and pass on the surviving subset — it must refuse outright.""" - rng = np.random.default_rng(5) - good = rng.normal(0.002, 0.01, 200) - corrupt = np.full(500, np.nan) - series = np.concatenate([good, corrupt]) - f = tmp_path / "returns.csv" - pd.Series(series, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--min-oos-periods", - "150", - ], - capture_output=True, - text=True, - ) - assert proc.returncode != 0 - err = json.loads(proc.stderr) - assert "NaN/Inf" in err["error"] - - -def test_cli_corrupt_file_with_explicit_opt_out_reports_the_drop(tmp_path): - rng = np.random.default_rng(5) - good = rng.normal(0.002, 0.01, 200) - corrupt = np.full(50, np.nan) - series = np.concatenate([good, corrupt]) - f = tmp_path / "returns.csv" - pd.Series(series, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--min-oos-periods", - "150", - "--allow-nonfinite-drop", - ], - capture_output=True, - text=True, - ) - assert proc.returncode == 0, proc.stderr - out = json.loads(proc.stdout) - assert out["n_obs_raw"] == 250 - assert out["n_nonfinite_dropped"] == 50 - assert out["n_obs"] == 200 - - -# --------------------------------------------------------------------------- -# HOLE 2: --oos-periods trusted beyond the actual finite return count -# --------------------------------------------------------------------------- - - -def test_cli_oos_periods_exceeding_finite_count_is_rejected(tmp_path): - """Claiming a 3-year OOS window on 30 real observations must raise, not be - recorded as a legitimate longer window.""" - rng = np.random.default_rng(9) - r = rng.normal(0.001, 0.01, 30) - f = tmp_path / "returns.csv" - pd.Series(r, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--oos-periods", - "756", # ~3y of daily data — far more than the 30 real obs - ], - capture_output=True, - text=True, - ) - assert proc.returncode != 0 - err = json.loads(proc.stderr) - assert "exceeds" in err["error"] - - -def test_cli_oos_periods_within_finite_count_is_accepted(tmp_path): - """A narrower --oos-periods claim (e.g. IS+OOS mixed file, only count the OOS - tail) is a legitimate use and must be honoured exactly.""" - rng = np.random.default_rng(9) - r = rng.normal(0.001, 0.01, 400) - f = tmp_path / "returns.csv" - pd.Series(r, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--oos-periods", - "252", - ], - capture_output=True, - text=True, - ) - assert proc.returncode == 0, proc.stderr - out = json.loads(proc.stdout) - assert out["oos_window_periods"] == 252 - assert out["n_obs"] == 400 # the t-stat itself still uses all finite obs - - -def test_cli_negative_min_oos_periods_rejected(tmp_path): - rng = np.random.default_rng(2) - r = rng.normal(0.001, 0.01, 100) - f = tmp_path / "returns.csv" - pd.Series(r, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--min-oos-periods", - "-5", - ], - capture_output=True, - text=True, - ) - assert proc.returncode != 0 - - -# --------------------------------------------------------------------------- -# End-to-end gate behaviour -# --------------------------------------------------------------------------- - - -def test_cli_gate_pass_requires_both_nw_and_window_checks(tmp_path): - rng = np.random.default_rng(13) - r = rng.normal(0.003, 0.01, 400) # strong positive drift, plenty of data - f = tmp_path / "returns.csv" - pd.Series(r, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--t-threshold", - "2.0", - "--min-oos-periods", - "252", - ], - capture_output=True, - text=True, - ) - assert proc.returncode == 0, proc.stderr - out = json.loads(proc.stdout) - assert out["gate_pass"] == (out["nw_pass"] and out["oos_window_pass"]) - - -def test_cli_short_window_fails_gate_even_with_strong_tstat(tmp_path): - rng = np.random.default_rng(13) - r = rng.normal(0.01, 0.01, 60) # strong drift, but short window - f = tmp_path / "returns.csv" - pd.Series(r, name="return").to_csv(f, index=False) - - proc = subprocess.run( - [ - sys.executable, - str(SCRIPTS / "nw-tstat-gate.py"), - "--returns", - str(f), - "--t-threshold", - "1.5", - "--min-oos-periods", - "252", - ], - capture_output=True, - text=True, - ) - assert proc.returncode == 0, proc.stderr - out = json.loads(proc.stdout) - assert out["oos_window_pass"] is False - assert out["gate_pass"] is False diff --git a/claude/skills/quant/investment-research-formal/SKILL.md b/claude/skills/quant/investment-research-formal/SKILL.md index 5e6c896a..08dd3025 100644 --- a/claude/skills/quant/investment-research-formal/SKILL.md +++ b/claude/skills/quant/investment-research-formal/SKILL.md @@ -1,15 +1,15 @@ --- name: investment-research-formal -description: Structured, auditable investment research with tracked hypotheses, experiments, and findings. Use when research needs an evidence chain for compliance, regulatory documentation (MiFID II suitability), published methodology, white papers, or peer review. Use when the user says "formal research", "document methodology", "audit trail", "compliance evidence", or "white paper". Complements investment-research (iterative) with traceability. +description: Structured, auditable investment research with tracked hypotheses, experiments, and findings. Use when research needs an evidence chain for compliance, regulatory documentation (MiFID II suitability), published methodology, white papers, or peer review. Use when the user says "formal research", "document methodology", "audit trail", "compliance evidence", or "white paper". Complements qute-research's `/research` (the research regime) with traceability. --- # Formal Investment Research -Structured research with full traceability: every decision links back to evidence, every finding links forward to application. For iterative exploration, use `investment-research` instead. +Structured research with full traceability: every decision links back to evidence, every finding links forward to application. For iterative exploration, use qute-research `/research` instead. -## When to Use This vs `investment-research` +## When to Use This vs qute-research `/research` -| Signal | Use `investment-research` | Use `investment-research-formal` | +| Signal | Use qute-research `/research` | Use `investment-research-formal` | |--------|--------------------------|----------------------------------| | Audience | You + immediate team | Compliance, regulators, external reviewers | | Lifespan | Until next calibration cycle | Permanent record | @@ -17,7 +17,7 @@ Structured research with full traceability: every decision links back to evidenc | Tracking | README + git | Hypothesis → Experiment → Finding chain | | Trigger phrases | "research", "backtest", "study" | "document methodology", "audit trail", "white paper" | -**Common pattern**: Start with `investment-research` for exploration, then formalize key findings with this skill when producing regulatory or publication deliverables. +**Common pattern**: Start with qute-research `/research` for exploration, then formalize key findings with this skill when producing regulatory or publication deliverables. ## Research Lifecycle @@ -85,7 +85,7 @@ Evidence from [E01](../experiments/E01-gold-allocation-sweep.md). ### Starting from Iterative Research -When formalizing results from an `investment-research` study: +When formalizing results from a qute-research `/research` line: 1. Identify the key decisions that were made (from README, git history, dashboard) 2. Reconstruct hypotheses retroactively (what did we actually test?) @@ -408,6 +408,6 @@ Include formulas where relevant.} | Skill | Role | |-------|------| -| `investment-research` | Iterative exploration (use first, formalize later) | +| qute-research `/research` | Iterative exploration (use first, formalize later) | | `investment-research-dashboard` | Interactive deliverables referenced by findings | | `analizy-pl-data` | Polish fund data from analizy.pl | diff --git a/claude/skills/quant/investment-research/SKILL.md b/claude/skills/quant/investment-research/SKILL.md deleted file mode 100644 index d97395e3..00000000 --- a/claude/skills/quant/investment-research/SKILL.md +++ /dev/null @@ -1,438 +0,0 @@ ---- -name: investment-research -description: Guides quantitative investment research — both fresh studies and iterative methodology refinement on existing systems. Use when starting a new research topic, structuring a research directory, comparing methodology variants, re-testing hypotheses against updated baselines, deciding between competing approaches, promoting research findings to production, or working with backtest, calibration, and signal design. Covers the full lifecycle from data sourcing through analysis to deliverable, plus the iterative loop of explore → lock → re-test on already-deployed subsystems. ---- - -# Investment Research Workflow - -Structured workflow for quantitative investment research. Guides projects from question → data → analysis → deliverable. - -## When to Use - -- Starting a new research topic (risk calibration, factor study, allocation optimization) -- Structuring a research directory -- Planning data sourcing and validation -- Building simulation/backtest pipelines -- Producing research deliverables (dashboards, reports, data files) -- Reviewing or extending existing research - -## Branch Lifecycle (Git mechanics) - -Research branches are **per-question, short-lived**. Work flow: - -``` -1. START git checkout -b research/{model}-{question-slug} dev - mkdir research/{model}/experiments/{exp-id}/ - update research/{model}/README.md (status: in-progress) - -2. ITERATE add experiments + intermediate results (no merge yet) - -3. CONCLUDE write research/{model}/findings/{question-slug}.md - update README.md status: concluded - -4. MERGE PR research/{model}-{slug} → dev - findings + experiments + README land on dev; branch deleted - -5. PROMOTE (optional, only if findings warrant prod change) - git checkout -b feat/{model}-{change} dev - modify /src/, /pipelines/, /config/ - PR dev → main; /promote → tag prod-{model}-vX.Y.Z-YYYYMMDD -``` - -**One branch = one question.** New question = new branch. The `research/{model}/` directory on `dev` is the long-lived home; branches are ephemeral. - -**A research branch modifies only `experiments/{exp-id}/`** — not the shared `scripts/` library, not `/src/`, not `/pipelines/`. Shared-methodology changes go on a separate `feat/*` branch (the promotion path). - -**Status states** (declared in model `README.md` per question): -- `in-progress` — branch open, work ongoing -- `concluded` — findings.md written, branch ready to merge -- `merged` — findings on `dev`, branch closed -- `abandoned` — merged with findings.md = "tried, didn't work, here's why" -- `superseded` — findings replaced by later research - -See `.claude/rules/research-workflow.md` and `.claude/rules/git-workflow.md` for the full conventions. - -## Methodology Lifecycle - -Investment research follows a different pattern than ML research. There's no train/test split — instead there's **expert input → data validation → simulation → calibration → delivery**. - -``` -┌─────────────┐ ┌──────────────┐ ┌───────────────┐ ┌─────────────┐ ┌────────────┐ -│ 1. QUESTION │───>│ 2. DATA │───>│ 3. ANALYSIS │───>│ 4. CALIBRATE│───>│ 5. DELIVER │ -│ │ │ │ │ │ │ │ │ │ -│ What are we │ │ Source, clean │ │ Simulate, │ │ Expert input│ │ Dashboard, │ -│ trying to │ │ validate, │ │ compute │ │ + data = │ │ JSON, report│ -│ decide? │ │ proxy │ │ metrics │ │ final params│ │ │ -└─────────────┘ └──────────────┘ └───────────────┘ └─────────────┘ └────────────┘ - │ │ │ │ │ - question.md data/raw/ scripts/*.py config/ output/{run}/ - data/processed/ scratch/ templates/ deliverable -``` - -## Signal Research Lifecycle (8 stages) - -For **signal-driven** research (TAA, factor models, fund scoring, sector rotation), the Analysis phase decomposes into 8 stages with one artifact each: - -| # | Stage | Artifact | -|---|---|---| -| 1 | Signal generation | List of candidate raw signals + economic story per signal | -| 2 | Per-signal anatomy | Per-signal dashboard (distribution + history + crisis traces) | -| 3 | Per-signal IC | IC table per signal × horizon × era | -| 4 | Distribution & normalization | Per-component normalization spec | -| 5 | Ensemble construction | Variants v{N} in EXPERIMENTS.md, ONE change each | -| 6 | Weight engine | Weight engine spec + corridor sensitivity per profile | -| 7 | Portfolio backtest | Per-profile + per-regime + per-asset attribution table | -| 8 | Lock & promote | STATUS update, EXPERIMENTS lock entry, spec §, feat/ branch | - -**MANDATORY for stage 7:** Use the repo's drift-aware backtest engine (in dm-evo: the `backtest` skill in dm-evo-core, vbt `run()`). Manual weighted-sum loops over monthly returns inflate IR by ~0.20 (empirically confirmed). - -**Stage 4 is a trap.** Normalization choice (per-asset rolling z vs bucket-pooled vs globally-pooled vs percentile rank vs tanh) materially changes which structural information survives — the default "z-score everything per-asset" reflex erases cross-asset structural premia (e.g. EM persistently cheap). Read the reference before designing your normalization layer. - -**Stage 4 lookahead hazard.** Pooled normalization (bucket or global) MUST use walk-forward pool stats — at each eval_date T, μ/σ from data `≤ T` (rolling window or expanding). A full-panel pool is lookahead even when per-cat inputs are PIT. Observed cost: ~13% IR inflation on a real project. Rolling 10Y / 5Y-min matches the per-cat rolling_z convention and is ~20 lines. See reference §Stage 4 "Pool normalization MUST be walk-forward". - -**Iteration discipline:** ONE change per variant. Don't layer "new normalization + new clip + new weights" into one variant — you can't attribute the result. - -Full playbook (per-stage decisions, anti-patterns, dir mapping): see `references/signal-research-lifecycle.md`. - -## Quick Start: Initialize a Research Topic - -A model directory accretes findings + experiments across many questions. Create on first question's branch: - -``` -research/{model}/ -├── README.md # Active + concluded questions index, status, prod state -├── EXPERIMENTS.md # Append-only chronological log -├── findings/ # Per-question findings (one .md per merged question) -│ └── {question-slug}.md # Written on conclusion; lands on dev via merge -├── experiments/ # Per-experiment artifacts -│ └── {exp-id}/ # Owned by one research branch — don't cross-modify -├── docs/ # Methodology spec(s) with LOCKED frontmatter -├── data/ -│ ├── raw/ # Untouched source files (Excel, CSV, API dumps) -│ ├── intermediate/ # Cleaned/transformed (parquets, merged datasets) -│ └── processed/ # Final analysis-ready datasets -├── scripts/ # Shared methodology library (modified only via feat/* branches) -├── templates/ # HTML templates, JSON schemas, report templates -├── output/ # Timestamped run directories -│ └── {YYYYMMDD-HHMMSS}/ # Each run is immutable snapshot -├── archive/ # Superseded scripts, old outputs -└── scratch/ # Temporary exploration (gitignored) -``` - -**On a research branch**, you only ADD to `experiments/{exp-id}/` and write `findings/{question-slug}.md` on conclusion. The README status update is the other branch-side change. - -**On the first-ever question for a model**, the merge to `dev` also creates the `README.md`, `EXPERIMENTS.md`, and any of the directories above that the question populates. - -### Mature-stage evolution: 4-track structure - -Once a topic accumulates ~10+ build_*.py files **and** the work splits into distinct activities (per-signal EDA + variant experiments + portfolio backtests + methodology comparisons), promote the flat structure to four tracks: - -``` -research/{topic-name}/ -├── validation/ ← per-signal EDA (eq_*, fi_*, dcf, build_dashboard.py) -├── scoring/ ← composite/variant experiments (backtest, ic_analysis, com_value_*) -├── backtesting/ ← portfolio P&L (drift-aware vbt) -├── comparison/ ← methodology diffs (v3 vs v4 indicator dashboard) -├── docs/ config/ data/ scripts/ -├── STATUS.md EXPERIMENTS.md README.md CLAUDE.md -``` - -**Don't preemptively split.** Start flat. Split when the flat structure hurts — i.e., when one directory (commonly `validation/` or `analyses/`) starts hosting work that doesn't match its name. The 8-stage lifecycle above maps cleanly: stages 2 → validation/, 3-5 → scoring/, 7 → backtesting/, methodology-diff dashboards → comparison/. - -### README Template - -Every model README is a living index of questions + production state: - -```markdown -# {Model Name} - -{One paragraph: what this model is + what it produces in production.} - -## Active questions - -| Question | Branch | Status | Findings | -|---|---|---|---| -| Does decay improve regime detection? | `research/{model}-momentum-decay` | in-progress | (pending) | - -## Concluded questions - -| Question | Findings | Promoted? | -|---|---|---| -| Should ERP use DCF vs Damodaran T12m? | findings/erp-dcf-vs-damodaran.md | yes — `prod-{model}-v4.0.0-20260408` | - -## Production state - -Latest tag: `git tag --list 'prod-{model}-*' | sort -V | tail -1`. -Methodology spec: `docs/signal-definitions-v{N}.md` (latest LOCKED version per the file's frontmatter `version` field). - -## Pipeline - -Run in order: -1. `uv run python build_data.py` — {what it does} -2. `uv run python simulate.py` — {what it does} -3. `uv run python build_output.py` — {what it does} - -## Key Decisions -- {Decision 1}: {rationale} -- {Decision 2}: {rationale} -``` - -The README is the model's living index. Adding a question = new row in Active. Concluding = move to Concluded with findings link. Promoting = note prod tag. - -## Phase 1: Question - -Before writing any code, document the research question. - -**Ask yourself:** -- What decision will this research inform? -- Who is the audience? (internal team, advisor, client) -- What is the deliverable? (dashboard, config file, report, data file) -- What are the expert's priors? (starting allocations, expected ranges, constraints) - -**Capture in README.md** — not a separate document. Keep it living. - -### Investment Research Question Types - -| Type | Example | Typical Deliverable | -|------|---------|-------------------| -| **Allocation** | "What weights for 5 risk profiles?" | Config JSON + dashboard | -| **Risk** | "What's the worst-case for this portfolio?" | Stress test report | -| **Performance** | "How did strategy X perform?" | Performance dashboard | -| **Factor** | "Does momentum work in Polish equities?" | Factor study + backtest | -| **Instrument** | "Which ETFs best proxy our asset classes?" | Comparison table + recommendation | -| **Calibration** | "Are our risk parameters still valid?" | Updated parameters + evidence | - -## Phase 2: Data - -### Data Sourcing - -Use the **market-datasets** skill for price/return data. For other sources: - -```python -# Standard data pipeline script pattern -""" -Build {description}. - -Sources: -- {Source 1}: {what it provides} -- {Source 2}: {what it provides} - -Produces: -- data/processed/{output_file} — {description} -""" -``` - -### Data Validation Checklist - -Before trusting any dataset: - -- [ ] **Coverage**: Does the date range cover all needed periods (including crisis periods)? -- [ ] **Frequency**: Is it daily/monthly/quarterly as needed? -- [ ] **Completeness**: Missing values? Gaps in time series? -- [ ] **Proxy validation**: If using synthetic/proxy data, how does it compare to real data? -- [ ] **Dividend treatment**: Total return or price return? Adjusted or raw? -- [ ] **Currency**: Consistent currency? FX adjustments needed? -- [ ] **Survivorship bias**: Are delisted/merged instruments handled? - -### Proxy Validation Pattern - -When using long-history proxies (synthetic indices, academic datasets), validate against real data in the overlap period: - -```python -# Compare proxy vs real in overlap window -overlap = proxy.merge(real, on='date', suffixes=('_proxy', '_real')) -print(f"Correlation: {overlap.corr()}") -print(f"Return diff: {(overlap.ret_proxy - overlap.ret_real).describe()}") -print(f"Vol ratio: {overlap.ret_proxy.std() / overlap.ret_real.std():.2f}") -``` - -Document the comparison in a `compare_*.py` script, then archive it once validated. - -## Phase 3: Analysis - -### Simulation Pattern - -For portfolio/allocation research, the standard approach is: - -1. **Sweep the parameter space** — don't guess, enumerate -2. **Compute risk metrics for every combination** -3. **Select from the feasible set** based on criteria + expert input - -**For portfolio backtests, MANDATORY:** use the repo's drift-aware backtest engine (in dm-evo: the `backtest` skill in dm-evo-core; elsewhere the project's own engine, e.g. quantbox). Do NOT roll your own monthly weighted-sum loop — manual loops skip intra-period weight drift and produce optimistically biased Sharpe/IR (empirically observed: +0.20 avg IR inflation on a 10-year monthly-rebalanced study). - -```python -# Cross-sectional metric sweep (no time-series rebalance — fine for static metrics) -results = [] -for weights in weight_combinations: - portfolio_returns = (returns * weights).sum(axis=1) - metrics = compute_risk_metrics(portfolio_returns) - results.append({**weights, **metrics}) - -# Time-series portfolio backtest (use the drift-aware engine, NOT the loop above). -# dm-evo example (dm-evo-core's own module): -from src.vectorbt_tools.backtesting import run as vbt_run -pf = vbt_run(prices, {"Strategy": w_df, "Benchmark": w_bench_df}, - rebalancing_freq="1M", fees=0.001) -# pf.stats(), pf.drawdowns.records_readable, etc. -``` - -### Standard Risk Metrics - -Always compute this core set (extend as needed): - -| Metric | Formula | Interpretation | -|--------|---------|----------------| -| Ann. Return | `(1+r).prod()^(12/n) - 1` | Compound annual growth | -| Ann. Volatility | `r.std() * sqrt(12)` | Annualized monthly std dev | -| Sharpe Ratio | `return / volatility` | Return per unit risk | -| Max Drawdown | `min(cumulative peak-to-trough)` | Worst peak-to-trough loss | -| Max DD Duration | `longest recovery time (months)` | Longest underwater period | -| Worst 12M | `min(rolling 12-month return)` | Worst rolling year | -| % Time DD > 5% | `pct of months below -5% from peak` | Pain frequency | -| Ulcer Index | `sqrt(mean(DD^2))` | RMS of drawdown (penalizes deep+long) | - -### Crisis Period Analysis - -Define named crisis windows and compute compound returns through each: - -```python -CRISES = { - "GFC 2007-09": ("2007-10", "2009-02"), - "COVID 2020": ("2020-02", "2020-03"), - "Rate Shock 2022": ("2022-01", "2022-09"), - "Dot-com 2000-02": ("2000-03", "2002-09"), -} -``` - -Crisis returns validate **monotonic risk progression** — P1 should lose least, P5 most, in every crisis. Non-monotonicity signals a data or methodology problem (or a genuinely unusual regime like 2022 rate shock hitting bonds). - -### Recency Analysis - -Always compare full-period vs recent-period metrics. Forward-looking guidance should use recent period, while tail risk uses full period. - -## Phase 4: Calibrate - -This is where investment research diverges most from ML. Calibration is a **human-in-the-loop** process. - -### Expert-Then-Data Pattern - -``` -Expert proposes starting parameters (SAA, bounds, constraints) - ↓ -Data validates/challenges expert proposals - ↓ -Adjustments documented with rationale - ↓ -Final parameters = expert + data evidence -``` - -### What to Calibrate - -| Parameter | Expert Provides | Data Validates | -|-----------|----------------|----------------| -| Asset allocations | Starting weights per profile | Risk metrics, drawdowns at those weights | -| Tactical bounds | Min/max ranges per asset | Metrics at corridor edges stay in-character | -| Risk targets | "P1 should lose max 10%" | Actual max DD at proposed allocation | -| Constraints | "P1 has no equity" | Whether constraint impacts return meaningfully | - -### Documenting Calibration Decisions - -In the dashboard or README, always show: -- **What expert proposed** (starting point) -- **What data showed** (backtest results) -- **What changed** (adjustments with rationale) -- **What stayed** (confirmed proposals) - -## Phase 5: Deliver - -### Deliverable Types - -| Type | When | How | -|------|------|-----| -| **Interactive dashboard** | Research presentation, stakeholder review | Use `investment-research-dashboard` skill | -| **Config JSON** | Parameters feeding production app | `templates/{name}.json` + timestamped copy | -| **Data file** | Input to another pipeline | `data/processed/{name}.parquet` | -| **Report** | Written analysis | Markdown or HTML | - -### Timestamped Output Pattern - -Every pipeline run produces an immutable snapshot: - -```python -from datetime import datetime -from pathlib import Path - -def make_run_dir(base: Path, manual: str | None = None) -> Path: - d = Path(manual) if manual else base / datetime.now().strftime("%Y%m%d-%H%M%S") - d.mkdir(parents=True, exist_ok=True) - return d -``` - -All scripts accept `--output-dir` for manual override, defaulting to auto-timestamped. A pipeline run should target the same directory: - -```bash -uv run python build_data.py # → output/20260306-150720/ -uv run python build_dashboard.py --output-dir output/20260306-150720 -``` - -### JSON Data Separation - -Never hardcode analysis results in templates. Always: -1. **Python computes** → writes JSON -2. **Template consumes** → `const DATA = {};` placeholder -3. **Builder injects** → replaces placeholder with real data - -This means templates are reusable across runs and the data is inspectable/diffable. - -## Script Naming Convention - -``` -build_asset_data.py # Phase 2: data sourcing & cleaning -compare_data_sources.py # Phase 2: validation (archive after use) -simulate_profiles.py # Phase 3: analysis/simulation -build_dashboard_data.py # Phase 5: compute deliverable data -build_template_data.py # Phase 5: compute app config data -build_dashboard_html.py # Phase 5: assemble final deliverable -``` - -Prefix with `build_` for pipeline scripts. Use `compare_`, `validate_`, `explore_` for one-time analysis scripts (archive when done). - -## Archiving - -Research generates throwaway scripts. Archive aggressively: - -**Archive when:** -- v1 script superseded by v2 -- One-time validation complete -- Data comparison done and documented -- Old output snapshots replaced - -**Keep active:** -- Current pipeline scripts -- Templates -- Processed data -- Latest output - -## Guidelines - -- **README is the source of truth** — not separate hypothesis/finding docs. Investment research is too iterative for formal hypothesis tracking. -- **Visual feedback over code review** — open the dashboard, spot issues with your eyes. Charts expose bugs that unit tests miss. -- **Subsample with care** — always preserve extremes (trough points, peak values) when reducing time series for charts. -- **Store ratios, display percentages** — JSON stores 0.057, charts show 5.7%. Avoids double-conversion bugs. -- **Expert input is data** — treat domain expert parameters as first-class inputs, not afterthoughts. -- **Archive, don't delete** — research is non-linear. You may need that "throwaway" script next quarter. - -## Reference Implementation - -`research/strategic-asset-allocation/` is the canonical example of this workflow applied to SAA calibration across 5 risk profiles. - -## Complementary Skills - -| Skill | Use For | -|-------|---------| -| `market-datasets` | Sourcing price/return data | -| the repo's backtest engine (dm-evo: `backtest` in dm-evo-core) | **MANDATORY for any portfolio-level backtest** — weight-driven simulation with drift, fees, multi-strategy comparison. Manual weighted-sum loops produce optimistically biased Sharpe/IR (~0.20 inflation observed). | -| `investment-research-dashboard` | Building interactive HTML deliverables | -| `investment-research-formal` | Formalizing findings for compliance/audit | -| `analizy-pl-data` | Polish fund data from analizy.pl | -| `evo-dm-brand` | Applying brand identity to dashboards | diff --git a/claude/skills/quant/investment-research/references/signal-research-lifecycle.md b/claude/skills/quant/investment-research/references/signal-research-lifecycle.md deleted file mode 100644 index 5d380b45..00000000 --- a/claude/skills/quant/investment-research/references/signal-research-lifecycle.md +++ /dev/null @@ -1,208 +0,0 @@ -# Signal Research Lifecycle - -Stage-by-stage playbook for quant signal research: from candidate signals through composite scoring to a verified portfolio backtest. Use when designing or iterating any signal-driven strategy (TAA, factor model, fund scoring, sector rotation). - -**Complementary to** the parent `investment-research` skill's 5-phase lifecycle (Question → Data → Analysis → Calibrate → Deliver). The 8 stages below decompose the **Analysis phase** for signal-based research specifically. - -## The 8 stages - -| # | Stage | Question | Artifact | Anti-pattern | -|---|---|---|---|---| -| 1 | Generation | What candidate signals could predict this? | List of 5–15 raw signals + economic story per signal | Throwing 50 ratios in a hopper (data mining) | -| 2 | Per-signal anatomy | Does each signal individually look like a signal, not noise? | Per-signal dashboard (distribution + history + crisis traces) | Skipping straight to IC tests without inspecting the time series | -| 3 | Per-signal IC | Does each signal predict forward returns? | IC table per signal × horizon × era | Only computing full-sample IC (hides regime fragility) | -| 4 | Distribution & normalization | How do we put signals in compatible units? | Per-component normalization spec, with documented preserved structural info | Z-scoring everything per-asset by reflex (erases structural info) | -| 5 | Ensemble construction | How do we combine N signals into one composite? | Variants v{N} documented in EXPERIMENTS.md, ONE change each | Layering "new normalization + new clip + new weights" into one variant | -| 6 | Weight engine | Given a composite signal, what weight per asset per profile? | Weight engine spec + corridor sensitivity per profile | Tightening corridors on a single tail event without recalibration | -| 7 | Portfolio backtest | Does the composite deliver risk-adjusted return after costs? | Per-profile + per-regime + per-asset attribution table | Manual weighted-sum loops (inflates IR ~0.20) — **MANDATORY: use the repo's drift-aware backtest engine** | -| 8 | Lock & promote | Has the candidate met all lock criteria? | STATUS update, EXPERIMENTS lock entry, spec §, feat/ branch | PROVISIONAL → LOCKED → PROVISIONAL flip cycles (lock once, with full evidence) | - -## Stage 1 — Signal generation - -**Source:** Factor literature (value/momentum/carry/quality/vol), regime classification, expert intuition, replicating known anomalies. - -**Discipline:** Every signal needs a *prior reason to work* before it gets a backtest. A random ratio with a great backtest IC is overfit until proven otherwise. - -**Output format** — one line per candidate: - -``` -SIGNAL_NAME = formula - Story: why this should predict {asset} - Source: paper / desk practice / regime hypothesis - Risk: known failure mode (e.g., "fails when curve inverts") -``` - -## Stage 2 — Per-signal anatomy - -**Tests per signal** (run before any combination): -- Distribution shape: histogram, percentiles (P5/P50/P95), fat-tail check -- Time-series stability: no regime breaks in scale/sign -- Coverage: no big NaN gaps, sensible warm-up -- Sanity: current value vs known regime ("Is HY OAS at +800bp visible in 2008?") -- Crisis traces: 2008/2020/2022 episodes look right - -**Artifact:** Per-signal section in a validation dashboard. One section per signal, four panels: raw input → derived value → z-score → final signal, full history. - -**Decision per signal:** keep / iterate (fix data) / kill (broken). - -## Stage 3 — Per-signal predictive power (IC) - -**Cross-sectional Spearman IC** at horizons 1M / 3M / 6M / 12M. - -**Era split is non-negotiable.** A signal that looks great full-sample but is dead post-2010 is more dangerous than one that's mediocre across eras. Standard era splits (adjust to your data start): -- 2000–07 pre-GFC -- 2008–09 GFC -- 2010–19 expansion -- 2020–21 COVID + recovery -- 2022 rate shock -- 2023–present - -**Decay curve** — when does the signal stop working? IC at 1M, 3M, 6M, 12M tells you the holding period. - -**IC table per signal × horizon × era.** Output: a panel of per-cell ICs with significance (use Newey-West for time-series IC stats). - -**Decision:** Which signals deserve a place in the composite. Note: weak-IC signals can still be useful as **negative-correlated overlays** — e.g., real-rate value signals lose on standalone IC for gold but can act as a brake on extreme overweights. Test in combination, not just standalone. - -## Stage 4 — Distribution & normalization design - -**Critical decision** — normalization choice changes which structural information survives: - -| Method | What it preserves | What it erases | Use when | -|---|---|---|---| -| **Per-asset rolling z** (legacy) | Per-asset historical context | Cross-asset structural premia | Default until you know better — but rarely the right choice | -| **Bucket-pooled z** | Cross-asset structure within bucket | Cross-bucket relativity | Bucket has ≥3 assets; want EQ_EM cheapness preserved relative to other EQs | -| **Globally-pooled z** | All cross-asset structure (per-cat means survive) | Per-asset historical context | Momentum-style signals; want EQ_US momentum advantage to persist | -| **Percentile rank** | Ordinal info, bounded [0,1] | Magnitude info | When magnitudes are non-comparable (mixed units) | -| **Tanh squashing** | Bounded output, soft saturation | Linear differentiation at extremes | Final mapping to [0,1] for weight engine | - -**Component clipping** — outlier guard. Carver's literal ±2σ at monthly cadence on indices is too tight (truncates real signal). **±3σ** is "fires only on true outliers" and matches no-clip on avg IR while providing a safety net. - -**Composite cap** — bound the final weighted z so tanh doesn't saturate. Typical: ±2.0 on a sum that can reach ±7 on agreement days. - -**Tanh σ** — softness of conviction curve. σ=1.5 saturates faster (sharper conviction); σ=2.0 keeps differentiation in the moderate-z range (better worst-profile protection). - -**Document per-category post-pool means.** They show what structural info survives. If `EQ_EM value_z` post-pool mean is +0.61 (EM persistently cheap), the strategy will tilt to EQ_EM by default — which is a feature if EM cheapness is real, a bug if it's bias. - -### ⚠️ Pool normalization MUST be walk-forward — no exceptions - -**The trap:** research panels often compute pool μ/σ over the FULL panel (all dates × all pool members) and apply those stats to every date. This is lookahead: the pool applied at date T contains data from T+1, T+2, etc. - -Per-cat rolling z upstream does NOT save you — the pool layer on top of PIT inputs still leaks if it uses full-panel stats. - -**Empirical cost observed (dm-evo TAA, 2026-04-24):** replacing full-panel pool with rolling 10Y / 5Y-min pool dropped v4.14.1 avg IR from +0.556 to +0.484 (−0.072, ~13% relative). Lock-candidate survived, but the leaky number was overstated. Other variants would likely show similar shrinkage. - -**Rule:** at each eval_date T, pool μ/σ must come from data satisfying `date ≤ T` (or `date ∈ (T−window, T]` for rolling). Never from the full panel. - -**Implementations, in order of preference:** -- **Rolling window + minimum** (matches per-cat rolling z convention, e.g. window=120 months, min=60). O(N_dates × pool_size) — trivial cost. -- **Expanding window with min-periods gate.** Grows with each run. Same cost shape. -- **Fixed calibration window** (Carver-original: calibrate on pre-backtest warmup period, apply constants thereafter). Deterministic and fast, but can drift off regime over long horizons. - -**Never acceptable:** full-panel pool in a backtest that measures IR/Sharpe/DD. It always flatters early-sample performance by importing late-sample structure. - -**Gate before locking any methodology:** if the variant uses a pooled component, confirm a walk-forward re-run matches within the noise floor of the relative ranking. If absolute numbers shift but ranking holds, lock against the walk-forward number, not the full-panel one. - -## Stage 5 — Ensemble construction - -**One change per variant.** Don't layer "new normalization + new clip + new weights" into v{N+1}. You can't attribute a result to any one change. - -**Common composite shapes:** - -``` -# Weighted z-sum with one primary + overlays -composite_z = 1.0·primary_z + 0.5·overlay_a_z + 0.5·overlay_b_z - -# Optional: clip components individually before summing -composite_z = 1.0·clip(primary, ±3) + 0.5·clip(overlay_a, ±3) + 0.5·clip(overlay_b, ±3) - -# Cap composite + tanh to [0,1] -final_z = clip(composite_z, ±2.0) -signal = (tanh(final_z / 2.0) + 1) / 2 -``` - -**Weight schemes:** -- **Equal-weighted** — robust, no overfit risk -- **IC-weighted** — fits historical importance, overfits future -- **FDM-corrected (Carver)** — `1/sqrt(w'·Σ·w)` divides by signal correlation; conservative when signals agree -- **Regression / ML** — last resort; needs walk-forward validation - -**Iteration discipline** — log each variant in `EXPERIMENTS.md`: - -```markdown -## YYYY-MM-DD — v{N+1}: {one-line change} -Hypothesis: {why this should help} -What changed: {single mechanical change vs v{N}} -Result: avg IR {x} → {y} (Δ {z}); per-profile table; era table -Decision: accept / reject / iterate -``` - -## Stage 6 — Weight engine - -Convert a [0,1] signal to a portfolio weight per asset per profile. - -**Standard mapping:** - -``` -weight[cat] = neutral[cat] + (signal[cat] − 0.5) × corridor_span[cat] -``` - -**Multi-profile** — same signal, different corridors. Each risk profile has its own (min, neutral, max) per category. Corridor *geometry* affects strategy character: -- Symmetric corridors enable bigger trend-following tilts (and bigger flash-crash drawdowns when caught long into a reversal) -- Wider equity corridors at moderate-equity-neutral profiles (the "P4 problem") create the largest reachable upside, which compounds losses in mean-reverting shocks - -**Floor consolidation + sum=1 normalization** — handle the case where a corridor floor (e.g., 5% min on FI_HY) interacts with the sum-to-1 constraint. Document the order of operations. - -**Output:** Per-profile weight DataFrame, one row per rebalance date. - -## Stage 7 — Portfolio backtest - -**MANDATORY:** Use the repo's drift-aware backtest engine (dm-evo: the `backtest` skill in dm-evo-core, vbt `run()`). Manual weighted-sum loops over monthly returns inflate IR by ~0.20 because they skip intra-month weight drift. - -**Standard outputs per variant** (all in one `pf` call so they share prices/dates/fees): -- Variants under test + current locked baseline + SAA benchmark -- avg + min IR across profiles -- Per-profile IR + Sharpe + MaxDD vs SAA -- Per-regime MaxDD via `pf.drawdowns.records_readable` filtered by `valley_idx` window -- Per-asset attribution via `pf.value(group_by=False)` (which assets contributed how much) -- Turnover + realized fees - -**Realistic fees from day 1.** 10bps per rebalance for liquid index ETFs; more for narrow/illiquid. Don't run zero-fee backtests then "add fees later" — you won't, and the unfees results will mislead your iteration. - -**Apples-to-apples comparison.** When ranking variants, all variants must use the SAME prices, SAME dates, SAME fees, SAME rebalance schedule. Easiest: pass them all as a dict to `vbt_run()` in a single call. - -## Stage 8 — Lock & promote - -**Lock criteria** (all must pass before flipping STATUS to LOCKED): - -- [ ] Beats baseline on avg IR by ≥X (define X up front, not after seeing the result) -- [ ] Beats baseline on min IR (worst-profile protection) -- [ ] No regime catastrophe (no era worse than baseline by ≥X pp) -- [ ] Turnover within 1.2× baseline -- [ ] MaxDD vs SAA: tied or shallower on majority of profiles -- [ ] Attribution understood — "the win comes from {factor}" (don't lock if you can't say where the alpha lives) -- [ ] Known weaknesses documented in spec §Known risks -- [ ] Reproducible: rerun from clean state produces same numbers - -**Then:** -1. Update STATUS.md row to LOCKED with date + drift-aware metrics -2. Append EXPERIMENTS.md entry with full rank table + decision -3. Update spec §{X} with formula + parameters + IR table + known risks -4. Open `feat/{subsystem}-v{X}` off `dev` for promotion (see `.claude/rules/research-workflow.md`) - -**Lock once.** Avoid PROVISIONAL → LOCKED → PROVISIONAL → LOCKED cycles by running drift-aware backtest *before* the first lock attempt, not as a retrofit. - -## Mapping to directory structure - -The 4-track directory pattern (`validation/` + `scoring/` + `backtesting/` + `comparison/`) maps cleanly to the 8 stages: - -| Stage | Directory | -|---|---| -| 1 — generation | `docs/signal-definitions-v{N}.md` | -| 2 — anatomy | `validation/` (per-signal modules + dashboard) | -| 3 — IC | `scoring/ic_analysis.py` | -| 4–5 — normalization + ensemble | `scoring/backtest.py` (variant loop) | -| 6 — weight engine | `src/{subsystem}/compute_weights.py` (or local equivalent) | -| 7 — backtest | `backtesting/backtest_vbt.py` | -| 8 — lock | `STATUS.md` + `EXPERIMENTS.md` + spec | - -See `investment-research` parent skill "Mature-stage directory evolution" section for when to split flat → 4-track. diff --git a/claude/skills/research/research-bakeoff/SKILL.md b/claude/skills/research/research-bakeoff/SKILL.md deleted file mode 100644 index ea909a84..00000000 --- a/claude/skills/research/research-bakeoff/SKILL.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: research-bakeoff -description: | - Bake-off / tournament: implement + evaluate N candidate approaches to a research problem in - parallel (each in its own worktree), judge each on the metrics that matter, and pick a winner — - synthesizing from the winner while grafting the best ideas from the runners-up. Use when the - solution space is wide and you want evidence, not a guess. Triggers: "bake-off X", "compare these - approaches", "which method is best for X", "tournament of approaches", "/research-bakeoff". - Launches a multi-agent Workflow (this skill authorizes the Workflow call). ---- - -# research-bakeoff — approach tournament - -Beats one-attempt-iterated when the solution space is wide. Each approach is built + measured -independently, judged on the same rubric, then synthesized. - -## When invoked -1. Get the **problem** and the **candidate approaches** from args/prompt. If approaches aren't given, - propose 3 distinct ones (e.g. simple-baseline / risk-first / signal-rich) and confirm in one line. -2. Invoke the `Workflow` tool with the script below, passing `args: { problem, approaches, rubric }`. - Each builder runs in `isolation:'worktree'` so they don't collide. -3. Present: the scored table, the **winner + why**, and the 1-2 ideas worth grafting from the losers. - -## Workflow -```js -export const meta = { - name: 'research-bakeoff', - description: 'Implement + evaluate N approaches, judge, pick a winner', - phases: [{ title: 'Build' }, { title: 'Judge' }], -} -const BUILT = { type:'object', required:['approach','metrics','branch'], properties:{ - approach:{type:'string'}, metrics:{type:'object'}, branch:{type:'string'}, notes:{type:'string'} } } -const SCORE = { type:'object', required:['approach','scores','verdict'], properties:{ - approach:{type:'string'}, scores:{type:'object'}, verdict:{type:'string'}, keep_ideas:{type:'string'} } } -const problem = (args && args.problem) || 'the research problem named in the invocation' -const APPROACHES = (args && args.approaches) || ['baseline / simplest defensible approach', 'risk-first approach', 'signal-rich approach'] -const rubric = (args && args.rubric) || 'IC, deflated-Sharpe, turnover/churn, explainability, robustness across windows' -const scored = await pipeline(APPROACHES, - a => agent(`Implement AND evaluate this approach to "${problem}": ${a}. Work entirely in your own worktree; produce the headline metrics. Report the metrics + your branch name.`, - { label: `build:${a.slice(0,18)}`, phase: 'Build', isolation: 'worktree', agentType: 'engineering-senior-developer', schema: BUILT }), - built => agent(`Judge this approach on the rubric "${rubric}". Be quantitative and skeptical. Approach + measured metrics: ${JSON.stringify(built)}`, - { label: `judge:${(built&&built.approach||'').slice(0,16)}`, phase: 'Judge', schema: SCORE, agentType: 'engineering-code-reviewer' }) -) -return { problem, rubric, approaches: scored.filter(Boolean) } -``` -Synthesize the winner yourself from the scored set; call out ideas to graft from runners-up. diff --git a/claude/skills/research/research-refute/SKILL.md b/claude/skills/research/research-refute/SKILL.md deleted file mode 100644 index 038fe97b..00000000 --- a/claude/skills/research/research-refute/SKILL.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -name: research-refute -description: | - Adversarially verify a research finding by spawning a panel of skeptics that each try to BREAK - it via a DIFFERENT failure mode (lookahead, overfitting, regime-dependence, data quality, - multiple-testing, fair-baseline). Use before trusting a quant/data result. Triggers: "refute X", - "is this finding real?", "stress-test this claim/signal/result", "verify this before I trust it", - "/research-refute". Launches a multi-agent Workflow (this skill authorizes the Workflow call). ---- - -# research-refute — adversarial verification panel - -Research's failure mode is *plausible-but-wrong*, not incomplete. This panel kills it before it -becomes a finding: N skeptics, each on a distinct failure lens, prompted to refute. Keep the -finding only if it survives (no fatal/serious refutation). - -## When invoked -1. Get the **claim** + where its **evidence/code** lives from the user's args/prompt. If the claim - is vague, ask exactly one clarifying question (what's asserted + which script/report/parquet backs it). -2. Invoke the `Workflow` tool with the script below, passing `args: { claim, evidence }`. Scale lens - count to effort (low → 3 lenses, high → all 6 + 2 generalists). -3. Present: lead with **SURVIVES / REFUTED**, then the fatal/serious refutations (with the fix each - implies), then the full panel. Never bury a fatal verdict. - -## Workflow -```js -export const meta = { - name: 'research-refute', - description: 'Adversarial verification of a research finding', - phases: [{ title: 'Refute' }], -} -const VERDICT = { type:'object', required:['lens','refuted','reason','severity'], properties:{ - lens:{type:'string'}, refuted:{type:'boolean'}, reason:{type:'string'}, - severity:{type:'string', enum:['fatal','serious','minor','none']}, - suggested_fix:{type:'string'} } } -const claim = (args && args.claim) || 'the finding stated in the invocation' -const evidence = (args && args.evidence) || 'the lab worktree / report referenced in the finding' -const LENSES = [ - 'lookahead / data-snooping bias — is any future information leaking into the signal or labels?', - 'overfitting / parameter sensitivity — does it survive a small change to every threshold/param?', - 'regime-dependence / subsample instability — does it hold out-of-window and per-regime, or only full-sample?', - 'data quality — survivorship, NaN-drops, stale/frozen prices, a single missing week killing rolling stats', - 'multiple-testing / p-hacking — how many variants were tried? does it survive a deflated-Sharpe / Bonferroni haircut?', - 'fair baseline — is it beating an honest baseline (passive ETF, naive rule), or just collecting beta?', -] -// Typed skeptics carry the checklist (deployed via agent-kit/.claude/agents → each lab repo). -// The data-quality lens goes to the pit-data-auditor (input/provenance forensics); every other -// lens goes to the quant-verifier (lookahead/overfit/baseline/multiple-testing checklist). Falls -// back gracefully if a repo lacks the typed agents. -// Widened so a reworded data lens (point-in-time, provenance, universe, mcap, volume) still routes -// to the data auditor rather than silently falling through to the verifier. -const lensAgentType = lens => - /data quality|survivorship|stale|frozen|point.?in.?time|provenance|universe|mcap|market.?cap|volume|delisting/i.test(lens) - ? 'pit-data-auditor' : 'quant-verifier' -const verdicts = (await parallel(LENSES.map(lens => () => - agent(`You are a hostile quant reviewer. Try HARD to REFUTE this finding through the single lens "${lens}". Read the referenced code/data; do not take the author's word. Default refuted=true if you find any plausible failure on this lens. Finding: ${claim}. Evidence location: ${evidence}.`, - { label: `refute:${lens.split(' ')[0]}`, phase: 'Refute', schema: VERDICT, agentType: lensAgentType(lens) })) -)).filter(Boolean) -const killers = verdicts.filter(v => v.refuted && (v.severity === 'fatal' || v.severity === 'serious')) -return { claim, survives: killers.length === 0, killers, verdicts } -``` -After it returns: state SURVIVES/REFUTED, list `killers` first (each with its `suggested_fix`), then the rest. If it survives, say what *would* still strengthen it. diff --git a/claude/skills/research/research-reproduce/SKILL.md b/claude/skills/research/research-reproduce/SKILL.md deleted file mode 100644 index 73d41f55..00000000 --- a/claude/skills/research/research-reproduce/SKILL.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -name: research-reproduce -description: | - Reproduce a result via INDEPENDENT paths (different implementation, different inputs, different - library) in parallel, then cross-check: agreement = trust, divergence = a likely bug. Use to - validate a metric/number before it ships. Triggers: "reproduce X", "cross-check this result/metric", - "can we replicate this number", "independent check of X", "/research-reproduce". Launches a - multi-agent Workflow (this skill authorizes the Workflow call). ---- - -# research-reproduce — independent reproduction + cross-check - -Catches the silent-bug class (NaN-drops, off-by-one windows, wrong join keys) by computing the same -result two-or-three independent ways and comparing. The reproducers must NOT read the original number -first — they compute, then report. - -## When invoked -1. Get the **result/metric** to reproduce and where its inputs live from args/prompt. -2. Invoke the `Workflow` tool with the script below, passing `args: { result, paths }`. -3. Present: **AGREE / DIVERGE**, the per-path values, and — if they diverge — the most likely cause - (which the cross-check agent names). Treat divergence as a bug to chase, not noise to average. - -## Workflow -```js -export const meta = { - name: 'research-reproduce', - description: 'Independent reproduction of a result + cross-check', - phases: [{ title: 'Reproduce' }, { title: 'Cross-check' }], -} -const REP = { type:'object', required:['path','value','method','notes'], properties:{ - path:{type:'string'}, value:{type:'string'}, method:{type:'string'}, notes:{type:'string'} } } -const result = (args && args.result) || 'the result/metric named in the invocation' -const PATHS = (args && args.paths) || [ - 'from the raw inputs via your own independent implementation', - 'from the committed intermediate artifacts (parquet/csv), recomputing the final step', - 'via a different library or formulation that should agree mathematically', -] -const reps = (await parallel(PATHS.map(p => () => - agent(`Independently reproduce this result: ${result}. Use this path ONLY: ${p}. Do NOT look up the original author's number before computing — compute it yourself, then report your value and exactly how you got it.`, - { label: `repro:${p.slice(0,18)}`, phase: 'Reproduce', schema: REP, agentType: 'parity-reproduction-engineer' })) -)).filter(Boolean) -const verdict = await agent(`These are independent reproductions of "${result}". Do they AGREE within reasonable tolerance? If they diverge, the divergence is almost certainly a bug — name the single most probable cause and where to look. Reproductions: ${JSON.stringify(reps)}`, - { phase: 'Cross-check', schema: { type:'object', required:['agree','spread','likely_cause'], properties:{ - agree:{type:'boolean'}, spread:{type:'string'}, likely_cause:{type:'string'} } } }) -return { result, reproductions: reps, verdict } -``` -Lead with `verdict.agree` (AGREE/DIVERGE); if DIVERGE, surface `verdict.likely_cause` prominently. diff --git a/claude/skills/research/research-robustness/SKILL.md b/claude/skills/research/research-robustness/SKILL.md deleted file mode 100644 index 115b6d78..00000000 --- a/claude/skills/research/research-robustness/SKILL.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: research-robustness -description: | - Stress a method or signal across a matrix of windows × regimes × parameters in parallel, collect - a robustness grid, and flag where it breaks. Use to check "does this hold out-of-sample / across - regimes?" before locking a methodology. Triggers: "robustness of X", "stress-test this signal - across windows/regimes", "sensitivity matrix", "does this hold out of sample", "/research-robustness". - Launches a multi-agent Workflow (this skill authorizes the Workflow call). ---- - -# research-robustness — robustness / sensitivity matrix - -Automates the "lock nothing until it persists across windows" rule: run the *same* method over many -conditions concurrently, then report where the headline metric is stable vs fragile. - -## When invoked -1. Get the **method/signal** (and where to run it) from args/prompt. Default the matrix to 3 windows × - 4 regimes unless the user names their own; ask only if the method isn't runnable as described. -2. Invoke the `Workflow` tool with the script below, passing `args: { method, windows, regimes }`. -3. Present the grid as a compact table (cell → metric, stable?), lead with **ROBUST / FRAGILE** and the - cells that break, and name the condition that breaks it. - -## Workflow -```js -export const meta = { - name: 'research-robustness', - description: 'Robustness/sensitivity matrix for a method or signal', - phases: [{ title: 'Grid' }, { title: 'Synthesize' }], -} -const CELL = { type:'object', required:['cell','metric','stable','note'], properties:{ - cell:{type:'string'}, metric:{type:'number'}, stable:{type:'boolean'}, note:{type:'string'} } } -const method = (args && args.method) || 'the method/signal named in the invocation' -const WINDOWS = (args && args.windows) || ['trailing 156w', 'trailing 104w', 'trailing 52w'] -const REGIMES = (args && args.regimes) || ['full sample', 'risk-on', 'risk-off', 'high-vol'] -const cells = WINDOWS.flatMap(w => REGIMES.map(r => ({ w, r }))) -const grid = (await parallel(cells.map(c => () => - agent(`Evaluate "${method}" on window=${c.w}, regime=${c.r}. Actually run the backtest/metric in the repo (do not estimate). Report the headline metric (Sharpe / IC / hit-rate as appropriate), whether it is STABLE vs the full-sample value (±25%), and any caveat.`, - { label: `cell:${c.w}|${c.r}`, phase: 'Grid', schema: CELL, agentType: 'engineering-data-engineer' })) -)).filter(Boolean) -const unstable = grid.filter(c => !c.stable) -const synth = await agent(`Given this robustness grid for "${method}", state ROBUST or FRAGILE, the single condition under which it most degrades, and whether it is safe to lock. Grid: ${JSON.stringify(grid)}`, - { phase: 'Synthesize', schema: { type:'object', required:['verdict','breaks_under','safe_to_lock'], properties:{ - verdict:{type:'string',enum:['robust','fragile','mixed']}, breaks_under:{type:'string'}, safe_to_lock:{type:'boolean'} } } }) -return { method, cells: grid.length, unstable: unstable.length, grid, synth } -``` -Render `grid` as a table; lead with `synth.verdict` + `synth.breaks_under`. diff --git a/claude/skills/research/research-sweep/SKILL.md b/claude/skills/research/research-sweep/SKILL.md deleted file mode 100644 index c44d82a1..00000000 --- a/claude/skills/research/research-sweep/SKILL.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -name: research-sweep -description: | - Multi-modal evidence sweep + synthesis for an open research question: fan out agents that each - gather evidence a DIFFERENT way (own data, correlation/benchmark, prior notes via atlas, external - literature via web, the code), blind to each other, then synthesize a cited, decisive answer that - surfaces agreements and conflicts. Use for "what do we know about X / what's the right Y". Triggers: - "research X", "what's the right benchmark/approach for X", "gather the evidence on X", "deep dive X", - "/research-sweep". Launches a multi-agent Workflow (this skill authorizes the Workflow call). ---- - -# research-sweep — multi-modal evidence → synthesis - -One search angle never finds everything. Each agent is blind to the others and reports only what its -mode shows; the synthesizer reconciles them into a decisive, confidence-rated answer. - -## When invoked -1. Get the **question** from args/prompt. Trim the modes to what's relevant (drop "web" for a purely - internal-data question; drop "atlas" if no vault). -2. Invoke the `Workflow` tool with the script below, passing `args: { question, modes }`. -3. Present the synthesized **answer + confidence**, then the conflicts between angles (those are the - interesting part), then the per-mode evidence as backup. - -## Workflow -```js -export const meta = { - name: 'research-sweep', - description: 'Multi-modal evidence sweep + synthesis for a research question', - phases: [{ title: 'Gather' }, { title: 'Synthesize' }], -} -const EV = { type:'object', required:['mode','findings','confidence'], properties:{ - mode:{type:'string'}, findings:{type:'string'}, confidence:{type:'string', enum:['high','medium','low']} } } -const question = (args && args.question) || 'the question named in the invocation' -const MODES = (args && args.modes) || [ - 'the data itself — compute from the fund/return series, do not assume', - 'correlation / benchmark-ETF evidence', - 'prior research + decisions in the vault (use atlas-query)', - 'external literature (use web search)', - 'the existing code / implementation', -] -// The "data itself" mode is routed to the pit-data-auditor so the data angle is a typed audit -// (PIT/provenance/integrity) rather than a blank subagent. Falls back gracefully where the agent -// isn't deployed. Deployed via agent-kit/.claude/agents → each lab repo. -const modeAgentType = m => /the data itself|from the fund\/return series|own data/i.test(m) - ? 'pit-data-auditor' : undefined -const evidence = (await parallel(MODES.map(m => () => - agent(`Investigate "${question}" using ONLY this mode: ${m}. Report what THIS angle shows and your confidence; stay blind to other angles — do not speculate beyond your mode.`, - { label: `mode:${m.slice(0,16)}`, phase: 'Gather', schema: EV, agentType: modeAgentType(m) })) -)).filter(Boolean) -const report = await agent(`Synthesize a cited, DECISIVE answer to "${question}" from this multi-angle evidence. State the answer, your confidence, and — most important — where the angles CONFLICT (and which to trust). Evidence: ${JSON.stringify(evidence)}`, - { phase: 'Synthesize', schema: { type:'object', required:['answer','confidence','conflicts'], properties:{ - answer:{type:'string'}, confidence:{type:'string'}, conflicts:{type:'string'} } } }) -return { question, evidence, report } -``` -Lead with `report.answer` + confidence; surface `report.conflicts` before the raw evidence. diff --git a/docs/playbooks/investment-research-workflow.md b/docs/playbooks/investment-research-workflow.md index cb8f8647..4f2d1c9d 100644 --- a/docs/playbooks/investment-research-workflow.md +++ b/docs/playbooks/investment-research-workflow.md @@ -15,7 +15,7 @@ Starting a new investment research question — factor analysis, fund comparison | Skill | Role | |-------|------| -| `investment-research` | Lifecycle framework (question → data → analysis → deliverable) | +| qute-research `/research` | Lifecycle and method protocols (`method-investment.md`, `method-signal.md`) — moved out of the kit 2026-09-28 (TOM-1221) | | `investment-research-formal` | Auditable tracking with hypothesis/experiment/finding | | `paper-reading` | Extract insights from papers, fund cards, prospectuses | | `investment-research-dashboard` | Self-contained Plotly.js HTML dashboards | @@ -26,18 +26,13 @@ Starting a new investment research question — factor analysis, fund comparison ### Phase 1: Frame the Question -Use `/investment-research` to structure the research question: +Open a line with qute-research's `/research line`; its method protocols say +what the question needs before any code: ``` -/investment-research "Does momentum factor work in Polish equity funds?" +/research line momentum-pl --question "Does momentum work in Polish equity funds?" ``` -This produces a research plan with: -- Clear hypothesis -- Required data sources -- Analysis approach -- Expected deliverable format - ### Phase 2: Gather Data Fetch relevant data using `market-datasets`: @@ -91,7 +86,7 @@ Promote from `scratch/` to `research/{study-name}/` with co-located scripts, dat ## Example: Momentum in Polish Equity Funds ``` -1. /investment-research "momentum factor in Polish equity funds" +1. /research line momentum-pl (qute-research) 2. Fetch 5-year monthly returns from Stooq for WIG components 3. Fetch fund NAVs from analizy.pl for equity funds 4. /paper-reading on Jegadeesh & Titman (1993), local momentum studies @@ -103,7 +98,7 @@ Promote from `scratch/` to `research/{study-name}/` with co-located scripts, dat ## Tips -- Start with `/investment-research` even for informal studies — it forces clear thinking +- Open a line with `/research line` even for informal studies — it forces clear thinking - Use formal tracking (`/investment-research-formal`) when results might be challenged - Always save large outputs to files — keep conversation context for decisions - Dashboard skill produces single HTML files — easy to email or share