Coverage for src/jquantstats/_reports/_portfolio.py: 100%
99 statements
« prev ^ index » next coverage.py v7.15.3, created at 2026-08-06 04:52 +0000
« prev ^ index » next coverage.py v7.15.3, created at 2026-08-06 04:52 +0000
1"""HTML report generation for portfolio analytics.
3This module defines the Report facade which produces a self-contained HTML
4document containing all relevant performance numbers and interactive Plotly
5visualisations for a Portfolio.
6"""
8from __future__ import annotations
10from collections.abc import Callable
11from pathlib import Path
12from typing import TYPE_CHECKING, Any
14import plotly.graph_objects as go
15import polars as pl
16from jinja2 import Environment, FileSystemLoader, select_autoescape
18if TYPE_CHECKING:
19 from ._protocol import PortfolioLike
21from ._formatting import _fmt, _is_finite, _plotly_div, _table_html
23# templates/ lives one level above this subpackage (at src/jquantstats/templates/)
24_TEMPLATES_DIR = Path(__file__).parent.parent / "templates"
25_env = Environment(
26 loader=FileSystemLoader(_TEMPLATES_DIR),
27 autoescape=select_autoescape(["html"]),
28)
30# ── Stats table ───────────────────────────────────────────────────────────────
32_METRIC_FORMATS: dict[str, tuple[str, str]] = {
33 "avg_return": (".2%", ""),
34 "avg_win": (".2%", ""),
35 "avg_loss": (".2%", ""),
36 "best": (".2%", ""),
37 "worst": (".2%", ""),
38 "sharpe": (".2f", ""),
39 "calmar": (".2f", ""),
40 "recovery_factor": (".2f", ""),
41 "max_drawdown": (".2%", ""),
42 "avg_drawdown": (".2%", ""),
43 "max_drawdown_duration": (".0f", " days"),
44 "win_rate": (".1%", ""),
45 "monthly_win_rate": (".1%", ""),
46 "profit_factor": (".2f", ""),
47 "payoff_ratio": (".2f", ""),
48 "volatility": (".2%", ""),
49 "skew": (".2f", ""),
50 "kurtosis": (".2f", ""),
51 "value_at_risk": (".2%", ""),
52 "conditional_value_at_risk": (".2%", ""),
53}
55_METRIC_LABELS: dict[str, str] = {
56 "avg_return": "Avg Return",
57 "avg_win": "Avg Win",
58 "avg_loss": "Avg Loss",
59 "best": "Best Period",
60 "worst": "Worst Period",
61 "sharpe": "Sharpe Ratio",
62 "calmar": "Calmar Ratio",
63 "recovery_factor": "Recovery Factor",
64 "max_drawdown": "Max Drawdown",
65 "avg_drawdown": "Avg Drawdown",
66 "max_drawdown_duration": "Max DD Duration",
67 "win_rate": "Win Rate",
68 "monthly_win_rate": "Monthly Win Rate",
69 "profit_factor": "Profit Factor",
70 "payoff_ratio": "Payoff Ratio",
71 "volatility": "Volatility (ann.)",
72 "skew": "Skewness",
73 "kurtosis": "Kurtosis",
74 "value_at_risk": "VaR (95 %)",
75 "conditional_value_at_risk": "CVaR (95 %)",
76}
78# Metrics where the *highest* value across assets is highlighted.
79_HIGHER_IS_BETTER: frozenset[str] = frozenset(
80 {"sharpe", "calmar", "recovery_factor", "win_rate", "monthly_win_rate", "profit_factor", "payoff_ratio"}
81)
83_CATEGORIES: list[tuple[str, list[str]]] = [
84 ("Returns", ["avg_return", "avg_win", "avg_loss", "best", "worst"]),
85 ("Risk-Adjusted Performance", ["sharpe", "calmar", "recovery_factor"]),
86 ("Drawdown", ["max_drawdown", "avg_drawdown", "max_drawdown_duration"]),
87 ("Win / Loss", ["win_rate", "monthly_win_rate", "profit_factor", "payoff_ratio"]),
88 ("Distribution & Risk", ["volatility", "skew", "kurtosis", "value_at_risk", "conditional_value_at_risk"]),
89]
92def _stats_table_html(summary: pl.DataFrame) -> str:
93 """Render a stats summary DataFrame as a styled HTML table.
95 Args:
96 summary: Output of `Stats.summary` — one row per metric,
97 one column per asset plus a ``metric`` column.
99 Returns:
100 An HTML ``<table>`` string ready to embed in a page.
101 """
102 assets = [c for c in summary.columns if c != "metric"]
104 # Build a fast lookup: metric_name → {asset: value}
105 metric_data: dict[str, dict[str, Any]] = {}
106 for row in summary.iter_rows(named=True):
107 name = str(row["metric"])
108 metric_data[name] = {a: row.get(a) for a in assets}
110 header_cells = "".join(f'<th class="asset-header">{a}</th>' for a in assets)
111 rows_html_parts: list[str] = []
113 for category_label, metrics in _CATEGORIES:
114 rows_html_parts.append(
115 f'<tr class="table-section-header">'
116 f'<td colspan="{len(assets) + 1}"><strong>{category_label}</strong></td>'
117 f"</tr>\n"
118 )
119 for metric in metrics:
120 if metric not in metric_data:
121 continue
122 rows_html_parts.append(_stats_metric_row_html(metric, metric_data[metric], assets))
124 rows_html = "".join(rows_html_parts)
125 return _table_html(header_cells, rows_html)
128def _best_asset(metric: str, values: dict[str, Any]) -> str | None:
129 """Return the asset with the highest finite value, for higher-is-better metrics.
131 Args:
132 metric: The metric name being rendered.
133 values: Mapping of asset name → value for this metric.
135 Returns:
136 The best asset name to highlight, or ``None`` when the metric is not
137 higher-is-better or has no finite values.
139 """
140 if metric not in _HIGHER_IS_BETTER:
141 return None
142 finite_pairs = [(a, float(v)) for a, v in values.items() if _is_finite(v)]
143 if not finite_pairs:
144 return None
145 return max(finite_pairs, key=lambda x: x[1])[0]
148def _stats_metric_row_html(metric: str, values: dict[str, Any], assets: list[str]) -> str:
149 """Render a single metric row, highlighting the best asset where applicable.
151 Args:
152 metric: The metric name (drives label, format, and highlight rule).
153 values: Mapping of asset name → value for this metric.
154 assets: Asset column names, in output order.
156 Returns:
157 An HTML ``<tr>`` string for the metric.
159 """
160 fmt, suffix = _METRIC_FORMATS.get(metric, (".4f", ""))
161 label = _METRIC_LABELS.get(metric, metric.replace("_", " ").title())
162 best_asset = _best_asset(metric, values)
163 cells = "".join(
164 f'<td class="metric-value{" best-value" if a == best_asset else ""}">{_fmt(values.get(a), fmt, suffix)}</td>'
165 for a in assets
166 )
167 return f'<tr><td class="metric-name">{label}</td>{cells}</tr>\n'
170# ── Report dataclass ──────────────────────────────────────────────────────────
173def _figure_div(fig: go.Figure, include_plotlyjs: bool | str) -> str:
174 """Return an HTML div string for *fig*.
176 Args:
177 fig: Plotly figure to serialise.
178 include_plotlyjs: Passed directly to `plotly.io.to_html`.
179 Pass ``"cdn"`` for the first figure so the CDN script tag is
180 injected; pass ``False`` for all subsequent figures.
182 Returns:
183 HTML string (not a full page).
184 """
185 return _plotly_div(fig, include_plotlyjs=include_plotlyjs)
188class Report:
189 """Facade for generating HTML reports from a Portfolio.
191 Provides a `to_html` method that assembles a self-contained,
192 dark-themed HTML document with a performance-statistics table and
193 multiple interactive Plotly charts.
195 Usage::
197 report = portfolio.report
198 html_str = report.to_html()
199 report.to_html(path="output/report.html")
200 """
202 __slots__ = ("_portfolio",)
204 def __init__(self, portfolio: PortfolioLike) -> None:
205 self._portfolio = portfolio
207 def to_html(
208 self,
209 title: str = "JQuantStats Portfolio Report",
210 path: str | Path | None = None,
211 ) -> str | Path:
212 """Render a full HTML report as a string or save it to a file.
214 The document is self-contained: Plotly.js is loaded once from the
215 CDN and all charts are embedded as ``<div>`` elements. No external
216 CSS framework is required.
218 Args:
219 title: HTML ``<title>`` text and visible page heading.
220 path: When given, write the report to this path and return the
221 resolved `pathlib.Path`. A ``.html`` suffix is appended
222 automatically when *path* has no file extension. When
223 ``None`` (default) the HTML string is returned directly.
225 Returns:
226 The HTML string when *path* is ``None``, otherwise the resolved
227 `pathlib.Path` of the written file.
228 """
229 pf = self._portfolio
231 # ── Metadata ──────────────────────────────────────────────────────────
232 has_date = "date" in pf.prices.columns
233 if has_date:
234 dates = pf.prices["date"]
235 start_date = str(dates.min())
236 end_date = str(dates.max())
237 n_periods = pf.prices.height
238 period_info = f"{start_date} → {end_date} | {n_periods:,} periods"
239 else:
240 start_date = ""
241 end_date = ""
242 period_info = f"{pf.prices.height:,} periods"
244 assets_list = ", ".join(pf.assets)
246 # ── Figures ───────────────────────────────────────────────────────────
247 # The first chart includes Plotly.js from CDN; subsequent ones reuse it.
248 _first = True
250 def _div(fig: go.Figure) -> str:
251 """Serialise *fig* to an HTML div, embedding Plotly.js only on the first call."""
252 nonlocal _first
253 include = "cdn" if _first else False
254 _first = False
255 return _figure_div(fig, include)
257 def _try_div(build_fig: Callable[[], go.Figure]) -> str:
258 """Call *build_fig()* and return the chart div; on error return a notice."""
259 try:
260 fig = build_fig()
261 return _div(fig)
262 except Exception as exc:
263 return f'<p class="chart-unavailable">Chart unavailable: {exc}</p>'
265 snapshot_div = _try_div(pf.plots.snapshot)
266 rolling_sharpe_div = _try_div(pf.plots.rolling_sharpe_plot)
267 rolling_vol_div = _try_div(pf.plots.rolling_volatility_plot)
268 annual_sharpe_div = _try_div(pf.plots.annual_sharpe_plot)
269 monthly_heatmap_div = _try_div(pf.plots.monthly_returns_heatmap)
270 corr_div = _try_div(pf.plots.correlation_heatmap)
271 lead_lag_div = _try_div(pf.plots.lead_lag_ir_plot)
272 trading_cost_div = _try_div(pf.plots.trading_cost_impact_plot)
274 # ── Stats table ───────────────────────────────────────────────────────
275 stats_table = _stats_table_html(pf.stats.summary())
277 # ── Turnover table ────────────────────────────────────────────────────
278 try:
279 turnover_df = pf.turnover_summary()
280 turnover_rows = "".join(
281 f'<tr><td class="metric-name">{row["metric"].replace("_", " ").title()}</td>'
282 f'<td class="metric-value">{row["value"]:.4f}</td></tr>'
283 for row in turnover_df.iter_rows(named=True)
284 )
285 turnover_html = (
286 '<table class="stats-table">'
287 "<thead><tr>"
288 '<th class="metric-header">Metric</th>'
289 '<th class="asset-header">Value</th>'
290 "</tr></thead>"
291 f"<tbody>{turnover_rows}</tbody>"
292 "</table>"
293 )
294 except Exception as exc:
295 turnover_html = f'<p class="chart-unavailable">Turnover data unavailable: {exc}</p>'
297 # ── Assemble HTML ─────────────────────────────────────────────────────
298 footer_date = end_date if has_date else ""
299 template = _env.get_template("portfolio_report.html")
300 html = template.render(
301 title=title,
302 period_info=period_info,
303 assets_list=assets_list,
304 aum=f"{pf.aum:,.0f}",
305 footer_date=footer_date,
306 snapshot_div=snapshot_div,
307 rolling_sharpe_div=rolling_sharpe_div,
308 rolling_vol_div=rolling_vol_div,
309 annual_sharpe_div=annual_sharpe_div,
310 monthly_heatmap_div=monthly_heatmap_div,
311 corr_div=corr_div,
312 lead_lag_div=lead_lag_div,
313 trading_cost_div=trading_cost_div,
314 stats_table=stats_table,
315 turnover_html=turnover_html,
316 container_max_width="1400px",
317 )
319 if path is None:
320 return html
322 p = Path(path)
323 if not p.suffix:
324 p = p.with_suffix(".html")
325 p.parent.mkdir(parents=True, exist_ok=True)
326 p.write_text(html, encoding="utf-8")
327 return p