guardrail/python-lab/notebooks/03_backtest_review.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

252 lines
8.3 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 03 - Backtest Review\n",
"\n",
"Loads backtest / experiment records written by the Rust CLI into\n",
"`data/experiments/` and shows their metrics side by side using\n",
"`guardrail_lab.experiments`.\n",
"\n",
"**Offline-safe:** if no records exist the notebook 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": [
"## Load experiment / backtest records\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from guardrail_lab.experiments import load_experiments, compare_table\n",
"\n",
"# Look in both the experiments dir and the backtests dir.\n",
"experiments = load_experiments(str(EXPERIMENTS_DIR))\n",
"backtests = load_experiments(str(BACKTESTS_DIR))\n",
"records = experiments + backtests\n",
"\n",
"if not records:\n",
" print(NO_DATA_HINT)\n",
" print(\"\\nLooked in:\")\n",
" print(\" -\", EXPERIMENTS_DIR)\n",
" print(\" -\", BACKTESTS_DIR)\n",
"else:\n",
" print(f\"Loaded {len(records)} record(s) \"\n",
" f\"({len(experiments)} experiments, {len(backtests)} backtests).\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Metrics comparison\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def _fmt(value, suffix=\"\"):\n",
" if value is None:\n",
" return \"n/a\"\n",
" return f\"{value:,.3f}{suffix}\" if isinstance(value, float) else f\"{value}{suffix}\"\n",
"\n",
"if records:\n",
" rows = compare_table(records)\n",
" table = [\n",
" {\n",
" \"tag\": r[\"tag\"],\n",
" \"preset\": r[\"preset\"],\n",
" \"steps\": r[\"steps\"],\n",
" \"fng\": r[\"fear_greed\"],\n",
" \"return\": _fmt(r[\"total_return_pct\"], \"%\"),\n",
" \"max_dd\": _fmt(r[\"max_drawdown_pct\"], \"%\"),\n",
" \"trades\": r[\"trade_count\"],\n",
" \"win%\": _fmt(r[\"win_rate_pct\"], \"%\"),\n",
" \"pf\": _fmt(r[\"profit_factor\"]),\n",
" \"calmar\": _fmt(r[\"calmar_ratio\"]),\n",
" \"excess\": _fmt(r[\"excess_return_pct\"], \"%\"),\n",
" \"final_nav\": _fmt(r[\"final_nav_usd\"]),\n",
" }\n",
" for r in rows\n",
" ]\n",
" render_table(\n",
" table,\n",
" [\n",
" (\"tag\", \"TAG\"),\n",
" (\"preset\", \"PRESET\"),\n",
" (\"steps\", \"STEPS\"),\n",
" (\"fng\", \"F&G\"),\n",
" (\"return\", \"RETURN\"),\n",
" (\"max_dd\", \"MAX_DD\"),\n",
" (\"trades\", \"TRADES\"),\n",
" (\"win%\", \"WIN\"),\n",
" (\"pf\", \"PROFIT_FACTOR\"),\n",
" (\"calmar\", \"CALMAR\"),\n",
" (\"excess\", \"EXCESS\"),\n",
" (\"final_nav\", \"FINAL_NAV\"),\n",
" ],\n",
" title=\"Backtest / experiment comparison\",\n",
" )\n",
"else:\n",
" print(NO_DATA_HINT)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Best / worst by total return\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if records:\n",
" scored = [\n",
" r for r in compare_table(records) if r[\"total_return_pct\"] is not None\n",
" ]\n",
" if scored:\n",
" best = max(scored, key=lambda r: r[\"total_return_pct\"])\n",
" worst = min(scored, key=lambda r: r[\"total_return_pct\"])\n",
" print(f\"Best total return : {best['tag']} \"\n",
" f\"({best['total_return_pct']:.3f}%, preset={best['preset']})\")\n",
" print(f\"Worst total return: {worst['tag']} \"\n",
" f\"({worst['total_return_pct']:.3f}%, preset={worst['preset']})\")\n",
" else:\n",
" print(\"No numeric total_return_pct values to rank.\")\n",
"else:\n",
" print(NO_DATA_HINT)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Notes\n",
"\n",
"* `EXCESS` is return over the buy-and-hold benchmark; a negative\n",
" value means the strategy trailed simply holding the basket over\n",
" that window.\n",
"* `CALMAR` = return / max drawdown; high values reflect very small\n",
" drawdowns in short synthetic runs.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}