Recall-guard / cmmd flow notebook¶
Interactive driver for the recall-guard pipeline. It imports the same recall_guard.portfolio.* and recall_guard.harness.* modules the CLIs use, walks through the pipeline cell by cell so you can stop and inspect intermediate state, and exposes a handful of functions to Excel via PyXLL when the kernel is running inside the PyXLL add-in.
Outside PyXLL (plain JupyterLab, VS Code, headless nbconvert), the @xl_func decorator is a no-op. Every cell still executes; you just do not get the Excel surface.
Three workflows live in this notebook:
- End-to-end run, equivalent to
scripts/run_cmmd_backtest.py, but cell by cell so you can inspect intermediate state. - Post-run analysis against an existing run dir, to re-render Cohen's d / pre-vs-post-cutoff gap / backtest tables without re-calling the LM.
- Excel surface via
@xl_funcwrappers near the bottom; intended to be imported bypyxll.cfgso Excel can call the same functions.
Setup¶
Resolve the repo root, load .env, and pick up pyxll if it is available.
from __future__ import annotations
import os
import sys
from pathlib import Path
ROOT = Path.cwd()
while not (ROOT / "pyproject.toml").exists() and ROOT != ROOT.parent:
ROOT = ROOT.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from dotenv import load_dotenv
load_dotenv(ROOT / ".env")
try:
from pyxll import xl_func # type: ignore[import-not-found]
PYXLL = True
except ImportError:
def xl_func(signature=None): # type: ignore[misc]
if callable(signature):
return signature
def deco(fn):
return fn
return deco
PYXLL = False
print(f"ROOT = {ROOT}")
print(f"PyXLL active: {PYXLL}")
Imports¶
The notebook talks to the same modules the CLIs talk to. No private API, no shim layer.
import hashlib
import json
import subprocess
import types
from datetime import date, datetime, timezone
import pandas as pd
from recall_guard.core.manifest import read_manifest, write_manifest
from recall_guard.harness.runner import parse_argv, run as harness_run
from recall_guard.portfolio.backtest import (
BacktestArtifactError,
run_backtest,
write_backtest_artifacts,
)
from recall_guard.portfolio.cmmd import apply_cmmd_filter
from recall_guard.portfolio.cohens_d import compute_cohens_d
from recall_guard.portfolio.prices import PriceFetchError, fetch_universe_prices
def _hash_prompt(prompt: str) -> str:
"""Match the harness's prompt_hash convention (sha256 hex, first 16 chars)."""
return hashlib.sha256(prompt.encode("utf-8")).hexdigest()[:16]
Workflow 1: end-to-end¶
Cell-by-cell version of scripts/run_cmmd_backtest.py. Run from the top to reproduce a fresh CMMD backtest. Stop at any cell to poke at the intermediate state.
Step 1 — eval set¶
10-year SWDA.L / XLK / IAU prompt set. The builder is deterministic for a fixed seed.
EVAL_PATH = ROOT / "data" / "eval" / "etf_portfolio.jsonl"
if not EVAL_PATH.exists():
sys.path.insert(0, str(ROOT / "scripts"))
import build_etf_portfolio_eval as builder
builder.main()
with EVAL_PATH.open() as f:
eval_rows = [json.loads(line) for line in f if line.strip()]
df_eval = pd.DataFrame([
{
"ticker": r["metadata"]["ticker"],
"date": r["metadata"]["date"],
"target_direction": r["target_direction"],
}
for r in eval_rows
])
df_eval["year"] = df_eval["date"].str[:4]
print(f"Total rows: {len(df_eval)}")
df_eval.groupby(["ticker", "year"]).size().unstack(fill_value=0)
Step 2 — pick or create a run directory¶
Set RUN_DIR to an existing run dir to skip the harness call (it takes ~3 minutes); leave it None to run a fresh harness pass on gpt-oss-20b.
RUN_DIR: Path | None = ROOT / "runs" / "cmmd_20260429T070616Z" # set to None to call the harness fresh
if RUN_DIR is None or not RUN_DIR.exists():
RUN_DIR = ROOT / "runs" / f"flow_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}"
RUN_DIR.mkdir(parents=True, exist_ok=True)
args = parse_argv([
"--eval-set", str(EVAL_PATH),
"--shortlist", "openai/gpt-oss-20b",
"--cutoffs", str(ROOT / "data" / "cutoffs.yaml"),
"--is-memorized", str(ROOT / "data" / "calibration" / "is_memorized.jsonl"),
"--oos-control", str(ROOT / "data" / "calibration" / "oos_control.jsonl"),
"--out-dir", str(RUN_DIR),
"--no-reference",
])
rc = harness_run(args)
assert rc == 0, f"harness exit {rc}"
print(f"RUN_DIR = {RUN_DIR}")
print("contents:", sorted(p.name for p in RUN_DIR.iterdir()))
Step 3 — Cohen's d per (model, MIA feature)¶
Reads records.jsonl, joins back to the eval set on prompt_hash, splits IS / OOS by the model's training cutoff, computes Cohen's d on the raw MIA values.
df_cohens = compute_cohens_d(
RUN_DIR,
EVAL_PATH,
cutoffs_path=ROOT / "data" / "cutoffs.yaml",
)
df_cohens
Step 4 — IS-vs-OOS accuracy gap¶
scripts/analyze_is_oos_gap.py writes is_oos_gap.csv in the run dir; we read it back here.
gap_path = RUN_DIR / "is_oos_gap.csv"
if not gap_path.exists():
subprocess.run(
[sys.executable, str(ROOT / "scripts" / "analyze_is_oos_gap.py"),
str(RUN_DIR), str(EVAL_PATH), str(ROOT / "data" / "cutoffs.yaml")],
check=True,
)
df_gap = pd.read_csv(gap_path)
df_gap
Step 5 — universe prices¶
Inner-joined EOD prices for {SWDA.L, XLK, IAU, BIL} over the eval set's date span. Any day where one ticker is missing (e.g. LSE holiday vs NYSE) is dropped from all four columns.
eval_dates = sorted({r["metadata"]["date"] for r in eval_rows})
prices = fetch_universe_prices(
tickers=["SWDA.L", "XLK", "IAU", "BIL"],
start=date.fromisoformat(eval_dates[0]),
end=date.fromisoformat(eval_dates[-1]),
)
print(f"prices: shape={prices.shape}, range {prices.index[0].date()} → {prices.index[-1].date()}")
prices.head()
Step 6 — backtest¶
run_backtest runs raw_alpha and cmmd on the same price matrix. We feed it the records from the run dir plus a prompt_metadata map keyed by prompt_hash (the harness's Record schema does not carry metadata.date / metadata.ticker, so the orchestrator builds the map from the eval set).
prompt_metadata = {
_hash_prompt(r["prompt"]): r["metadata"]
for r in eval_rows
}
with (RUN_DIR / "records.jsonl").open() as f:
records = [
types.SimpleNamespace(**json.loads(line))
for line in f if line.strip()
]
result = run_backtest(records, prices, prompt_metadata, seed=0, bootstrap_n=1000)
print(f"raw Sharpe : {result.raw.sharpe_annualised}")
print(f"cmmd Sharpe : {result.cmmd.sharpe_annualised}")
print(f"rel improvement: {result.relative_sharpe_improvement * 100:+.2f}%")
print(f"warnings : {result.warnings}")
result.equity_curves.tail()
Step 7 — equity curves¶
Inline render of the equity curves. The PNG also lives in the run dir as equity_curves.png.
import matplotlib.pyplot as plt
ax = result.equity_curves.plot(figsize=(10, 5))
ax.set_ylabel("equity (normalised)")
ax.set_title("raw_alpha vs cmmd vs buy_and_hold_swda")
ax.grid(alpha=0.3)
ax.legend(loc="best")
plt.tight_layout()
plt.show()
Step 8 — write artifacts (optional)¶
scripts/run_cmmd_backtest.py already writes the artifacts when it runs end-to-end; this cell exists so you can call the writer manually after experimenting in earlier cells (e.g., a different cmmd_quantile).
WRITE_ARTIFACTS = False # flip to True to overwrite the artifact set in RUN_DIR
if WRITE_ARTIFACTS:
paths = write_backtest_artifacts(result, RUN_DIR)
for name, p in paths.items():
print(f" {name:25s} {p}")
Workflow 2: post-run analysis¶
Drop a finished run dir into the cell below to re-render its tables without recomputing anything. Useful after scripts/run_cmmd_backtest.py has finished and you just want to see the numbers in a notebook.
def summarise_run(run_dir: Path) -> None:
"""Print the headline tables from a finished run dir."""
print(f"== {run_dir.name} ==")
manifest = json.loads((run_dir / "manifest.json").read_text())
bt = manifest.get("backtest")
if bt:
print(f"signal_model={bt['signal_model']}, universe={bt['universe']}")
print(f"cmmd_quantile={bt['cmmd_quantile']}, threshold={bt['cmmd_threshold_value']:.4f}")
print(f"n_is={bt['n_is_rows']}, n_oos={bt['n_oos_rows']} (sum={bt['n_is_rows']+bt['n_oos_rows']})")
print()
for fname in ("backtest_summary.md", "is_oos_gap.md", "cohens_d.md"):
p = run_dir / fname
if p.exists():
print(p.read_text())
print("---")
summarise_run(RUN_DIR)
Workflow 3: Excel surface (PyXLL)¶
Thin @xl_func-decorated wrappers around the same functions used above. Outside PyXLL the decorator is a no-op so cells still execute. Inside PyXLL — i.e. when the notebook kernel is being driven by Excel via the add-in — these names become Excel UDFs once you point your pyxll.cfg at this notebook (or a tiny .py shim that imports from it).
Wiring guidance:
- PyXLL must be configured to use the same Python interpreter as the project. On Windows that is
.venv/Scripts/python.exeafteruv sync. - In
pyxll.cfg, pointmodulesatdocs/notebooks/flow.ipynb(PyXLL accepts notebook paths since v5) or at a.pyshim that doesfrom notebooks.flow import xl_compute_cohens_d, xl_fetch_prices, xl_run_backtest. - Reload via the PyXLL ribbon button in Excel after edits.
@xl_func("str eval_path, str run_dir, str cutoffs_path: dataframe<index=False>")
def xl_compute_cohens_d(eval_path: str, run_dir: str, cutoffs_path: str) -> pd.DataFrame:
"""Cohen's d table for a finished run dir.
Parameters
----------
eval_path:
Path to the eval-set JSONL (e.g. ``data/eval/etf_portfolio.jsonl``).
run_dir:
Path to a harness run directory containing ``records.jsonl`` and
``summary.csv``.
cutoffs_path:
Path to the per-model cutoff registry (``data/cutoffs.yaml``).
"""
return compute_cohens_d(
Path(run_dir),
Path(eval_path),
cutoffs_path=Path(cutoffs_path),
)
@xl_func("str ticker_list, date start, date end: dataframe<index=True>")
def xl_fetch_prices(ticker_list: str, start: date, end: date) -> pd.DataFrame:
"""EOD inner-joined price matrix. ``ticker_list`` is comma-separated."""
tickers = [t.strip() for t in ticker_list.split(",") if t.strip()]
return fetch_universe_prices(tickers, start, end)
@xl_func("str run_dir, str eval_path, float quantile: object")
def xl_run_backtest(run_dir: str, eval_path: str, quantile: float = 0.80) -> dict:
"""Run the cmmd-backtest end-to-end against an existing harness run dir.
Returns the headline metrics as a flat dict so Excel can spread
them across cells. Re-pulls the universe prices each call;
bypass that by calling the lower-level ``run_backtest`` directly
if you already have a price matrix in scope.
"""
run_dir_path = Path(run_dir)
eval_path_path = Path(eval_path)
eval_rows = [
json.loads(line)
for line in eval_path_path.read_text().splitlines()
if line.strip()
]
metadata = {_hash_prompt(r["prompt"]): r["metadata"] for r in eval_rows}
records = [
types.SimpleNamespace(**json.loads(line))
for line in (run_dir_path / "records.jsonl").read_text().splitlines()
if line.strip()
]
eval_dates = sorted({r["metadata"]["date"] for r in eval_rows})
px = fetch_universe_prices(
["SWDA.L", "XLK", "IAU", "BIL"],
date.fromisoformat(eval_dates[0]),
date.fromisoformat(eval_dates[-1]),
)
res = run_backtest(records, px, metadata, cmmd_quantile=quantile)
return {
"raw_sharpe_point": res.raw.sharpe_annualised[0],
"cmmd_sharpe_point": res.cmmd.sharpe_annualised[0],
"rel_sharpe_pct": res.relative_sharpe_improvement * 100,
"raw_total_return_pct": res.raw.total_return_pct,
"cmmd_total_return_pct": res.cmmd.total_return_pct,
"cmmd_threshold": res.cmmd.cmmd_threshold,
"warnings": ", ".join(res.warnings) or "",
}
print("Excel surface registered:")
for name in ("xl_compute_cohens_d", "xl_fetch_prices", "xl_run_backtest"):
print(f" {name}")
Notes for Windows¶
- vectorbt / numba / llvmlite wheels for Python 3.14 on Windows have not been validated against this project; if
uv syncfails, fall back to the pandas-only path the spec'sresearch.mddescribes. start.shis bash; usestart.ps1(PowerShell mirror) or invokeuv run python harness.py …directly from cmd / PowerShell..envshould use LF line endings; Git'score.autocrlf=trueon Windows can otherwise rewrite it on checkout andpython-dotenvwill treat the trailing\ras part of the value.