Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: shadow account — extract/backtest/render/scan + HTML report + skill

warren618c090d1fce8f2
diff --git a/agent/api_server.py b/agent/api_server.py
index 6c7fa3329..3ee94b23f 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -18,7 +18,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Query, Request, Security, UploadFile, status
-from fastapi.responses import StreamingResponse
+from fastapi.responses import FileResponse, StreamingResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, Field
from fastapi.middleware.cors import CORSMiddleware
@@ -823,6 +823,34 @@ _BLOCKED_UPLOAD_EXT = {
}
+_SHADOW_ID_RE = __import__("re").compile(r"^shadow_[0-9a-f]{8}$")
+
+
[email protected]("/shadow-reports/{shadow_id}")
+async def get_shadow_report(shadow_id: str, format: str = "html"):
+ """Serve a rendered Shadow Account report (HTML by default, PDF if available).
+
+ Reports live under ``~/.vibe-trading/shadow_reports/<shadow_id>.{html,pdf}``.
+ """
+ if not _SHADOW_ID_RE.match(shadow_id):
+ raise HTTPException(status_code=400, detail="invalid shadow_id")
+ if format not in ("html", "pdf"):
+ raise HTTPException(status_code=400, detail="format must be html or pdf")
+
+ reports_dir = Path.home() / ".vibe-trading" / "shadow_reports"
+ path = reports_dir / f"{shadow_id}.{format}"
+ if not path.exists():
+ raise HTTPException(status_code=404, detail=f"Shadow report not found: {shadow_id}.{format}")
+
+ media_type = "text/html; charset=utf-8" if format == "html" else "application/pdf"
+ # Inline so browsers render HTML/PDF directly instead of forcing download.
+ return FileResponse(
+ path,
+ media_type=media_type,
+ headers={"Content-Disposition": f'inline; filename="{shadow_id}.{format}"'},
+ )
+
+
@app.post("/upload", dependencies=[Depends(require_auth)])
async def upload_file(file: UploadFile):
"""Upload any document or data file (max 50MB).
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index d06ac00ac..6c58b7a36 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -54,9 +54,18 @@ Decide which workflow to use based on the request:
**Trade journal** — user uploads a CSV/Excel broker export (交割单) or asks to analyze their own trading history:
1. `load_skill("trade-journal")` — read analysis methodology and report templates
-2. `analyze_trade_journal(file_path=..., analysis_type="full")` — parse + profile
+2. `analyze_trade_journal(file_path=..., analysis_type="full")` — parse + profile + behavior diagnostics
3. Present results as the markdown report in the skill. Offer follow-ups: time-slice, symbol deep-dive, market split.
-4. Behavior diagnostics + strategy extraction are Phase 4b — tell the user they're coming, don't fabricate.
+4. If the user asks "now what / can I do better / what if I had discipline", switch to the **Shadow Account** flow below.
+
+**Shadow Account** — user asks to extract their strategy, "train a shadow", multi-market backtest their own profitable pattern, or ask "how much am I leaving on the table":
+1. **MUST** `load_skill("shadow-account")` as the FIRST tool call before any shadow_* tool — the skill defines rules, methodology, attribution semantics, and is required context
+2. Confirm the journal has been parsed (same session or known `journal_path`). If not, run `analyze_trade_journal` first.
+3. `extract_shadow_strategy(journal_path=...)` → show rules, ask user to confirm they look like their own behavior
+4. `run_shadow_backtest(shadow_id=..., journal_path=...)` → multi-market metrics + delta attribution
+5. `render_shadow_report(shadow_id=...)` → share html/pdf path, lead with the Section 5 "you vs shadow" delta
+6. Optional: `scan_shadow_signals(shadow_id=...)` on request (always attach the research-only disclaimer)
+**Never** call `extract_shadow_strategy` / `run_shadow_backtest` / `render_shadow_report` / `scan_shadow_signals` without first loading the `shadow-account` skill in the same session.
## Guidelines
diff --git a/agent/src/shadow_account/__init__.py b/agent/src/shadow_account/__init__.py
new file mode 100644
index 000000000..022b3b356
--- /dev/null
+++ b/agent/src/shadow_account/__init__.py
@@ -0,0 +1,53 @@
+"""Shadow Account — extract a user's profitable pattern as a re-runnable shadow.
+
+Public API (for tools/tests/external callers):
+ extract_shadow_profile: journal → ShadowProfile
+ ShadowProfile / ShadowRule / ShadowBacktestResult / AttributionBreakdown
+ storage: save_profile / load_profile / find_by_journal_hash
+"""
+
+from src.shadow_account.backtester import (
+ SUPPORTED_MARKETS,
+ run_shadow_backtest,
+ select_multi_market_codes,
+)
+from src.shadow_account.codegen import (
+ render_config,
+ render_signal_engine,
+ validate_generated,
+ write_run_dir,
+)
+from src.shadow_account.extractor import extract_shadow_profile
+from src.shadow_account.reporter import render_shadow_report
+from src.shadow_account.models import (
+ AttributionBreakdown,
+ ShadowBacktestResult,
+ ShadowProfile,
+ ShadowRule,
+)
+from src.shadow_account.storage import (
+ find_by_journal_hash,
+ load_profile,
+ new_shadow_id,
+ save_profile,
+)
+
+__all__ = [
+ "AttributionBreakdown",
+ "SUPPORTED_MARKETS",
+ "ShadowBacktestResult",
+ "ShadowProfile",
+ "ShadowRule",
+ "extract_shadow_profile",
+ "find_by_journal_hash",
+ "load_profile",
+ "new_shadow_id",
+ "render_config",
+ "render_shadow_report",
+ "render_signal_engine",
+ "run_shadow_backtest",
+ "save_profile",
+ "select_multi_market_codes",
+ "validate_generated",
+ "write_run_dir",
+]
diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.py
new file mode 100644
index 000000000..7fdb82a9b
--- /dev/null
+++ b/agent/src/shadow_account/backtester.py
@@ -0,0 +1,529 @@
+"""Shadow Account — multi-market backtest driver + delta-PnL attribution.
+
+Responsibilities:
+ 1. Pick representative symbols per market based on the user's preferred
+ markets (with a liquid-basket fallback).
+ 2. Render a run_dir (via ``codegen.write_run_dir``) and call
+ ``src.tools.backtest_tool.run_backtest``.
+ 3. Parse the emitted artifacts (metrics JSON / equity CSV) back into a
+ ``ShadowBacktestResult``.
+ 4. Compute attribution: noise trades, missed signals, early/late exits,
+ overtrading — each as signed PnL.
+
+The attribution algorithm is deliberately arithmetic-only: no LLM, no
+simulation rebuild. This keeps the numbers auditable and reproducible.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import replace
+from pathlib import Path
+from typing import Any
+
+import pandas as pd
+
+from src.shadow_account.codegen import write_run_dir
+from src.shadow_account.models import (
+ AttributionBreakdown,
+ ShadowBacktestResult,
+ ShadowProfile,
+)
+from src.shadow_account.storage import runs_dir
+from src.tools.trade_journal_parsers import parse_file, records_to_dataframe
+from src.tools.trade_journal_tool import pair_trades_fifo
+
+logger = logging.getLogger(__name__)
+
+SUPPORTED_MARKETS: tuple[str, ...] = ("china_a", "hk", "us", "crypto")
+
+_LIQUID_BASKETS: dict[str, list[str]] = {
+ "china_a": ["600519.SH", "000858.SZ", "300750.SZ", "600036.SH", "000001.SZ"],
+ "hk": ["00700.HK", "09988.HK", "03690.HK", "00388.HK", "01810.HK"],
+ "us": ["AAPL", "MSFT", "NVDA", "AMZN", "GOOGL"],
+ "crypto": ["BTC-USDT", "ETH-USDT", "SOL-USDT", "BNB-USDT", "XRP-USDT"],
+}
+
+
+# ---------------- Code selection ----------------
+
+def select_multi_market_codes(
+ profile: ShadowProfile,
+ *,
+ per_market_count: int = 5,
+ markets: tuple[str, ...] = SUPPORTED_MARKETS,
+) -> dict[str, list[str]]:
+ """Pick representative tickers for each target market.
+
+ Priority:
+ 1. If the profile's source_market is in the target set and is in the
+ liquid basket, surface it first.
+ 2. Fill remaining markets from their liquid basket.
+
+ Args:
+ profile: Shadow profile (source_market guides prioritization).
+ per_market_count: Cap per market (clamped to basket size).
+ markets: Markets to include.
+
+ Returns:
+ Dict market → list of codes, non-empty for every requested market
+ that has a known basket.
+ """
+ selection: dict[str, list[str]] = {}
+ for market in markets:
+ basket = _LIQUID_BASKETS.get(market)
+ if not basket:
+ continue
+ selection[market] = basket[: max(1, per_market_count)]
+ return selection
+
+
+def flatten_codes(selection: dict[str, list[str]]) -> list[str]:
+ """Flatten per-market selection into a unique, order-preserving code list."""
+ seen: set[str] = set()
+ out: list[str] = []
+ for codes in selection.values():
+ for c in codes:
+ if c not in seen:
+ out.append(c)
+ seen.add(c)
+ return out
+
+
+# ---------------- Backtest execution ----------------
+
+def run_shadow_backtest(
+ profile: ShadowProfile,
+ *,
+ window_start: str,
+ window_end: str,
+ markets: tuple[str, ...] = SUPPORTED_MARKETS,
+ per_market_count: int = 5,
+ source: str = "auto",
+ initial_capital: float = 1_000_000.0,
+ journal_path: str | Path | None = None,
+ run_backtest_fn: Any | None = None,
+) -> ShadowBacktestResult:
+ """Drive a multi-market backtest from a ShadowProfile.
+
+ Args:
+ profile: ShadowProfile to replay.
+ window_start / window_end: ISO dates.
+ markets: Target market buckets.
+ per_market_count: Codes per market.
+ source: Loader source (``auto`` routes by suffix).
+ initial_capital: Starting cash.
+ journal_path: Original journal path (used to compute attribution
+ against the user's realized trades). Attribution is skipped if
+ None or the file is missing.
+ run_backtest_fn: Injection point for tests — callable(run_dir_str)
+ returning the same JSON payload as
+ ``src.tools.backtest_tool.run_backtest``. Defaults to the real
+ entrypoint.
+
+ Returns:
+ ShadowBacktestResult with per-market + combined metrics, equity
+ curves (when emitted), and attribution (zeros when unavailable).
+ """
+ selection = select_multi_market_codes(
+ profile, per_market_count=per_market_count, markets=markets,
+ )
+ codes = flatten_codes(selection)
+ if not codes:
+ raise ValueError("No codes available for requested markets.")
+
+ run_dir = runs_dir(profile.shadow_id)
+ write_run_dir(
+ profile,
+ run_dir,
+ codes=codes,
+ start_date=window_start,
+ end_date=window_end,
+ source=source,
+ initial_capital=initial_capital,
+ )
+
+ backtest_fn = run_backtest_fn or _default_run_backtest_fn()
+ payload = json.loads(backtest_fn(str(run_dir)))
+
+ per_market, combined, equity_curves = _summarize_artifacts(
+ payload=payload, run_dir=run_dir, selection=selection,
+ )
+
+ attribution, shadow_pnl, real_pnl = _attribution_or_zero(
+ profile=profile,
+ journal_path=journal_path,
+ combined=combined,
+ )
+
+ result = ShadowBacktestResult(
+ shadow_id=profile.shadow_id,
+ per_market=per_market,
+ combined=combined,
+ equity_curves=equity_curves,
+ attribution=attribution,
+ shadow_total_pnl=shadow_pnl,
+ real_total_pnl=real_pnl,
+ delta_pnl=round(shadow_pnl - real_pnl, 2),
+ )
+ _cache_result(run_dir, result)
+ return result
+
+
+def load_cached_result(shadow_id: str) -> ShadowBacktestResult | None:
+ """Load the last cached backtest result for a shadow, if any."""
+ cache_path = runs_dir(shadow_id) / "shadow_result.json"
+ if not cache_path.exists():
+ return None
+ try:
+ data = json.loads(cache_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ attr = data.get("attribution") or {}
+ return ShadowBacktestResult(
+ shadow_id=data["shadow_id"],
+ per_market=data.get("per_market") or {},
+ combined=data.get("combined") or {},
+ equity_curves={
+ k: [(str(pt[0]), float(pt[1])) for pt in v]
+ for k, v in (data.get("equity_curves") or {}).items()
+ },
+ attribution=AttributionBreakdown(
+ missed_signals_pnl=float(attr.get("missed_signals_pnl", 0.0)),
+ noise_trades_pnl=float(attr.get("noise_trades_pnl", 0.0)),
+ early_exit_pnl=float(attr.get("early_exit_pnl", 0.0)),
+ late_exit_pnl=float(attr.get("late_exit_pnl", 0.0)),
+ overtrading_pnl=float(attr.get("overtrading_pnl", 0.0)),
+ counterfactual_trades=tuple(attr.get("counterfactual_trades") or ()),
+ ),
+ shadow_total_pnl=float(data.get("shadow_total_pnl", 0.0)),
+ real_total_pnl=float(data.get("real_total_pnl", 0.0)),
+ delta_pnl=float(data.get("delta_pnl", 0.0)),
+ )
+
+
+def _cache_result(run_dir: Path, result: ShadowBacktestResult) -> None:
+ """Persist a ShadowBacktestResult so downstream tools don't re-backtest."""
+ from dataclasses import asdict as _asdict
+
+ payload = _asdict(result)
+ try:
+ (run_dir / "shadow_result.json").write_text(
+ json.dumps(payload, ensure_ascii=False, indent=2, default=str),
+ encoding="utf-8",
+ )
+ except OSError as exc: # pragma: no cover — disk failure is non-fatal
+ logger.warning("Failed to cache shadow result: %s", exc)
+
+
+def _default_run_backtest_fn():
+ from src.tools.backtest_tool import run_backtest
+ return run_backtest
+
+
+# ---------------- Artifact parsing ----------------
+
+def _summarize_artifacts(
+ *,
+ payload: dict[str, Any],
+ run_dir: Path,
+ selection: dict[str, list[str]],
+) -> tuple[dict[str, dict[str, float]], dict[str, float], dict[str, list[tuple[str, float]]]]:
+ """Turn raw backtest output into (per_market, combined, equity_curves).
+
+ Gracefully degrades when artifacts are missing (e.g. data fetch failed):
+ returns empty dicts and a combined dict containing the error reason.
+ """
+ artifacts = payload.get("artifacts") or {}
+ status = payload.get("status", "error")
+
+ combined = _load_metrics(artifacts, run_dir)
+ equity_points = _load_equity_curve(artifacts, run_dir)
+
+ # Only surface an error when we genuinely have no metrics. A non-ok
+ # status with usable metrics typically means a transient data-source
+ # warning (e.g. yfinance flaked on one market) — downgrading to ok is
+ # more faithful to what the user actually has.
+ if not combined and status != "ok":
+ combined = {"error": payload.get("stderr", "")[-200:] or "backtest failed"}
+
+ per_market = _per_market_breakdown(combined, selection)
+ equity_curves = {"combined": equity_points} if equity_points else {}
+ return per_market, combined, equity_curves
+
+
+def _load_metrics(artifacts: dict[str, str], run_dir: Path) -> dict[str, float]:
+ """Pull a numeric metrics dict from the run_dir.
+
+ Looks for ``metrics.json`` first (preferred), then ``metrics.csv``.
+ Unknown shape → empty dict (caller treats as failure).
+ """
+ for key in ("metrics.json", "metrics", "metrics.csv"):
+ path_str = artifacts.get(key)
+ if not path_str:
+ continue
+ path = Path(path_str)
+ if not path.exists():
+ continue
+ try:
+ if path.suffix == ".json":
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return _coerce_numeric(data)
+ if path.suffix == ".csv":
+ df = pd.read_csv(path)
+ if df.empty:
+ return {}
+ row = df.iloc[-1].to_dict()
+ return _coerce_numeric(row)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ logger.warning("Failed to parse metrics %s: %s", path, exc)
+
+ # Fallback: scan run_dir for a metrics file.
+ for path in run_dir.glob("**/metrics.*"):
+ try:
+ if path.suffix == ".json":
+ return _coerce_numeric(json.loads(path.read_text(encoding="utf-8")))
+ if path.suffix == ".csv":
+ df = pd.read_csv(path)
+ if not df.empty:
+ return _coerce_numeric(df.iloc[-1].to_dict())
+ except Exception:
+ continue
+ return {}
+
+
+def _load_equity_curve(artifacts: dict[str, str], run_dir: Path) -> list[tuple[str, float]]:
+ """Load the equity curve as [(iso_date, equity), ...]."""
+ candidates: list[Path] = []
+ for key in ("equity.csv", "equity", "equity_curve.csv"):
+ path_str = artifacts.get(key)
+ if path_str:
+ candidates.append(Path(path_str))
+ candidates.extend(run_dir.glob("**/equity*.csv"))
+
+ seen: set[Path] = set()
+ for path in candidates:
+ if path in seen or not path.exists():
+ continue
+ seen.add(path)
+ try:
+ df = pd.read_csv(path)
+ except (OSError, pd.errors.ParserError) as exc:
+ logger.warning("Failed to read equity csv %s: %s", path, exc)
+ continue
+ if df.empty:
+ continue
+ date_col = next((c for c in df.columns if c.lower() in ("date", "datetime", "timestamp")), df.columns[0])
+ equity_col = next(
+ (c for c in df.columns if c.lower() in ("equity", "equity_curve", "value", "net_value")),
+ df.columns[-1],
+ )
+ return [(str(row[date_col]), float(row[equity_col])) for _, row in df.iterrows()]
+ return []
+
+
+def _coerce_numeric(data: dict[str, Any]) -> dict[str, float]:
+ """Keep only the scalar numeric fields from a metrics dict."""
+ out: dict[str, float] = {}
+ for key, value in data.items():
+ if isinstance(value, bool):
+ continue
+ if isinstance(value, (int, float)):
+ out[str(key)] = float(value)
+ return out
+
+
+def _per_market_breakdown(
+ combined: dict[str, float],
+ selection: dict[str, list[str]],
+) -> dict[str, dict[str, float]]:
+ """Project the combined metrics into each requested market.
+
+ v1 limitation: the runner emits a single combined metrics file regardless
+ of cross-market composition, so per-market rows reuse the combined
+ metrics. This is faithful (same backtest) but intentionally lossy; a
+ follow-up can split equity by market attribution.
+ """
+ if not combined:
+ return {market: {} for market in selection}
+ return {market: dict(combined) for market in selection}
+
+
+# ---------------- Attribution ----------------
+
+def _attribution_or_zero(
+ *,
+ profile: ShadowProfile,
+ journal_path: str | Path | None,
+ combined: dict[str, float],
+) -> tuple[AttributionBreakdown, float, float]:
+ """Compute attribution if the journal is available, else return zeros."""
+ shadow_pnl = float(combined.get("total_return_abs") or combined.get("total_pnl") or 0.0)
+ if not journal_path:
+ return _zero_attribution(), shadow_pnl, 0.0
+ path = Path(journal_path)
+ if not path.exists():
+ return _zero_attribution(), shadow_pnl, 0.0
+
+ try:
+ _, records = parse_file(path)
+ trades_df = records_to_dataframe(records)
+ roundtrips = pair_trades_fifo(trades_df)
+ except Exception as exc:
+ logger.warning("Attribution skipped — journal parse failed: %s", exc)
+ return _zero_attribution(), shadow_pnl, 0.0
+
+ if not roundtrips:
+ return _zero_attribution(), shadow_pnl, 0.0
+
+ return _compute_attribution(profile=profile, roundtrips=roundtrips, shadow_pnl=shadow_pnl)
+
+
+def _zero_attribution() -> AttributionBreakdown:
+ return AttributionBreakdown(
+ missed_signals_pnl=0.0,
+ noise_trades_pnl=0.0,
+ early_exit_pnl=0.0,
+ late_exit_pnl=0.0,
+ overtrading_pnl=0.0,
+ counterfactual_trades=(),
+ )
+
+
+def _compute_attribution(
+ *,
+ profile: ShadowProfile,
+ roundtrips: list[dict[str, Any]],
+ shadow_pnl: float,
+) -> tuple[AttributionBreakdown, float, float]:
+ """Attribute the delta between user's real PnL and shadow PnL.
+
+ Decomposition (signed — positive means shadow would have earned more):
+
+ noise_trades_pnl = -Σ realized_pnl on rule-violating trades
+ (user's unexplained losses that shadow avoids)
+ early_exit_pnl = +Σ shortfall on winning trades exited before
+ the median rule holding range
+ late_exit_pnl = +Σ excess loss on losing trades held past the
+ median rule holding range
+ overtrading_pnl = -Σ realized_pnl on trades beyond the shadow's
+ expected trade budget (1 trade per 2*hold_days)
+ missed_signals_pnl = shadow_pnl - real_pnl - (noise+early+late+over)
+ (residual — everything the above can't explain)
+
+ ``counterfactual_trades`` lists the top-5 |impact| roundtrips for
+ Section 6 of the report.
+ """
+ rule_hold_lo, rule_hold_hi = _aggregate_holding_range(profile)
+ noise = 0.0
+ early = 0.0
+ late = 0.0
+ real_pnl = 0.0
+ counterfactuals: list[dict[str, Any]] = []
+
+ for rt in roundtrips:
+ pnl = float(rt["pnl"])
+ real_pnl += pnl
+ hold = float(rt["hold_days"])
+ within_rule = rule_hold_lo <= hold <= rule_hold_hi
+ impact = 0.0
+ reason = ""
+ if not within_rule:
+ noise += -pnl
+ impact += -pnl
+ reason = "rule_violation"
+ if pnl > 0 and hold < rule_hold_lo:
+ shortfall = pnl * max(0.0, (rule_hold_lo - hold) / max(rule_hold_lo, 1))
+ early += shortfall
+ impact += shortfall
+ reason = reason or "early_exit"
+ if pnl < 0 and hold > rule_hold_hi:
+ excess = -pnl * max(0.0, (hold - rule_hold_hi) / max(rule_hold_hi, 1))
+ late += excess
+ impact += excess
+ reason = reason or "late_exit"
+ if impact != 0.0:
+ counterfactuals.append({
+ "symbol": rt["symbol"],
+ "buy_dt": str(rt["buy_dt"]),
+ "sell_dt": str(rt["sell_dt"]),
+ "hold_days": hold,
+ "pnl": round(pnl, 2),
+ "impact": round(impact, 2),
+ "reason": reason,
+ })
+
+ overtrading = _overtrading_pnl(profile=profile, roundtrips=roundtrips)
+ explained = noise + early + late + overtrading
+ missed = round(shadow_pnl - real_pnl - explained, 2)
+
+ counterfactuals.sort(key=lambda r: abs(r["impact"]), reverse=True)
+ top5 = tuple(counterfactuals[:5])
+
+ return (
+ AttributionBreakdown(
+ missed_signals_pnl=round(missed, 2),
+ noise_trades_pnl=round(noise, 2),
+ early_exit_pnl=round(early, 2),
+ late_exit_pnl=round(late, 2),
+ overtrading_pnl=round(overtrading, 2),
+ counterfactual_trades=top5,
+ ),
+ round(shadow_pnl, 2),
+ round(real_pnl, 2),
+ )
+
+
+def _aggregate_holding_range(profile: ShadowProfile) -> tuple[float, float]:
+ """Union holding-day ranges across all rules (lo=min, hi=max)."""
+ if not profile.rules:
+ return (1.0, 30.0)
+ los = [r.holding_days_range[0] for r in profile.rules]
+ his = [r.holding_days_range[1] for r in profile.rules]
+ return (float(min(los)), float(max(his)))
+
+
+def _overtrading_pnl(
+ *,
+ profile: ShadowProfile,
+ roundtrips: list[dict[str, Any]],
+) -> float:
+ """Excess-frequency PnL: trades beyond the shadow's expected budget.
+
+ Shadow runs roughly 1 trade per ``2 * median_hold_days`` bars. We
+ compare against the user's actual roundtrip count over the same span.
+ Excess trades' PnL is totaled with a negative sign (shadow would've
+ skipped them, so real PnL — positive or negative — is "noise").
+ """
+ if not roundtrips:
+ return 0.0
+ median_hold, _ = profile.typical_holding_days
+ if median_hold <= 0:
+ return 0.0
+ span_days = (
+ pd.Timestamp(roundtrips[-1]["sell_dt"]) - pd.Timestamp(roundtrips[0]["buy_dt"])
+ ).total_seconds() / 86400.0
+ expected = max(1.0, span_days / max(2 * median_hold, 1.0))
+ actual = len(roundtrips)
+ if actual <= expected:
+ return 0.0
+ # Penalize the cheapest (lowest |pnl|) extras — those look like noise.
+ extras = sorted(roundtrips, key=lambda rt: abs(float(rt["pnl"])))
+ extra_count = int(actual - expected)
+ extra_pnl = sum(float(rt["pnl"]) for rt in extras[:extra_count])
+ return -extra_pnl
+
+
+__all__ = [
+ "SUPPORTED_MARKETS",
+ "flatten_codes",
+ "load_cached_result",
+ "run_shadow_backtest",
+ "select_multi_market_codes",
+]
+
+
+# Re-export for convenience (see __init__.py).
+def _touch_replace_reexport(): # pragma: no cover
+ return replace
diff --git a/agent/src/shadow_account/codegen.py b/agent/src/shadow_account/codegen.py
new file mode 100644
index 000000000..6552773b5
--- /dev/null
+++ b/agent/src/shadow_account/codegen.py
@@ -0,0 +1,184 @@
+"""Shadow Account — code generation (rules → signal_engine.py + config.json).
+
+Inputs are always a ``ShadowProfile`` (contract-stable). Outputs are:
+ * ``signal_engine.py`` source, validated with ``ast.parse`` + a shape
+ check on ``class SignalEngine.generate``.
+ * ``config.json`` dict, ready to drop into a run_dir.
+
+No external I/O here — callers (backtester) are responsible for writing
+files and launching ``run_backtest``.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+from pathlib import Path
+from typing import Any
+
+from jinja2 import Environment, FileSystemLoader, select_autoescape
+
+from src.shadow_account.models import ShadowProfile, ShadowRule
+
+_TEMPLATES_DIR = Path(__file__).parent / "templates"
+_SIGNAL_ENGINE_TEMPLATE = "signal_engine.py.j2"
+
+
+def _env() -> Environment:
+ """Jinja2 environment rooted at our templates directory."""
+ return Environment(
+ loader=FileSystemLoader(str(_TEMPLATES_DIR)),
+ autoescape=select_autoescape(enabled_extensions=("html", "xml")),
+ trim_blocks=True,
+ lstrip_blocks=True,
+ )
+
+
+def _rule_to_context(rule: ShadowRule) -> dict[str, Any]:
+ """Flatten a ShadowRule into the scalar fields the template consumes."""
+ market = str(rule.entry_condition.get("market", "other"))
+ hour = rule.entry_condition.get("entry_hour") or {}
+ hold_lo, hold_hi = rule.holding_days_range
+ hold_days = max(1, int(round((hold_lo + hold_hi) / 2)))
+ return {
+ "rule_id": rule.rule_id,
+ "market": market,
+ "entry_hour_min": int(hour.get("min", 0)),
+ "entry_hour_max": int(hour.get("max", 23)),
+ "hold_days": hold_days,
+ "weight": float(rule.weight),
+ }
+
+
+def render_signal_engine(profile: ShadowProfile) -> str:
+ """Render the SignalEngine Python source for a profile.
+
+ Args:
+ profile: ShadowProfile carrying the rules to replay.
+
+ Returns:
+ Python source string. The caller is expected to ``validate_generated``
+ before writing to disk.
+ """
+ template = _env().get_template(_SIGNAL_ENGINE_TEMPLATE)
+ return template.render(
+ shadow_id=profile.shadow_id,
+ profitable_roundtrips=profile.profitable_roundtrips,
+ date_range=list(profile.date_range),
+ preferred_markets=list(profile.preferred_markets),
+ rules=[_rule_to_context(r) for r in profile.rules],
+ )
+
+
+def validate_generated(source: str) -> tuple[bool, str]:
+ """Static-check a generated signal_engine source.
+
+ Checks:
+ 1. ``ast.parse`` succeeds.
+ 2. Module defines ``class SignalEngine``.
+ 3. ``SignalEngine`` has a ``generate`` method with one positional
+ arg besides self.
+
+ Returns:
+ (ok, error_msg). ``error_msg`` is empty on success.
+ """
+ try:
+ tree = ast.parse(source)
+ except SyntaxError as exc:
+ return False, f"SyntaxError: {exc}"
+
+ signal_cls: ast.ClassDef | None = None
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ClassDef) and node.name == "SignalEngine":
+ signal_cls = node
+ break
+ if signal_cls is None:
+ return False, "class SignalEngine not found"
+
+ generate: ast.FunctionDef | None = None
+ for node in signal_cls.body:
+ if isinstance(node, ast.FunctionDef) and node.name == "generate":
+ generate = node
+ break
+ if generate is None:
+ return False, "SignalEngine.generate method not found"
+
+ non_self_args = [a for a in generate.args.args if a.arg != "self"]
+ if len(non_self_args) < 1:
+ return False, "SignalEngine.generate must accept a data_map argument"
+ return True, ""
+
+
+def render_config(
+ profile: ShadowProfile,
+ *,
+ codes: list[str],
+ start_date: str,
+ end_date: str,
+ source: str = "auto",
+ initial_capital: float = 1_000_000.0,
+ interval: str = "1D",
+ extra: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Build the ``config.json`` dict for a shadow backtest run.
+
+ Args:
+ profile: ShadowProfile (used only for metadata, not for engine logic).
+ codes: Symbols to backtest across.
+ start_date / end_date: ISO dates.
+ source: Loader source; ``auto`` routes by symbol suffix.
+ initial_capital: Starting cash.
+ interval: Bar size (daily default).
+ extra: Arbitrary overrides merged last.
+ """
+ cfg: dict[str, Any] = {
+ "source": source,
+ "codes": codes,
+ "start_date": start_date,
+ "end_date": end_date,
+ "interval": interval,
+ "initial_capital": initial_capital,
+ "engine": "daily",
+ "shadow_id": profile.shadow_id,
+ }
+ if extra:
+ cfg.update(extra)
+ return cfg
+
+
+def write_run_dir(
+ profile: ShadowProfile,
+ run_dir: Path,
+ *,
+ codes: list[str],
+ start_date: str,
+ end_date: str,
+ source: str = "auto",
+ initial_capital: float = 1_000_000.0,
+) -> Path:
+ """Materialize a full run_dir with ``code/signal_engine.py`` + ``config.json``.
+
+ Raises:
+ ValueError: Generated signal_engine fails static validation.
+ """
+ run_dir = Path(run_dir)
+ (run_dir / "code").mkdir(parents=True, exist_ok=True)
+
+ source_code = render_signal_engine(profile)
+ ok, err = validate_generated(source_code)
+ if not ok:
+ raise ValueError(f"Generated signal_engine failed validation: {err}")
+
+ (run_dir / "code" / "signal_engine.py").write_text(source_code, encoding="utf-8")
+ cfg = render_config(
+ profile,
+ codes=codes,
+ start_date=start_date,
+ end_date=end_date,
+ source=source,
+ initial_capital=initial_capital,
+ )
+ (run_dir / "config.json").write_text(
+ json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8",
+ )
+ return run_dir
diff --git a/agent/src/shadow_account/extractor.py b/agent/src/shadow_account/extractor.py
new file mode 100644
index 000000000..75dc42c09
--- /dev/null
+++ b/agent/src/shadow_account/extractor.py
@@ -0,0 +1,371 @@
+"""Shadow Account — strategy extraction from profitable roundtrips.
+
+Pipeline:
+ trades_df → FIFO pair → filter (pnl > 0) → feature engineer
+ → KMeans cluster (k auto 2-5) → per-cluster decision tree (max_depth=3)
+ → path extraction → structured entry_condition dict
+ → LLM-light natural-language translation (template fallback if no LLM)
+
+Design constraints:
+ * No external price-data calls in v1. All features are derivable from
+ the journal itself (holding_days, pnl_pct, entry hour/weekday, market).
+ Price-dependent features (prior_N_return, rsi) are stubbed with None
+ and dropped from the feature matrix if unavailable.
+ * Must survive tiny samples: <5 profitable roundtrips → explicit error.
+ <2 clusters → degrade to a single-cluster heuristic rule.
+ * Rules are immutable ShadowRule objects — codegen's only input.
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pandas as pd
+
+from src.shadow_account.models import ShadowProfile, ShadowRule
+from src.shadow_account.storage import hash_journal, new_shadow_id, now_iso
+from src.tools.trade_journal_parsers import parse_file, records_to_dataframe
+from src.tools.trade_journal_tool import pair_trades_fifo
+
+logger = logging.getLogger(__name__)
+
+MIN_PROFITABLE_ROUNDTRIPS = 5
+DEFAULT_MAX_RULES = 5
+DEFAULT_MIN_SUPPORT = 3
+_NUMERIC_FEATURES = ("holding_days", "pnl_pct", "entry_hour", "entry_weekday")
+_CATEGORICAL_FEATURES = ("market",)
+
+
+# ---------------- Public API ----------------
+
+def extract_shadow_profile(
+ journal_path: str | Path,
+ *,
+ min_support: int = DEFAULT_MIN_SUPPORT,
+ max_rules: int = DEFAULT_MAX_RULES,
+ llm_translator: Any | None = None,
+) -> ShadowProfile:
+ """Extract a ShadowProfile from a broker journal file.
+
+ Args:
+ journal_path: CSV/Excel exported from a supported broker.
+ min_support: Minimum profitable roundtrips backing any single rule.
+ max_rules: Cap on the number of rules returned.
+ llm_translator: Optional callable (dict) -> str for translating
+ structured entry_condition into natural-language text. If None,
+ a deterministic f-string fallback is used.
+
+ Returns:
+ ShadowProfile (not yet persisted — caller decides whether to save).
+
+ Raises:
+ ValueError: Fewer than MIN_PROFITABLE_ROUNDTRIPS profitable roundtrips.
+ """
+ path = Path(journal_path)
+ fmt, records = parse_file(path)
+ if not records:
+ raise ValueError(f"No trade records parsed from {path} (format={fmt})")
+ trades_df = records_to_dataframe(records)
+
+ roundtrips = pair_trades_fifo(trades_df)
+ total = len(roundtrips)
+ if total == 0:
+ raise ValueError("No complete buy→sell roundtrips found in journal.")
+
+ profitable = [rt for rt in roundtrips if rt["pnl"] > 0]
+ if len(profitable) < MIN_PROFITABLE_ROUNDTRIPS:
+ raise ValueError(
+ f"Insufficient profitable roundtrips: {len(profitable)} "
+ f"(need ≥{MIN_PROFITABLE_ROUNDTRIPS}).",
+ )
+
+ features_df = _compute_features(profitable, trades_df)
+ rules = _extract_rules(
+ features_df,
+ min_support=min_support,
+ max_rules=max_rules,
+ llm_translator=llm_translator,
+ )
+
+ source_market = _dominant(trades_df["market"])
+ preferred_markets = tuple(trades_df["market"].value_counts().index.tolist())
+ hold = features_df["holding_days"].dropna()
+ typical_holding = (
+ round(float(hold.median()), 2) if len(hold) else 0.0,
+ round(float(hold.quantile(0.75)), 2) if len(hold) else 0.0,
+ )
+ date_range = (
+ str(trades_df["datetime"].min()),
+ str(trades_df["datetime"].max()),
+ )
+ profile_text = _render_profile_text(
+ total_profitable=len(profitable),
+ total_all=total,
+ typical_holding=typical_holding,
+ source_market=source_market,
+ preferred_markets=preferred_markets,
+ )
+
+ return ShadowProfile(
+ shadow_id=new_shadow_id(),
+ created_at=now_iso(),
+ journal_hash=hash_journal(path),
+ source_market=source_market,
+ profitable_roundtrips=len(profitable),
+ total_roundtrips=total,
+ date_range=date_range,
+ profile_text=profile_text,
+ rules=tuple(rules),
+ preferred_markets=preferred_markets,
+ typical_holding_days=typical_holding,
+ )
+
+
+# ---------------- Feature engineering ----------------
+
+def _compute_features(
+ roundtrips: list[dict[str, Any]],
+ trades_df: pd.DataFrame,
+) -> pd.DataFrame:
+ """Compute a features row per profitable roundtrip.
+
+ Columns: symbol, market, holding_days, pnl, pnl_pct, entry_hour,
+ entry_weekday, buy_dt, sell_dt.
+ """
+ market_by_symbol = (
+ trades_df.drop_duplicates("symbol").set_index("symbol")["market"].to_dict()
+ )
+ rows: list[dict[str, Any]] = []
+ for rt in roundtrips:
+ buy_dt = pd.Timestamp(rt["buy_dt"])
+ sell_dt = pd.Timestamp(rt["sell_dt"])
+ rows.append({
+ "symbol": rt["symbol"],
+ "market": market_by_symbol.get(rt["symbol"], "other"),
+ "holding_days": float(rt["hold_days"]),
+ "pnl": float(rt["pnl"]),
+ "pnl_pct": float(rt["pnl_pct"]),
+ "entry_hour": int(buy_dt.hour),
+ "entry_weekday": int(buy_dt.weekday()),
+ "buy_dt": buy_dt,
+ "sell_dt": sell_dt,
+ })
+ return pd.DataFrame(rows)
+
+
+# ---------------- Cluster + decision-tree rule extraction ----------------
+
+def _extract_rules(
+ features_df: pd.DataFrame,
+ *,
+ min_support: int,
+ max_rules: int,
+ llm_translator: Any | None,
+) -> list[ShadowRule]:
+ """Cluster profitable roundtrips, derive one rule per dense cluster."""
+ if len(features_df) < min_support:
+ return [_heuristic_single_rule(features_df, min_support, llm_translator)]
+
+ cluster_labels = _auto_cluster(features_df, max_k=min(max_rules, 5))
+ rules: list[ShadowRule] = []
+ total_profitable = len(features_df)
+ used_markets: set[str] = set()
+
+ for cluster_id in sorted(set(cluster_labels)):
+ cluster_mask = cluster_labels == cluster_id
+ cluster_df = features_df[cluster_mask]
+ if len(cluster_df) < min_support:
+ continue
+ rule = _cluster_to_rule(
+ cluster_df=cluster_df,
+ rule_index=len(rules) + 1,
+ total_profitable=total_profitable,
+ llm_translator=llm_translator,
+ )
+ # Deduplicate near-identical rules (same market + same holding band)
+ key = (rule.entry_condition.get("market"), rule.holding_days_range)
+ if key in used_markets:
+ continue
+ used_markets.add(key)
+ rules.append(rule)
+ if len(rules) >= max_rules:
+ break
+
+ if not rules:
+ rules = [_heuristic_single_rule(features_df, min_support, llm_translator)]
+ return rules
+
+
+def _auto_cluster(features_df: pd.DataFrame, *, max_k: int) -> np.ndarray:
+ """Pick a cluster count via simple silhouette heuristic (fallback k=2).
+
+ Uses only numeric features; scales by z-score to avoid holding_days
+ dominating pnl_pct.
+ """
+ from sklearn.cluster import KMeans
+ from sklearn.preprocessing import StandardScaler
+
+ numeric = features_df[list(_NUMERIC_FEATURES)].astype(float).to_numpy()
+ if len(numeric) <= 2 or max_k < 2:
+ return np.zeros(len(numeric), dtype=int)
+ scaled = StandardScaler().fit_transform(numeric)
+
+ best_k, best_score = 2, -1.0
+ try:
+ from sklearn.metrics import silhouette_score
+ for k in range(2, min(max_k, len(numeric) - 1) + 1):
+ labels = KMeans(n_clusters=k, n_init=5, random_state=42).fit_predict(scaled)
+ if len(set(labels)) < 2:
+ continue
+ score = silhouette_score(scaled, labels)
+ if score > best_score:
+ best_k, best_score = k, score
+ except Exception as exc: # pragma: no cover — sklearn edge cases
+ logger.debug("silhouette selection failed, fallback k=2: %s", exc)
+
+ return KMeans(n_clusters=best_k, n_init=5, random_state=42).fit_predict(scaled)
+
+
+def _cluster_to_rule(
+ *,
+ cluster_df: pd.DataFrame,
+ rule_index: int,
+ total_profitable: int,
+ llm_translator: Any | None,
+) -> ShadowRule:
+ """Summarize a cluster as one ShadowRule.
+
+ Entry condition uses p10–p90 numeric bounds + dominant market. This is
+ lighter than a decision tree and stays interpretable with tiny samples;
+ we can swap to DecisionTreeClassifier in v2 when features widen.
+ """
+ market = _dominant(cluster_df["market"])
+ hold_days = cluster_df["holding_days"]
+ hold_lo = max(1, int(round(float(hold_days.quantile(0.10)))))
+ hold_hi = max(hold_lo, int(round(float(hold_days.quantile(0.90)))))
+ hours = cluster_df["entry_hour"]
+ hour_lo = int(round(float(hours.quantile(0.10))))
+ hour_hi = int(round(float(hours.quantile(0.90))))
+
+ entry_condition: dict[str, Any] = {
+ "market": market,
+ "entry_hour": {"min": hour_lo, "max": hour_hi},
+ }
+ exit_condition: dict[str, Any] = {
+ "holding_days": {"min": hold_lo, "max": hold_hi},
+ }
+
+ samples = tuple(
+ f"{row.symbol}@{pd.Timestamp(row.buy_dt).date().isoformat()}"
+ for row in cluster_df.head(3).itertuples(index=False)
+ )
+ support = int(len(cluster_df))
+ coverage = round(support / max(total_profitable, 1), 3)
+
+ human = _translate_rule(
+ entry_condition=entry_condition,
+ exit_condition=exit_condition,
+ holding_range=(hold_lo, hold_hi),
+ translator=llm_translator,
+ )
+
+ return ShadowRule(
+ rule_id=f"R{rule_index}",
+ human_text=human,
+ entry_condition=entry_condition,
+ exit_condition=exit_condition,
+ holding_days_range=(hold_lo, hold_hi),
+ support_count=support,
+ coverage_rate=coverage,
+ sample_trades=samples,
+ )
+
+
+def _heuristic_single_rule(
+ features_df: pd.DataFrame,
+ min_support: int,
+ llm_translator: Any | None,
+) -> ShadowRule:
+ """Degenerate fallback when clustering/tree yield nothing usable."""
+ return _cluster_to_rule(
+ cluster_df=features_df,
+ rule_index=1,
+ total_profitable=max(len(features_df), min_support),
+ llm_translator=llm_translator,
+ )
+
+
+# ---------------- Natural-language translation ----------------
+
+_MARKET_LABELS = {
+ "china_a": "China A-share",
+ "us": "US equity",
+ "hk": "HK equity",
+ "crypto": "Crypto",
+ "other": "Other",
+}
+
+RULE_TEXT_MAX = 80
+
+
+def _translate_rule(
+ *,
+ entry_condition: dict[str, Any],
+ exit_condition: dict[str, Any],
+ holding_range: tuple[int, int],
+ translator: Any | None,
+) -> str:
+ """Turn a structured rule dict into a concise English sentence (<=80 chars)."""
+ if translator is not None:
+ try:
+ text = translator({
+ "entry_condition": entry_condition,
+ "exit_condition": exit_condition,
+ "holding_range": holding_range,
+ })
+ if isinstance(text, str) and text.strip():
+ return text.strip()[:RULE_TEXT_MAX]
+ except Exception as exc: # pragma: no cover — LLM failure, fallback
+ logger.warning("LLM rule translator failed, falling back: %s", exc)
+
+ market_label = _MARKET_LABELS.get(entry_condition.get("market", "other"), "Other")
+ hour_range = entry_condition.get("entry_hour", {})
+ hour_text = ""
+ if hour_range:
+ lo, hi = hour_range.get("min"), hour_range.get("max")
+ hour_text = f" at {lo}:00" if lo == hi else f" between {lo}:00-{hi}:00"
+ hold_lo, hold_hi = holding_range
+ hold_text = f"hold {hold_lo}-{hold_hi}d" if hold_lo != hold_hi else f"hold {hold_lo}d"
+ entry_text = f"Enter {market_label}{hour_text}"
+ return f"{entry_text}, {hold_text}"[:RULE_TEXT_MAX]
+
+
+# ---------------- Utilities ----------------
+
+def _dominant(series: pd.Series) -> str:
+ """Most frequent value in a series, or the first if tied."""
+ if series.empty:
+ return "other"
+ return str(series.value_counts().idxmax())
+
+
+def _render_profile_text(
+ *,
+ total_profitable: int,
+ total_all: int,
+ typical_holding: tuple[float, float],
+ source_market: str,
+ preferred_markets: tuple[str, ...],
+) -> str:
+ """Build the Section 1 one-paragraph portrait (English)."""
+ median, p75 = typical_holding
+ markets_label = ", ".join(_MARKET_LABELS.get(m, m) for m in preferred_markets[:3])
+ source_label = _MARKET_LABELS.get(source_market, source_market)
+ return (
+ f"{total_profitable} of your {total_all} closed roundtrips were profitable. "
+ f"Primary market: {source_label} (also active in {markets_label}). "
+ f"Median holding period {median:.1f}d; most positions closed within {p75:.1f}d."
+ )
diff --git a/agent/src/shadow_account/fonts.py b/agent/src/shadow_account/fonts.py
new file mode 100644
index 000000000..864f6f1b2
--- /dev/null
+++ b/agent/src/shadow_account/fonts.py
@@ -0,0 +1,143 @@
+"""Shadow Account — font handling for PDF rendering.
+
+Tries to guarantee that Chinese characters render; falls back to DejaVu Sans
+(English-only, logs a warning) when CJK resources are unavailable. Matplotlib
+and weasyprint both consume ``cjk_font_path()`` or at least see the family
+name via ``apply_matplotlib_cjk_font``.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+from pathlib import Path
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+_NOTO_URL = (
+ "https://github.com/notofonts/noto-cjk/raw/main/Sans/OTF/SimplifiedChinese/"
+ "NotoSansCJKsc-Regular.otf"
+)
+_FONT_NAME = "NotoSansCJKsc-Regular.otf"
+_FALLBACK_FAMILY = "DejaVu Sans"
+
+
+def fonts_dir() -> Path:
+ """Return the Shadow Account fonts cache dir (auto-created)."""
+ d = Path.home() / ".vibe-trading" / "fonts"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def _system_cjk_candidates() -> list[Path]:
+ """Enumerate locally-installed CJK fonts we can reuse without downloading."""
+ candidates: list[Path] = []
+ env = os.environ
+ windir = env.get("WINDIR") or env.get("SystemRoot")
+ if windir:
+ win_fonts = Path(windir) / "Fonts"
+ for name in (
+ "msyh.ttc", "msyh.ttf", "msyhbd.ttc",
+ "simhei.ttf", "simsun.ttc", "simkai.ttf",
+ "NotoSansCJK-Regular.ttc",
+ ):
+ candidates.append(win_fonts / name)
+ for p in (
+ "/System/Library/Fonts/PingFang.ttc",
+ "/System/Library/Fonts/STHeiti Light.ttc",
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
+ "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
+ ):
+ candidates.append(Path(p))
+ return candidates
+
+
+def cjk_font_path(*, allow_download: bool = True, timeout: float = 10.0) -> Optional[Path]:
+ """Resolve a CJK font file path.
+
+ Resolution order:
+ 1. Cached copy in ``fonts_dir()``.
+ 2. First available system font from ``_system_cjk_candidates``.
+ 3. Download Noto CJK (optional).
+
+ Returns ``None`` when every option fails — callers should then fall
+ back to the DejaVu family.
+ """
+ cached = fonts_dir() / _FONT_NAME
+ if cached.exists() and cached.stat().st_size > 0:
+ return cached
+
+ for candidate in _system_cjk_candidates():
+ if candidate.exists():
+ try:
+ shutil.copy(candidate, cached)
+ return cached
+ except OSError as exc:
+ logger.debug("Failed to cache system font %s: %s", candidate, exc)
+
+ if not allow_download:
+ return None
+
+ try:
+ import urllib.request
+ req = urllib.request.Request(_NOTO_URL, headers={"User-Agent": "vibe-trading"})
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ cached.write_bytes(resp.read())
+ if cached.stat().st_size > 0:
+ return cached
+ except Exception as exc: # pragma: no cover — network-dependent
+ logger.warning("CJK font download failed (%s); falling back to DejaVu.", exc)
+
+ return None
+
+
+def apply_matplotlib_cjk_font() -> str:
+ """Configure matplotlib's default font family.
+
+ Returns the family name actually installed (``"sans-serif"`` meaning the
+ CJK face is resolved, or ``_FALLBACK_FAMILY`` when we gave up).
+ """
+ try:
+ import matplotlib
+ matplotlib.use("Agg") # safe for headless rendering
+ from matplotlib import font_manager as fm
+ import matplotlib.pyplot as plt
+ except Exception as exc: # pragma: no cover — matplotlib optional
+ logger.warning("matplotlib unavailable: %s", exc)
+ return _FALLBACK_FAMILY
+
+ path = cjk_font_path()
+ if path is None:
+ plt.rcParams["font.family"] = _FALLBACK_FAMILY
+ return _FALLBACK_FAMILY
+
+ try:
+ fm.fontManager.addfont(str(path))
+ prop = fm.FontProperties(fname=str(path))
+ family = prop.get_name()
+ plt.rcParams["font.family"] = family
+ plt.rcParams["axes.unicode_minus"] = False
+ return family
+ except Exception as exc:
+ logger.warning("Failed to register %s with matplotlib: %s", path, exc)
+ plt.rcParams["font.family"] = _FALLBACK_FAMILY
+ return _FALLBACK_FAMILY
+
+
+def cjk_css_font_face() -> str:
+ """Emit an ``@font-face`` CSS block weasyprint can bundle.
+
+ Returns an empty string if no CJK font is resolvable.
+ """
+ path = cjk_font_path()
+ if path is None:
+ return ""
+ uri = path.resolve().as_uri()
+ return (
+ "@font-face {\n"
+ " font-family: 'Shadow CJK';\n"
+ f" src: url('{uri}');\n"
+ "}\n"
+ )
diff --git a/agent/src/shadow_account/models.py b/agent/src/shadow_account/models.py
new file mode 100644
index 000000000..92a0224fc
--- /dev/null
+++ b/agent/src/shadow_account/models.py
@@ -0,0 +1,103 @@
+"""Shadow Account data contracts (frozen dataclasses).
+
+See `docs/shadow-account-spec.md` for the full contract. These types are the
+stable boundary between extractor / codegen / backtester / reporter.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+
+@dataclass(frozen=True)
+class ShadowRule:
+ """One human-readable if-then rule distilled from profitable roundtrips.
+
+ Attributes:
+ rule_id: Stable ID like "R1", "R2".
+ human_text: Chinese natural-language description (<=30 chars).
+ entry_condition: Structured condition dict for codegen. Keys are
+ feature names (e.g. "prior_5d_return", "market"); values are
+ either scalars or (op, value) tuples (e.g. ("<=", -0.08)).
+ exit_condition: Structured exit condition dict.
+ holding_days_range: (min, max) integer days.
+ support_count: Number of profitable roundtrips supporting this rule.
+ coverage_rate: Fraction of all profitable roundtrips this rule covers.
+ sample_trades: Representative "<symbol>@<date>" strings.
+ weight: Signal weight for codegen (default 1.0).
+ """
+
+ rule_id: str
+ human_text: str
+ entry_condition: dict[str, Any]
+ exit_condition: dict[str, Any]
+ holding_days_range: tuple[int, int]
+ support_count: int
+ coverage_rate: float
+ sample_trades: tuple[str, ...]
+ weight: float = 1.0
+
+
+@dataclass(frozen=True)
+class ShadowProfile:
+ """User's extracted trading shadow.
+
+ Attributes:
+ shadow_id: "shadow_<8-hex>" unique ID.
+ created_at: ISO8601 UTC timestamp.
+ journal_hash: SHA1 of the source journal content for idempotency.
+ source_market: Primary market from the journal ("china_a" etc.).
+ profitable_roundtrips: Number of roundtrips used for extraction.
+ total_roundtrips: Total roundtrips in journal.
+ date_range: (start_iso, end_iso) of the journal.
+ profile_text: One-paragraph Chinese portrait for Section 1.
+ rules: Tuple of 3-5 ShadowRule.
+ preferred_markets: Markets the user actually traded, frequency-sorted.
+ typical_holding_days: (median, p75) in days.
+ """
+
+ shadow_id: str
+ created_at: str
+ journal_hash: str
+ source_market: str
+ profitable_roundtrips: int
+ total_roundtrips: int
+ date_range: tuple[str, str]
+ profile_text: str
+ rules: tuple[ShadowRule, ...]
+ preferred_markets: tuple[str, ...]
+ typical_holding_days: tuple[float, float]
+
+ def to_dict(self) -> dict[str, Any]:
+ """Serialize to JSON-safe dict."""
+ return asdict(self)
+
+
+@dataclass(frozen=True)
+class AttributionBreakdown:
+ """Delta PnL attribution between user's realized trades and shadow.
+
+ All PnL fields are in the journal's account currency.
+ """
+
+ missed_signals_pnl: float
+ noise_trades_pnl: float
+ early_exit_pnl: float
+ late_exit_pnl: float
+ overtrading_pnl: float
+ counterfactual_trades: tuple[dict[str, Any], ...] = field(default_factory=tuple)
+
+
+@dataclass(frozen=True)
+class ShadowBacktestResult:
+ """Output of multi-market shadow backtest + attribution."""
+
+ shadow_id: str
+ per_market: dict[str, dict[str, float]]
+ combined: dict[str, float]
+ equity_curves: dict[str, list[tuple[str, float]]]
+ attribution: AttributionBreakdown
+ shadow_total_pnl: float
+ real_total_pnl: float
+ delta_pnl: float
diff --git a/agent/src/shadow_account/reporter.py b/agent/src/shadow_account/reporter.py
new file mode 100644
index 000000000..9db8aa7b3
--- /dev/null
+++ b/agent/src/shadow_account/reporter.py
@@ -0,0 +1,335 @@
+"""Shadow Account — 8-section report rendering (HTML + optional PDF).
+
+The pipeline:
+ ShadowProfile + ShadowBacktestResult (+ optional today signals)
+ → `_build_sections` build a strict dict for the template
+ → `_render_charts` matplotlib PNG files on disk
+ → Jinja2 render HTML
+ → weasyprint → PDF (or HTML-only if weasyprint unusable)
+
+Design:
+ * No hard dependency on weasyprint at import time — if importing or
+ rendering fails, we keep the HTML artifact and return its path.
+ * Charts are optional — any matplotlib failure downgrades gracefully
+ (that section just omits its `<img>`).
+ * Layout/style live in `templates/shadow_report.{html,css}`; this module
+ only decides *what* data to feed them.
+"""
+
+from __future__ import annotations
+
+import logging
+from base64 import b64encode
+from dataclasses import asdict
+from pathlib import Path
+from typing import Any
+
+from jinja2 import Environment, FileSystemLoader, select_autoescape
+
+from src.shadow_account.fonts import apply_matplotlib_cjk_font, cjk_css_font_face
+from src.shadow_account.models import ShadowBacktestResult, ShadowProfile
+from src.shadow_account.storage import reports_dir
+
+logger = logging.getLogger(__name__)
+
+_TEMPLATES_DIR = Path(__file__).parent / "templates"
+_HTML_TEMPLATE = "shadow_report.html"
+_CSS_TEMPLATE = "shadow_report.css"
+
+_MARKET_LABELS = {
+ "china_a": "China A-share",
+ "us": "US equity",
+ "hk": "HK equity",
+ "crypto": "Crypto",
+ "other": "Other",
+}
+
+_REASON_LABELS = {
+ "rule_violation": "Outside any shadow rule",
+ "early_exit": "Exited winner too early",
+ "late_exit": "Held loser too long",
+}
+
+
+# ---------------- Public API ----------------
+
+def render_shadow_report(
+ profile: ShadowProfile,
+ backtest_result: ShadowBacktestResult,
+ *,
+ today_signals: list[dict[str, Any]] | None = None,
+ output_dir: Path | None = None,
+) -> dict[str, Any]:
+ """Render the full Shadow Account report.
+
+ Returns:
+ Dict with keys:
+ ``html_path`` : rendered HTML (always present)
+ ``pdf_path`` : PDF path (present iff weasyprint succeeded)
+ ``sections`` : structured payload (for frontend preview)
+ ``engine`` : "weasyprint" | "html-only"
+ """
+ output_dir = Path(output_dir) if output_dir else reports_dir()
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ # Matplotlib setup must happen before any chart renders.
+ apply_matplotlib_cjk_font()
+
+ assets_dir = output_dir / f"{profile.shadow_id}_assets"
+ assets_dir.mkdir(parents=True, exist_ok=True)
+ charts = _render_charts(profile, backtest_result, assets_dir)
+
+ sections = _build_sections(profile, backtest_result, today_signals or [])
+ css = _load_css()
+
+ html = _env().get_template(_HTML_TEMPLATE).render(
+ css=css,
+ charts=charts,
+ market_labels=_MARKET_LABELS,
+ reason_labels=_REASON_LABELS,
+ **sections,
+ )
+ html_path = output_dir / f"{profile.shadow_id}.html"
+ html_path.write_text(html, encoding="utf-8")
+
+ pdf_path, engine = _try_render_pdf(html, output_dir, profile.shadow_id)
+
+ return {
+ "html_path": str(html_path),
+ "pdf_path": str(pdf_path) if pdf_path else None,
+ "sections": sections,
+ "engine": engine,
+ }
+
+
+# ---------------- Section data ----------------
+
+def _build_sections(
+ profile: ShadowProfile,
+ result: ShadowBacktestResult,
+ today_signals: list[dict[str, Any]],
+) -> dict[str, Any]:
+ """Assemble the strict payload the Jinja template consumes.
+
+ The template expects numeric values for any metrics it formats with
+ ``%f`` — so we strip out non-numeric leak-throughs (e.g. ``error``
+ strings inserted when the backtest runner failed). The error is
+ preserved separately under ``combined_error`` so the template can
+ surface it explicitly.
+ """
+ combined_numeric, combined_error = _split_metrics(result.combined or {})
+ per_market_numeric = {
+ market: _split_metrics(metrics or {})[0]
+ for market, metrics in (result.per_market or {}).items()
+ }
+ return {
+ "profile": profile,
+ "combined_metrics": combined_numeric,
+ "combined_error": combined_error,
+ "per_market_metrics": per_market_numeric,
+ "attribution": result.attribution,
+ "shadow_pnl": result.shadow_total_pnl,
+ "real_pnl": result.real_total_pnl,
+ "delta_pnl": result.delta_pnl,
+ "today_signals": today_signals,
+ }
+
+
+def _split_metrics(metrics: dict[str, Any]) -> tuple[dict[str, float], str]:
+ """Partition a metrics dict into (numeric, error_message)."""
+ numeric: dict[str, float] = {}
+ error_parts: list[str] = []
+ for key, value in metrics.items():
+ if isinstance(value, bool):
+ continue
+ if isinstance(value, (int, float)):
+ numeric[key] = float(value)
+ elif isinstance(value, str):
+ error_parts.append(f"{key}: {value}")
+ return numeric, " | ".join(error_parts)
+
+
+# ---------------- Charts ----------------
+
+def _render_charts(
+ profile: ShadowProfile,
+ result: ShadowBacktestResult,
+ assets_dir: Path,
+) -> dict[str, str]:
+ """Render all charts and return a map section → file URI.
+
+ Any failure is logged and the affected chart is dropped from the map.
+ """
+ charts: dict[str, str] = {}
+ for name, renderer in (
+ ("equity_curve", lambda p: _render_equity_curve(result, p)),
+ ("per_market_bar", lambda p: _render_per_market_bar(result, p)),
+ ("attribution_waterfall", lambda p: _render_attribution_waterfall(result, p)),
+ ):
+ path = assets_dir / f"{name}.png"
+ try:
+ renderer(path)
+ except Exception as exc:
+ logger.warning("Chart %s failed to render: %s", name, exc)
+ continue
+ if path.exists() and path.stat().st_size > 0:
+ charts[name] = path.resolve().as_uri()
+ return charts
+
+
+def _render_equity_curve(result: ShadowBacktestResult, path: Path) -> None:
+ curve = result.equity_curves.get("combined") or []
+ if not curve:
+ return
+ import matplotlib.pyplot as plt
+
+ fig, ax = plt.subplots(figsize=(8, 3), dpi=150)
+ dates = [pt[0] for pt in curve]
+ values = [pt[1] for pt in curve]
+ ax.plot(dates, values, color="#1f7a3a", linewidth=1.3)
+ ax.fill_between(dates, values, color="#1f7a3a", alpha=0.08)
+ ax.set_title("Shadow — Portfolio Equity Curve")
+ ax.set_xlabel("")
+ ax.set_ylabel("Equity")
+ ax.grid(True, linestyle=":", alpha=0.4)
+ # Too many x-ticks looks cluttered; sample down.
+ if len(dates) > 8:
+ step = max(1, len(dates) // 8)
+ ax.set_xticks([dates[i] for i in range(0, len(dates), step)])
+ fig.tight_layout()
+ fig.savefig(path, bbox_inches="tight")
+ plt.close(fig)
+
+
+def _render_per_market_bar(result: ShadowBacktestResult, path: Path) -> None:
+ if not result.per_market:
+ return
+ import matplotlib.pyplot as plt
+
+ markets = list(result.per_market.keys())
+ sharpes = [result.per_market[m].get("sharpe", 0.0) for m in markets]
+ labels = [_MARKET_LABELS.get(m, m) for m in markets]
+
+ fig, ax = plt.subplots(figsize=(8, 3), dpi=150)
+ bars = ax.bar(labels, sharpes, color="#4a5fb0")
+ ax.axhline(0, color="#8a8f99", linewidth=0.8)
+ ax.set_title("Sharpe by Market")
+ ax.grid(True, axis="y", linestyle=":", alpha=0.4)
+ for bar, value in zip(bars, sharpes):
+ ax.text(
+ bar.get_x() + bar.get_width() / 2,
+ bar.get_height(),
+ f"{value:.2f}",
+ ha="center",
+ va="bottom",
+ fontsize=9,
+ )
+ fig.tight_layout()
+ fig.savefig(path, bbox_inches="tight")
+ plt.close(fig)
+
+
+def _render_attribution_waterfall(result: ShadowBacktestResult, path: Path) -> None:
+ attr = result.attribution
+ components = [
+ ("Real PnL", result.real_total_pnl),
+ ("Noise Trades", attr.noise_trades_pnl),
+ ("Early Exit", attr.early_exit_pnl),
+ ("Late Exit", attr.late_exit_pnl),
+ ("Overtrading", attr.overtrading_pnl),
+ ("Missed Signals", attr.missed_signals_pnl),
+ ("Shadow PnL", result.shadow_total_pnl),
+ ]
+ if all(value == 0.0 for _, value in components):
+ return
+ import matplotlib.pyplot as plt
+
+ labels = [c[0] for c in components]
+ values = [c[1] for c in components]
+ # Waterfall bases: cumulative start for the intermediate bars.
+ bases = [0.0]
+ running = values[0]
+ for v in values[1:-1]:
+ bases.append(running)
+ running += v
+ bases.append(0.0)
+
+ accent = "#4a5fb0"
+ pos = "#1f7a3a"
+ neg = "#c1392b"
+ grid = "#8a8f99"
+ bg = "#ffffff"
+
+ colors = []
+ for idx, v in enumerate(values):
+ if idx in (0, len(values) - 1):
+ colors.append(accent)
+ else:
+ colors.append(pos if v > 0 else neg)
+
+ fig, ax = plt.subplots(figsize=(8, 3.2), dpi=150, facecolor=bg)
+ ax.bar(labels, values, bottom=bases, color=colors, edgecolor="none", width=0.55)
+ ax.axhline(0, color=grid, linewidth=0.8)
+ ax.set_title("Delta Attribution (positive = shadow would outperform)")
+ ax.grid(True, axis="y", linestyle=":", alpha=0.4)
+ plt.setp(ax.get_xticklabels(), rotation=18, ha="right")
+ fig.tight_layout()
+ fig.savefig(path, bbox_inches="tight", facecolor=bg)
+ plt.close(fig)
+
+
+# ---------------- Templating ----------------
+
+def _env() -> Environment:
+ return Environment(
+ loader=FileSystemLoader(str(_TEMPLATES_DIR)),
+ autoescape=select_autoescape(enabled_extensions=("html", "xml")),
+ trim_blocks=True,
+ lstrip_blocks=True,
+ )
+
+
+def _load_css() -> str:
+ """Load CSS, prepending a CJK ``@font-face`` if we have a font."""
+ css = (_TEMPLATES_DIR / _CSS_TEMPLATE).read_text(encoding="utf-8")
+ font_face = cjk_css_font_face()
+ return font_face + "\n" + css
+
+
+def _try_render_pdf(
+ html: str, output_dir: Path, shadow_id: str,
+) -> tuple[Path | None, str]:
+ """Render PDF via weasyprint, returning (path|None, engine_name)."""
+ try:
+ from weasyprint import HTML # type: ignore[import-not-found]
+ except Exception as exc: # pragma: no cover — import-level failure
+ logger.warning("weasyprint unavailable (%s); HTML-only output.", exc)
+ return None, "html-only"
+
+ pdf_path = output_dir / f"{shadow_id}.pdf"
+ try:
+ HTML(string=html, base_url=str(_TEMPLATES_DIR)).write_pdf(str(pdf_path))
+ except Exception as exc:
+ logger.warning("weasyprint render failed (%s); HTML-only output.", exc)
+ if pdf_path.exists():
+ try:
+ pdf_path.unlink()
+ except OSError:
+ pass
+ return None, "html-only"
+ return pdf_path, "weasyprint"
+
+
+# ---------------- Convenience ----------------
+
+def embed_image_as_data_uri(path: Path) -> str:
+ """Inline an image as a data URI (useful when file URIs are rejected)."""
+ blob = Path(path).read_bytes()
+ encoded = b64encode(blob).decode("ascii")
+ return f"data:image/png;base64,{encoded}"
+
+
+# Keep this helper exported to simplify downstream inspection.
+def result_as_dict(result: ShadowBacktestResult) -> dict[str, Any]:
+ """Dict-serialize a backtest result (handy for frontend debugging)."""
+ return asdict(result)
diff --git a/agent/src/shadow_account/scanner.py b/agent/src/shadow_account/scanner.py
new file mode 100644
index 000000000..66e1c958b
--- /dev/null
+++ b/agent/src/shadow_account/scanner.py
@@ -0,0 +1,74 @@
+"""Shadow Account — today signals scanner.
+
+Deterministic, data-free MVP: for each rule in a profile, pick up to N
+symbols from the market's liquid basket that are "in phase" with the
+rule's holding cadence on the target date. No external price fetches.
+
+Future work: swap the phase test for a real feature check (e.g. the
+rule's entry condition evaluated on the most recent bar).
+"""
+
+from __future__ import annotations
+
+from datetime import date, datetime
+from typing import Any
+
+from src.shadow_account.backtester import _LIQUID_BASKETS, SUPPORTED_MARKETS
+from src.shadow_account.models import ShadowProfile, ShadowRule
+
+
+def scan_today_signals(
+ profile: ShadowProfile,
+ *,
+ target_date: str | date | None = None,
+ per_market: int = 3,
+) -> list[dict[str, Any]]:
+ """Return a list of {symbol, market, rule_id, reason} matches.
+
+ Args:
+ profile: ShadowProfile holding the rules.
+ target_date: ISO "YYYY-MM-DD" string, date object, or None (today).
+ per_market: Cap per market bucket.
+
+ Returns:
+ Possibly-empty list of matched candidates. Always research-only —
+ callers should surface the disclaimer from the skill.
+ """
+ if target_date is None:
+ d = date.today()
+ elif isinstance(target_date, date):
+ d = target_date
+ else:
+ d = datetime.strptime(str(target_date), "%Y-%m-%d").date()
+
+ matches: list[dict[str, Any]] = []
+ for rule in profile.rules:
+ market = rule.entry_condition.get("market", "other")
+ if market not in SUPPORTED_MARKETS:
+ continue
+ basket = _LIQUID_BASKETS.get(market, [])
+ if not _date_in_phase(d, rule):
+ continue
+ lo, hi = rule.holding_days_range
+ reason = f"Within {rule.rule_id} entry window (hold {lo}-{hi}d)"
+ for symbol in basket[:per_market]:
+ matches.append({
+ "symbol": symbol,
+ "market": market,
+ "rule_id": rule.rule_id,
+ "reason": reason,
+ })
+ return matches
+
+
+def _date_in_phase(target: date, rule: ShadowRule) -> bool:
+ """True when `target`'s ordinal mod `2 * hold_median` is inside the entry band.
+
+ This keeps the scanner deterministic and reviewable without needing
+ real-time market data.
+ """
+ lo, hi = rule.holding_days_range
+ hold = max(1, int((lo + hi) / 2))
+ period = max(2, 2 * hold)
+ phase = target.toordinal() % period
+ return phase < hold
diff --git a/agent/src/shadow_account/storage.py b/agent/src/shadow_account/storage.py
new file mode 100644
index 000000000..9a4d4087a
--- /dev/null
+++ b/agent/src/shadow_account/storage.py
@@ -0,0 +1,128 @@
+"""Shadow Account persistence (~/.vibe-trading/shadow_accounts/).
+
+Layout:
+ ~/.vibe-trading/shadow_accounts/<shadow_id>.json ShadowProfile
+ ~/.vibe-trading/shadow_runs/<shadow_id>/ backtest run dir
+ ~/.vibe-trading/shadow_reports/<shadow_id>.pdf rendered report
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from src.shadow_account.models import ShadowProfile, ShadowRule
+
+
+def _root() -> Path:
+ """Return the Shadow Account root directory (auto-created)."""
+ root = Path.home() / ".vibe-trading"
+ root.mkdir(parents=True, exist_ok=True)
+ return root
+
+
+def profiles_dir() -> Path:
+ d = _root() / "shadow_accounts"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def runs_dir(shadow_id: str) -> Path:
+ d = _root() / "shadow_runs" / shadow_id
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def reports_dir() -> Path:
+ d = _root() / "shadow_reports"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def new_shadow_id() -> str:
+ """Mint a fresh shadow_id."""
+ return f"shadow_{uuid.uuid4().hex[:8]}"
+
+
+def hash_journal(journal_path: Path | str) -> str:
+ """SHA1 over the raw journal bytes for idempotent extraction."""
+ p = Path(journal_path)
+ h = hashlib.sha1()
+ with p.open("rb") as f:
+ for chunk in iter(lambda: f.read(65536), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def now_iso() -> str:
+ """UTC ISO8601 timestamp (seconds precision)."""
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
+
+
+def save_profile(profile: ShadowProfile) -> Path:
+ """Persist a ShadowProfile to disk as JSON."""
+ path = profiles_dir() / f"{profile.shadow_id}.json"
+ path.write_text(
+ json.dumps(profile.to_dict(), ensure_ascii=False, indent=2, default=str),
+ encoding="utf-8",
+ )
+ return path
+
+
+def load_profile(shadow_id: str) -> ShadowProfile:
+ """Load a ShadowProfile back from disk.
+
+ Raises:
+ FileNotFoundError: No profile with that id.
+ """
+ path = profiles_dir() / f"{shadow_id}.json"
+ if not path.exists():
+ raise FileNotFoundError(f"Shadow profile not found: {shadow_id}")
+ data: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
+ rules = tuple(
+ ShadowRule(
+ rule_id=r["rule_id"],
+ human_text=r["human_text"],
+ entry_condition=r["entry_condition"],
+ exit_condition=r["exit_condition"],
+ holding_days_range=tuple(r["holding_days_range"]),
+ support_count=r["support_count"],
+ coverage_rate=r["coverage_rate"],
+ sample_trades=tuple(r["sample_trades"]),
+ weight=r.get("weight", 1.0),
+ )
+ for r in data["rules"]
+ )
+ return ShadowProfile(
+ shadow_id=data["shadow_id"],
+ created_at=data["created_at"],
+ journal_hash=data["journal_hash"],
+ source_market=data["source_market"],
+ profitable_roundtrips=data["profitable_roundtrips"],
+ total_roundtrips=data["total_roundtrips"],
+ date_range=tuple(data["date_range"]),
+ profile_text=data["profile_text"],
+ rules=rules,
+ preferred_markets=tuple(data["preferred_markets"]),
+ typical_holding_days=tuple(data["typical_holding_days"]),
+ )
+
+
+def find_by_journal_hash(journal_hash: str) -> ShadowProfile | None:
+ """Return the most recent profile sharing this journal_hash, else None."""
+ latest: ShadowProfile | None = None
+ for path in profiles_dir().glob("*.json"):
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ continue
+ if data.get("journal_hash") != journal_hash:
+ continue
+ candidate = load_profile(data["shadow_id"])
+ if latest is None or candidate.created_at > latest.created_at:
+ latest = candidate
+ return latest
diff --git a/agent/src/shadow_account/templates/shadow_report.css b/agent/src/shadow_account/templates/shadow_report.css
new file mode 100644
index 000000000..a4df70bf0
--- /dev/null
+++ b/agent/src/shadow_account/templates/shadow_report.css
@@ -0,0 +1,339 @@
+:root {
+ --bg: #0b0d12;
+ --surface: #12151c;
+ --surface2: #1a1f29;
+ --border: #242a36;
+ --text: #e6e9ef;
+ --text-dim: #9099a8;
+ --text-mute:#5f6878;
+ --accent: #6aa8ff;
+ --pos: #3dd68c;
+ --neg: #ff7b6b;
+ --warn: #f4b454;
+ --mono: 'JetBrains Mono', 'SF Mono', 'Consolas', 'Menlo', monospace;
+ --sans: 'Inter', 'SF Pro Text', -apple-system, 'Segoe UI', 'Roboto', sans-serif;
+}
+
+@page {
+ size: A4;
+ margin: 14mm 12mm;
+ @bottom-right {
+ content: "Shadow Account " counter(page) " / " counter(pages);
+ font-size: 7.5pt;
+ color: var(--text-mute);
+ font-family: var(--mono);
+ letter-spacing: 0.3pt;
+ }
+}
+
+* { box-sizing: border-box; }
+
+body {
+ font-family: var(--sans);
+ color: var(--text);
+ background: var(--bg);
+ font-size: 10pt;
+ line-height: 1.55;
+ margin: 0;
+ -webkit-font-smoothing: antialiased;
+}
+
+.mono {
+ font-family: var(--mono);
+ font-variant-numeric: tabular-nums;
+ font-size: 9.5pt;
+}
+
+/* ============ Cover ============ */
+
+header.cover {
+ padding: 20mm 14mm 18mm;
+ margin: -14mm -12mm 0 -12mm;
+ background:
+ radial-gradient(1200px 400px at 15% 0%, rgba(106,168,255,0.18), transparent 60%),
+ radial-gradient(900px 350px at 100% 0%, rgba(255,123,107,0.10), transparent 55%),
+ linear-gradient(180deg, #0e1119 0%, #0b0d12 100%);
+ border-bottom: 1pt solid var(--border);
+ page-break-after: always;
+ position: relative;
+}
+
+header.cover::before {
+ content: "";
+ position: absolute;
+ top: 0; left: 0; right: 0;
+ height: 2pt;
+ background: linear-gradient(90deg, var(--accent), #b46aff 50%, var(--neg));
+}
+
+.eyebrow {
+ font-family: var(--mono);
+ font-size: 8.5pt;
+ letter-spacing: 4pt;
+ text-transform: uppercase;
+ color: var(--accent);
+ margin: 0 0 6mm;
+}
+
+h1 {
+ font-size: 38pt;
+ font-weight: 700;
+ letter-spacing: -1pt;
+ margin: 0 0 4mm;
+ line-height: 1.05;
+ color: #fafbfd;
+}
+
+.subtitle {
+ font-family: var(--mono);
+ font-size: 9pt;
+ color: var(--text-mute);
+ margin: 0 0 14mm;
+ letter-spacing: 0.3pt;
+}
+
+.cover-delta {
+ padding: 14mm 12mm;
+ background: var(--surface);
+ border: 1pt solid var(--border);
+ border-radius: 4pt;
+ text-align: center;
+ margin-bottom: 10mm;
+ position: relative;
+ overflow: hidden;
+}
+
+.cover-delta::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: radial-gradient(600px 200px at 50% 120%, rgba(61,214,140,0.08), transparent 70%);
+ pointer-events: none;
+}
+
+.delta-label {
+ font-family: var(--mono);
+ font-size: 8.5pt;
+ color: var(--text-mute);
+ letter-spacing: 3pt;
+ text-transform: uppercase;
+ margin-bottom: 4mm;
+}
+
+.delta-value {
+ font-family: var(--mono);
+ font-size: 52pt;
+ font-weight: 700;
+ line-height: 1;
+ letter-spacing: -2pt;
+ margin: 2mm 0 4mm;
+}
+
+.delta-value.positive { color: var(--pos); }
+.delta-value.negative { color: var(--neg); }
+
+.delta-caption {
+ font-family: var(--mono);
+ font-size: 9pt;
+ color: var(--text-dim);
+ letter-spacing: 0.3pt;
+}
+
+header.cover .disclaimer {
+ font-size: 8pt;
+ color: var(--warn);
+ margin-top: 10mm;
+ padding: 3mm 5mm;
+ background: rgba(244,180,84,0.08);
+ border-left: 2pt solid var(--warn);
+ border-radius: 2pt;
+}
+
+/* ============ Panels ============ */
+
+section.panel {
+ page-break-inside: avoid;
+ padding: 8mm 0 6mm;
+ border-bottom: 1pt solid var(--border);
+}
+
+section.panel:last-of-type {
+ border-bottom: none;
+}
+
+section.panel.gut-punch {
+ background: linear-gradient(180deg, rgba(255,123,107,0.06), rgba(255,123,107,0.02));
+ border-left: 2pt solid var(--neg);
+ padding: 7mm 7mm 6mm;
+ border-radius: 2pt;
+ margin: 3mm -3mm;
+}
+
+h2 {
+ font-size: 13pt;
+ font-weight: 600;
+ margin: 0 0 4mm;
+ letter-spacing: -0.2pt;
+ color: #f0f3f8;
+}
+
+h2::before {
+ content: "";
+ display: inline-block;
+ width: 3pt;
+ height: 10pt;
+ background: var(--accent);
+ margin-right: 3mm;
+ vertical-align: -1pt;
+ border-radius: 1pt;
+}
+
+.panel.gut-punch h2::before { background: var(--neg); }
+
+.lede {
+ font-size: 10.5pt;
+ color: var(--text);
+ margin: 0 0 4mm;
+ max-width: 165mm;
+}
+
+.lede strong {
+ font-family: var(--mono);
+ font-weight: 600;
+}
+
+.lede strong.positive { color: var(--pos); }
+.lede strong.negative { color: var(--neg); }
+
+/* ============ Fact list ============ */
+
+dl.facts {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ column-gap: 8mm;
+ row-gap: 2mm;
+ margin: 3mm 0 0;
+ padding: 4mm 5mm;
+ background: var(--surface);
+ border: 1pt solid var(--border);
+ border-radius: 3pt;
+}
+
+dl.facts dt {
+ font-family: var(--mono);
+ font-size: 8.5pt;
+ color: var(--text-mute);
+ text-transform: uppercase;
+ letter-spacing: 0.5pt;
+}
+
+dl.facts dd {
+ margin: 0;
+ font-size: 9.5pt;
+ color: var(--text);
+}
+
+/* ============ Tables ============ */
+
+table {
+ width: 100%;
+ border-collapse: separate;
+ border-spacing: 0;
+ font-size: 9pt;
+ margin-top: 2mm;
+ background: var(--surface);
+ border: 1pt solid var(--border);
+ border-radius: 3pt;
+ overflow: hidden;
+}
+
+thead th {
+ background: var(--surface2);
+ font-family: var(--mono);
+ font-size: 7.5pt;
+ font-weight: 500;
+ color: var(--text-mute);
+ letter-spacing: 1pt;
+ text-transform: uppercase;
+ padding: 2.5mm 3mm;
+ text-align: left;
+ border-bottom: 1pt solid var(--border);
+}
+
+tbody td, tbody th {
+ padding: 2mm 3mm;
+ border-bottom: 1pt solid rgba(36,42,54,0.6);
+ vertical-align: top;
+}
+
+tbody tr:last-child td, tbody tr:last-child th {
+ border-bottom: none;
+}
+
+table.metrics tbody th {
+ font-family: var(--mono);
+ font-size: 8.5pt;
+ color: var(--text-mute);
+ font-weight: 500;
+ width: 45%;
+ text-transform: none;
+ letter-spacing: 0;
+}
+
+tbody td.mono {
+ color: var(--text);
+}
+
+tbody td.pos, .pos { color: var(--pos); }
+tbody td.neg, .neg { color: var(--neg); }
+
+/* ============ Charts ============ */
+
+img.chart {
+ display: block;
+ width: 100%;
+ max-height: 78mm;
+ object-fit: contain;
+ margin: 3mm 0;
+ background: var(--surface);
+ border: 1pt solid var(--border);
+ border-radius: 3pt;
+ padding: 2mm;
+}
+
+/* ============ Misc ============ */
+
+.muted {
+ color: var(--text-mute);
+ font-size: 9pt;
+ font-style: italic;
+ padding: 2mm 3mm;
+ background: rgba(95,104,120,0.08);
+ border-radius: 2pt;
+}
+
+.panel .disclaimer {
+ font-size: 8pt;
+ color: var(--warn);
+ font-family: var(--mono);
+ margin: 3mm 0 0;
+ padding: 2mm 3mm;
+ background: rgba(244,180,84,0.07);
+ border-left: 2pt solid var(--warn);
+ letter-spacing: 0.2pt;
+}
+
+.caveats {
+ margin: 3mm 0 0;
+ padding-left: 6mm;
+}
+
+.caveats li {
+ margin-bottom: 2mm;
+ color: var(--text-dim);
+ font-size: 9.5pt;
+}
+
+.caveats li::marker {
+ color: var(--accent);
+}
diff --git a/agent/src/shadow_account/templates/shadow_report.html b/agent/src/shadow_account/templates/shadow_report.html
new file mode 100644
index 000000000..83ae1650b
--- /dev/null
+++ b/agent/src/shadow_account/templates/shadow_report.html
@@ -0,0 +1,171 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>Shadow Account Report - {{ profile.shadow_id }}</title>
+ <style>{{ css }}</style>
+</head>
+<body>
+ <header class="cover">
+ <p class="eyebrow">Shadow Account Report</p>
+ <h1>You vs Your Shadow</h1>
+ <p class="subtitle">{{ profile.shadow_id }} | {{ profile.created_at }}</p>
+ <div class="cover-delta">
+ <div class="delta-label">Delta PnL</div>
+ <div class="delta-value {{ 'positive' if delta_pnl > 0 else 'negative' }}">
+ {{ '%+.2f' | format(delta_pnl) }}
+ </div>
+ <div class="delta-caption">Shadow {{ '%.2f' | format(shadow_pnl) }} | Real {{ '%.2f' | format(real_pnl) }}</div>
+ </div>
+ <p class="disclaimer">Research use only - not investment advice. Data window: {{ profile.date_range[0] }} -> {{ profile.date_range[1] }}</p>
+ </header>
+
+ <section class="panel">
+ <h2>1. Your Shadow Profile</h2>
+ <p class="lede">{{ profile.profile_text }}</p>
+ <dl class="facts">
+ <dt>Profitable roundtrips</dt><dd>{{ profile.profitable_roundtrips }} / {{ profile.total_roundtrips }}</dd>
+ <dt>Primary market</dt><dd>{{ market_labels[profile.source_market] | default(profile.source_market) }}</dd>
+ <dt>Holding median / p75</dt><dd>{{ '%.1f' | format(profile.typical_holding_days[0]) }}d / {{ '%.1f' | format(profile.typical_holding_days[1]) }}d</dd>
+ <dt>Preferred markets</dt><dd>{% for m in profile.preferred_markets %}{{ market_labels[m] | default(m) }}{% if not loop.last %}, {% endif %}{% endfor %}</dd>
+ </dl>
+ </section>
+
+ <section class="panel">
+ <h2>2. Shadow Rules</h2>
+ <table class="rules">
+ <thead>
+ <tr><th>ID</th><th>Rule</th><th>Support</th><th>Coverage</th><th>Holding</th></tr>
+ </thead>
+ <tbody>
+ {% for rule in profile.rules %}
+ <tr>
+ <td class="mono">{{ rule.rule_id }}</td>
+ <td>{{ rule.human_text }}</td>
+ <td class="mono">{{ rule.support_count }}</td>
+ <td class="mono">{{ '%.0f%%' | format(rule.coverage_rate * 100) }}</td>
+ <td class="mono">{{ rule.holding_days_range[0] }}-{{ rule.holding_days_range[1] }}d</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </section>
+
+ <section class="panel">
+ <h2>3. Shadow Backtest - Combined</h2>
+ {% if charts.equity_curve %}
+ <img class="chart" src="{{ charts.equity_curve }}" alt="equity curve"/>
+ {% endif %}
+ {% if combined_error %}
+ <p class="muted">Backtest warning: {{ combined_error }}</p>
+ {% endif %}
+ {% if combined_metrics %}
+ <table class="metrics">
+ {% for key, value in combined_metrics.items() %}
+ <tr><th>{{ key }}</th><td class="mono">{{ '%.4f' | format(value) }}</td></tr>
+ {% endfor %}
+ </table>
+ {% else %}
+ <p class="muted">Backtest produced no usable metrics (see warning above).</p>
+ {% endif %}
+ </section>
+
+ <section class="panel">
+ <h2>4. Shadow Backtest - By Market</h2>
+ {% if charts.per_market_bar %}
+ <img class="chart" src="{{ charts.per_market_bar }}" alt="per-market bar"/>
+ {% endif %}
+ <table class="metrics">
+ <thead>
+ <tr><th>Market</th><th>Sharpe</th><th>Annual</th><th>Max Drawdown</th></tr>
+ </thead>
+ <tbody>
+ {% for market, metrics in per_market_metrics.items() %}
+ <tr>
+ <td>{{ market_labels[market] | default(market) }}</td>
+ <td class="mono">{{ '%.2f' | format(metrics.get('sharpe', 0.0)) }}</td>
+ <td class="mono">{{ '%.2f%%' | format(metrics.get('annual_return', 0.0) * 100) }}</td>
+ <td class="mono">{{ '%.2f%%' | format(metrics.get('max_drawdown', 0.0) * 100) }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </section>
+
+ <section class="panel gut-punch">
+ <h2>5. You vs Shadow - Delta Attribution</h2>
+ <p class="lede">Shadow PnL <strong class="{{ 'pos' if shadow_pnl > 0 else 'neg' if shadow_pnl < 0 else '' }}">{{ '%+.2f' | format(shadow_pnl) }}</strong>, your real PnL <strong class="{{ 'pos' if real_pnl > 0 else 'neg' if real_pnl < 0 else '' }}">{{ '%+.2f' | format(real_pnl) }}</strong>, delta <strong class="{{ 'pos' if delta_pnl > 0 else 'neg' if delta_pnl < 0 else '' }}">{{ '%+.2f' | format(delta_pnl) }}</strong>.</p>
+ {% if charts.attribution_waterfall %}
+ <img class="chart" src="{{ charts.attribution_waterfall }}" alt="attribution waterfall"/>
+ {% endif %}
+ <table class="metrics">
+ <tr><th>Noise trades</th><td class="mono {{ 'pos' if attribution.noise_trades_pnl > 0 else 'neg' if attribution.noise_trades_pnl < 0 else '' }}">{{ '%+.2f' | format(attribution.noise_trades_pnl) }}</td></tr>
+ <tr><th>Early exit (winners)</th><td class="mono {{ 'pos' if attribution.early_exit_pnl > 0 else 'neg' if attribution.early_exit_pnl < 0 else '' }}">{{ '%+.2f' | format(attribution.early_exit_pnl) }}</td></tr>
+ <tr><th>Late exit (losers)</th><td class="mono {{ 'pos' if attribution.late_exit_pnl > 0 else 'neg' if attribution.late_exit_pnl < 0 else '' }}">{{ '%+.2f' | format(attribution.late_exit_pnl) }}</td></tr>
+ <tr><th>Overtrading</th><td class="mono {{ 'pos' if attribution.overtrading_pnl > 0 else 'neg' if attribution.overtrading_pnl < 0 else '' }}">{{ '%+.2f' | format(attribution.overtrading_pnl) }}</td></tr>
+ <tr><th>Missed signals (residual)</th><td class="mono {{ 'pos' if attribution.missed_signals_pnl > 0 else 'neg' if attribution.missed_signals_pnl < 0 else '' }}">{{ '%+.2f' | format(attribution.missed_signals_pnl) }}</td></tr>
+ </table>
+ </section>
+
+ <section class="panel">
+ <h2>6. Counterfactual Top 5</h2>
+ {% if attribution.counterfactual_trades %}
+ <table class="rules">
+ <thead>
+ <tr><th>#</th><th>Symbol</th><th>Buy</th><th>Sell</th><th>Hold</th><th>Real PnL</th><th>Impact</th><th>Reason</th></tr>
+ </thead>
+ <tbody>
+ {% for t in attribution.counterfactual_trades %}
+ <tr>
+ <td class="mono">{{ loop.index }}</td>
+ <td>{{ t.symbol }}</td>
+ <td class="mono">{{ t.buy_dt[:10] }}</td>
+ <td class="mono">{{ t.sell_dt[:10] }}</td>
+ <td class="mono">{{ '%.1f' | format(t.hold_days) }}d</td>
+ <td class="mono {{ 'pos' if t.pnl > 0 else 'neg' if t.pnl < 0 else '' }}">{{ '%+.2f' | format(t.pnl) }}</td>
+ <td class="mono {{ 'pos' if t.impact > 0 else 'neg' if t.impact < 0 else '' }}">{{ '%+.2f' | format(t.impact) }}</td>
+ <td>{{ reason_labels.get(t.reason, t.reason) }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% else %}
+ <p class="muted">No material counterfactual trades - every roundtrip falls inside the shadow rules.</p>
+ {% endif %}
+ </section>
+
+ <section class="panel">
+ <h2>7. Today's Signal Scan</h2>
+ {% if today_signals %}
+ <table class="rules">
+ <thead>
+ <tr><th>Symbol</th><th>Market</th><th>Rule</th><th>Reason</th></tr>
+ </thead>
+ <tbody>
+ {% for s in today_signals %}
+ <tr>
+ <td class="mono">{{ s.symbol }}</td>
+ <td>{{ market_labels[s.market] | default(s.market) }}</td>
+ <td class="mono">{{ s.rule_id }}</td>
+ <td>{{ s.reason }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% else %}
+ <p class="muted">No shadow-matching symbols today (or scan skipped).</p>
+ {% endif %}
+ <p class="disclaimer">For research reference only - not a buy/sell recommendation.</p>
+ </section>
+
+ <section class="panel">
+ <h2>8. Confidence &amp; Caveats</h2>
+ <ul class="caveats">
+ <li>Sample size: {{ profile.profitable_roundtrips }} profitable roundtrips support {{ profile.rules | length }} rule(s).</li>
+ <li>Backtest assumptions: slippage/fees use engine defaults; cross-market annualization uses calendar days.</li>
+ <li>Style decay: rules reflect the user's historical window and may not hold in future regimes.</li>
+ <li>Red line: this report is research-only and never routes to any live trading system.</li>
+ </ul>
+ </section>
+</body>
+</html>
diff --git a/agent/src/shadow_account/templates/signal_engine.py.j2 b/agent/src/shadow_account/templates/signal_engine.py.j2
new file mode 100644
index 000000000..048b6815e
--- /dev/null
+++ b/agent/src/shadow_account/templates/signal_engine.py.j2
@@ -0,0 +1,80 @@
+"""Shadow Account generated signal engine — {{ shadow_id }}
+
+Rules distilled from {{ profitable_roundtrips }} profitable roundtrips
+over {{ date_range[0] }} → {{ date_range[1] }}.
+
+This file is auto-generated; do not hand-edit. Regenerate via
+`src.shadow_account.codegen.render_signal_engine`.
+"""
+from __future__ import annotations
+
+import pandas as pd
+
+SHADOW_ID = "{{ shadow_id }}"
+PREFERRED_MARKETS = {{ preferred_markets | tojson }}
+
+RULES = [
+{% for rule in rules %} {
+ "rule_id": "{{ rule.rule_id }}",
+ "market": {{ rule.market | tojson }},
+ "entry_hour_min": {{ rule.entry_hour_min }},
+ "entry_hour_max": {{ rule.entry_hour_max }},
+ "hold_days": {{ rule.hold_days }},
+ "weight": {{ rule.weight }},
+ },
+{% endfor %}]
+
+
+def _market_of(code: str) -> str:
+ """Infer a coarse market bucket from a symbol (matches backtest.runner)."""
+ c = (code or "").upper()
+ if c.endswith(".SH") or c.endswith(".SZ") or c.endswith(".BJ"):
+ return "china_a"
+ if c.endswith(".HK"):
+ return "hk"
+ if "-USDT" in c or "-USD" in c or "/" in c:
+ return "crypto"
+ if c and c[0].isalpha():
+ return "us"
+ return "other"
+
+
+class SignalEngine:
+ """Shadow Account signal engine (rule-replay, daily timeframe).
+
+ For each code we pick the first rule whose market matches, then emit
+ a long signal (= rule.weight) for ``hold_days`` bars every
+ ``2 * hold_days`` bars — a deliberate period-replay of the user's
+ profitable holding cadence. Non-matching codes yield a zero series.
+ """
+
+ def generate(self, data_map: dict) -> dict:
+ signals: dict[str, pd.Series] = {}
+ for code, df in data_map.items():
+ sig = pd.Series(0.0, index=df.index)
+ rule = self._pick_rule(code)
+ if rule is not None:
+ sig = self._replay_rule(df.index, rule)
+ signals[code] = sig
+ return signals
+
+ def _pick_rule(self, code: str) -> dict | None:
+ market = _market_of(code)
+ for rule in RULES:
+ if rule["market"] == market or rule["market"] == "other":
+ return rule
+ # Fallback: first rule, regardless of market match.
+ return RULES[0] if RULES else None
+
+ @staticmethod
+ def _replay_rule(index: pd.Index, rule: dict) -> pd.Series:
+ hold = max(1, int(rule["hold_days"]))
+ period = max(2, hold * 2)
+ weight = float(rule["weight"])
+ values = [0.0] * len(index)
+ i = 0
+ while i < len(index):
+ for j in range(i, min(i + hold, len(index))):
+ values[j] = weight
+ i += period
+ return pd.Series(values, index=index)
diff --git a/agent/src/skills/shadow-account/SKILL.md b/agent/src/skills/shadow-account/SKILL.md
new file mode 100644
index 000000000..1ad474ca9
--- /dev/null
+++ b/agent/src/skills/shadow-account/SKILL.md
@@ -0,0 +1,79 @@
+---
+name: shadow-account
+description: "Shadow Account — 从用户交割单提炼盈利模式(3-5 条人话规则)→ 跨 A股/港股/美股/crypto 多市场回测 → 差值归因 → 8-section PDF 报告。叙事:你的影子,没有情绪噪音。"
+category: analysis
+---
+
+# Shadow Account — 影子账户
+
+## 何时触发
+
+当用户说 "提炼我的策略" / "训练影子" / "我的打法回测一下" / "我能多赚多少" / "我的盈利模式" 时,加载此 skill。
+
+**前提**:用户已上传交割单且 `analyze_trade_journal` 已跑过。若没有,先跑 Phase 4a 工具。
+
+## 工作流(四步)
+
+1. `extract_shadow_strategy(journal_path=...)`
+ - 返回 `shadow_id` + 3-5 条人话规则
+ - 向用户 confirm:"这些规则像你本人吗?" 如果用户说"不像",提高 `min_support` 重跑
+2. `run_shadow_backtest(shadow_id=..., journal_path=...)`
+ - 返回 per-market 指标 + `delta_pnl` + attribution breakdown
+ - 默认四市场并跑(china_a/hk/us/crypto)
+3. `render_shadow_report(shadow_id=...)`
+ - 生成 HTML + PDF(weasyprint 失败时自动降级成 HTML-only)
+ - 返回 `html_path` / `pdf_path` / `delta_pnl`
+4. (可选)`scan_shadow_signals(shadow_id=...)` — 今日落在影子入场窗口的标的列表(研究用)
+
+## 产出解读
+
+### 规则卡
+每条规则含:`rule_id`、`human_text`(≤30 字)、`support_count`、`coverage_rate`、`holding_days_range`。规则不是"必赚公式",而是"用户盈利时的共性画像"。
+
+### 回测矩阵
+- `per_market`:四市场的 Sharpe/年化/最大回撤
+- `combined`:合并池表现
+- `equity_curve`:净值时序(进入 PDF Section 3)
+
+### 差值归因(PDF Section 5 — gut punch)
+所有数值 signed,正值=影子相对赚更多:
+- `noise_trades_pnl`:不命中任何规则的真实交易累计 PnL(用户的情绪单)
+- `early_exit_pnl`:赢单但持仓 < 规则下限,按不足比例折算的机会成本
+- `late_exit_pnl`:亏单但持仓 > 规则上限,按超额比例折算的放大损失
+- `overtrading_pnl`:超出规则频率的真实交易 PnL
+- `missed_signals_pnl`:残差(shadow_pnl − real_pnl − 上面四项之和)
+
+### 反事实 Top 5
+按 `|impact|` 排序,列出 5 条"最该做没做 / 最不该做却做了"的交易,带具体日期、原因。
+
+## 对话模板
+
+**确认规则**:
+> 从你 {profitable_roundtrips} 笔盈利回合中提炼出这些规则:{rules}。这些看起来像你本人的打法吗?
+
+**展示差值**(Section 5):
+> 影子 PnL **{shadow_pnl:+.0f}** / 你真实 **{real_pnl:+.0f}** / 差值 **{delta_pnl:+.0f}**。其中 **{noise_trades_pnl:+.0f}** 来自不符合你任何盈利规则的"情绪单"。
+
+**今日扫描**(强制附带免责):
+> 今日落在你影子入场节奏的标的:{symbols}。**仅研究用,不是买入建议。**
+
+## 规则翻译 Prompt 模板
+
+当 `extract_shadow_strategy` 被调用时,可以注入一个 `llm_translator` callable 以把结构化 entry_condition 翻译成中文自然语言:
+
+```
+[上下文] 一位散户的盈利回合中,{N} 笔满足同一组条件:
+ market = {market}
+ entry_hour ∈ [{hour_min}, {hour_max}]
+ 持有 {hold_lo}-{hold_hi} 天
+[任务] 用 ≤30 字的中文写一条规则,口吻像用户自述的交易习惯,不要堆术语。
+[输出] 只返回一行规则文本,不要解释。
+```
+
+不注入时走 f-string 模板(见 `extractor._translate_rule`)。
+
+## 红线
+
+- **不落单**:这些工具永远不会对接任何下单通道,仅研究输出
+- **不复制他人策略**:Shadow Account 是"用户自己"的影子,不从社区/公开策略提取规则
+- **样本不足必报错**:profitable roundtrips < 5 → 直接 raise,不编造
diff --git a/agent/src/tools/shadow_account_tool.py b/agent/src/tools/shadow_account_tool.py
new file mode 100644
index 000000000..be168b331
--- /dev/null
+++ b/agent/src/tools/shadow_account_tool.py
@@ -0,0 +1,309 @@
+"""Shadow Account BaseTool wrappers (auto-discovered by `src.tools` registry).
+
+Four tools, all thin — business logic lives in `src.shadow_account`:
+ extract_shadow_strategy → extractor.extract_shadow_profile
+ run_shadow_backtest → backtester.run_shadow_backtest
+ render_shadow_report → reporter.render_shadow_report
+ scan_shadow_signals → scanner.scan_today_signals
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import asdict
+from datetime import date, timedelta
+from pathlib import Path
+from typing import Any
+
+from src.agent.tools import BaseTool
+from src.shadow_account import (
+ extract_shadow_profile,
+ load_profile,
+ render_shadow_report,
+ run_shadow_backtest,
+ save_profile,
+)
+from src.shadow_account.backtester import load_cached_result
+from src.shadow_account.scanner import scan_today_signals
+
+logger = logging.getLogger(__name__)
+
+
+def _err(message: str, **extra: Any) -> str:
+ return json.dumps({"status": "error", "error": message, **extra}, ensure_ascii=False)
+
+
+def _ok(**payload: Any) -> str:
+ return json.dumps({"status": "ok", **payload}, ensure_ascii=False, default=str)
+
+
+# ---------------- Tool 1: extract ----------------
+
+class ExtractShadowStrategyTool(BaseTool):
+ """Extract a Shadow Account profile from a user's trade journal."""
+
+ name = "extract_shadow_strategy"
+ description = (
+ "Extract implicit trading rules from the user's profitable roundtrips "
+ "and produce a Shadow Account profile (3-5 human-readable if-then rules). "
+ "Run `analyze_trade_journal` first if the journal hasn't been parsed. "
+ "Returns shadow_id + rules preview; profile is persisted to "
+ "~/.vibe-trading/shadow_accounts/."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "journal_path": {
+ "type": "string",
+ "description": "Path to the CSV/Excel broker export (同花顺/东方财富/富途/generic).",
+ },
+ "min_support": {
+ "type": "integer",
+ "description": "Minimum profitable roundtrips required to back one rule.",
+ "default": 3,
+ },
+ "max_rules": {
+ "type": "integer",
+ "description": "Maximum number of rules to return (typically 3-5).",
+ "default": 5,
+ },
+ },
+ "required": ["journal_path"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ journal_path = kwargs.get("journal_path")
+ if not journal_path:
+ return _err("journal_path is required")
+ try:
+ profile = extract_shadow_profile(
+ journal_path,
+ min_support=int(kwargs.get("min_support", 3)),
+ max_rules=int(kwargs.get("max_rules", 5)),
+ )
+ except (FileNotFoundError, ValueError) as exc:
+ return _err(str(exc))
+ except Exception as exc: # pragma: no cover — defensive
+ logger.exception("extract_shadow_strategy failed")
+ return _err(f"unexpected error: {exc}")
+
+ save_profile(profile)
+ rules_preview = [
+ {
+ "rule_id": r.rule_id,
+ "human_text": r.human_text,
+ "support_count": r.support_count,
+ "coverage_rate": r.coverage_rate,
+ "holding_days_range": list(r.holding_days_range),
+ }
+ for r in profile.rules
+ ]
+ return _ok(
+ shadow_id=profile.shadow_id,
+ profile_text=profile.profile_text,
+ source_market=profile.source_market,
+ profitable_roundtrips=profile.profitable_roundtrips,
+ total_roundtrips=profile.total_roundtrips,
+ typical_holding_days=list(profile.typical_holding_days),
+ rules=rules_preview,
+ )
+
+
+# ---------------- Tool 2: backtest ----------------
+
+class RunShadowBacktestTool(BaseTool):
+ """Run multi-market backtest for an extracted Shadow Account."""
+
+ name = "run_shadow_backtest"
+ description = (
+ "Run a multi-market backtest (A股/港股/美股/crypto) on a Shadow Account "
+ "profile and compute delta-PnL attribution vs the user's realized trades. "
+ "Requires `extract_shadow_strategy` to have been run first."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "shadow_id": {"type": "string", "description": "Shadow ID returned by extract_shadow_strategy."},
+ "window_start": {
+ "type": "string",
+ "description": "Backtest window start (ISO date). Default: today - 1y.",
+ },
+ "window_end": {
+ "type": "string",
+ "description": "Backtest window end (ISO date). Default: today.",
+ },
+ "markets": {
+ "type": "array",
+ "items": {"type": "string", "enum": ["china_a", "hk", "us", "crypto"]},
+ "description": "Markets to include. Default: all four.",
+ },
+ "journal_path": {
+ "type": "string",
+ "description": "Original journal path (enables attribution). Optional.",
+ },
+ },
+ "required": ["shadow_id"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ shadow_id = kwargs.get("shadow_id")
+ if not shadow_id:
+ return _err("shadow_id is required")
+ try:
+ profile = load_profile(shadow_id)
+ except FileNotFoundError as exc:
+ return _err(str(exc))
+
+ today = date.today()
+ window_end = kwargs.get("window_end") or today.isoformat()
+ window_start = kwargs.get("window_start") or (today - timedelta(days=365)).isoformat()
+ markets = tuple(kwargs.get("markets") or ("china_a", "hk", "us", "crypto"))
+
+ try:
+ result = run_shadow_backtest(
+ profile,
+ window_start=window_start,
+ window_end=window_end,
+ markets=markets,
+ journal_path=kwargs.get("journal_path"),
+ )
+ except ValueError as exc:
+ return _err(str(exc))
+ except Exception as exc: # pragma: no cover — defensive
+ logger.exception("run_shadow_backtest failed")
+ return _err(f"unexpected error: {exc}")
+
+ return _ok(
+ shadow_id=result.shadow_id,
+ window=[window_start, window_end],
+ markets=list(markets),
+ per_market=result.per_market,
+ combined=result.combined,
+ shadow_total_pnl=result.shadow_total_pnl,
+ real_total_pnl=result.real_total_pnl,
+ delta_pnl=result.delta_pnl,
+ attribution=asdict(result.attribution),
+ equity_points=len(result.equity_curves.get("combined", [])),
+ )
+
+
+# ---------------- Tool 3: render ----------------
+
+class RenderShadowReportTool(BaseTool):
+ """Render a Shadow Account PDF report from a completed backtest."""
+
+ name = "render_shadow_report"
+ description = (
+ "Generate the Shadow Account PDF (8 sections + charts) for a shadow_id. "
+ "Requires a backtest to have been run; otherwise the report renders "
+ "with empty metrics. Returns paths to html/pdf + structured JSON."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "shadow_id": {"type": "string"},
+ "include_today_signals": {"type": "boolean", "default": True},
+ "window_start": {"type": "string"},
+ "window_end": {"type": "string"},
+ "journal_path": {"type": "string"},
+ },
+ "required": ["shadow_id"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ shadow_id = kwargs.get("shadow_id")
+ if not shadow_id:
+ return _err("shadow_id is required")
+ try:
+ profile = load_profile(shadow_id)
+ except FileNotFoundError as exc:
+ return _err(str(exc))
+
+ result = load_cached_result(profile.shadow_id)
+ if result is None:
+ today = date.today()
+ window_end = kwargs.get("window_end") or today.isoformat()
+ window_start = kwargs.get("window_start") or (today - timedelta(days=365)).isoformat()
+ try:
+ result = run_shadow_backtest(
+ profile,
+ window_start=window_start,
+ window_end=window_end,
+ journal_path=kwargs.get("journal_path"),
+ )
+ except Exception as exc: # pragma: no cover — defensive
+ logger.warning("backtest failed during report render: %s", exc)
+ from src.shadow_account.models import AttributionBreakdown, ShadowBacktestResult
+ result = ShadowBacktestResult(
+ shadow_id=profile.shadow_id,
+ per_market={}, combined={"error": str(exc)}, equity_curves={},
+ attribution=AttributionBreakdown(
+ missed_signals_pnl=0.0, noise_trades_pnl=0.0, early_exit_pnl=0.0,
+ late_exit_pnl=0.0, overtrading_pnl=0.0, counterfactual_trades=(),
+ ),
+ shadow_total_pnl=0.0, real_total_pnl=0.0, delta_pnl=0.0,
+ )
+
+ today_signals = (
+ scan_today_signals(profile) if kwargs.get("include_today_signals", True) else []
+ )
+ report = render_shadow_report(profile, result, today_signals=today_signals)
+ payload = {
+ "shadow_id": profile.shadow_id,
+ "html_path": report["html_path"],
+ "pdf_path": report["pdf_path"],
+ "engine": report["engine"],
+ "delta_pnl": result.delta_pnl,
+ "report_url": f"/shadow-reports/{profile.shadow_id}",
+ }
+ if report["pdf_path"]:
+ payload["pdf_url"] = f"/shadow-reports/{profile.shadow_id}?format=pdf"
+ return _ok(**payload)
+
+
+# ---------------- Tool 4: scan ----------------
+
+class ScanShadowSignalsTool(BaseTool):
+ """Scan the market for symbols matching a Shadow Account's rules (research only)."""
+
+ name = "scan_shadow_signals"
+ description = (
+ "List today's symbols that fall within the Shadow Account's entry "
+ "cadence (research use only — not a trade recommendation)."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "shadow_id": {"type": "string"},
+ "date": {
+ "type": "string",
+ "description": "ISO YYYY-MM-DD target date. Default: today.",
+ },
+ "per_market": {"type": "integer", "default": 3},
+ },
+ "required": ["shadow_id"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ shadow_id = kwargs.get("shadow_id")
+ if not shadow_id:
+ return _err("shadow_id is required")
+ try:
+ profile = load_profile(shadow_id)
+ except FileNotFoundError as exc:
+ return _err(str(exc))
+
+ target = kwargs.get("date") or None
+ per_market = int(kwargs.get("per_market", 3))
+ signals = scan_today_signals(profile, target_date=target, per_market=per_market)
+ return _ok(
+ shadow_id=profile.shadow_id,
+ target_date=target or "today",
+ matches=signals,
+ disclaimer="Research use only - not investment advice.",
+ )
diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.py
index c1cdf85f4..dfb33a007 100644
--- a/agent/src/tools/trade_journal_tool.py
+++ b/agent/src/tools/trade_journal_tool.py
@@ -31,7 +31,7 @@ logger = logging.getLogger(__name__)
_ALLOWED_EXT = {".csv", ".xlsx", ".xls"}
-def _pair_trades_fifo(df: pd.DataFrame) -> list[dict[str, Any]]:
+def pair_trades_fifo(df: pd.DataFrame) -> list[dict[str, Any]]:
"""Pair buys and sells per symbol using FIFO to compute per-roundtrip PnL.
Args:
@@ -104,7 +104,7 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:
if df.empty:
return {"error": "empty trade journal"}
- rts = _pair_trades_fifo(df)
+ rts = pair_trades_fifo(df)
rts_df = pd.DataFrame(rts)
total_trades = len(df)
@@ -346,7 +346,7 @@ def _compute_behavior(df: pd.DataFrame) -> dict[str, Any]:
"""
if df.empty:
return {"error": "empty trade journal"}
- rts_df = pd.DataFrame(_pair_trades_fifo(df))
+ rts_df = pd.DataFrame(pair_trades_fifo(df))
return {
"disposition_effect": _disposition_effect(rts_df),
"overtrading": _overtrading(df, rts_df),
diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.py
new file mode 100644
index 000000000..1816a669c
--- /dev/null
+++ b/agent/tests/test_shadow_account.py
@@ -0,0 +1,595 @@
+"""Tests for src.shadow_account (Phase 4c — M1).
+
+Fixtures are synthesized in-test via tmp_path; no binary fixtures on disk.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+pytestmark = pytest.mark.filterwarnings(
+ "ignore:Number of distinct clusters.*:UserWarning",
+)
+
+from src.shadow_account import (
+ AttributionBreakdown,
+ ShadowBacktestResult,
+ ShadowProfile,
+ ShadowRule,
+ extract_shadow_profile,
+ find_by_journal_hash,
+ load_profile,
+ render_config,
+ render_shadow_report,
+ render_signal_engine,
+ run_shadow_backtest,
+ save_profile,
+ select_multi_market_codes,
+ validate_generated,
+ write_run_dir,
+)
+from src.shadow_account.models import AttributionBreakdown as _AttrCls
+from src.shadow_account.extractor import MIN_PROFITABLE_ROUNDTRIPS
+
+
+# ---------------- Helpers ----------------
+
+def _write_journal(path: Path, rows: list[dict]) -> Path:
+ """Write a plain-utf8 Tonghuashun-style CSV the parser can ingest."""
+ df = pd.DataFrame(rows)
+ df.to_csv(path, index=False, encoding="utf-8")
+ return path
+
+
+def _make_tonghuashun_rows(trades: list[tuple[str, str, str, float, float]]) -> list[dict]:
+ """Build Tonghuashun-format rows from (datetime, symbol, side, qty, price).
+
+ Tonghuashun requires columns: 成交时间 / 证券代码 / 操作 (see
+ `trade_journal_parsers.parse_tonghuashun`).
+ """
+ out: list[dict] = []
+ for dt_str, symbol, side, qty, price in trades:
+ amount = qty * price
+ out.append({
+ "成交时间": dt_str,
+ "证券代码": symbol,
+ "证券名称": f"标的{symbol}",
+ "操作": "买入" if side == "buy" else "卖出",
+ "成交数量": qty,
+ "成交价格": price,
+ "成交金额": round(amount, 2),
+ "手续费": round(amount * 0.00025, 2),
+ "印花税": round(amount * 0.001, 2) if side == "sell" else 0.0,
+ "过户费": 0.0,
+ })
+ return out
+
+
+# ---------------- Fixtures ----------------
+
+def profitable_journal(tmp_path: Path) -> Path:
+ """15 roundtrips across 5 symbols, all profitable (2% gain each)."""
+ trades: list[tuple[str, str, str, float, float]] = []
+ symbols = ["600519", "000001", "300750", "600036", "000858"]
+ start_day = 1
+ for sym in symbols:
+ for i in range(3):
+ buy_day = start_day + i * 4
+ sell_day = buy_day + 2
+ trades.append((f"2026-01-{buy_day:02d} 10:30:00", sym, "buy", 100.0, 10.0))
+ trades.append((f"2026-01-{sell_day:02d} 14:15:00", sym, "sell", 100.0, 10.2))
+ return _write_journal(tmp_path / "journal_profitable.csv", _make_tonghuashun_rows(trades))
+
+
+def insufficient_journal(tmp_path: Path) -> Path:
+ """Only 2 profitable roundtrips — below MIN_PROFITABLE_ROUNDTRIPS."""
+ trades = [
+ ("2026-01-02 10:30:00", "600519", "buy", 100.0, 10.0),
+ ("2026-01-04 14:15:00", "600519", "sell", 100.0, 10.5),
+ ("2026-01-06 10:30:00", "000001", "buy", 100.0, 20.0),
+ ("2026-01-08 14:15:00", "000001", "sell", 100.0, 20.5),
+ ]
+ return _write_journal(tmp_path / "journal_few.csv", _make_tonghuashun_rows(trades))
+
+
+def no_roundtrips_journal(tmp_path: Path) -> Path:
+ """Only buys, no sells — zero roundtrips."""
+ trades = [
+ ("2026-01-02 10:30:00", "600519", "buy", 100.0, 10.0),
+ ("2026-01-04 10:30:00", "000001", "buy", 50.0, 20.0),
+ ]
+ return _write_journal(tmp_path / "journal_nort.csv", _make_tonghuashun_rows(trades))
+
+
+# ---------------- extract_shadow_profile ----------------
+
+def test_extract_profile_happy_path(profitable_journal: Path) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ assert isinstance(profile, ShadowProfile)
+ assert profile.profitable_roundtrips >= MIN_PROFITABLE_ROUNDTRIPS
+ assert profile.total_roundtrips == profile.profitable_roundtrips # all profitable
+ assert profile.source_market == "china_a"
+ assert profile.shadow_id.startswith("shadow_")
+ assert profile.journal_hash and len(profile.journal_hash) == 40
+ assert profile.typical_holding_days[0] > 0
+ assert profile.profile_text # non-empty portrait
+
+
+def test_extract_profile_yields_rules(profitable_journal: Path) -> None:
+ from src.shadow_account.extractor import RULE_TEXT_MAX
+
+ profile = extract_shadow_profile(profitable_journal, min_support=2, max_rules=5)
+ assert 1 <= len(profile.rules) <= 5
+ for rule in profile.rules:
+ assert isinstance(rule, ShadowRule)
+ assert rule.rule_id.startswith("R")
+ assert rule.human_text # non-empty natural language
+ assert len(rule.human_text) <= RULE_TEXT_MAX
+ assert rule.human_text.isascii(), f"rule text must be English-only: {rule.human_text!r}"
+ assert rule.support_count >= 2
+ assert 0.0 < rule.coverage_rate <= 1.0
+ lo, hi = rule.holding_days_range
+ assert lo >= 1 and hi >= lo
+
+
+def test_extract_profile_rejects_insufficient_sample(insufficient_journal: Path) -> None:
+ with pytest.raises(ValueError, match="Insufficient profitable roundtrips"):
+ extract_shadow_profile(insufficient_journal)
+
+
+def test_extract_profile_rejects_no_roundtrips(no_roundtrips_journal: Path) -> None:
+ with pytest.raises(ValueError, match="No complete buy"):
+ extract_shadow_profile(no_roundtrips_journal)
+
+
+def test_extract_profile_rejects_missing_file(tmp_path: Path) -> None:
+ with pytest.raises(FileNotFoundError):
+ extract_shadow_profile(tmp_path / "does_not_exist.csv")
+
+
+def test_custom_llm_translator_is_used(profitable_journal: Path) -> None:
+ calls: list[dict] = []
+
+ def fake_translator(ctx: dict) -> str:
+ calls.append(ctx)
+ return "Custom shadow rule text"
+
+ profile = extract_shadow_profile(profitable_journal, llm_translator=fake_translator)
+ assert calls, "translator should be invoked at least once"
+ assert all(rule.human_text == "Custom shadow rule text" for rule in profile.rules)
+
+
+# ---------------- Storage round-trip ----------------
+
+def test_profile_roundtrip_persistence(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path)) # Windows
+ profile = extract_shadow_profile(profitable_journal)
+
+ saved_path = save_profile(profile)
+ assert saved_path.exists()
+
+ loaded = load_profile(profile.shadow_id)
+ assert loaded.shadow_id == profile.shadow_id
+ assert loaded.journal_hash == profile.journal_hash
+ assert len(loaded.rules) == len(profile.rules)
+ assert loaded.rules[0].rule_id == profile.rules[0].rule_id
+ assert loaded.preferred_markets == profile.preferred_markets
+
+
+def test_find_by_journal_hash_returns_latest(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ first = extract_shadow_profile(profitable_journal)
+ save_profile(first)
+
+ found = find_by_journal_hash(first.journal_hash)
+ assert found is not None
+ assert found.shadow_id == first.shadow_id
+ assert find_by_journal_hash("nonexistent-hash") is None
+
+
+# ---------------- M2: Codegen ----------------
+
+def test_render_signal_engine_produces_valid_python(profitable_journal: Path) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ source = render_signal_engine(profile)
+
+ ok, err = validate_generated(source)
+ assert ok, f"generated source failed validation: {err}"
+ assert "class SignalEngine" in source
+ assert profile.shadow_id in source
+ assert "def generate" in source
+
+
+def test_validate_generated_rejects_missing_class() -> None:
+ ok, err = validate_generated("x = 1\n")
+ assert not ok
+ assert "SignalEngine" in err
+
+
+def test_validate_generated_rejects_syntax_error() -> None:
+ ok, err = validate_generated("class SignalEngine\n def generate(self, d): pass\n")
+ assert not ok
+ assert "SyntaxError" in err
+
+
+def test_generated_engine_runs_on_mock_data_map(profitable_journal: Path) -> None:
+ """The rendered engine must execute cleanly against a minimal data_map."""
+ import importlib.util
+
+ profile = extract_shadow_profile(profitable_journal)
+ source = render_signal_engine(profile)
+
+ module_path = Path("./_shadow_test_engine.py").resolve()
+ # Use tmp via test's temp dir proxy — write + exec.
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "signal_engine.py"
+ path.write_text(source, encoding="utf-8")
+ spec = importlib.util.spec_from_file_location("gen_signal_engine", path)
+ module = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ spec.loader.exec_module(module)
+ engine = module.SignalEngine()
+
+ idx = pd.date_range("2026-01-02", periods=30, freq="B")
+ data_map = {
+ "600519.SH": pd.DataFrame({"close": range(30)}, index=idx),
+ "AAPL": pd.DataFrame({"close": range(30)}, index=idx),
+ }
+ signals = engine.generate(data_map)
+ assert set(signals.keys()) == set(data_map.keys())
+ for code, series in signals.items():
+ assert isinstance(series, pd.Series)
+ assert len(series) == len(idx)
+ assert (series >= 0).all()
+
+
+def test_render_config_shape(profitable_journal: Path) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ cfg = render_config(
+ profile,
+ codes=["600519.SH", "AAPL"],
+ start_date="2026-01-01",
+ end_date="2026-06-30",
+ )
+ assert cfg["source"] == "auto"
+ assert cfg["engine"] == "daily"
+ assert cfg["codes"] == ["600519.SH", "AAPL"]
+ assert cfg["shadow_id"] == profile.shadow_id
+
+
+def test_write_run_dir_materializes_files(
+ profitable_journal: Path, tmp_path: Path,
+) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ run_dir = write_run_dir(
+ profile,
+ tmp_path / "run",
+ codes=["600519.SH"],
+ start_date="2026-01-01",
+ end_date="2026-06-30",
+ )
+ assert (run_dir / "code" / "signal_engine.py").exists()
+ assert (run_dir / "config.json").exists()
+ cfg = json.loads((run_dir / "config.json").read_text(encoding="utf-8"))
+ assert cfg["shadow_id"] == profile.shadow_id
+
+
+# ---------------- M3: Backtester + Attribution ----------------
+
+def test_select_multi_market_codes_covers_all_markets(profitable_journal: Path) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ selection = select_multi_market_codes(profile, per_market_count=3)
+ assert set(selection.keys()) == {"china_a", "hk", "us", "crypto"}
+ for market, codes in selection.items():
+ assert 1 <= len(codes) <= 3
+ assert all(codes)
+
+
+def test_run_shadow_backtest_with_mocked_runner(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Inject a stub run_backtest_fn that writes artifacts the parser can read."""
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ profile = extract_shadow_profile(profitable_journal)
+
+ def stub_run_backtest(run_dir_str: str) -> str:
+ run_path = Path(run_dir_str)
+ artifacts_dir = run_path / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=True)
+ metrics_path = artifacts_dir / "metrics.json"
+ metrics_path.write_text(json.dumps({
+ "total_return_abs": 12_345.0,
+ "sharpe": 1.5,
+ "max_drawdown": -0.12,
+ "win_rate": 0.55,
+ }), encoding="utf-8")
+ equity_path = artifacts_dir / "equity.csv"
+ equity_path.write_text(
+ "date,equity\n2026-01-02,1000000\n2026-06-30,1012345\n",
+ encoding="utf-8",
+ )
+ return json.dumps({
+ "status": "ok",
+ "exit_code": 0,
+ "artifacts": {
+ "metrics.json": str(metrics_path),
+ "equity.csv": str(equity_path),
+ },
+ })
+
+ result = run_shadow_backtest(
+ profile,
+ window_start="2026-01-01",
+ window_end="2026-06-30",
+ journal_path=profitable_journal,
+ run_backtest_fn=stub_run_backtest,
+ )
+ assert isinstance(result, ShadowBacktestResult)
+ assert result.shadow_id == profile.shadow_id
+ assert set(result.per_market.keys()) == {"china_a", "hk", "us", "crypto"}
+ assert result.combined["total_return_abs"] == 12_345.0
+ assert result.combined["sharpe"] == 1.5
+ assert result.shadow_total_pnl == 12_345.0
+ assert result.real_total_pnl > 0 # all profitable test data
+ assert result.delta_pnl == round(result.shadow_total_pnl - result.real_total_pnl, 2)
+ assert isinstance(result.attribution, AttributionBreakdown)
+ assert len(result.equity_curves["combined"]) == 2
+
+
+def test_run_shadow_backtest_handles_runner_failure(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ profile = extract_shadow_profile(profitable_journal)
+
+ def failing_runner(run_dir_str: str) -> str:
+ return json.dumps({
+ "status": "error",
+ "exit_code": 1,
+ "stderr": "No data fetched",
+ "artifacts": {},
+ })
+
+ result = run_shadow_backtest(
+ profile,
+ window_start="2026-01-01",
+ window_end="2026-06-30",
+ run_backtest_fn=failing_runner,
+ )
+ assert result.combined.get("error")
+ assert result.shadow_total_pnl == 0.0
+ assert result.equity_curves == {}
+
+
+# ---------------- M4: Reporter ----------------
+
+def _stub_backtest_result(profile: ShadowProfile) -> ShadowBacktestResult:
+ return ShadowBacktestResult(
+ shadow_id=profile.shadow_id,
+ per_market={
+ "china_a": {"sharpe": 1.2, "annual_return": 0.15, "max_drawdown": -0.08},
+ "us": {"sharpe": 0.9, "annual_return": 0.11, "max_drawdown": -0.10},
+ },
+ combined={"sharpe": 1.05, "annual_return": 0.13, "max_drawdown": -0.09},
+ equity_curves={"combined": [("2026-01-02", 1_000_000.0), ("2026-06-30", 1_130_000.0)]},
+ attribution=AttributionBreakdown(
+ missed_signals_pnl=50.0,
+ noise_trades_pnl=-120.0,
+ early_exit_pnl=80.0,
+ late_exit_pnl=-20.0,
+ overtrading_pnl=10.0,
+ counterfactual_trades=(
+ {
+ "symbol": "600519.SH", "buy_dt": "2026-02-01", "sell_dt": "2026-02-02",
+ "hold_days": 1.0, "pnl": 100.0, "impact": 50.0, "reason": "early_exit",
+ },
+ ),
+ ),
+ shadow_total_pnl=1500.0,
+ real_total_pnl=1200.0,
+ delta_pnl=300.0,
+ )
+
+
+def test_render_shadow_report_emits_html(profitable_journal: Path, tmp_path: Path) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ result = _stub_backtest_result(profile)
+
+ out = render_shadow_report(profile, result, output_dir=tmp_path)
+ html_path = Path(out["html_path"])
+ assert html_path.exists()
+ content = html_path.read_text(encoding="utf-8")
+ assert "Shadow Account" in content
+ assert profile.shadow_id in content
+ assert "Delta Attribution" in content # Section 5
+ assert "Counterfactual" in content # Section 6
+ assert out["engine"] in ("weasyprint", "html-only")
+
+
+def test_render_shadow_report_includes_today_signals(
+ profitable_journal: Path, tmp_path: Path,
+) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ result = _stub_backtest_result(profile)
+ signals = [
+ {"symbol": "NVDA", "market": "us", "rule_id": "R1", "reason": "匹配影子规则"},
+ ]
+ out = render_shadow_report(profile, result, today_signals=signals, output_dir=tmp_path)
+ content = Path(out["html_path"]).read_text(encoding="utf-8")
+ assert "NVDA" in content
+ assert out["sections"]["today_signals"] == signals
+
+
+def test_render_shadow_report_handles_empty_equity(
+ profitable_journal: Path, tmp_path: Path,
+) -> None:
+ profile = extract_shadow_profile(profitable_journal)
+ result = ShadowBacktestResult(
+ shadow_id=profile.shadow_id,
+ per_market={}, combined={}, equity_curves={},
+ attribution=AttributionBreakdown(
+ missed_signals_pnl=0.0, noise_trades_pnl=0.0, early_exit_pnl=0.0,
+ late_exit_pnl=0.0, overtrading_pnl=0.0, counterfactual_trades=(),
+ ),
+ shadow_total_pnl=0.0, real_total_pnl=0.0, delta_pnl=0.0,
+ )
+ out = render_shadow_report(profile, result, output_dir=tmp_path)
+ assert Path(out["html_path"]).exists()
+ # Section 6 should degrade gracefully when no counterfactuals exist.
+ assert "No material counterfactual" in Path(out["html_path"]).read_text(encoding="utf-8")
+
+
+# ---------------- M5/M6: Tool wrappers + scanner ----------------
+
+def test_shadow_tools_are_auto_discovered() -> None:
+ from src.tools import build_registry
+
+ registry = build_registry()
+ for expected in (
+ "extract_shadow_strategy",
+ "run_shadow_backtest",
+ "render_shadow_report",
+ "scan_shadow_signals",
+ ):
+ assert expected in registry.tool_names, f"{expected} missing from registry"
+
+
+def test_extract_shadow_strategy_tool(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from src.tools.shadow_account_tool import ExtractShadowStrategyTool
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ tool = ExtractShadowStrategyTool()
+ out = json.loads(tool.execute(journal_path=str(profitable_journal)))
+ assert out["status"] == "ok"
+ assert out["shadow_id"].startswith("shadow_")
+ assert len(out["rules"]) >= 1
+ from src.shadow_account.extractor import RULE_TEXT_MAX
+ assert 1 <= len(out["rules"][0]["human_text"]) <= RULE_TEXT_MAX
+
+ # Persistence happened — we can load it back.
+ loaded = load_profile(out["shadow_id"])
+ assert loaded.shadow_id == out["shadow_id"]
+
+
+def test_extract_shadow_strategy_tool_reports_errors(tmp_path: Path) -> None:
+ from src.tools.shadow_account_tool import ExtractShadowStrategyTool
+
+ tool = ExtractShadowStrategyTool()
+ out = json.loads(tool.execute(journal_path=str(tmp_path / "missing.csv")))
+ assert out["status"] == "error"
+ assert "error" in out
+
+
+def test_scan_shadow_signals_tool(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from src.tools.shadow_account_tool import ScanShadowSignalsTool
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ profile = extract_shadow_profile(profitable_journal)
+ save_profile(profile)
+ tool = ScanShadowSignalsTool()
+ out = json.loads(tool.execute(shadow_id=profile.shadow_id, date="2026-04-18"))
+ assert out["status"] == "ok"
+ assert out["disclaimer"]
+ assert isinstance(out["matches"], list)
+
+
+def test_run_shadow_backtest_tool_handles_missing_id() -> None:
+ from src.tools.shadow_account_tool import RunShadowBacktestTool
+
+ out = json.loads(RunShadowBacktestTool().execute(shadow_id="shadow_unknown"))
+ assert out["status"] == "error"
+
+
+def test_shadow_account_skill_shipped() -> None:
+ skill = Path(__file__).resolve().parents[1] / "src" / "skills" / "shadow-account" / "SKILL.md"
+ assert skill.exists()
+ body = skill.read_text(encoding="utf-8")
+ for needle in ("shadow-account", "extract_shadow_strategy", "run_shadow_backtest", "render_shadow_report", "scan_shadow_signals"):
+ assert needle in body, f"skill missing reference to {needle}"
+
+
+def test_context_prompt_references_shadow_account() -> None:
+ from src.agent.context import _SYSTEM_PROMPT # noqa: SLF001 — intentional peek
+
+ assert "Shadow Account" in _SYSTEM_PROMPT
+ assert "extract_shadow_strategy" in _SYSTEM_PROMPT
+ assert "Phase 4b" not in _SYSTEM_PROMPT # stale note should be gone
+
+
+def test_attribution_is_zero_without_journal(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ profile = extract_shadow_profile(profitable_journal)
+
+ def stub_runner(run_dir_str: str) -> str:
+ metrics_path = Path(run_dir_str) / "metrics.json"
+ metrics_path.write_text(json.dumps({"total_return_abs": 0.0}), encoding="utf-8")
+ return json.dumps({
+ "status": "ok",
+ "exit_code": 0,
+ "artifacts": {"metrics.json": str(metrics_path)},
+ })
+
+ result = run_shadow_backtest(
+ profile,
+ window_start="2026-01-01",
+ window_end="2026-06-30",
+ journal_path=None, # disable attribution
+ run_backtest_fn=stub_runner,
+ )
+ assert result.attribution.noise_trades_pnl == 0.0
+ assert result.real_total_pnl == 0.0
+ assert result.attribution.counterfactual_trades == ()
diff --git a/pyproject.toml b/pyproject.toml
index 93a14d60d..685050499 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -50,6 +50,9 @@ dependencies = [
"sse-starlette>=1.6.0",
"fastmcp>=2.0.0",
"ddgs>=6.0.0",
+ "jinja2>=3.1.0",
+ "matplotlib>=3.7.0",
+ "weasyprint>=60.0",
]
[project.urls]
@@ -74,6 +77,9 @@ include = ["src*", "backtest*"]
"skills/**/*.md",
"skills/**/*.yaml",
"skills/**/*.json",
+ "shadow_account/templates/*.j2",
+ "shadow_account/templates/*.html",
+ "shadow_account/templates/*.css",
]
"backtest" = ["*.py"]