Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(shadow): render the report PDF via reportlab when weasyprint cannot run

Yufeng He193349dae981
diff --git a/agent/requirements.txt b/agent/requirements.txt
index 323dca266..01d4bca1a 100644
--- a/agent/requirements.txt
+++ b/agent/requirements.txt
@@ -66,3 +66,5 @@ ddgs>=6.0.0
jinja2>=3.1.0
matplotlib>=3.7.0
weasyprint>=60.0
+# Pure-Python PDF fallback where weasyprint's system pango/cairo libs are missing
+reportlab>=4.0
diff --git a/agent/src/shadow_account/fonts.py b/agent/src/shadow_account/fonts.py
index 864f6f1b2..5eeb21800 100644
--- a/agent/src/shadow_account/fonts.py
+++ b/agent/src/shadow_account/fonts.py
@@ -54,6 +54,11 @@ def _system_cjk_candidates() -> list[Path]:
return candidates
+def system_cjk_candidates() -> list[Path]:
+ """Public alias: reportlab needs this list but not the download path."""
+ return _system_cjk_candidates()
+
+
def cjk_font_path(*, allow_download: bool = True, timeout: float = 10.0) -> Optional[Path]:
"""Resolve a CJK font file path.
diff --git a/agent/src/shadow_account/pdf_fallback.py b/agent/src/shadow_account/pdf_fallback.py
new file mode 100644
index 000000000..dc2c2574d
--- /dev/null
+++ b/agent/src/shadow_account/pdf_fallback.py
@@ -0,0 +1,425 @@
+"""Shadow Account — pure-Python PDF fallback renderer.
+
+weasyprint renders the faithful PDF, but it needs system libraries
+(pango/cairo) that pip cannot install, so hosts without them used to get
+HTML-only reports. This module renders the same section payload with
+reportlab platypus: identical data, intentionally simpler layout. All
+reportlab imports stay inside functions so importing this module costs
+nothing on hosts that never need the fallback.
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any
+from urllib.parse import unquote, urlparse
+from urllib.request import url2pathname
+from xml.sax.saxutils import escape
+
+from .fonts import system_cjk_candidates
+
+logger = logging.getLogger(__name__)
+
+# reportlab's TTFont only understands TrueType-flavored fonts. The first
+# candidate that registers wins; .ttc files are tried with subfontIndex=0.
+_FONT_FAMILY = "VibeShadowCJK"
+_font_ready: bool | None = None # None=unprobed, True=family registered
+
+
+def _ensure_font() -> str:
+ """Register a CJK-capable TTF once and return the family name to use."""
+ global _font_ready
+ if _font_ready:
+ return _FONT_FAMILY
+
+ from reportlab.pdfbase import pdfmetrics
+ from reportlab.pdfbase.ttfonts import TTFont
+
+ for path in system_cjk_candidates():
+ try:
+ pdfmetrics.registerFont(TTFont(_FONT_FAMILY, str(path), subfontIndex=0))
+ except Exception:
+ continue
+ _font_ready = True
+ return _FONT_FAMILY
+
+ logger.warning("No TrueType CJK font found; PDF fallback uses Helvetica.")
+ _font_ready = True
+ return "Helvetica"
+
+
+def _file_uri_to_path(uri: str) -> Path | None:
+ """Convert a file:// URI back to a local path, or None if not a file URI."""
+ parsed = urlparse(uri)
+ if parsed.scheme != "file":
+ return None
+ return Path(url2pathname(unquote(parsed.path)))
+
+
+def _signed(value: float, digits: int = 2) -> str:
+ return f"{value:+.{digits}f}"
+
+
+def _colored(value: float, text: str) -> str:
+ color = "#1f7a3a" if value > 0 else "#c0392b" if value < 0 else "#444444"
+ return f'<font color="{color}">{escape(text)}</font>'
+
+
+def render_pdf_reportlab(
+ *,
+ sections: dict[str, Any],
+ charts: dict[str, str],
+ market_labels: dict[str, str],
+ reason_labels: dict[str, str],
+ pdf_path: Path,
+) -> None:
+ """Render the 8-section shadow report to ``pdf_path`` via reportlab.
+
+ Raises on any failure; the caller decides whether to fall back to
+ HTML-only output.
+ """
+ from reportlab.lib import colors
+ from reportlab.lib.pagesizes import A4
+ from reportlab.lib.styles import ParagraphStyle
+ from reportlab.lib.units import mm
+ from reportlab.platypus import (
+ Image,
+ Paragraph,
+ SimpleDocTemplate,
+ Spacer,
+ Table,
+ TableStyle,
+ )
+
+ family = _ensure_font()
+
+ def style(name: str, size: int, leading: float, **kw: Any) -> ParagraphStyle:
+ return ParagraphStyle(
+ name, fontName=family, fontSize=size, leading=leading, **kw
+ )
+
+ h1 = style("h1", 22, 27, spaceAfter=4 * mm)
+ h2 = style(
+ "h2",
+ 13,
+ 17,
+ spaceBefore=6 * mm,
+ spaceAfter=2.5 * mm,
+ textColor=colors.HexColor("#1a1a2e"),
+ )
+ body = style("body", 9.5, 14)
+ muted = style("muted", 8.5, 12, textColor=colors.HexColor("#777777"))
+ eyebrow = style("eyebrow", 10, 13, textColor=colors.HexColor("#777777"))
+ big = style("big", 20, 24, spaceBefore=2 * mm, spaceAfter=1 * mm)
+ cell = style("cell", 8.5, 11)
+ header_cell = style("hcell", 8.5, 11, textColor=colors.white)
+
+ page_width = A4[0] - 30 * mm
+
+ def para(text: str, st: ParagraphStyle = cell) -> Paragraph:
+ # Caller passes raw strings; markup is only added by _colored.
+ return Paragraph(escape(text), st)
+
+ def make_table(
+ header: list[str], rows: list[list[Any]], widths: list[float] | None = None
+ ) -> Table:
+ data: list[list[Any]] = []
+ if header:
+ data.append([Paragraph(escape(h), header_cell) for h in header])
+ for row in rows:
+ data.append([c if isinstance(c, Paragraph) else para(str(c)) for c in row])
+ col_widths = [w * page_width for w in widths] if widths else None
+ table = Table(data, colWidths=col_widths, repeatRows=1 if header else 0)
+ style_rules = [
+ ("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#cccccc")),
+ ("VALIGN", (0, 0), (-1, -1), "TOP"),
+ ("TOPPADDING", (0, 0), (-1, -1), 3),
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
+ ]
+ if header:
+ style_rules += [
+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1a1a2e")),
+ (
+ "ROWBACKGROUNDS",
+ (0, 1),
+ (-1, -1),
+ [colors.white, colors.HexColor("#f7f7fa")],
+ ),
+ ]
+ else:
+ style_rules.append(
+ (
+ "ROWBACKGROUNDS",
+ (0, 0),
+ (-1, -1),
+ [colors.white, colors.HexColor("#f7f7fa")],
+ )
+ )
+ table.setStyle(TableStyle(style_rules))
+ return table
+
+ def chart_image(key: str) -> Image | None:
+ uri = charts.get(key)
+ if not uri:
+ return None
+ path = _file_uri_to_path(uri)
+ if path is None or not path.exists():
+ return None
+ from reportlab.lib.utils import ImageReader
+
+ width_px, height_px = ImageReader(str(path)).getSize()
+ height = page_width * height_px / width_px
+ return Image(str(path), width=page_width, height=height)
+
+ profile = sections["profile"]
+ attribution = sections["attribution"]
+ shadow_pnl = sections["shadow_pnl"]
+ real_pnl = sections["real_pnl"]
+ delta_pnl = sections["delta_pnl"]
+
+ def market_label(code: str) -> str:
+ return market_labels.get(code, code)
+
+ story: list[Any] = []
+
+ # Cover
+ story.append(Paragraph("Shadow Account Report", eyebrow))
+ story.append(Paragraph("You vs Your Shadow", h1))
+ story.append(para(f"{profile.shadow_id} | {profile.created_at}", muted))
+ story.append(Spacer(1, 3 * mm))
+ story.append(para("Delta PnL", muted))
+ if delta_pnl is not None:
+ story.append(Paragraph(_colored(delta_pnl, _signed(delta_pnl)), big))
+ story.append(para(f"Shadow {shadow_pnl:.2f} | Real {real_pnl:.2f}", muted))
+ else:
+ story.append(
+ para(
+ "unavailable - the shadow backtest produced no usable metrics, "
+ "so no comparison is shown",
+ muted,
+ )
+ )
+ story.append(Spacer(1, 2 * mm))
+ story.append(
+ para(
+ "Research use only - not investment advice. "
+ f"Data window: {profile.date_range[0]} -> {profile.date_range[1]}",
+ muted,
+ )
+ )
+
+ # 1. Profile
+ story.append(Paragraph("1. Your Shadow Profile", h2))
+ story.append(para(profile.profile_text, body))
+ story.append(Spacer(1, 1.5 * mm))
+ facts = [
+ [
+ "Profitable roundtrips",
+ f"{profile.profitable_roundtrips} / {profile.total_roundtrips}",
+ ],
+ ["Primary market", market_label(profile.source_market)],
+ [
+ "Holding median / p75",
+ f"{profile.typical_holding_days[0]:.1f}d / {profile.typical_holding_days[1]:.1f}d",
+ ],
+ [
+ "Preferred markets",
+ ", ".join(market_label(m) for m in profile.preferred_markets),
+ ],
+ ]
+ story.append(make_table([], facts, widths=[0.3, 0.7]))
+
+ # 2. Rules
+ story.append(Paragraph("2. Shadow Rules", h2))
+ rule_rows = [
+ [
+ r.rule_id,
+ para(r.human_text),
+ str(r.support_count),
+ f"{r.coverage_rate * 100:.0f}%",
+ f"{r.holding_days_range[0]}-{r.holding_days_range[1]}d",
+ ]
+ for r in profile.rules
+ ]
+ story.append(
+ make_table(
+ ["ID", "Rule", "Support", "Coverage", "Holding"],
+ rule_rows,
+ widths=[0.08, 0.56, 0.12, 0.12, 0.12],
+ )
+ )
+
+ # 3. Combined backtest
+ story.append(Paragraph("3. Shadow Backtest - Combined", h2))
+ img = chart_image("equity_curve")
+ if img is not None:
+ story.append(img)
+ combined_error = sections.get("combined_error") or ""
+ if combined_error:
+ story.append(para(f"Backtest warning: {combined_error}", muted))
+ combined_metrics = sections["combined_metrics"]
+ if combined_metrics:
+ story.append(
+ make_table(
+ [],
+ [[k, f"{v:.4f}"] for k, v in combined_metrics.items()],
+ widths=[0.5, 0.5],
+ )
+ )
+ else:
+ story.append(
+ para("Backtest produced no usable metrics (see warning above).", muted)
+ )
+
+ # 4. Per-market backtest
+ story.append(Paragraph("4. Shadow Backtest - By Market", h2))
+ img = chart_image("per_market_bar")
+ if img is not None:
+ story.append(img)
+ market_rows = [
+ [
+ market_label(market),
+ f"{metrics.get('sharpe', 0.0):.2f}",
+ f"{metrics.get('annual_return', 0.0) * 100:.2f}%",
+ f"{metrics.get('max_drawdown', 0.0) * 100:.2f}%",
+ ]
+ for market, metrics in sections["per_market_metrics"].items()
+ ]
+ story.append(
+ make_table(
+ ["Market", "Sharpe", "Annual", "Max Drawdown"],
+ market_rows,
+ widths=[0.4, 0.2, 0.2, 0.2],
+ )
+ )
+
+ # 5. Delta attribution
+ story.append(Paragraph("5. You vs Shadow - Delta Attribution", h2))
+ if shadow_pnl is not None:
+ lede = (
+ f"Shadow PnL {_colored(shadow_pnl, _signed(shadow_pnl))}, "
+ f"your real PnL {_colored(real_pnl, _signed(real_pnl))}, "
+ f"delta {_colored(delta_pnl, _signed(delta_pnl))}."
+ )
+ story.append(Paragraph(lede, body))
+ else:
+ story.append(
+ para(
+ "The shadow backtest did not produce usable metrics, so Shadow PnL, "
+ "delta, and the attribution below are not computed for this run.",
+ muted,
+ )
+ )
+ img = chart_image("attribution_waterfall")
+ if img is not None:
+ story.append(img)
+
+ def attr_row(label: str, value: float) -> list[Any]:
+ return [label, Paragraph(_colored(value, _signed(value)), cell)]
+
+ story.append(
+ make_table(
+ [],
+ [
+ attr_row("Noise trades", attribution.noise_trades_pnl),
+ attr_row("Early exit (winners)", attribution.early_exit_pnl),
+ attr_row("Late exit (losers)", attribution.late_exit_pnl),
+ attr_row("Overtrading", attribution.overtrading_pnl),
+ attr_row("Missed signals (residual)", attribution.missed_signals_pnl),
+ ],
+ widths=[0.5, 0.5],
+ )
+ )
+ if attribution.excluded_currencies:
+ excluded = ", ".join(
+ f"{count} in {currency}"
+ for currency, count in attribution.excluded_currencies.items()
+ )
+ story.append(
+ para(
+ "Real PnL above covers the shadow pool's settlement currency only. "
+ "There is no FX translation layer, so roundtrips settling elsewhere "
+ f"are excluded rather than summed against it: {excluded}.",
+ muted,
+ )
+ )
+
+ # 6. Counterfactual top 5
+ story.append(Paragraph("6. Counterfactual Top 5", h2))
+ if attribution.counterfactual_trades:
+ cf_rows = [
+ [
+ str(i),
+ t["symbol"],
+ str(t["buy_dt"])[:10],
+ str(t["sell_dt"])[:10],
+ f"{t['hold_days']:.1f}d",
+ Paragraph(_colored(t["pnl"], _signed(t["pnl"])), cell),
+ Paragraph(_colored(t["impact"], _signed(t["impact"])), cell),
+ para(reason_labels.get(t["reason"], t["reason"])),
+ ]
+ for i, t in enumerate(attribution.counterfactual_trades, start=1)
+ ]
+ story.append(
+ make_table(
+ ["#", "Symbol", "Buy", "Sell", "Hold", "Real PnL", "Impact", "Reason"],
+ cf_rows,
+ widths=[0.05, 0.13, 0.13, 0.13, 0.09, 0.13, 0.13, 0.21],
+ )
+ )
+ else:
+ story.append(
+ para(
+ "No material counterfactual trades - every roundtrip falls inside the shadow rules.",
+ muted,
+ )
+ )
+
+ # 7. Today's signals
+ story.append(Paragraph("7. Today's Signal Scan", h2))
+ today_signals = sections["today_signals"]
+ if today_signals:
+ signal_rows = [
+ [
+ s["symbol"],
+ market_label(s["market"]),
+ s["rule_id"],
+ para(str(s["reason"])),
+ ]
+ for s in today_signals
+ ]
+ story.append(
+ make_table(
+ ["Symbol", "Market", "Rule", "Reason"],
+ signal_rows,
+ widths=[0.16, 0.2, 0.12, 0.52],
+ )
+ )
+ else:
+ story.append(para("No shadow-matching symbols today (or scan skipped).", muted))
+ story.append(
+ para("For research reference only - not a buy/sell recommendation.", muted)
+ )
+
+ # 8. Caveats
+ story.append(Paragraph("8. Confidence &amp; Caveats", h2))
+ caveats = [
+ f"Sample size: {profile.profitable_roundtrips} profitable roundtrips support {len(profile.rules)} rule(s).",
+ "Backtest assumptions: slippage/fees use engine defaults; cross-market annualization uses calendar days.",
+ "Style decay: rules reflect the user's historical window and may not hold in future regimes.",
+ "Red line: this report is research-only and never routes to any live trading system.",
+ ]
+ for caveat in caveats:
+ story.append(para(f"• {caveat}", body))
+
+ doc = SimpleDocTemplate(
+ str(pdf_path),
+ pagesize=A4,
+ leftMargin=15 * mm,
+ rightMargin=15 * mm,
+ topMargin=15 * mm,
+ bottomMargin=15 * mm,
+ title=f"Shadow Account Report - {profile.shadow_id}",
+ )
+ doc.build(story)
diff --git a/agent/src/shadow_account/reporter.py b/agent/src/shadow_account/reporter.py
index 77d6920ac..8e85e005b 100644
--- a/agent/src/shadow_account/reporter.py
+++ b/agent/src/shadow_account/reporter.py
@@ -5,11 +5,13 @@ The pipeline:
→ `_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)
+ → weasyprint → PDF, falling back to reportlab, else HTML-only
Design:
* No hard dependency on weasyprint at import time — if importing or
- rendering fails, we keep the HTML artifact and return its path.
+ rendering fails, the pure-Python reportlab fallback in
+ `pdf_fallback` renders the same section payload with a simpler
+ layout; HTML is only the last resort when both engines fail.
* 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
@@ -28,6 +30,7 @@ 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.pdf_fallback import render_pdf_reportlab
from src.shadow_account.storage import reports_dir
logger = logging.getLogger(__name__)
@@ -65,9 +68,9 @@ def render_shadow_report(
Returns:
Dict with keys:
``html_path`` : rendered HTML (always present)
- ``pdf_path`` : PDF path (present iff weasyprint succeeded)
+ ``pdf_path`` : PDF path (present iff a PDF engine succeeded)
``sections`` : structured payload (for frontend preview)
- ``engine`` : "weasyprint" | "html-only"
+ ``engine`` : "weasyprint" | "reportlab" | "html-only"
"""
output_dir = Path(output_dir) if output_dir else reports_dir()
output_dir.mkdir(parents=True, exist_ok=True)
@@ -92,7 +95,7 @@ def render_shadow_report(
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)
+ pdf_path, engine = _render_pdf(html, sections, charts, output_dir, profile.shadow_id)
return {
"html_path": str(html_path),
@@ -322,7 +325,7 @@ def _try_render_pdf(
from weasyprint import HTML # type: ignore[import-not-found]
except Exception as exc: # pragma: no cover — import-level failure
_WEASYPRINT_HTML = False
- logger.warning("weasyprint unavailable (%s); HTML-only output.", exc)
+ logger.warning("weasyprint unavailable (%s); trying reportlab.", exc)
return None, "html-only"
_WEASYPRINT_HTML = HTML
@@ -330,7 +333,7 @@ def _try_render_pdf(
try:
_WEASYPRINT_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)
+ logger.warning("weasyprint render failed (%s); trying reportlab.", exc)
if pdf_path.exists():
try:
pdf_path.unlink()
@@ -340,6 +343,53 @@ def _try_render_pdf(
return pdf_path, "weasyprint"
+def _render_pdf(
+ html: str,
+ sections: dict[str, Any],
+ charts: dict[str, str],
+ output_dir: Path,
+ shadow_id: str,
+) -> tuple[Path | None, str]:
+ """Render the PDF, preferring weasyprint and falling back to reportlab.
+
+ weasyprint needs system pango/cairo libraries that pip cannot install;
+ on hosts without them the report used to degrade to HTML-only. The
+ reportlab path in `pdf_fallback` renders the same section data with a
+ simpler layout, so a PDF comes out on any host.
+ """
+ pdf_path, engine = _try_render_pdf(html, output_dir, shadow_id)
+ if pdf_path is not None:
+ return pdf_path, engine
+ return _try_render_pdf_reportlab(sections, charts, output_dir, shadow_id)
+
+
+def _try_render_pdf_reportlab(
+ sections: dict[str, Any],
+ charts: dict[str, str],
+ output_dir: Path,
+ shadow_id: str,
+) -> tuple[Path | None, str]:
+ """Render PDF via reportlab platypus, returning (path|None, engine_name)."""
+ pdf_path = output_dir / f"{shadow_id}.pdf"
+ try:
+ render_pdf_reportlab(
+ sections=sections,
+ charts=charts,
+ market_labels=_MARKET_LABELS,
+ reason_labels=_REASON_LABELS,
+ pdf_path=pdf_path,
+ )
+ except Exception as exc:
+ logger.warning("reportlab 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, "reportlab"
+
+
# ---------------- Convenience ----------------
def embed_image_as_data_uri(path: Path) -> str:
diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.py
index d21b8e4ad..41144a896 100644
--- a/agent/tests/test_shadow_account.py
+++ b/agent/tests/test_shadow_account.py
@@ -912,7 +912,7 @@ def test_render_shadow_report_emits_html(profitable_journal: Path, tmp_path: Pat
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")
+ assert out["engine"] in ("weasyprint", "reportlab", "html-only")
@pytest.mark.unit
@@ -1023,6 +1023,76 @@ def test_weasyprint_probe_is_cached_when_available(
assert attempts == ["weasyprint"]
+def test_reportlab_fallback_renders_pdf_when_weasyprint_missing(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Hosts without weasyprint's system libs still get a PDF via reportlab."""
+ from src.shadow_account import reporter
+
+ monkeypatch.setattr(reporter, "_WEASYPRINT_HTML", False) # probe already failed
+ profile = extract_shadow_profile(profitable_journal)
+ result = _stub_backtest_result(profile)
+
+ out = reporter.render_shadow_report(profile, result, output_dir=tmp_path)
+
+ assert out["engine"] == "reportlab"
+ pdf_path = Path(out["pdf_path"])
+ assert pdf_path.exists()
+ assert pdf_path.read_bytes()[:5] == b"%PDF-"
+ assert pdf_path.stat().st_size > 2000
+
+
+def test_reportlab_fallback_escapes_cjk_and_markup_chars(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """CJK text and XML-special chars in run data must not break platypus."""
+ from src.shadow_account import reporter
+
+ monkeypatch.setattr(reporter, "_WEASYPRINT_HTML", False)
+ profile = extract_shadow_profile(profitable_journal)
+ result = _stub_backtest_result(profile)
+ signals = [
+ {
+ "symbol": "600519.SH",
+ "market": "china_a",
+ "rule_id": "R1",
+ "reason": "匹配影子规则 <b> & 其他",
+ }
+ ]
+
+ out = reporter.render_shadow_report(
+ profile, result, today_signals=signals, output_dir=tmp_path,
+ )
+
+ assert out["engine"] == "reportlab"
+ assert Path(out["pdf_path"]).exists()
+
+
+def test_pdf_degrades_to_html_only_when_both_engines_fail(
+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """HTML remains the last resort, and no partial PDF is left behind."""
+ from src.shadow_account import reporter
+
+ monkeypatch.setattr(reporter, "_WEASYPRINT_HTML", False)
+
+ def boom(**kwargs: object) -> None:
+ raise RuntimeError("no reportlab")
+
+ monkeypatch.setattr(reporter, "render_pdf_reportlab", boom)
+ profile = extract_shadow_profile(profitable_journal)
+ result = _stub_backtest_result(profile)
+
+ out = reporter.render_shadow_report(profile, result, output_dir=tmp_path)
+
+ assert out["engine"] == "html-only"
+ assert out["pdf_path"] is None
+ assert not (tmp_path / f"{profile.shadow_id}.pdf").exists()
+
+
# ---------------- M5/M6: Tool wrappers + scanner ----------------
@pytest.mark.unit
diff --git a/pyproject.toml b/pyproject.toml
index 4169d45bb..f7af0c131 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -72,6 +72,11 @@ dependencies = [
"jinja2>=3.1.0",
"matplotlib>=3.7.0",
"weasyprint>=60.0",
+ # weasyprint needs system pango/cairo libraries pip cannot install; where
+ # they are missing the shadow report degraded to HTML-only. reportlab
+ # ships binary wheels everywhere and backs the pure-Python PDF fallback
+ # (shadow_account/pdf_fallback.py) so the PDF renders on any host.
+ "reportlab>=4.0",
"prompt_toolkit>=3.0.0",
]
diff --git a/requirements-lock.txt b/requirements-lock.txt
index af6068169..b24142a3a 100644
--- a/requirements-lock.txt
+++ b/requirements-lock.txt
@@ -354,9 +354,7 @@ brotli==1.2.0 ; platform_python_implementation == 'CPython' \
--hash=sha256:f8d635cafbbb0c61327f942df2e3f474dde1cff16c3cd0580564774eaba1ee13 \
--hash=sha256:fc1530af5c3c275b8524f2e24841cbe2599d74462455e9bae5109e9ff42e9361 \
--hash=sha256:ff09cd8c5eec3b9d02d2408db41be150d8891c5566addce57513bf546e3d6c6d
- # via
- # fonttools
- # httpx
+ # via fonttools
brotlicffi==1.2.0.1 ; platform_python_implementation != 'CPython' \
--hash=sha256:2c85e65913cf2b79c57a3fdd05b98d9731d9255dc0cb696b09376cc091b9cddd \
--hash=sha256:37cb587d32bf7168e2218c455e22e409ad1f3157c6c71945879a311f3e6b6abf \
@@ -373,9 +371,7 @@ brotlicffi==1.2.0.1 ; platform_python_implementation != 'CPython' \
--hash=sha256:da2e82a08e7778b8bc539d27ca03cdd684113e81394bfaaad8d0dfc6a17ddede \
--hash=sha256:e015af99584c6db1490a69a210c765953e473e63adc2d891ac3062a737c9e851 \
--hash=sha256:f2a5575653b0672638ba039b82fda56854934d7a6a24d4b8b5033f73ab43cbc1
- # via
- # fonttools
- # httpx
+ # via fonttools
bs4==0.0.2 \
--hash=sha256:a48685c58f50fe127722417bae83fe6badf500d54b55f7e39ffe43b798653925 \
--hash=sha256:abf8742c0805ef7f662dce4b51cca104cffe52b835238afc169142ab9b3fbccc
@@ -431,6 +427,7 @@ certifi==2026.6.17 \
# curl-cffi
# httpcore
# httpx
+ # langchain-openai
# requests
cffi==2.0.0 \
--hash=sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb \
@@ -655,6 +652,7 @@ charset-normalizer==3.4.7 \
--hash=sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464
# via
# ccxt
+ # reportlab
# requests
click==8.5.0 \
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
@@ -718,9 +716,7 @@ coincurve==21.0.0 ; python_full_version < '3.14' and implementation_name == 'cpy
colorama==0.4.6 ; sys_platform == 'win32' \
--hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
--hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
- # via
- # click
- # tqdm
+ # via tqdm
contourpy==1.3.3 \
--hash=sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69 \
--hash=sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc \
@@ -962,10 +958,6 @@ exceptiongroup==1.3.1 \
--hash=sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219 \
--hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598
# via fastmcp-slim
-fake-useragent==2.2.0 \
- --hash=sha256:4e6ab6571e40cc086d788523cf9e018f618d07f9050f822ff409a4dfe17c16b2 \
- --hash=sha256:67f35ca4d847b0d298187443aaf020413746e56acd985a611908c73dba2daa24
- # via ddgs
fastapi==0.141.1 \
--hash=sha256:bfb91aa2d334c61cb35ba9a116fc123b3d3df31640b801cf57a7a78ec3f603b3 \
--hash=sha256:e8822fc40db1e1858054d7a949a888695bc9bdce70139178e33bd2871a453ca1
@@ -1180,9 +1172,7 @@ h11==0.16.0 \
h2==4.4.1 \
--hash=sha256:0e25f1462b23c9cb82d9eb02e28bc706dac2a68cb457c6a0d74d63c8a2a5d0e6 \
--hash=sha256:4e866ffb1a869ae14dd9b5e6beb5c24a13da0495ad72b65925ded182521c1516
- # via
- # -r agent/requirements.txt
- # httpx
+ # via -r agent/requirements.txt
hpack==4.2.0 \
--hash=sha256:0895cfa3b5531fc65fe439c05eb65144f123bf7a394fcaa56aa423548d8e45c0 \
--hash=sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986
@@ -1252,8 +1242,8 @@ httpx==0.28.1 \
--hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
# via
# -r agent/requirements.txt
- # ddgs
# fastmcp-slim
+ # langchain-core
# langgraph-sdk
# langsmith
# mcp
@@ -1829,6 +1819,7 @@ lxml==6.1.2 \
# python-docx
# python-pptx
# tushare
+ # yfinance
markdown-it-py==4.2.0 \
--hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
@@ -2559,6 +2550,7 @@ pillow==12.3.0 \
# -r agent/requirements.txt
# matplotlib
# python-pptx
+ # reportlab
# weasyprint
platformdirs==4.11.5 \
--hash=sha256:89f8d42695853b89c7170bd49bc3dc593f98a71e695ede88e06a3b247bc4563b \
@@ -3214,6 +3206,10 @@ regex==2026.7.19 \
--hash=sha256:fe31f28c94402043161876a258a9c6f757cb485905c7614ce8d6cd40e6b7bdc1 \
--hash=sha256:ffd8893ccc1c2fce6e0d6ca402d716fe1b29db70c7132609a05955e31b2aa8f2
# via tiktoken
+reportlab==5.0.1 \
+ --hash=sha256:1c36e6bb0e71780c72331eba60da7f602e8d4389a8723825af71342e49d791e8 \
+ --hash=sha256:ebd13154be1c8515e665de70bd2d303ae9ddc3ef47e44afd5116441ca0283a26
+ # via -r agent/requirements.txt
requests==2.34.2 \
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
--hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
@@ -3574,10 +3570,6 @@ sniffio==1.3.1 \
# via
# langsmith
# openai
-socksio==1.0.0 \
- --hash=sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3 \
- --hash=sha256:f88beb3da5b5c38b9890469de67d0cb0f9d494b78b106ca1845f96c10b91c4ac
- # via httpx
soupsieve==2.9.2 \
--hash=sha256:4a55d8cf158a9c2e587fa4922f1bbb91d68ac829e2d6f25403a85747c71daf74 \
--hash=sha256:8089a26fd974ca7a1f30276d3d8492ab266ab15af581642dfe8aa162e0c1c823