guardrail/python-lab/notebooks/05_trade_attribution.ipynb
caelum0x 41138e2780 feat(phase2): notebooks, all-docs end-to-end, native strategy-ensemble crate
- 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>
2026-06-15 12:23:09 +03:00

234 lines
7.5 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 05 - Trade Attribution\n",
"\n",
"Per-asset attribution of confirmed swaps using\n",
"`guardrail_lab.attribution`. Each `tx_confirmed` is correlated with\n",
"its preceding `order_proposed` (destination symbol) and risk\n",
"decision (final executed amount).\n",
"\n",
"**Offline-safe:** an empty log prints a hint.\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": [
"## Per-asset attribution\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from guardrail_lab.db import load_events\n",
"from guardrail_lab.attribution import trade_attribution, regime_timeline\n",
"\n",
"events = load_events(str(DB_PATH)) if DB_PATH else []\n",
"attribution = trade_attribution(events)\n",
"\n",
"if not attribution:\n",
" print(NO_DATA_HINT)\n",
"else:\n",
" total_usd = sum(a[\"total_amount_usd\"] for a in attribution)\n",
" total_trades = sum(a[\"count\"] for a in attribution)\n",
" print(f\"Confirmed swaps: {total_trades} | Total notional: {total_usd:,.2f} USD\\n\")\n",
" render_table(\n",
" [\n",
" {\n",
" \"symbol\": a[\"symbol\"],\n",
" \"trades\": a[\"count\"],\n",
" \"notional_usd\": f\"{a['total_amount_usd']:,.2f}\",\n",
" \"share\": f\"{(a['total_amount_usd'] / total_usd * 100.0):.1f}%\" if total_usd else \"n/a\",\n",
" }\n",
" for a in attribution\n",
" ],\n",
" [\n",
" (\"symbol\", \"SYMBOL\"),\n",
" (\"trades\", \"TRADES\"),\n",
" (\"notional_usd\", \"NOTIONAL_USD\"),\n",
" (\"share\", \"SHARE\"),\n",
" ],\n",
" title=\"Per-asset trade attribution\",\n",
" )\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Notional sparkline by asset\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def bar(value, max_value, width=30):\n",
" if not max_value:\n",
" return \"\"\n",
" filled = int(round(value / max_value * width))\n",
" return \"█\" * filled + \"·\" * (width - filled)\n",
"\n",
"if attribution:\n",
" max_usd = max(a[\"total_amount_usd\"] for a in attribution)\n",
" for a in attribution:\n",
" print(f\"{a['symbol']:>6} {bar(a['total_amount_usd'], max_usd)} \"\n",
" f\"{a['total_amount_usd']:,.2f}\")\n",
"else:\n",
" print(NO_DATA_HINT)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Regime timeline (context)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if events:\n",
" timeline = regime_timeline(events)\n",
" if timeline:\n",
" render_table(\n",
" timeline,\n",
" [(\"timestamp\", \"TIMESTAMP\"), (\"regime\", \"REGIME\")],\n",
" title=\"Regime classifications over time\",\n",
" )\n",
" else:\n",
" print(\"No regime_classified events in the log yet.\")\n",
"else:\n",
" print(NO_DATA_HINT)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Notes\n",
"\n",
"* Notional uses the risk-adjusted amount when a `risk_approved` /\n",
" `risk_clipped` decision is present, otherwise the proposed order\n",
" amount.\n",
"* Unknown destinations are bucketed under `UNKNOWN` rather than\n",
" dropped.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}