- python-lab/notebooks: 6 runnable offline-safe notebooks (closes the last plan.md gap). - docs: OpenAPI now covers all 56 routes (+/journal /ensemble /skills /version); new CLI.md + API.md; refreshed WHATS_NEW/PRIZE_MAP/FEATURE_MATRIX/PRODUCT_OVERVIEW/INDEX. - crates/strategy-ensemble: native Rust ensemble meta-allocator (blend by regime, 9 tests, clippy-clean), registered in workspace. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
300 lines
9.9 KiB
Plaintext
300 lines
9.9 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# 02 - Signal Research\n",
|
|
"\n",
|
|
"Regime classifications and per-asset scores over the event log.\n",
|
|
"Uses `guardrail_lab.regime_analysis` for the transition matrix,\n",
|
|
"time-in-regime, and per-regime exposure, plus the raw\n",
|
|
"`asset_scored` events for the signal table.\n",
|
|
"\n",
|
|
"**Offline-safe:** an empty event log prints a hint instead of\n",
|
|
"raising.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# --- Guardrail Alpha notebook bootstrap (offline-safe) ---\n",
|
|
"import sys\n",
|
|
"from pathlib import Path\n",
|
|
"\n",
|
|
"\n",
|
|
"def _find_repo_root(start: Path) -> Path:\n",
|
|
" \"\"\"Return the first ancestor that contains python-lab/guardrail_lab.\"\"\"\n",
|
|
" for candidate in [start, *start.parents]:\n",
|
|
" if (candidate / \"python-lab\" / \"guardrail_lab\").is_dir():\n",
|
|
" return candidate\n",
|
|
" return start\n",
|
|
"\n",
|
|
"\n",
|
|
"# In a notebook __file__ is undefined, so anchor on the current working dir.\n",
|
|
"REPO_ROOT = _find_repo_root(Path.cwd())\n",
|
|
"LAB_PATH = REPO_ROOT / \"python-lab\"\n",
|
|
"if str(LAB_PATH) not in sys.path:\n",
|
|
" sys.path.insert(0, str(LAB_PATH))\n",
|
|
"\n",
|
|
"\n",
|
|
"def _first_existing(*candidates: Path):\n",
|
|
" \"\"\"Return the first path that exists, else None.\"\"\"\n",
|
|
" for path in candidates:\n",
|
|
" if path.exists():\n",
|
|
" return path\n",
|
|
" return None\n",
|
|
"\n",
|
|
"\n",
|
|
"DATA_DIR = REPO_ROOT / \"data\"\n",
|
|
"CONFIG_DIR = REPO_ROOT / \"configs\"\n",
|
|
"\n",
|
|
"# Prefer a real run; fall back to the seeded demo artifacts if present.\n",
|
|
"DB_PATH = _first_existing(\n",
|
|
" DATA_DIR / \"guardrail_alpha.db\",\n",
|
|
" DATA_DIR / \"demo_guardrail_alpha.db\",\n",
|
|
")\n",
|
|
"RUN_REPORT_PATH = _first_existing(\n",
|
|
" DATA_DIR / \"run_report.json\",\n",
|
|
" DATA_DIR / \"demo_run_report.json\",\n",
|
|
")\n",
|
|
"EXPERIMENTS_DIR = DATA_DIR / \"experiments\"\n",
|
|
"BACKTESTS_DIR = DATA_DIR / \"backtests\"\n",
|
|
"ELIGIBLE_ASSETS_PATH = CONFIG_DIR / \"eligible_assets.bsc.json\"\n",
|
|
"ASSET_CATEGORIES_PATH = CONFIG_DIR / \"asset_categories.json\"\n",
|
|
"\n",
|
|
"NO_DATA_HINT = (\n",
|
|
" \"No data found under data/. Run the agent (paper/live) or seed a demo run \"\n",
|
|
" \"first, e.g. python3 -m guardrail_lab.seed (from python-lab/), then \"\n",
|
|
" \"re-run this notebook. The notebook is offline-safe and will not raise.\"\n",
|
|
")\n",
|
|
"\n",
|
|
"print(\"repo root :\", REPO_ROOT)\n",
|
|
"print(\"event log :\", DB_PATH if DB_PATH else \"(none yet)\")\n",
|
|
"print(\"run report:\", RUN_REPORT_PATH if RUN_REPORT_PATH else \"(none yet)\")\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def render_table(rows, columns, title=None):\n",
|
|
" \"\"\"Print an aligned text table. rows: list[dict]; columns: list[(key,label)].\"\"\"\n",
|
|
" if title:\n",
|
|
" print(title)\n",
|
|
" print(\"=\" * len(title))\n",
|
|
" if not rows:\n",
|
|
" print(\"(no rows)\")\n",
|
|
" return\n",
|
|
" labels = [label for _, label in columns]\n",
|
|
" keys = [key for key, _ in columns]\n",
|
|
" cells = [[(\"\" if r.get(k) is None else str(r.get(k))) for k in keys] for r in rows]\n",
|
|
" widths = [\n",
|
|
" max(len(labels[i]), *(len(row[i]) for row in cells)) for i in range(len(keys))\n",
|
|
" ]\n",
|
|
" header = \" \".join(labels[i].ljust(widths[i]) for i in range(len(keys)))\n",
|
|
" print(header)\n",
|
|
" print(\" \".join(\"-\" * widths[i] for i in range(len(keys))))\n",
|
|
" for row in cells:\n",
|
|
" print(\" \".join(row[i].ljust(widths[i]) for i in range(len(keys))))\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Load events\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from guardrail_lab.db import load_events, event_counts\n",
|
|
"\n",
|
|
"events = load_events(str(DB_PATH)) if DB_PATH else []\n",
|
|
"if not events:\n",
|
|
" print(NO_DATA_HINT)\n",
|
|
"else:\n",
|
|
" print(f\"Loaded {len(events)} events.\")\n",
|
|
" counts = event_counts(events)\n",
|
|
" render_table(\n",
|
|
" [{\"event_type\": k, \"count\": v} for k, v in counts.items()],\n",
|
|
" [(\"event_type\", \"EVENT_TYPE\"), (\"count\", \"COUNT\")],\n",
|
|
" title=\"Event-type counts\",\n",
|
|
" )\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Regime analytics\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from guardrail_lab.regime_analysis import analyze_regimes\n",
|
|
"\n",
|
|
"if events:\n",
|
|
" analysis = analyze_regimes(events)\n",
|
|
"\n",
|
|
" print(f\"Regimes observed: {analysis.transitions.regimes or '(none)'}\")\n",
|
|
" print(f\"Total transitions: {analysis.transitions.total_transitions}\\n\")\n",
|
|
"\n",
|
|
" render_table(\n",
|
|
" [\n",
|
|
" {\n",
|
|
" \"regime\": t.regime,\n",
|
|
" \"classifications\": t.classifications,\n",
|
|
" \"fraction\": f\"{t.fraction:.2%}\",\n",
|
|
" \"seconds\": f\"{t.seconds:.1f}\",\n",
|
|
" }\n",
|
|
" for t in analysis.time_in_regime\n",
|
|
" ],\n",
|
|
" [\n",
|
|
" (\"regime\", \"REGIME\"),\n",
|
|
" (\"classifications\", \"COUNT\"),\n",
|
|
" (\"fraction\", \"SHARE\"),\n",
|
|
" (\"seconds\", \"SECONDS\"),\n",
|
|
" ],\n",
|
|
" title=\"Time in regime\",\n",
|
|
" )\n",
|
|
" print()\n",
|
|
" render_table(\n",
|
|
" [\n",
|
|
" {\n",
|
|
" \"regime\": e.regime,\n",
|
|
" \"orders\": e.order_count,\n",
|
|
" \"avg_order_usd\": f\"{e.avg_order_usd:,.2f}\",\n",
|
|
" \"exposure_x\": f\"{e.exposure_multiplier:.3f}\",\n",
|
|
" }\n",
|
|
" for e in analysis.exposure\n",
|
|
" ],\n",
|
|
" [\n",
|
|
" (\"regime\", \"REGIME\"),\n",
|
|
" (\"orders\", \"ORDERS\"),\n",
|
|
" (\"avg_order_usd\", \"AVG_ORDER_USD\"),\n",
|
|
" (\"exposure_x\", \"EXPOSURE_x\"),\n",
|
|
" ],\n",
|
|
" title=\"Exposure multiplier by regime\",\n",
|
|
" )\n",
|
|
"else:\n",
|
|
" print(NO_DATA_HINT)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Asset scores\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# asset_scored events: {\"symbol\": ..., \"score\": ...}\n",
|
|
"def _to_float(value):\n",
|
|
" try:\n",
|
|
" return float(value)\n",
|
|
" except (TypeError, ValueError):\n",
|
|
" return None\n",
|
|
"\n",
|
|
"if events:\n",
|
|
" score_rows = []\n",
|
|
" for ev in events:\n",
|
|
" if ev.get(\"event_type\") != \"asset_scored\":\n",
|
|
" continue\n",
|
|
" payload = ev.get(\"payload\") or {}\n",
|
|
" score_rows.append(\n",
|
|
" {\n",
|
|
" \"timestamp\": ev.get(\"timestamp\", \"\"),\n",
|
|
" \"symbol\": payload.get(\"symbol\", \"?\"),\n",
|
|
" \"score\": _to_float(payload.get(\"score\")),\n",
|
|
" }\n",
|
|
" )\n",
|
|
"\n",
|
|
" # Aggregate: mean score + count per symbol, ranked.\n",
|
|
" agg = {}\n",
|
|
" for r in score_rows:\n",
|
|
" sym = r[\"symbol\"]\n",
|
|
" slot = agg.setdefault(sym, {\"symbol\": sym, \"n\": 0, \"sum\": 0.0, \"last\": None})\n",
|
|
" slot[\"n\"] += 1\n",
|
|
" if r[\"score\"] is not None:\n",
|
|
" slot[\"sum\"] += r[\"score\"]\n",
|
|
" slot[\"last\"] = r[\"score\"]\n",
|
|
"\n",
|
|
" ranked = sorted(\n",
|
|
" (\n",
|
|
" {\n",
|
|
" \"symbol\": s[\"symbol\"],\n",
|
|
" \"times_scored\": s[\"n\"],\n",
|
|
" \"mean_score\": f\"{(s['sum'] / s['n']):.3f}\" if s[\"n\"] else \"n/a\",\n",
|
|
" \"last_score\": f\"{s['last']:.3f}\" if s[\"last\"] is not None else \"n/a\",\n",
|
|
" }\n",
|
|
" for s in agg.values()\n",
|
|
" ),\n",
|
|
" key=lambda x: x[\"mean_score\"],\n",
|
|
" reverse=True,\n",
|
|
" )\n",
|
|
"\n",
|
|
" if ranked:\n",
|
|
" render_table(\n",
|
|
" ranked,\n",
|
|
" [\n",
|
|
" (\"symbol\", \"SYMBOL\"),\n",
|
|
" (\"times_scored\", \"TIMES_SCORED\"),\n",
|
|
" (\"mean_score\", \"MEAN_SCORE\"),\n",
|
|
" (\"last_score\", \"LAST_SCORE\"),\n",
|
|
" ],\n",
|
|
" title=\"Asset scores (ranked by mean score)\",\n",
|
|
" )\n",
|
|
" else:\n",
|
|
" print(\"No asset_scored events in the log yet.\")\n",
|
|
"else:\n",
|
|
" print(NO_DATA_HINT)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Notes\n",
|
|
"\n",
|
|
"* The exposure multiplier (`EXPOSURE_x`) shows how much larger or\n",
|
|
" smaller proposed orders were during each regime versus the\n",
|
|
" overall mean order size (1.0 = baseline).\n",
|
|
"* Higher mean scores indicate assets the signal stack favoured most\n",
|
|
" consistently across cycles.\n"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"name": "python",
|
|
"version": "3.11"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|