- 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>
259 lines
8.8 KiB
Plaintext
259 lines
8.8 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# 04 - Live PnL Analysis\n",
|
|
"\n",
|
|
"NAV curve and drawdown from the event log. Uses\n",
|
|
"`guardrail_lab.metrics.nav_series` for the NAV curve and\n",
|
|
"`guardrail_lab.drawdown` for the underwater series and worst\n",
|
|
"drawdown episodes. Charts are rendered as text sparklines so the\n",
|
|
"notebook runs with the base stack (no matplotlib required).\n",
|
|
"\n",
|
|
"**Offline-safe:** an empty NAV history 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": [
|
|
"## NAV curve\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from guardrail_lab.db import load_events\n",
|
|
"from guardrail_lab.metrics import nav_series, max_drawdown, trade_count\n",
|
|
"\n",
|
|
"events = load_events(str(DB_PATH)) if DB_PATH else []\n",
|
|
"curve = nav_series(events)\n",
|
|
"\n",
|
|
"if not curve:\n",
|
|
" print(NO_DATA_HINT)\n",
|
|
"else:\n",
|
|
" navs = [nav for _, nav in curve]\n",
|
|
" start, end = navs[0], navs[-1]\n",
|
|
" ret_pct = (end - start) / start * 100.0 if start else 0.0\n",
|
|
" print(f\"NAV points : {len(curve)}\")\n",
|
|
" print(f\"Starting NAV : {start:,.2f}\")\n",
|
|
" print(f\"Latest NAV : {end:,.2f}\")\n",
|
|
" print(f\"Total return : {ret_pct:+.3f}%\")\n",
|
|
" print(f\"Peak NAV : {max(navs):,.2f}\")\n",
|
|
" print(f\"Trough NAV : {min(navs):,.2f}\")\n",
|
|
" print(f\"Max drawdown : {max_drawdown(navs) * 100.0:.3f}%\")\n",
|
|
" print(f\"Confirmed trades: {trade_count(events)}\")\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## NAV sparkline (text)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def sparkline(values):\n",
|
|
" \"\"\"ASCII sparkline using block characters; safe for any terminal.\"\"\"\n",
|
|
" if not values:\n",
|
|
" return \"(empty)\"\n",
|
|
" blocks = \"▁▂▃▄▅▆▇█\"\n",
|
|
" lo, hi = min(values), max(values)\n",
|
|
" span = (hi - lo) or 1.0\n",
|
|
" return \"\".join(blocks[min(7, int((v - lo) / span * 7))] for v in values)\n",
|
|
"\n",
|
|
"if curve:\n",
|
|
" navs = [nav for _, nav in curve]\n",
|
|
" print(\"NAV:\", sparkline(navs))\n",
|
|
" render_table(\n",
|
|
" [\n",
|
|
" {\"timestamp\": ts, \"nav_usd\": f\"{nav:,.2f}\"}\n",
|
|
" for ts, nav in curve\n",
|
|
" ],\n",
|
|
" [(\"timestamp\", \"TIMESTAMP\"), (\"nav_usd\", \"NAV_USD\")],\n",
|
|
" title=\"NAV series\",\n",
|
|
" )\n",
|
|
"else:\n",
|
|
" print(NO_DATA_HINT)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Drawdown analysis\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from guardrail_lab.drawdown import analyze_drawdown_from_events\n",
|
|
"\n",
|
|
"if events and curve:\n",
|
|
" report = analyze_drawdown_from_events(events, top_n=5)\n",
|
|
" print(f\"Max drawdown : {report.max_drawdown_pct:.4f}%\")\n",
|
|
" print(f\"Peak : {report.peak_timestamp or 'n/a'}\")\n",
|
|
" print(f\"Trough : {report.trough_timestamp or 'n/a'}\")\n",
|
|
" dd_secs = report.max_drawdown_seconds\n",
|
|
" rec_secs = report.max_recovery_seconds\n",
|
|
" print(f\"Drawdown dur. : {dd_secs if dd_secs is not None else 'n/a'} s\")\n",
|
|
" print(f\"Recovery dur. : {rec_secs if rec_secs is not None else 'n/a (unrecovered)'} s\\n\")\n",
|
|
"\n",
|
|
" underwater = [p.drawdown_pct for p in report.points]\n",
|
|
" print(\"Underwater:\", sparkline([-x for x in underwater]) if underwater else \"(empty)\")\n",
|
|
" print()\n",
|
|
"\n",
|
|
" if report.episodes:\n",
|
|
" render_table(\n",
|
|
" [\n",
|
|
" {\n",
|
|
" \"depth_pct\": f\"{ep.depth_pct:.4f}%\",\n",
|
|
" \"peak\": ep.peak_timestamp,\n",
|
|
" \"trough\": ep.trough_timestamp,\n",
|
|
" \"recovered\": ep.recovered,\n",
|
|
" }\n",
|
|
" for ep in report.episodes\n",
|
|
" ],\n",
|
|
" [\n",
|
|
" (\"depth_pct\", \"DEPTH\"),\n",
|
|
" (\"peak\", \"PEAK_TS\"),\n",
|
|
" (\"trough\", \"TROUGH_TS\"),\n",
|
|
" (\"recovered\", \"RECOVERED\"),\n",
|
|
" ],\n",
|
|
" title=\"Worst drawdown episodes\",\n",
|
|
" )\n",
|
|
" else:\n",
|
|
" print(\"No drawdown episodes (NAV never declined below a prior peak).\")\n",
|
|
"else:\n",
|
|
" print(NO_DATA_HINT)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Notes\n",
|
|
"\n",
|
|
"* NAV is taken from `portfolio_reconciled` events; each one carries\n",
|
|
" a high-precision `nav_usd`.\n",
|
|
"* The underwater sparkline is inverted (taller = deeper drawdown).\n"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"name": "python",
|
|
"version": "3.11"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|