diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37f08dff..4013ee39 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,18 +6,6 @@ on: pull_request: jobs: - reporting-contract: - # Enforce the bundled reporting lib's self-contained + injection-safe - # contract shipped with the investment-research-dashboard skill. - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: astral-sh/setup-uv@v5 - - name: pytest (reporting contract) - run: >- - uvx --with pandas --with numpy --with plotly pytest - claude/skills/quant/investment-research-dashboard/reporting/test_reporting.py -q - secret-scan: # No secrets or private infra details in a public repo (TOM-1257). # Rules: .gitleaks.toml. Known public-history findings: .gitleaksignore. diff --git a/INVENTORY.md b/INVENTORY.md index 4f8440db..d96baa09 100644 --- a/INVENTORY.md +++ b/INVENTORY.md @@ -18,17 +18,15 @@ 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 (12, grouped by directory under `claude/skills/`) +## Skills (10, grouped by directory under `claude/skills/`) -### Quant / data (`quant/`, 7) +### Quant / data (`quant/`, 5) | Name | Description | |---|---| | `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-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) | @@ -60,7 +58,12 @@ them, and qute-essentials depends on it), `brand-sonte` (archived project). `acceptance-gates`, `investment-research` (now its method protocols), `research-refute`, `-reproduce`, `-robustness`, `-sweep`, `-bakeoff` — see the -qute-research README in `tomlupo/qute-plugins`. +qute-research README in `tomlupo/qute-plugins`. On 2026-09-29 the last two +followed: `investment-research-dashboard` is its `research-dashboard` skill (the +`reporting/` library and its contract tests), and `investment-research-formal`'s +METHODOLOGY skeleton, MiFID II mapping and literature note are its +`skills/research/references/methodology-document.md`. The kit carries no research +skills. ## Agents (2) diff --git a/README.md b/README.md index 150fae78..5d51f2de 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ releases, or self-updates. ## The kit: `claude/` -12 generic skills (quant/data, engineering, visual/UX), 2 agents, 3 settings +10 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). diff --git a/claude/skills/quant/investment-research-dashboard/SKILL.md b/claude/skills/quant/investment-research-dashboard/SKILL.md deleted file mode 100644 index 77f3d581..00000000 --- a/claude/skills/quant/investment-research-dashboard/SKILL.md +++ /dev/null @@ -1,534 +0,0 @@ ---- -name: investment-research-dashboard -description: Builds self-contained HTML dashboards for investment and finance research using Plotly.js. Use when building interactive dashboards, research reports, or data visualizations for portfolio analysis, risk metrics, fund performance, asset allocation, drawdowns, or any quantitative finance presentation. Produces single-file HTML with embedded data — no server needed, shareable, works offline. -allowed-tools: Write, Bash, Read, Edit, Glob, Grep ---- - -# Investment Research Dashboard - -Build professional, self-contained HTML dashboards for quantitative finance research. Single HTML file output with embedded JSON data and Plotly.js charts — no build step, no server, fully shareable. - -## When to Use - -- Portfolio analysis dashboards (risk profiles, allocations, performance) -- Fund/strategy performance reports (returns, drawdowns, benchmarks) -- Risk metric visualizations (VaR, drawdowns, stress tests, correlations) -- Asset allocation studies (efficient frontier, rebalancing analysis) -- Any quantitative finance presentation needing interactive charts - -## Reuse the canonical dashboard FIRST - -**Before building anything, search for an existing canonical report builder and -reuse it. Only create a new one if none fits.** Rationale: stop re-implementing -bespoke dashboards — one canonical, self-contained template, reused. - -This skill bundles the canonical reporting library at `reporting/` -(`base` primitives + `backtest_dashboard` + `research_story`, mastered from -`dm-evo-lab/research/_lib/reporting/`). It is the default path. - -**Step 0 — glob for an existing builder** before writing a line of HTML: - -```bash -# this skill's own bundled lib -ls "$SKILL_DIR"/reporting/{base,backtest_dashboard,research_story}.py -# the canonical source in a research workspace -ls **/research/_lib/reporting/*.py -# any existing bespoke builders in the target repo -ls **/build_*dashboard*.py **/build_*report*.py **/*_dashboard.py -``` - -**Decision:** - -1. **A canonical template fits** (`backtest_dashboard` for an equity/DD/metrics - backtest; `research_story` for a numbered narrative; `base` for a custom - layout) → **import it and pass a payload. Do NOT hand-roll a new template.** - - ```python - import sys; from pathlib import Path - sys.path.insert(0, str(Path(__file__).resolve().parent)) # dir holding reporting/ - from reporting import backtest_dashboard, research_story, base - - html = backtest_dashboard.render(payload) # see reporting/README.md for schema - Path("output/dashboard.html").write_text(html, encoding="utf-8") - ``` - -2. **An existing bespoke builder in the repo already covers it** → reuse/extend - that, don't fork a parallel one. - -3. **Nothing suitable exists** → only then build from scratch — and even then, - **use the bundled `reporting.base` primitives** (`page`, `section`, `table`, - `plot`, `kpi_row`, `inline_plotly`) so the result is self-contained *by - construction*. The from-scratch guidance below applies to this case. - -Read `reporting/README.md` for the full API + payload contracts. - -## Quick Start - -A dashboard has two parts: **Python data builder** and **HTML template**. - -### 1. Python Data Builder - -Computes all metrics and writes a JSON file: - -```python -import json -from pathlib import Path -from datetime import datetime - -def make_run_dir(base: Path, manual_override: str | None = None) -> Path: - if manual_override: - d = Path(manual_override) - else: - d = base / datetime.now().strftime("%Y%m%d-%H%M%S") - d.mkdir(parents=True, exist_ok=True) - return d - -def build_data() -> dict: - """Build all dashboard data. Return a single dict.""" - return { - "metadata": {"title": "...", "generated": "...", "period": "..."}, - "profiles": { ... }, # per-entity data - "summary": { ... }, # aggregate metrics - # ... domain-specific sections - } - -data = build_data() -run_dir = make_run_dir(Path("output")) -(run_dir / "dashboard_data.json").write_text( - json.dumps(data, separators=(",", ":")), encoding="utf-8" -) -``` - -### 2. HTML Template - -Self-contained file with a `DATA` placeholder: - -```html - - - - - -Dashboard Title - -__PLOTLY_INLINE__ - - - - - - - -``` - -### 3. HTML Builder - -Injects JSON into the template: - -```python -import sys; from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parent)) # dir holding reporting/ -from reporting import base # bundled canonical primitives - -DATA_PLACEHOLDER = "const DATA = {};" -template = Path("templates/dashboard_template.html").read_text(encoding="utf-8") -data_str = json.dumps(data, separators=(",", ":")) -html = ( - template - .replace("__PLOTLY_INLINE__", base.inline_plotly()) # embed plotly.min.js — no CDN - .replace(DATA_PLACEHOLDER, f"const DATA = {data_str};") -) -Path(run_dir / "dashboard.html").write_text(html, encoding="utf-8") -``` - -`base.inline_plotly()` reads `plotly.min.js` from the installed `plotly` package -and returns a `` — the file is then fully offline with zero -external references. - -## Architecture - -``` -project/ - templates/ - dashboard_template.html # HTML + CSS + JS with DATA placeholder - build_data.py # Python: compute metrics → JSON - build_html.py # Python: inject JSON → self-contained HTML - output/ - {YYYYMMDD-HHMMSS}/ # Timestamped run output - dashboard_data.json - dashboard.html # Final deliverable -``` - -**Key principle**: Template never changes between runs. All variable content comes from JSON data. The template is pure presentation logic. - -### When to Split vs Single-File - -| Approach | When to use | Trade-off | -|----------|-------------|-----------| -| **Split** (separate template + data builder) | Production dashboards rebuilt regularly with new data. >500 lines of HTML. Team collaboration on styling. | Template editable in HTML editor, data builder testable independently. | -| **Single-file** (HTML in Python string) | Research/exploration dashboards that change frequently. <500 lines HTML. Fast iteration during development. | Faster iteration, no file juggling, but harder to maintain long-term. | - -For single-file approach, use `HTML.replace("__DATA_JSON__", json.dumps(data))` pattern. For split approach, use `const DATA = {};` placeholder in the template file. - -### Hard split rule (enforced) - -The trade-off above describes the choice during initial implementation. Once a -dashboard crosses the thresholds below, **the split is mandatory**, not -optional — single-file mode is for exploration, not for production-grade -dashboards that get rebuilt and reviewed by collaborators. - -**Trigger conditions** (any one is sufficient): - -- Python builder file > 500 lines (`wc -l build_dashboard.py`) -- Inlined HTML/CSS/JS string > 500 lines (length of the triple-quoted block) -- Dashboard is rebuilt by an automated pipeline (cron, CI, scheduled report) -- Two or more people (incl. future-you and an AI agent) will edit the file - -**Required architecture once triggered:** - -``` -{pipeline_dir}/ -├── build_dashboard.py # thin orchestrator (≤100 lines): args, run_dir, calls into dashboard.{data,html} -├── dashboard/ -│ ├── __init__.py -│ ├── data.py # build_data(...) -> dict; pure compute, no HTML -│ ├── html.py # render_html(data, template_path) -> str; inject + write -│ └── charts.py # (optional) Plotly trace builders, shared layout helpers -└── templates/ - └── dashboard.html # template with `const DATA = {};` placeholder; no Python here -``` - -**Each module has one job:** - -| File | Responsibility | Forbidden content | -|---|---|---| -| `build_dashboard.py` | Orchestration only — argparse, run_dir, calls into `dashboard.data` and `dashboard.html` | Metric computation, HTML strings, chart code | -| `dashboard/data.py` | Compute every number/series the template needs; emit a single nested dict | HTML, CSS, JS, Plotly JSON, file I/O of HTML | -| `dashboard/html.py` | Read template, inject `const DATA = {...};`, write final `.html` | Metric computation, dataframe slicing | -| `dashboard/charts.py` (optional) | Plotly trace + layout helpers, shared across panels | Domain logic, file I/O | -| `templates/dashboard.html` | All HTML, CSS, JS, Plotly rendering; reads `const DATA` only | Python, dynamic file paths, inline data values | - -**Pre-merge compliance checklist** — run before any PR that adds or touches a dashboard: - -- [ ] `wc -l build_dashboard.py` ≤ 100 (orchestrator stays thin) -- [ ] `dashboard/` package exists with at minimum `data.py` and `html.py` -- [ ] `templates/*.html` exists; the `.html` is the only place ` -{header_html} - -{body_prefix_html} -
-{body_sections} -
-{footer} - -""" diff --git a/claude/skills/quant/investment-research-dashboard/reporting/research_story.py b/claude/skills/quant/investment-research-dashboard/reporting/research_story.py deleted file mode 100644 index ead45293..00000000 --- a/claude/skills/quant/investment-research-dashboard/reporting/research_story.py +++ /dev/null @@ -1,79 +0,0 @@ -"""The step-by-step research narrative template. - -``render(sections, *, thesis, kpis, ...)`` assembles a self-contained -storytelling dashboard: a title + thesis banner + KPI row + numbered -reasoning-block-plus-evidence sections + sticky nav. - -Generalized from ``research/saa-finalization/scratch/scripts/build_story.py``. -Each section is a ``base.section(...)`` dict, typically built with a ``why(...)`` -reasoning block followed by evidence cards/plots/tables. -""" - -from __future__ import annotations - -from . import base - - -def why(lead: str, body: str, *, kind: str = "") -> str: - """A reasoning block — the WHY. - - ``lead`` is plain text (escaped); ``body`` is the trusted HTML fragment; - ``kind`` is a tone class (``""|good|bad|warn``, allowlisted). - """ - k = base._kind(kind) - k = f" {k}" if k else "" - lead_html = f'{base._esc(lead)}' if lead else "" - return f'
{lead_html}{body}
' - - -def card(title: str, inner_html: str, *, note: str | None = None) -> str: - """An evidence card. - - ``title``/``note`` are plain text (escaped); ``inner_html`` is trusted HTML. - """ - head = f"

{base._esc(title)}

" if title else "" - cap = ( - f'
{base._esc(note)}
' - if note - else "" - ) - return f'
{head}{inner_html}{cap}
' - - -def render( - sections: list, - *, - title: str, - thesis: str | None = None, - kpis: list[dict] | None = None, - subtitle: str | None = None, - eyebrow: str | None = None, - badges: list[str] | None = None, - favicon: str | None = "📊", - footer_html: str = "", - extra_head: str = "", - extra_script: str = "", -) -> str: - """Render the narrative story report. - - ``sections`` is a list of :func:`base.section` dicts (each with a ``step`` - label for the numbered arc). ``kpis`` is passed to :func:`base.kpi_row` and - rendered above the sections. - """ - body_prefix = "" - if kpis: - body_prefix = f'
{base.kpi_row(kpis)}
' - - return base.page( - title, - sections, - favicon=favicon, - subtitle=subtitle, - thesis=thesis, - eyebrow=eyebrow, - badges=badges, - body_prefix_html=body_prefix, - footer_html=footer_html, - extra_head=extra_head, - extra_script=extra_script, - ) diff --git a/claude/skills/quant/investment-research-dashboard/reporting/test_reporting.py b/claude/skills/quant/investment-research-dashboard/reporting/test_reporting.py deleted file mode 100644 index 34ccc378..00000000 --- a/claude/skills/quant/investment-research-dashboard/reporting/test_reporting.py +++ /dev/null @@ -1,384 +0,0 @@ -"""Contract tests for the bundled reporting lib. - -Guards the four properties the review flagged: - 1. drawdown is optional — derived from equity when absent (no JS crash path). - 2. embedded JSON is script-safe — ```` cannot break out of a block. - 3. section title/step/id are escaped/slugged — data cannot inject HTML. - 4. rendered reports are truly offline — zero external script/link/img refs. - -Run (needs plotly/pandas in the venv): pytest test_reporting.py -q -""" - -from __future__ import annotations - -import re -import sys -from pathlib import Path - -import pandas as pd - -sys.path.insert( - 0, str(Path(__file__).resolve().parent.parent) -) # dir holding reporting/ -from reporting import backtest_dashboard, base, research_story # noqa: E402 - -# Catch every external-reference form, not just double-quoted http(s): -# - a fetching tag (link/script/img/source/iframe/embed/object/video/audio/ -# track/input) with src/href/data/poster = http(s):// or protocol-relative // -# - CSS url(...) and @import pointing off-box (incl. protocol-relative) -# Data URIs (data:) and in-page anchors stay allowed — those are self-contained. -_REMOTE = r"(?:https?:)?//" -_FETCH_TAG = r"link|script|img|source|iframe|embed|object|video|audio|track|input" -_EXTERNAL_REFS = [ - re.compile( - rf"""<(?:{_FETCH_TAG})\b[^>]*?\b(?:src|href|data|poster)\s*=\s*["']?\s*{_REMOTE}""", - re.I, - ), - re.compile(rf"""url\(\s*["']?\s*{_REMOTE}""", re.I), - re.compile(rf"""@import\s+["']?\s*{_REMOTE}""", re.I), -] - -# The vendored plotly.min.js is inlined verbatim and contains http(s) URLs as JS -# *string data* (help links etc.) — not DOM references. Strip only INLINE -# ", re.I | re.S -) - - -def _has_external_refs(html: str) -> list[str]: - markup = _INLINE_SCRIPT.sub("", html) - hits: list[str] = [] - for pat in _EXTERNAL_REFS: - hits += pat.findall(markup) - return hits - - -# --- 2. script-safe JSON ----------------------------------------------------- - - -def test_dumps_escapes_script_terminator(): - out = base.dumps({"x": ""}) - assert "" not in out - assert "<\\/script>" in out - - -def test_dumps_escapes_line_separators(): - out = base.dumps({"x": "a\u2028b\u2029c"}) - assert "\u2028" not in out - assert "\u2029" not in out - assert "\\u2028" in out and "\\u2029" in out - - -def test_plot_payload_is_script_safe(): - frag = base.plot([{"x": [1], "y": [1], "name": ""}], {}, "d") - # the raw closing tag must not appear unescaped inside the emitted ' not in frag - - -# --- 3. escaped title / step / slugged id ------------------------------------ - - -def test_section_title_and_step_escaped(): - html = base.page( - "T", [base.section("hi", step="1", evidence_html="x")] - ) - assert "hi" not in html - assert "<b>hi</b>" in html - assert "<i>1</i>" in html - - -def test_section_id_slugged_and_nav_matches(): - # a custom id with unsafe chars must be slugged consistently in anchor + nav href - sec = base.section("Title", id='x" onload="alert(1)', evidence_html="e") - html = base.page("T", [sec]) - assert 'onload="alert(1)"' not in html - slug = base._slug('x" onload="alert(1)') - assert f'id="{slug}"' in html - assert f'href="#{slug}"' in html - - -def test_reasoning_and_evidence_html_stay_raw(): - # these ARE trusted raw HTML — must pass through unescaped - html = base.page( - "T", - [base.section("S", reasoning_html="keep", evidence_html="me")], - ) - assert "keep" in html - assert "me" in html - - -# --- 1. optional drawdown ---------------------------------------------------- - - -def test_backtest_render_without_drawdown(): - # a hand-built payload that omits drawdown must still render (JS derives it) - payload = { - "title": "no-dd", - "profiles": { - "P1": { - "series": { - "s": { - "dates": ["2020-01-01", "2020-01-02"], - "equity": [1.0, 0.9], - "color": "#000", - } - }, - "metrics": {"s": {"CAGR": 0.0}}, - } - }, - } - html = backtest_dashboard.render(payload) - assert "ddOf(s)" in html # fallback wired in - assert "s.drawdown.map(" not in html # no unconditional access - assert not _has_external_refs(html) - - -def test_series_helpers_populate_drawdown(): - idx = pd.date_range("2020-01-01", periods=10, freq="D") - r = pd.Series([0.01] * 5 + [-0.02] * 5, index=idx) - s = backtest_dashboard.series_from_returns(r, color="#000") - assert "drawdown" in s and len(s["drawdown"]) == len(s["equity"]) - - -# --- 4. offline output ------------------------------------------------------- - - -def test_backtest_dashboard_offline(): - idx = pd.date_range("2020-01-01", periods=30, freq="B") - r = pd.Series([0.001] * 30, index=idx) - payload = { - "title": "t", - "profiles": { - "P1": { - "series": { - "s": backtest_dashboard.series_from_returns(r, color="#000") - }, - "metrics": {}, - } - }, - } - html = backtest_dashboard.render(payload) - assert not _has_external_refs(html) - assert "Plotly.newPlot" in html - - -def test_header_fields_escaped(): - html = base.page( - "T", - [base.section("S", evidence_html="x")], - eyebrow="", - subtitle="", - thesis="t", - badges=["b"], - ) - # tags only the payload could introduce must not appear un-escaped - # (the page skeleton legitimately contains

/

/

, so we check - # payload-specific tokens: an injected ") - assert _has_external_refs('') - assert _has_external_refs("") - assert _has_external_refs("") - # but data URIs and in-page anchors are fine, and JS-string URLs are ignored - assert not _has_external_refs('') - assert not _has_external_refs('x') - assert not _has_external_refs('') - - -def test_profile_section_anchors_unique(): - idx = pd.date_range("2020-01-01", periods=10, freq="B") - r = pd.Series([0.001] * 10, index=idx) - s = lambda: backtest_dashboard.series_from_returns(r, color="#000") # noqa: E731 - # two titles that slug to the same value must get distinct section anchors - payload = { - "title": "t", - "profiles": { - "A B": {"series": {"x": s()}, "metrics": {}}, - "A_B": {"series": {"y": s()}, "metrics": {}}, - }, - } - html = backtest_dashboard.render(payload) - anchors = re.findall(r'
2pp without reducing annualized return by >0.5pp." - -## Rationale - -Why we believe this might be true: -- {Theoretical basis or market intuition} -- {Supporting literature: see literature/author-year-slug.md} -- {Empirical observation from prior work} - -## Success Criteria - -Quantitative thresholds that determine validated vs rejected: -- [ ] Max DD reduction > 2pp for P1, P2, P3 -- [ ] Ann. return reduction < 0.5pp -- [ ] Improvement consistent across full-period AND recent-period - -## Test Plan - -| # | Experiment | What It Tests | -|---|-----------|---------------| -| 1 | E01-{name} | {description} | -| 2 | E02-{name} | {description} | - -## Results - -| Experiment | Outcome | Key Metric | -|-----------|---------|------------| -| E01 | {PASS/FAIL} | {value} | - -## Conclusion - -**Status**: {VALIDATED / REJECTED / INCONCLUSIVE} - -{One paragraph summarizing the verdict with key numbers.} - -**If validated** → Finding: F{nn}-{slug}.md -**If rejected** → {Why, and what we learned} -**If inconclusive** → {What additional evidence is needed} -``` - -### Experiment (E01-{slug}.md) - -```markdown -# E01: {Experiment Name} - -**Status**: RUNNING -**Date**: YYYY-MM-DD -**Hypothesis**: H01-{slug}.md - -## Objective - -{What specific question does this experiment answer?} - -## Setup - -### Data -- Period: {start} to {end} ({N} months) -- Assets: {list} -- Source: {data source and validation status} -- Frequency: {monthly/daily} - -### Parameters -| Parameter | Value | Rationale | -|-----------|-------|-----------| -| Rebalancing | Quarterly | {why} | -| Cost assumption | 0 bps | {why} | -| Weight step | 5% | {why} | -| Benchmark | {what} | {why} | - -### Methodology -1. {Step 1} -2. {Step 2} -3. {Step 3} - -### Reproducibility -```bash -uv run python scripts/{script}.py --config {config} -``` -Output: `output/{run-dir}/` - -## Results - -### Primary Metrics -| Profile | Metric Before | Metric After | Delta | -|---------|--------------|-------------|-------| -| P1 | | | | -| P2 | | | | - -### Key Observations -- {Observation 1} -- {Observation 2} - -### Artifacts -- Data: `data/processed/{file}` -- Charts: `output/{run}/` -- Dashboard: `output/{run}/dashboard.html` - -## Conclusion - -{Does this support or refute H01? With what confidence?} - -## Limitations -- {Limitation 1: e.g., no transaction costs} -- {Limitation 2: e.g., USD-only, no FX for PLN portfolios} -``` - -### Finding (F01-{slug}.md) - -```markdown -# F01: {Finding Title} - -**Status**: DRAFT -**Date**: YYYY-MM-DD -**Confidence**: HIGH / MEDIUM / LOW - -## Summary - -{One paragraph: what we found, with key numbers.} - -## Evidence Chain - -| Source | Reference | Key Result | -|--------|-----------|------------| -| Hypothesis | H01-{slug}.md | {original claim} | -| Experiment | E01-{slug}.md | {supporting result} | -| Experiment | E02-{slug}.md | {confirming result} | - -## Quantitative Evidence - -| Metric | Before | After | Significance | -|--------|--------|-------|-------------| -| Max DD (P1) | -12.3% | -10.2% | 2.1pp improvement | -| Ann. Return (P1) | 5.9% | 5.7% | 0.2pp cost | - -## Implications - -### For Production -- {What parameter changes should be made} -- {Which config files need updating} - -### For Clients -- {How this affects risk profile communication} -- {Suitability documentation impact} - -### For Future Research -- {What new questions this raises} - -## Limitations & Caveats - -- {When this finding might not hold} -- {Data limitations} -- {Assumptions that could be violated} - -## Regulatory Notes - -{If applicable: MiFID II suitability relevance, documentation requirements, -how this finding supports the "acting in client's best interest" obligation.} - -## Application - -**Applied**: YES / NO / PARTIAL -**Applied to**: {config file, dashboard, app parameter} -**Applied date**: YYYY-MM-DD -**Applied by**: {name} -``` - -### Literature Note ({author-year}-{slug}.md) - -```markdown -# {Author} ({Year}) — {Short Title} - -**Source**: {journal/working paper/blog} -**URL**: {link} -**Relevance**: {HIGH/MEDIUM/LOW} - -## Key Claims -1. {Main finding relevant to our research} -2. {Secondary finding} - -## Methodology -- {Data period and universe} -- {Approach} -- {Key assumptions} - -## Relevance to Our Work -- {How it supports/challenges our approach} -- {What we can adapt} -- {What doesn't apply (different market, period, etc.)} - -## Actionable Ideas -- [ ] {Specific thing to test based on this paper} -- [ ] {Parameter to consider} - -## Related Hypotheses -- H{nn}-{slug}: {how it connects} -``` - -### METHODOLOGY.md (Formal Methodology Document) - -```markdown -# {Study Title} — Methodology - -**Version**: 1.0 -**Date**: YYYY-MM-DD -**Authors**: {names} -**Status**: UNDER REVIEW / PUBLISHED - -## 1. Objective -{What decision this methodology supports. One paragraph.} - -## 2. Scope -- Asset classes: {list} -- Instruments: {types} -- Geography: {markets} -- Time horizon: {period} - -## 3. Data Sources -| Source | Coverage | Frequency | Validation | -|--------|----------|-----------|------------| -| {name} | {period} | {freq} | {how validated} | - -## 4. Methodology - -### 4.1 {Step Name} -{Description with enough detail to reproduce. -Include formulas where relevant.} - -### 4.2 {Step Name} -... - -## 5. Assumptions & Limitations -1. {Assumption}: {justification} -2. {Limitation}: {impact} - -## 6. Results Summary -{Key findings with references to Finding documents.} - -| Finding | Reference | Confidence | -|---------|-----------|------------| -| {title} | F01-{slug}.md | HIGH | - -## 7. Sensitivity Analysis -{How results change under different assumptions.} - -## 8. Conclusions & Recommendations -{Actionable output: parameters, allocations, constraints.} - -## 9. Review History -| Date | Reviewer | Action | -|------|----------|--------| -| YYYY-MM-DD | {name} | Initial draft | -| YYYY-MM-DD | {name} | Approved | - -## Appendices -- A: Detailed tables -- B: Reproducibility instructions -- C: Regulatory mapping (MiFID II suitability requirements) -``` - -## Complementary Skills - -| Skill | Role | -|-------|------| -| 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-formal/references/templates.md b/claude/skills/quant/investment-research-formal/references/templates.md deleted file mode 100644 index 41e334fb..00000000 --- a/claude/skills/quant/investment-research-formal/references/templates.md +++ /dev/null @@ -1,277 +0,0 @@ -# Formal Research Templates - -Templates for structured, auditable investment research documents. - -## Hypothesis (H01-{slug}.md) - -```markdown -# H01: {Testable Statement} - -**Status**: TESTING -**Date**: YYYY-MM-DD -**Author**: {name} -**Study**: {study-name} - -## Statement - -{Clear, falsifiable claim. One sentence.} - -Example: "Adding a 10% gold allocation to bond-heavy profiles (P1-P3) -reduces max drawdown by >2pp without reducing annualized return by >0.5pp." - -## Rationale - -Why we believe this might be true: -- {Theoretical basis or market intuition} -- {Supporting literature: see literature/author-year-slug.md} -- {Empirical observation from prior work} - -## Success Criteria - -Quantitative thresholds that determine validated vs rejected: -- [ ] Max DD reduction > 2pp for P1, P2, P3 -- [ ] Ann. return reduction < 0.5pp -- [ ] Improvement consistent across full-period AND recent-period - -## Test Plan - -| # | Experiment | What It Tests | -|---|-----------|---------------| -| 1 | E01-{name} | {description} | -| 2 | E02-{name} | {description} | - -## Results - -| Experiment | Outcome | Key Metric | -|-----------|---------|------------| -| E01 | {PASS/FAIL} | {value} | - -## Conclusion - -**Status**: {VALIDATED / REJECTED / INCONCLUSIVE} - -{One paragraph summarizing the verdict with key numbers.} - -**If validated** → Finding: F{nn}-{slug}.md -**If rejected** → {Why, and what we learned} -**If inconclusive** → {What additional evidence is needed} -``` - -## Experiment (E01-{slug}.md) - -```markdown -# E01: {Experiment Name} - -**Status**: RUNNING -**Date**: YYYY-MM-DD -**Hypothesis**: H01-{slug}.md - -## Objective - -{What specific question does this experiment answer?} - -## Setup - -### Data -- Period: {start} to {end} ({N} months) -- Assets: {list} -- Source: {data source and validation status} -- Frequency: {monthly/daily} - -### Parameters -| Parameter | Value | Rationale | -|-----------|-------|-----------| -| Rebalancing | Quarterly | {why} | -| Cost assumption | 0 bps | {why} | -| Weight step | 5% | {why} | -| Benchmark | {what} | {why} | - -### Methodology -1. {Step 1} -2. {Step 2} -3. {Step 3} - -### Reproducibility -```bash -uv run python scripts/{script}.py --config {config} -``` -Output: `output/{run-dir}/` - -## Results - -### Primary Metrics -| Profile | Metric Before | Metric After | Delta | -|---------|--------------|-------------|-------| -| P1 | | | | -| P2 | | | | - -### Key Observations -- {Observation 1} -- {Observation 2} - -### Artifacts -- Data: `data/processed/{file}` -- Charts: `output/{run}/` -- Dashboard: `output/{run}/dashboard.html` - -## Conclusion - -{Does this support or refute H01? With what confidence?} - -## Limitations -- {Limitation 1: e.g., no transaction costs} -- {Limitation 2: e.g., USD-only, no FX for PLN portfolios} -``` - -## Finding (F01-{slug}.md) - -```markdown -# F01: {Finding Title} - -**Status**: DRAFT -**Date**: YYYY-MM-DD -**Confidence**: HIGH / MEDIUM / LOW - -## Summary - -{One paragraph: what we found, with key numbers.} - -## Evidence Chain - -| Source | Reference | Key Result | -|--------|-----------|------------| -| Hypothesis | H01-{slug}.md | {original claim} | -| Experiment | E01-{slug}.md | {supporting result} | -| Experiment | E02-{slug}.md | {confirming result} | - -## Quantitative Evidence - -| Metric | Before | After | Significance | -|--------|--------|-------|-------------| -| Max DD (P1) | -12.3% | -10.2% | 2.1pp improvement | -| Ann. Return (P1) | 5.9% | 5.7% | 0.2pp cost | - -## Implications - -### For Production -- {What parameter changes should be made} -- {Which config files need updating} - -### For Clients -- {How this affects risk profile communication} -- {Suitability documentation impact} - -### For Future Research -- {What new questions this raises} - -## Limitations & Caveats - -- {When this finding might not hold} -- {Data limitations} -- {Assumptions that could be violated} - -## Regulatory Notes - -{If applicable: MiFID II suitability relevance, documentation requirements, -how this finding supports the "acting in client's best interest" obligation.} - -## Application - -**Applied**: YES / NO / PARTIAL -**Applied to**: {config file, dashboard, app parameter} -**Applied date**: YYYY-MM-DD -**Applied by**: {name} -``` - -## Literature Note ({author-year}-{slug}.md) - -```markdown -# {Author} ({Year}) — {Short Title} - -**Source**: {journal/working paper/blog} -**URL**: {link} -**Relevance**: {HIGH/MEDIUM/LOW} - -## Key Claims -1. {Main finding relevant to our research} -2. {Secondary finding} - -## Methodology -- {Data period and universe} -- {Approach} -- {Key assumptions} - -## Relevance to Our Work -- {How it supports/challenges our approach} -- {What we can adapt} -- {What doesn't apply (different market, period, etc.)} - -## Actionable Ideas -- [ ] {Specific thing to test based on this paper} -- [ ] {Parameter to consider} - -## Related Hypotheses -- H{nn}-{slug}: {how it connects} -``` - -## METHODOLOGY.md (Formal Methodology Document) - -```markdown -# {Study Title} — Methodology - -**Version**: 1.0 -**Date**: YYYY-MM-DD -**Authors**: {names} -**Status**: UNDER REVIEW / PUBLISHED - -## 1. Objective -{What decision this methodology supports. One paragraph.} - -## 2. Scope -- Asset classes: {list} -- Instruments: {types} -- Geography: {markets} -- Time horizon: {period} - -## 3. Data Sources -| Source | Coverage | Frequency | Validation | -|--------|----------|-----------|------------| -| {name} | {period} | {freq} | {how validated} | - -## 4. Methodology - -### 4.1 {Step Name} -{Description with enough detail to reproduce. -Include formulas where relevant.} - -### 4.2 {Step Name} -... - -## 5. Assumptions & Limitations -1. {Assumption}: {justification} -2. {Limitation}: {impact} - -## 6. Results Summary -{Key findings with references to Finding documents.} - -| Finding | Reference | Confidence | -|---------|-----------|------------| -| {title} | F01-{slug}.md | HIGH | - -## 7. Sensitivity Analysis -{How results change under different assumptions.} - -## 8. Conclusions & Recommendations -{Actionable output: parameters, allocations, constraints.} - -## 9. Review History -| Date | Reviewer | Action | -|------|----------|--------| -| YYYY-MM-DD | {name} | Initial draft | -| YYYY-MM-DD | {name} | Approved | - -## Appendices -- A: Detailed tables -- B: Reproducibility instructions -- C: Regulatory mapping (MiFID II suitability requirements) -``` diff --git a/docs/playbooks/investment-research-workflow.md b/docs/playbooks/investment-research-workflow.md index 4f2d1c9d..75d3aa09 100644 --- a/docs/playbooks/investment-research-workflow.md +++ b/docs/playbooks/investment-research-workflow.md @@ -16,9 +16,9 @@ Starting a new investment research question — factor analysis, fund comparison | Skill | Role | |-------|------| | 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 | +| qute-research `skills/research/references/methodology-document.md` | The methodology document for an external audience (MiFID II mapping, literature notes), built from the line's own evidence chain | | `paper-reading` | Extract insights from papers, fund cards, prospectuses | -| `investment-research-dashboard` | Self-contained Plotly.js HTML dashboards | +| qute-research `/research-dashboard` | Self-contained Plotly.js HTML dashboards (`/finding-report` for one finding) | | `market-datasets` | Multi-source data fetching | | `gist-report` | Shareable HTML report via gist | @@ -53,9 +53,9 @@ For exploratory work: - Save intermediate results to files, not conversation For formal research (publishable, auditable): -- Use `/investment-research-formal` to track hypotheses, experiments, findings -- Each experiment gets a documented result -- Findings link back to specific experiments +- Pre-register the claim, then record each result with `/finding` (qute-research) +- Write the methodology document from that chain — qute-research's + `skills/research/references/methodology-document.md` ### Phase 4: Deliver @@ -63,7 +63,7 @@ Choose deliverable format based on audience: **Interactive dashboard** (self-serve exploration): ``` -/investment-research-dashboard +/research-dashboard ``` Produces a self-contained HTML file with Plotly.js charts — no server needed. @@ -91,7 +91,7 @@ Promote from `scratch/` to `research/{study-name}/` with co-located scripts, dat 3. Fetch fund NAVs from analizy.pl for equity funds 4. /paper-reading on Jegadeesh & Titman (1993), local momentum studies 5. Build factor portfolios in scratch/momentum-pl/ -6. /investment-research-dashboard for interactive factor analytics +6. /research-dashboard (qute-research) for interactive factor analytics 7. /gist-report for stakeholder summary 8. Promote to research/momentum-pl/ if foundational ``` @@ -99,6 +99,6 @@ Promote from `scratch/` to `research/{study-name}/` with co-located scripts, dat ## Tips - 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 +- Write the methodology document (qute-research `methodology-document.md`) 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