quantstats-pro 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. quantstats/__init__.py +163 -0
  2. quantstats/_compat.py +431 -0
  3. quantstats/_montecarlo.py +296 -0
  4. quantstats/_numpy_compat.py +289 -0
  5. quantstats/_plotting/__init__.py +0 -0
  6. quantstats/_plotting/core.py +2173 -0
  7. quantstats/_plotting/wrappers.py +2109 -0
  8. quantstats/_reporting/__init__.py +12 -0
  9. quantstats/_reporting/engine.py +37 -0
  10. quantstats/_reporting/sections.py +223 -0
  11. quantstats/alphadecay/__init__.py +25 -0
  12. quantstats/alphadecay/core.py +712 -0
  13. quantstats/alphadecay/plotting.py +206 -0
  14. quantstats/montecarlo/__init__.py +34 -0
  15. quantstats/montecarlo/analytics.py +291 -0
  16. quantstats/montecarlo/base.py +92 -0
  17. quantstats/montecarlo/core.py +175 -0
  18. quantstats/montecarlo/models/__init__.py +15 -0
  19. quantstats/montecarlo/models/bayesian.py +88 -0
  20. quantstats/montecarlo/models/block_bootstrap.py +108 -0
  21. quantstats/montecarlo/models/bootstrap.py +38 -0
  22. quantstats/montecarlo/models/garch.py +83 -0
  23. quantstats/montecarlo/models/gbm.py +44 -0
  24. quantstats/montecarlo/models/heston.py +103 -0
  25. quantstats/montecarlo/models/jump_diffusion.py +86 -0
  26. quantstats/montecarlo/models/shuffle.py +49 -0
  27. quantstats/montecarlo/models/trimmed.py +50 -0
  28. quantstats/montecarlo/plotting.py +324 -0
  29. quantstats/montecarlo/registry.py +34 -0
  30. quantstats/plots.py +27 -0
  31. quantstats/py.typed +0 -0
  32. quantstats/report.html +64 -0
  33. quantstats/report_alpha_decay.html +43 -0
  34. quantstats/report_montecarlo.html +62 -0
  35. quantstats/report_simple.html +58 -0
  36. quantstats/reports.py +3502 -0
  37. quantstats/stats.py +3321 -0
  38. quantstats/utils.py +1011 -0
  39. quantstats/version.py +1 -0
  40. quantstats_pro-0.4.1.dist-info/METADATA +509 -0
  41. quantstats_pro-0.4.1.dist-info/RECORD +43 -0
  42. quantstats_pro-0.4.1.dist-info/WHEEL +4 -0
  43. quantstats_pro-0.4.1.dist-info/licenses/LICENSE.txt +202 -0
quantstats/reports.py ADDED
@@ -0,0 +1,3502 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # QuantStats: Portfolio analytics for quants
4
+ # https://github.com/ranaroussi/quantstats
5
+ #
6
+ # Copyright 2019-2025 Ran Aroussi
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ import re as _regex
21
+ from base64 import b64encode as _b64encode
22
+ from datetime import datetime as _dt
23
+ from math import ceil as _ceil
24
+ from math import sqrt as _sqrt
25
+
26
+ import numpy as _np
27
+ import pandas as _pd
28
+ from tabulate import tabulate as _tabulate
29
+
30
+ from . import __version__
31
+
32
+ # Lazy imports to avoid circular dependency during package initialization
33
+ _stats = None
34
+ _utils = None
35
+ _plots = None
36
+
37
+
38
+ def _get_stats():
39
+ global _stats
40
+ if _stats is None:
41
+ from . import stats
42
+ _stats = stats
43
+ return _stats
44
+
45
+
46
+ def _get_utils():
47
+ global _utils
48
+ if _utils is None:
49
+ from . import utils
50
+ _utils = utils
51
+ return _utils
52
+
53
+
54
+ def _get_plots():
55
+ global _plots
56
+ if _plots is None:
57
+ from . import plots
58
+ _plots = plots
59
+ return _plots
60
+ import tempfile
61
+ import webbrowser
62
+ from io import StringIO
63
+ from pathlib import Path
64
+
65
+ from dateutil.relativedelta import relativedelta
66
+
67
+ try:
68
+ from IPython.display import HTML as iHTML
69
+ from IPython.display import display as iDisplay
70
+ except ImportError:
71
+ pass # IPython not available, display functions won't be used
72
+
73
+
74
+ def _get_trading_periods(periods_per_year=252):
75
+ """
76
+ Calculate trading periods for different time windows.
77
+
78
+ This helper function computes the number of trading periods for full year
79
+ and half year periods, which are commonly used in financial calculations
80
+ for annualization and rolling window analysis.
81
+
82
+ Parameters
83
+ ----------
84
+ periods_per_year : int, default 252
85
+ Number of trading periods in a year (e.g., 252 for daily data,
86
+ 12 for monthly data)
87
+
88
+ Returns
89
+ -------
90
+ tuple
91
+ A tuple containing (periods_per_year, half_year_periods)
92
+
93
+ Examples
94
+ --------
95
+ >>> _get_trading_periods(252) # Daily data
96
+ (252, 126)
97
+ >>> _get_trading_periods(12) # Monthly data
98
+ (12, 6)
99
+ """
100
+ # Calculate half year periods using ceiling to ensure we get at least half
101
+ half_year = _ceil(periods_per_year / 2)
102
+ return periods_per_year, half_year
103
+
104
+
105
+ def _print_parameters_table(
106
+ benchmark_title=None,
107
+ periods_per_year=252,
108
+ rf=0.0,
109
+ compounded=True,
110
+ match_dates=True,
111
+ ):
112
+ """
113
+ Print a formatted parameters table for terminal/console output.
114
+
115
+ Parameters
116
+ ----------
117
+ benchmark_title : str or None
118
+ Benchmark name/ticker
119
+ periods_per_year : int
120
+ Number of trading periods per year
121
+ rf : float
122
+ Risk-free rate
123
+ compounded : bool
124
+ Whether returns are compounded
125
+ match_dates : bool
126
+ Whether dates are matched with benchmark
127
+ """
128
+ width = 40
129
+ print("=" * width)
130
+ print(" Parameters")
131
+ print("-" * width)
132
+ if benchmark_title:
133
+ print(f"{'Benchmark':<25}{benchmark_title.upper():>15}")
134
+ print(f"{'Periods/Year':<25}{periods_per_year:>15}")
135
+ print(f"{'Risk-Free Rate':<25}{rf:>14.1%}")
136
+ print(f"{'Compounded':<25}{'Yes' if compounded else 'No':>15}")
137
+ if benchmark_title:
138
+ print(f"{'Match Dates':<25}{'Yes' if match_dates else 'No':>15}")
139
+ print("=" * width)
140
+ print()
141
+
142
+
143
+ def _match_dates(returns, benchmark):
144
+ """
145
+ Align returns and benchmark data to start from the same date.
146
+
147
+ This function ensures that both the returns and benchmark series start
148
+ from the same date by finding the latest start date where both series
149
+ have non-zero values. This is crucial for accurate performance comparisons.
150
+
151
+ Parameters
152
+ ----------
153
+ returns : pd.Series or pd.DataFrame
154
+ Returns data that may be a Series or DataFrame with multiple columns
155
+ benchmark : pd.Series
156
+ Benchmark returns data
157
+
158
+ Returns
159
+ -------
160
+ tuple
161
+ A tuple containing (aligned_returns, aligned_benchmark) both starting
162
+ from the same date
163
+
164
+ Examples
165
+ --------
166
+ >>> returns_aligned, bench_aligned = _match_dates(returns, benchmark)
167
+ """
168
+ # Handle different types of returns data (Series vs DataFrame)
169
+ if isinstance(returns, _pd.DataFrame):
170
+ # For DataFrame, use the first column to find the start date
171
+ loc = max(returns[returns.columns[0]].ne(0).idxmax(), benchmark.ne(0).idxmax())
172
+ else:
173
+ # For Series, find the maximum of start dates for both series
174
+ loc = max(returns.ne(0).idxmax(), benchmark.ne(0).idxmax())
175
+
176
+ # Slice both series to start from the latest common start date
177
+ returns = returns.loc[loc:]
178
+ benchmark = benchmark.loc[loc:]
179
+
180
+ return returns, benchmark
181
+
182
+
183
+ def html(
184
+ returns,
185
+ benchmark=None,
186
+ rf=0.0,
187
+ grayscale=False,
188
+ title="Strategy Tearsheet",
189
+ output=None,
190
+ compounded=True,
191
+ periods_per_year=252,
192
+ download_filename="quantstats-tearsheet.html",
193
+ figfmt="svg",
194
+ template_path=None,
195
+ match_dates=True,
196
+ **kwargs,
197
+ ):
198
+ """
199
+ Generate an HTML tearsheet report for portfolio performance analysis.
200
+
201
+ This function creates a comprehensive HTML report containing performance
202
+ metrics, visualizations, and analysis of investment returns. The report
203
+ includes comparisons with benchmarks, drawdown analysis, and various
204
+ performance charts.
205
+
206
+ Parameters
207
+ ----------
208
+ returns : pd.Series or pd.DataFrame
209
+ Daily returns data for the strategy/portfolio
210
+ benchmark : pd.Series, str, or None, default None
211
+ Benchmark returns for comparison. Can be a Series of returns,
212
+ a ticker symbol string, or None for no benchmark
213
+ rf : float, default 0.0
214
+ Risk-free rate for calculations (as decimal, e.g., 0.02 for 2%)
215
+ grayscale : bool, default False
216
+ Whether to generate charts in grayscale instead of color
217
+ title : str, default "Strategy Tearsheet"
218
+ Title to display at the top of the HTML report
219
+ output : str or None, default None
220
+ File path to save the HTML report. If None, downloads in browser
221
+ compounded : bool, default True
222
+ Whether to compound returns for calculations
223
+ periods_per_year : int, default 252
224
+ Number of trading periods per year for annualization
225
+ download_filename : str, default "quantstats-tearsheet.html"
226
+ Filename for browser download if output is None
227
+ figfmt : str, default "svg"
228
+ Format for embedded charts ('svg', 'png', 'jpg')
229
+ template_path : str or None, default None
230
+ Path to custom HTML template file. Uses default if None
231
+ match_dates : bool, default True
232
+ Whether to align returns and benchmark start dates
233
+ **kwargs
234
+ Additional keyword arguments for customization:
235
+ - strategy_title: Custom name for the strategy
236
+ - benchmark_title: Custom name for the benchmark
237
+ - active_returns: Whether to show active returns vs benchmark
238
+
239
+ Returns
240
+ -------
241
+ None
242
+ Generates HTML file either as download or saved to specified path
243
+
244
+ Examples
245
+ --------
246
+ >>> html(returns, benchmark='^GSPC', title='My Strategy')
247
+ >>> html(returns, output='report.html', grayscale=True)
248
+
249
+ Raises
250
+ ------
251
+ FileNotFoundError
252
+ If custom template_path doesn't exist
253
+ """
254
+ # Clean returns data by removing NaN values if date matching is enabled
255
+ if match_dates:
256
+ returns = returns.dropna()
257
+
258
+ # Get trading periods for calculations
259
+ win_year, win_half_year = _get_trading_periods(periods_per_year)
260
+
261
+ # Secure file path handling for HTML template
262
+ if template_path is None:
263
+ # Use default template path - report.html in same directory
264
+ template_path = Path(__file__).parent / 'report.html'
265
+ else:
266
+ template_path = Path(template_path)
267
+
268
+ # Resolve to absolute path and validate template file existence
269
+ template_path = template_path.resolve()
270
+
271
+ if not template_path.exists():
272
+ raise FileNotFoundError(f"Template file not found: {template_path}")
273
+ if not template_path.is_file():
274
+ raise ValueError(f"Template path is not a file: {template_path}")
275
+
276
+ # Read template securely with UTF-8 encoding
277
+ tpl = template_path.read_text(encoding='utf-8')
278
+
279
+ # prepare timeseries
280
+ if match_dates:
281
+ returns = returns.dropna()
282
+ # Clean and prepare returns data for analysis
283
+ returns = _get_utils()._prepare_returns(returns)
284
+
285
+ # Handle strategy title - can be single string or list for multiple columns
286
+ strategy_title = kwargs.get("strategy_title", "Strategy")
287
+ if (
288
+ isinstance(returns, _pd.DataFrame)
289
+ and len(returns.columns) > 1
290
+ and isinstance(strategy_title, str)
291
+ ):
292
+ strategy_title = list(returns.columns)
293
+
294
+ # Process benchmark data if provided
295
+ if benchmark is not None:
296
+ benchmark_title = kwargs.get("benchmark_title", "Benchmark")
297
+ # Auto-determine benchmark title if not provided
298
+ if kwargs.get("benchmark_title") is None:
299
+ if isinstance(benchmark, str):
300
+ benchmark_title = benchmark
301
+ elif isinstance(benchmark, _pd.Series):
302
+ benchmark_title = benchmark.name if benchmark.name else "Benchmark"
303
+ elif isinstance(benchmark, _pd.DataFrame):
304
+ col_name = benchmark[benchmark.columns[0]].name
305
+ benchmark_title = col_name if col_name else "Benchmark"
306
+
307
+ # Ensure benchmark_title is a string for .upper() call
308
+ if benchmark_title is None:
309
+ benchmark_title = "Benchmark"
310
+ # Store original benchmark before any alignment for accurate EOY calculations
311
+ # This preserves the full benchmark data including non-trading days
312
+ if isinstance(benchmark, str):
313
+ # Download the full benchmark data
314
+ benchmark_original = _get_utils().download_returns(benchmark)
315
+ if rf != 0:
316
+ benchmark_original = _get_utils().to_excess_returns(
317
+ benchmark_original, rf, nperiods=periods_per_year
318
+ )
319
+ elif isinstance(benchmark, _pd.Series):
320
+ benchmark_original = benchmark.copy()
321
+ else:
322
+ benchmark_original = benchmark
323
+ # Prepare benchmark data to match returns index and risk-free rate
324
+ benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
325
+ # Align dates between returns and benchmark if requested
326
+ if match_dates is True:
327
+ returns, benchmark = _match_dates(returns, benchmark)
328
+ else:
329
+ benchmark_title = None
330
+ benchmark_original = None
331
+
332
+ # Format date range for display in template
333
+ date_range = returns.index.strftime("%e %b, %Y")
334
+ tpl = tpl.replace("{{date_range}}", date_range[0] + " - " + date_range[-1])
335
+
336
+ # Build title with compounding indicator (only show if compounded)
337
+ full_title = f"{title} (Compounded)" if compounded else title
338
+ tpl = tpl.replace("{{title}}", full_title)
339
+ tpl = tpl.replace("{{v}}", __version__)
340
+ tpl = tpl.replace(
341
+ "{{generated_at}}",
342
+ _dt.now().strftime("%d %b, %Y %H:%M").lstrip("0"),
343
+ )
344
+
345
+ # Build parameters string for subtitle
346
+ params_parts = []
347
+
348
+ # Add user-provided parameters first if present
349
+ user_params = kwargs.get("parameters", {})
350
+ if user_params:
351
+ for key, value in user_params.items():
352
+ params_parts.append(f"{key}: {value}")
353
+
354
+ # Add auto-detected parameters (always show key params)
355
+ if benchmark_title:
356
+ params_parts.append(f"Benchmark: {benchmark_title.upper()}")
357
+ params_parts.append(f"Periods/Year: {periods_per_year}")
358
+ params_parts.append(f"RF: {rf:.1%}")
359
+
360
+ params_str = " &bull; ".join(params_parts)
361
+ if params_str:
362
+ params_str += " | "
363
+ tpl = tpl.replace("{{params}}", params_str)
364
+
365
+ # Add matched dates indicator
366
+ matched_dates_str = " (matched dates)" if match_dates and benchmark is not None else ""
367
+ tpl = tpl.replace("{{matched_dates}}", matched_dates_str)
368
+
369
+ # Set names for data series to be used in charts and tables
370
+ if benchmark is not None:
371
+ benchmark.name = benchmark_title
372
+ if isinstance(returns, _pd.Series):
373
+ returns.name = strategy_title
374
+ elif isinstance(returns, _pd.DataFrame):
375
+ returns.columns = (
376
+ strategy_title if isinstance(strategy_title, list) else [strategy_title]
377
+ )
378
+
379
+ # Generate comprehensive performance metrics table
380
+ mtrx = metrics(
381
+ returns=returns,
382
+ benchmark=benchmark,
383
+ rf=rf,
384
+ display=False,
385
+ mode="full",
386
+ sep=True,
387
+ internal="True",
388
+ compounded=compounded,
389
+ periods_per_year=periods_per_year,
390
+ prepare_returns=False,
391
+ benchmark_title=benchmark_title,
392
+ strategy_title=strategy_title,
393
+ )[2:]
394
+
395
+ # Format metrics table for HTML display
396
+ mtrx.index.name = "Metric"
397
+ tpl = tpl.replace("{{metrics}}", _html_table(mtrx))
398
+
399
+ # Handle table formatting for multiple columns
400
+ if isinstance(returns, _pd.DataFrame):
401
+ num_cols = len(returns.columns)
402
+ # Replace empty table rows with horizontal rule separators
403
+ for i in reversed(range(num_cols + 1, num_cols + 3)):
404
+ str_td = "<td></td>" * i
405
+ tpl = tpl.replace(
406
+ f"<tr>{str_td}</tr>", f'<tr><td colspan="{i}"><hr></td></tr>'
407
+ )
408
+
409
+ # Clean up table formatting with horizontal rules
410
+ tpl = tpl.replace(
411
+ "<tr><td></td><td></td><td></td></tr>", '<tr><td colspan="3"><hr></td></tr>'
412
+ )
413
+ tpl = tpl.replace(
414
+ "<tr><td></td><td></td></tr>", '<tr><td colspan="2"><hr></td></tr>'
415
+ )
416
+
417
+ # Generate end-of-year (EOY) returns comparison table
418
+ if benchmark is not None:
419
+ # Use original benchmark for EOY comparison to preserve accurate yearly returns
420
+ # This prevents loss of benchmark returns on non-trading days
421
+ benchmark_for_eoy = benchmark_original if benchmark_original is not None else benchmark
422
+ yoy = _get_stats().compare(
423
+ returns, benchmark_for_eoy, "YE", compounded=compounded, prepare_returns=False
424
+ )
425
+ # Set appropriate column names based on data type
426
+ if isinstance(returns, _pd.Series):
427
+ yoy.columns = [benchmark_title, strategy_title, "Multiplier", "Won"]
428
+ elif isinstance(returns, _pd.DataFrame):
429
+ yoy.columns = list(
430
+ _pd.core.common.flatten([benchmark_title, strategy_title])
431
+ )
432
+ yoy.index.name = "Year"
433
+ tpl = tpl.replace("{{eoy_title}}", "<h3>EOY Returns vs Benchmark</h3>")
434
+ tpl = tpl.replace("{{eoy_table}}", _html_table(yoy))
435
+ else:
436
+ # Generate EOY returns table without benchmark comparison
437
+ # pct multiplier
438
+ yoy = _pd.DataFrame(_get_utils().group_returns(returns, returns.index.year) * 100)
439
+ if isinstance(returns, _pd.Series):
440
+ yoy.columns = ["Return"]
441
+ yoy["Cumulative"] = _get_utils().group_returns(returns, returns.index.year, True) * 100
442
+ # Don't add "%" here - the CSS in report.html handles it via :after pseudo-element
443
+ # Adding "%" in Python causes double "%" display (bug #475)
444
+ elif isinstance(returns, _pd.DataFrame):
445
+ # Don't show cumulative for multiple strategy portfolios
446
+ # just show compounded like when we have a benchmark
447
+ yoy.columns = list(_pd.core.common.flatten(strategy_title))
448
+
449
+ yoy.index.name = "Year"
450
+ tpl = tpl.replace("{{eoy_title}}", "<h3>EOY Returns</h3>")
451
+ tpl = tpl.replace("{{eoy_table}}", _html_table(yoy))
452
+
453
+ # Generate drawdown analysis table
454
+ if isinstance(returns, _pd.Series):
455
+ # Calculate drawdown series and get worst drawdown periods
456
+ dd = _get_stats().to_drawdown_series(returns)
457
+ dd_info = _get_stats().drawdown_details(dd).sort_values(
458
+ by="max drawdown", ascending=True
459
+ )[:10]
460
+ dd_info = dd_info[["start", "end", "max drawdown", "days"]]
461
+ dd_info.columns = ["Started", "Recovered", "Drawdown", "Days"]
462
+ tpl = tpl.replace("{{dd_info}}", _html_table(dd_info, False))
463
+ elif isinstance(returns, _pd.DataFrame):
464
+ # Handle multiple strategy columns
465
+ dd_info_list = []
466
+ for col in returns.columns:
467
+ dd = _get_stats().to_drawdown_series(returns[col])
468
+ dd_info = _get_stats().drawdown_details(dd).sort_values(
469
+ by="max drawdown", ascending=True
470
+ )[:10]
471
+ dd_info = dd_info[["start", "end", "max drawdown", "days"]]
472
+ dd_info.columns = ["Started", "Recovered", "Drawdown", "Days"]
473
+ dd_info_list.append(_html_table(dd_info, False))
474
+
475
+ # Combine all drawdown tables with headers
476
+ dd_html_table = ""
477
+ for html_str, col in zip(dd_info_list, returns.columns, strict=False):
478
+ dd_html_table = (
479
+ dd_html_table + f"<h3>{col}</h3><br>" + StringIO(html_str).read()
480
+ )
481
+ tpl = tpl.replace("{{dd_info}}", dd_html_table)
482
+
483
+ # Get active returns setting for plots
484
+ active = kwargs.get("active_returns", False)
485
+
486
+ # Generate all the performance plots and embed them in the HTML
487
+ # plots
488
+ figfile = _get_utils()._file_stream()
489
+ _get_plots().returns(
490
+ returns,
491
+ benchmark,
492
+ grayscale=grayscale,
493
+ figsize=(8, 5),
494
+ subtitle=False,
495
+ savefig={"fname": figfile, "format": figfmt},
496
+ show=False,
497
+ ylabel="",
498
+ compound=compounded,
499
+ prepare_returns=False,
500
+ )
501
+ tpl = tpl.replace("{{returns}}", _embed_figure(figfile, figfmt))
502
+
503
+ # Log returns plot for better visualization of performance
504
+ figfile = _get_utils()._file_stream()
505
+ _get_plots().log_returns(
506
+ returns,
507
+ benchmark,
508
+ grayscale=grayscale,
509
+ figsize=(8, 4),
510
+ subtitle=False,
511
+ savefig={"fname": figfile, "format": figfmt},
512
+ show=False,
513
+ ylabel="",
514
+ compound=compounded,
515
+ prepare_returns=False,
516
+ )
517
+ tpl = tpl.replace("{{log_returns}}", _embed_figure(figfile, figfmt))
518
+
519
+ # Volatility-matched returns plot (only if benchmark exists)
520
+ if benchmark is not None:
521
+ figfile = _get_utils()._file_stream()
522
+ _get_plots().returns(
523
+ returns,
524
+ benchmark,
525
+ match_volatility=True,
526
+ grayscale=grayscale,
527
+ figsize=(8, 4),
528
+ subtitle=False,
529
+ savefig={"fname": figfile, "format": figfmt},
530
+ show=False,
531
+ ylabel="",
532
+ compound=compounded,
533
+ prepare_returns=False,
534
+ )
535
+ tpl = tpl.replace("{{vol_returns}}", _embed_figure(figfile, figfmt))
536
+
537
+ # Yearly returns comparison chart
538
+ figfile = _get_utils()._file_stream()
539
+ _get_plots().yearly_returns(
540
+ returns,
541
+ benchmark,
542
+ grayscale=grayscale,
543
+ figsize=(8, 4),
544
+ subtitle=False,
545
+ savefig={"fname": figfile, "format": figfmt},
546
+ show=False,
547
+ ylabel="",
548
+ compounded=compounded,
549
+ prepare_returns=False,
550
+ )
551
+ tpl = tpl.replace("{{eoy_returns}}", _embed_figure(figfile, figfmt))
552
+
553
+ # Returns distribution histogram
554
+ figfile = _get_utils()._file_stream()
555
+ _get_plots().histogram(
556
+ returns,
557
+ benchmark,
558
+ grayscale=grayscale,
559
+ figsize=(7, 4),
560
+ subtitle=False,
561
+ savefig={"fname": figfile, "format": figfmt},
562
+ show=False,
563
+ ylabel="",
564
+ compounded=compounded,
565
+ prepare_returns=False,
566
+ )
567
+ tpl = tpl.replace("{{monthly_dist}}", _embed_figure(figfile, figfmt))
568
+
569
+ # Daily returns scatter plot
570
+ figfile = _get_utils()._file_stream()
571
+ _get_plots().daily_returns(
572
+ returns,
573
+ benchmark,
574
+ grayscale=grayscale,
575
+ figsize=(8, 3),
576
+ subtitle=False,
577
+ savefig={"fname": figfile, "format": figfmt},
578
+ show=False,
579
+ ylabel="",
580
+ prepare_returns=False,
581
+ active=active,
582
+ )
583
+ tpl = tpl.replace("{{daily_returns}}", _embed_figure(figfile, figfmt))
584
+
585
+ # Rolling beta analysis (only if benchmark exists)
586
+ if benchmark is not None:
587
+ figfile = _get_utils()._file_stream()
588
+ _get_plots().rolling_beta(
589
+ returns,
590
+ benchmark,
591
+ grayscale=grayscale,
592
+ figsize=(8, 3),
593
+ subtitle=False,
594
+ window1=win_half_year,
595
+ window2=win_year,
596
+ savefig={"fname": figfile, "format": figfmt},
597
+ show=False,
598
+ ylabel="",
599
+ prepare_returns=False,
600
+ )
601
+ tpl = tpl.replace("{{rolling_beta}}", _embed_figure(figfile, figfmt))
602
+
603
+ # Rolling volatility analysis
604
+ figfile = _get_utils()._file_stream()
605
+ _get_plots().rolling_volatility(
606
+ returns,
607
+ benchmark,
608
+ grayscale=grayscale,
609
+ figsize=(8, 3),
610
+ subtitle=False,
611
+ savefig={"fname": figfile, "format": figfmt},
612
+ show=False,
613
+ ylabel="",
614
+ period=win_half_year,
615
+ periods_per_year=win_year,
616
+ )
617
+ tpl = tpl.replace("{{rolling_vol}}", _embed_figure(figfile, figfmt))
618
+
619
+ # Rolling Sharpe ratio analysis
620
+ figfile = _get_utils()._file_stream()
621
+ _get_plots().rolling_sharpe(
622
+ returns,
623
+ grayscale=grayscale,
624
+ figsize=(8, 3),
625
+ subtitle=False,
626
+ savefig={"fname": figfile, "format": figfmt},
627
+ show=False,
628
+ ylabel="",
629
+ period=win_half_year,
630
+ periods_per_year=win_year,
631
+ )
632
+ tpl = tpl.replace("{{rolling_sharpe}}", _embed_figure(figfile, figfmt))
633
+
634
+ # Rolling Sortino ratio analysis
635
+ figfile = _get_utils()._file_stream()
636
+ _get_plots().rolling_sortino(
637
+ returns,
638
+ grayscale=grayscale,
639
+ figsize=(8, 3),
640
+ subtitle=False,
641
+ savefig={"fname": figfile, "format": figfmt},
642
+ show=False,
643
+ ylabel="",
644
+ period=win_half_year,
645
+ periods_per_year=win_year,
646
+ )
647
+ tpl = tpl.replace("{{rolling_sortino}}", _embed_figure(figfile, figfmt))
648
+
649
+ # Drawdown periods analysis
650
+ figfile = _get_utils()._file_stream()
651
+ if isinstance(returns, _pd.Series):
652
+ _get_plots().drawdowns_periods(
653
+ returns,
654
+ grayscale=grayscale,
655
+ figsize=(8, 4),
656
+ subtitle=False,
657
+ title=returns.name,
658
+ savefig={"fname": figfile, "format": figfmt},
659
+ show=False,
660
+ ylabel="",
661
+ compounded=compounded,
662
+ prepare_returns=False,
663
+ )
664
+ tpl = tpl.replace("{{dd_periods}}", _embed_figure(figfile, figfmt))
665
+ elif isinstance(returns, _pd.DataFrame):
666
+ # Handle multiple strategy columns
667
+ embed = []
668
+ for col in returns.columns:
669
+ _get_plots().drawdowns_periods(
670
+ returns[col],
671
+ grayscale=grayscale,
672
+ figsize=(8, 4),
673
+ subtitle=False,
674
+ title=col,
675
+ savefig={"fname": figfile, "format": figfmt},
676
+ show=False,
677
+ ylabel="",
678
+ compounded=compounded,
679
+ prepare_returns=False,
680
+ )
681
+ embed.append(figfile)
682
+ tpl = tpl.replace("{{dd_periods}}", _embed_figure(embed, figfmt))
683
+
684
+ # Underwater (drawdown) plot
685
+ figfile = _get_utils()._file_stream()
686
+ _get_plots().drawdown(
687
+ returns,
688
+ grayscale=grayscale,
689
+ figsize=(8, 3),
690
+ subtitle=False,
691
+ savefig={"fname": figfile, "format": figfmt},
692
+ show=False,
693
+ ylabel="",
694
+ )
695
+ tpl = tpl.replace("{{dd_plot}}", _embed_figure(figfile, figfmt))
696
+
697
+ # Monthly returns heatmap
698
+ figfile = _get_utils()._file_stream()
699
+ if isinstance(returns, _pd.Series):
700
+ _get_plots().monthly_heatmap(
701
+ returns,
702
+ benchmark,
703
+ grayscale=grayscale,
704
+ figsize=(8, 4),
705
+ cbar=False,
706
+ returns_label=returns.name,
707
+ savefig={"fname": figfile, "format": figfmt},
708
+ show=False,
709
+ ylabel="",
710
+ compounded=compounded,
711
+ active=active,
712
+ )
713
+ tpl = tpl.replace("{{monthly_heatmap}}", _embed_figure(figfile, figfmt))
714
+ elif isinstance(returns, _pd.DataFrame):
715
+ # Handle multiple strategy columns
716
+ embed = []
717
+ for col in returns.columns:
718
+ _get_plots().monthly_heatmap(
719
+ returns[col],
720
+ benchmark,
721
+ grayscale=grayscale,
722
+ figsize=(8, 4),
723
+ cbar=False,
724
+ returns_label=col,
725
+ savefig={"fname": figfile, "format": figfmt},
726
+ show=False,
727
+ ylabel="",
728
+ compounded=compounded,
729
+ active=active,
730
+ )
731
+ embed.append(figfile)
732
+ tpl = tpl.replace("{{monthly_heatmap}}", _embed_figure(embed, figfmt))
733
+
734
+ # Returns distribution analysis
735
+ figfile = _get_utils()._file_stream()
736
+
737
+ if isinstance(returns, _pd.Series):
738
+ _get_plots().distribution(
739
+ returns,
740
+ grayscale=grayscale,
741
+ figsize=(8, 4),
742
+ subtitle=False,
743
+ title=returns.name,
744
+ savefig={"fname": figfile, "format": figfmt},
745
+ show=False,
746
+ ylabel="",
747
+ compounded=compounded,
748
+ prepare_returns=False,
749
+ )
750
+ tpl = tpl.replace("{{returns_dist}}", _embed_figure(figfile, figfmt))
751
+ elif isinstance(returns, _pd.DataFrame):
752
+ # Handle multiple strategy columns
753
+ embed = []
754
+ for col in returns.columns:
755
+ _get_plots().distribution(
756
+ returns[col],
757
+ grayscale=grayscale,
758
+ figsize=(8, 4),
759
+ subtitle=False,
760
+ title=col,
761
+ savefig={"fname": figfile, "format": figfmt},
762
+ show=False,
763
+ ylabel="",
764
+ compounded=compounded,
765
+ prepare_returns=False,
766
+ )
767
+ embed.append(figfile)
768
+ tpl = tpl.replace("{{returns_dist}}", _embed_figure(embed, figfmt))
769
+
770
+ # Clean up any remaining template placeholders
771
+ tpl = _regex.sub(r"\{\{(.*?)\}\}", "", tpl)
772
+ tpl = tpl.replace("white-space:pre;", "")
773
+
774
+ # Handle output - either download in browser or save to file
775
+ if output is None:
776
+ if _get_utils()._in_notebook():
777
+ _download_html(tpl, download_filename)
778
+ else:
779
+ # Save to temp file and open in browser
780
+ with tempfile.NamedTemporaryFile(
781
+ mode="w", suffix=".html", delete=False, encoding="utf-8"
782
+ ) as f:
783
+ f.write(tpl)
784
+ temp_path = f.name
785
+ webbrowser.open("file://" + temp_path)
786
+ return
787
+
788
+ # Write HTML content to specified output file
789
+ with open(output, "w", encoding="utf-8") as f:
790
+ f.write(tpl)
791
+
792
+
793
+ # Metric rows removed from the simple tearsheet (matched by normalized label,
794
+ # i.e. case-insensitive and ignoring '%').
795
+ _SIMPLE_DROP_METRICS = [
796
+ "Max DD Date",
797
+ "Max DD Period Start",
798
+ "Max DD Period End",
799
+ "Risk-Adjusted Return",
800
+ "Risk-Return Ratio",
801
+ "Avg. Return",
802
+ "Avg. Win",
803
+ "Avg. Loss",
804
+ "Win/Loss Ratio",
805
+ "Profit Ratio",
806
+ ]
807
+
808
+
809
+ def html_simple(
810
+ returns,
811
+ benchmark=None,
812
+ rf=0.0,
813
+ grayscale=False,
814
+ title="Strategy Tearsheet",
815
+ output=None,
816
+ compounded=True,
817
+ periods_per_year=252,
818
+ download_filename="quantstats-tearsheet.html",
819
+ figfmt="svg",
820
+ template_path=None,
821
+ match_dates=True,
822
+ **kwargs,
823
+ ):
824
+ """
825
+ Generate a simplified HTML tearsheet for equity-curve evaluation.
826
+
827
+ A leaner variant of :func:`html` that keeps the metrics and charts most
828
+ relevant when judging an equity curve, and drops noisier sections. Relative
829
+ to the full report it removes the rolling beta/Sharpe/Sortino charts, the
830
+ cumulative daily-returns chart, the monthly-returns heatmap and the return
831
+ quantiles chart; the monthly-returns histogram is replaced by a daily one.
832
+ The metrics table drops averages/ratios and max-drawdown dates, and the
833
+ worst-drawdowns table is limited to the top 5.
834
+
835
+ Parameters mirror :func:`html`. ``returns`` should be a daily-returns Series
836
+ (or single/multi-column DataFrame). ``benchmark`` is optional.
837
+ """
838
+ from ._reporting import engine, sections
839
+
840
+ if match_dates:
841
+ returns = returns.dropna()
842
+
843
+ win_year, win_half_year = _get_trading_periods(periods_per_year)
844
+
845
+ if template_path is None:
846
+ template_path = Path(__file__).parent / "report_simple.html"
847
+ else:
848
+ template_path = Path(template_path)
849
+ template_path = template_path.resolve()
850
+ if not template_path.exists():
851
+ raise FileNotFoundError(f"Template file not found: {template_path}")
852
+ if not template_path.is_file():
853
+ raise ValueError(f"Template path is not a file: {template_path}")
854
+ tpl = template_path.read_text(encoding="utf-8")
855
+
856
+ if match_dates:
857
+ returns = returns.dropna()
858
+ returns = _get_utils()._prepare_returns(returns)
859
+
860
+ strategy_title = kwargs.get("strategy_title", "Strategy")
861
+ if (
862
+ isinstance(returns, _pd.DataFrame)
863
+ and len(returns.columns) > 1
864
+ and isinstance(strategy_title, str)
865
+ ):
866
+ strategy_title = list(returns.columns)
867
+
868
+ benchmark_original = None
869
+ if benchmark is not None:
870
+ benchmark_title = kwargs.get("benchmark_title")
871
+ if benchmark_title is None:
872
+ if isinstance(benchmark, str):
873
+ benchmark_title = benchmark
874
+ elif isinstance(benchmark, _pd.Series):
875
+ benchmark_title = benchmark.name if benchmark.name else "Benchmark"
876
+ elif isinstance(benchmark, _pd.DataFrame):
877
+ col_name = benchmark[benchmark.columns[0]].name
878
+ benchmark_title = col_name if col_name else "Benchmark"
879
+ if benchmark_title is None:
880
+ benchmark_title = "Benchmark"
881
+
882
+ if isinstance(benchmark, str):
883
+ benchmark_original = _get_utils().download_returns(benchmark)
884
+ if rf != 0:
885
+ benchmark_original = _get_utils().to_excess_returns(
886
+ benchmark_original, rf, nperiods=periods_per_year
887
+ )
888
+ elif isinstance(benchmark, _pd.Series):
889
+ benchmark_original = benchmark.copy()
890
+ else:
891
+ benchmark_original = benchmark
892
+
893
+ benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
894
+ if match_dates is True:
895
+ returns, benchmark = _match_dates(returns, benchmark)
896
+ else:
897
+ benchmark_title = None
898
+
899
+ # Header substitutions
900
+ date_range = returns.index.strftime("%e %b, %Y")
901
+ full_title = f"{title} (Compounded)" if compounded else title
902
+
903
+ params_parts = []
904
+ user_params = kwargs.get("parameters", {})
905
+ if user_params:
906
+ for key, value in user_params.items():
907
+ params_parts.append(f"{key}: {value}")
908
+ if benchmark_title:
909
+ params_parts.append(f"Benchmark: {benchmark_title.upper()}")
910
+ params_parts.append(f"Periods/Year: {periods_per_year}")
911
+ params_parts.append(f"RF: {rf:.1%}")
912
+ params_str = " &bull; ".join(params_parts)
913
+ if params_str:
914
+ params_str += " | "
915
+
916
+ matched_dates_str = (
917
+ " (matched dates)" if match_dates and benchmark is not None else ""
918
+ )
919
+
920
+ if benchmark is not None:
921
+ benchmark.name = benchmark_title
922
+ if isinstance(returns, _pd.Series):
923
+ returns.name = strategy_title
924
+ elif isinstance(returns, _pd.DataFrame):
925
+ returns.columns = (
926
+ strategy_title if isinstance(strategy_title, list) else [strategy_title]
927
+ )
928
+
929
+ # Metrics table (full set minus the simple drop list)
930
+ metrics_html = sections.metrics_table(
931
+ returns,
932
+ benchmark=benchmark,
933
+ rf=rf,
934
+ compounded=compounded,
935
+ periods_per_year=periods_per_year,
936
+ drop_rows=_SIMPLE_DROP_METRICS,
937
+ collapse_separators=True,
938
+ style_separators=True,
939
+ strategy_title=strategy_title,
940
+ benchmark_title=benchmark_title,
941
+ prepare_returns=False,
942
+ )
943
+
944
+ # EOY table
945
+ eoy_html = sections.eoy_table(
946
+ returns,
947
+ benchmark=benchmark,
948
+ benchmark_original=benchmark_original,
949
+ compounded=compounded,
950
+ strategy_title=strategy_title,
951
+ benchmark_title=benchmark_title,
952
+ )
953
+ eoy_title = (
954
+ "<h3>EOY Returns vs Benchmark</h3>"
955
+ if benchmark is not None
956
+ else "<h3>EOY Returns</h3>"
957
+ )
958
+
959
+ # Worst 5 drawdowns table
960
+ if isinstance(returns, _pd.Series):
961
+ dd_info_html = sections.dd_table(returns, top=5)
962
+ else:
963
+ parts = []
964
+ for col in returns.columns:
965
+ parts.append(f"<h3>{col}</h3><br>" + sections.dd_table(returns[col], top=5))
966
+ dd_info_html = "".join(parts)
967
+
968
+ fragments = {
969
+ "title": full_title,
970
+ "date_range": date_range[0] + " - " + date_range[-1],
971
+ "matched_dates": matched_dates_str,
972
+ "params": params_str,
973
+ "v": __version__,
974
+ "generated_at": _dt.now().strftime("%d %b, %Y %H:%M").lstrip("0"),
975
+ "metrics": metrics_html,
976
+ "eoy_title": eoy_title,
977
+ "eoy_table": eoy_html,
978
+ "dd_info": dd_info_html,
979
+ }
980
+
981
+ # Charts kept in the simple report
982
+ fragments["returns"] = sections.plot_section(
983
+ "returns", returns, benchmark=benchmark, figfmt=figfmt,
984
+ grayscale=grayscale, figsize=(8, 5), subtitle=False, ylabel="",
985
+ compound=compounded, prepare_returns=False,
986
+ )
987
+ fragments["log_returns"] = sections.plot_section(
988
+ "log_returns", returns, benchmark=benchmark, figfmt=figfmt,
989
+ grayscale=grayscale, figsize=(8, 4), subtitle=False, ylabel="",
990
+ compound=compounded, prepare_returns=False,
991
+ )
992
+ if benchmark is not None:
993
+ fragments["vol_returns"] = sections.plot_section(
994
+ "returns", returns, benchmark=benchmark, figfmt=figfmt,
995
+ match_volatility=True, grayscale=grayscale, figsize=(8, 4),
996
+ subtitle=False, ylabel="", compound=compounded, prepare_returns=False,
997
+ )
998
+ fragments["eoy_returns"] = sections.plot_section(
999
+ "yearly_returns", returns, benchmark=benchmark, figfmt=figfmt,
1000
+ grayscale=grayscale, figsize=(8, 4), subtitle=False, ylabel="",
1001
+ compounded=compounded, prepare_returns=False,
1002
+ )
1003
+ fragments["daily_dist"] = sections.plot_section(
1004
+ "histogram", returns, benchmark=benchmark, figfmt=figfmt,
1005
+ resample="D", grayscale=grayscale, figsize=(7, 4), subtitle=False,
1006
+ ylabel="", compounded=compounded, xlim_quantile=0.01, adaptive_bins=80,
1007
+ prepare_returns=False,
1008
+ )
1009
+ fragments["rolling_vol"] = sections.plot_section(
1010
+ "rolling_volatility", returns, benchmark=benchmark, figfmt=figfmt,
1011
+ grayscale=grayscale, figsize=(8, 3), subtitle=False, ylabel="",
1012
+ period=win_half_year, periods_per_year=win_year,
1013
+ )
1014
+ if isinstance(returns, _pd.Series):
1015
+ fragments["dd_periods"] = sections.plot_section(
1016
+ "drawdowns_periods", returns, benchmark=None, figfmt=figfmt,
1017
+ grayscale=grayscale, figsize=(8, 4), subtitle=False,
1018
+ title=returns.name, ylabel="", compounded=compounded,
1019
+ prepare_returns=False,
1020
+ )
1021
+ fragments["dd_plot"] = sections.plot_section(
1022
+ "drawdown", returns, benchmark=None, figfmt=figfmt,
1023
+ grayscale=grayscale, figsize=(8, 3), subtitle=False, ylabel="",
1024
+ )
1025
+
1026
+ rendered = engine.render_report(tpl, fragments)
1027
+
1028
+ if output is None:
1029
+ if _get_utils()._in_notebook():
1030
+ _download_html(rendered, download_filename)
1031
+ else:
1032
+ with tempfile.NamedTemporaryFile(
1033
+ mode="w", suffix=".html", delete=False, encoding="utf-8"
1034
+ ) as f:
1035
+ f.write(rendered)
1036
+ temp_path = f.name
1037
+ webbrowser.open("file://" + temp_path)
1038
+ return
1039
+
1040
+ with open(output, "w", encoding="utf-8") as f:
1041
+ f.write(rendered)
1042
+
1043
+
1044
+ # Cross-model comparison columns: (summary_key, display_label, is_percent, highlight_risk)
1045
+ _MC_TABLE_COLUMNS = [
1046
+ ("cagr_p5", "CAGR p5", True, True),
1047
+ ("cagr_median", "CAGR Median", True, False),
1048
+ ("cagr_p95", "CAGR p95", True, False),
1049
+ ("maxdd_median", "MaxDD Median", True, False),
1050
+ ("maxdd_p95", "MaxDD Worst 5%", True, True),
1051
+ ("terminal_median", "Return Median", True, False),
1052
+ ("prob_loss", "P(Loss)", True, True),
1053
+ ("cvar_5", "CVaR 5%", True, True),
1054
+ ("bust_prob", "P(Bust)", True, True),
1055
+ ("goal_prob", "P(Goal)", True, False),
1056
+ ("realism_pct", "Hist. Percentile", False, False),
1057
+ ]
1058
+
1059
+ _MC_KPI_METRICS = [
1060
+ ("cagr_p5", "CAGR p5", True),
1061
+ ("cagr_median", "CAGR Median", True),
1062
+ ("maxdd_p95", "MaxDD Worst 5%", True),
1063
+ ("prob_loss", "P(Loss)", True),
1064
+ ("cvar_5", "CVaR 5%", True),
1065
+ ("bust_prob", "P(Bust)", True),
1066
+ ]
1067
+
1068
+ # Visual tone and one-line hint for each KPI card.
1069
+ _MC_KPI_CARD_META = {
1070
+ "cagr_p5": ("risk", "5% worst-case annual return"),
1071
+ "cagr_median": ("upside", "central annual return scenario"),
1072
+ "maxdd_p95": ("risk", "drawdown exceeded by 5% of paths"),
1073
+ "prob_loss": ("risk", "paths ending below break-even"),
1074
+ "cvar_5": ("risk", "average loss in the worst 5% tail"),
1075
+ "bust_prob": ("risk", "paths hitting the bust drawdown"),
1076
+ }
1077
+
1078
+
1079
+ def _mc_format_value(key: str, val: float, is_pct: bool) -> str:
1080
+ if key == "realism_pct":
1081
+ return f"{val:.0f}%"
1082
+ if is_pct:
1083
+ return f"{val * 100:,.1f}%"
1084
+ return f"{val:,.2f}"
1085
+
1086
+
1087
+ def _mc_cvar_label(horizon: int, periods: float) -> str:
1088
+ years = horizon / periods if periods else 1.0
1089
+ if abs(years - 1.0) < 0.05:
1090
+ return "CVaR 5% (1y)"
1091
+ if abs(years - round(years)) < 0.05 and years >= 1:
1092
+ return f"CVaR 5% ({int(round(years))}y)"
1093
+ return f"CVaR 5% ({horizon}p)"
1094
+
1095
+
1096
+ def _mc_build_rows(results, columns, extra: dict[str, dict] | None = None):
1097
+ """Build formatted comparison rows keyed by model label."""
1098
+ rows = {}
1099
+ for res in results.values():
1100
+ summary = dict(res.summary)
1101
+ if extra and res.label in extra:
1102
+ summary.update(extra[res.label])
1103
+ row = {}
1104
+ for key, label, is_pct, _ in columns:
1105
+ if key not in summary:
1106
+ continue
1107
+ row[label] = _mc_format_value(key, summary[key], is_pct)
1108
+ rows[res.label] = row
1109
+ return rows
1110
+
1111
+
1112
+ def _mc_comparison_html(rows, columns):
1113
+ """Render comparison table with risk-quantile columns highlighted."""
1114
+ risk_labels = {label for _, label, _, risk in columns if risk}
1115
+ active_cols = [
1116
+ (label, risk)
1117
+ for _, label, _, risk in columns
1118
+ if any(label in row for row in rows.values())
1119
+ ]
1120
+ parts = [
1121
+ "<table><thead><tr><th>Model</th>",
1122
+ *[f"<th>{label}</th>" for label, _ in active_cols],
1123
+ "</tr></thead><tbody>",
1124
+ ]
1125
+ for model, row in rows.items():
1126
+ row_cls = ' class="historical"' if model.startswith("Historical") else ""
1127
+ parts.append(f"<tr{row_cls}><td><strong>{model}</strong></td>")
1128
+ for label, risk in active_cols:
1129
+ val = row.get(label, "—")
1130
+ cls = ' class="risk"' if risk and label in risk_labels else ""
1131
+ parts.append(f"<td{cls}>{val}</td>")
1132
+ parts.append("</tr>")
1133
+ parts.append("</tbody></table>")
1134
+ return "".join(parts)
1135
+
1136
+
1137
+ def _mc_kpi_row_html(metrics: dict[str, float], cvar_label: str) -> str:
1138
+ """KPI cards for a metrics dict (median or envelope)."""
1139
+ label_map = {key: label for key, label, _ in _MC_KPI_METRICS}
1140
+ label_map["cvar_5"] = cvar_label
1141
+
1142
+ parts = ['<div class="kpi-grid">']
1143
+ for key, label, is_pct in _MC_KPI_METRICS:
1144
+ if key not in metrics:
1145
+ continue
1146
+ display = _mc_format_value(key, metrics[key], is_pct)
1147
+ tone, hint = _MC_KPI_CARD_META.get(key, ("neutral", ""))
1148
+ if tone == "upside" and metrics[key] < 0:
1149
+ tone = "risk"
1150
+ hint_html = f'<div class="hint">{hint}</div>' if hint else ""
1151
+ parts.append(
1152
+ f'<div class="kpi {tone}"><div class="label">{label_map.get(key, label)}</div>'
1153
+ f'<div class="value">{display}</div>{hint_html}</div>'
1154
+ )
1155
+ parts.append("</div>")
1156
+ return "".join(parts)
1157
+
1158
+
1159
+ def _mc_risk_summary_html(median: dict[str, float], cvar_label: str) -> str:
1160
+ """Neutral KPI cards: median across Monte Carlo models."""
1161
+ if not median:
1162
+ return '<p class="note">No Monte Carlo models in this run.</p>'
1163
+ return _mc_kpi_row_html(median, cvar_label)
1164
+
1165
+
1166
+ def _mc_envelope_attribution_html(
1167
+ envelope: dict[str, float],
1168
+ attribution: dict[str, str],
1169
+ cvar_label: str,
1170
+ ) -> str:
1171
+ """Conservative envelope KPIs and per-metric source model attribution."""
1172
+ if not envelope:
1173
+ return ""
1174
+ label_map = {key: label for key, label, _ in _MC_KPI_METRICS}
1175
+ label_map["cvar_5"] = cvar_label
1176
+
1177
+ parts = [
1178
+ '<h4>Conservative Envelope</h4>',
1179
+ _mc_kpi_row_html(envelope, cvar_label),
1180
+ '<p class="note">Envelope extremes across Monte Carlo models '
1181
+ "(most conservative quantiles).</p>",
1182
+ ]
1183
+ if attribution:
1184
+ parts.append(
1185
+ "<table><thead><tr><th>Metric</th><th>Envelope</th>"
1186
+ "<th>Source Model</th></tr></thead><tbody>"
1187
+ )
1188
+ for key, label, is_pct in _MC_KPI_METRICS:
1189
+ if key not in envelope:
1190
+ continue
1191
+ val = _mc_format_value(key, envelope[key], is_pct)
1192
+ src = attribution.get(key, "—")
1193
+ parts.append(
1194
+ f"<tr><td>{label_map.get(key, label)}</td>"
1195
+ f"<td>{val}</td><td>{src}</td></tr>"
1196
+ )
1197
+ parts.append("</tbody></table>")
1198
+ return "".join(parts)
1199
+
1200
+
1201
+ def _mc_stress_section_html(
1202
+ stress_comparison_html: str,
1203
+ envelope: dict[str, float],
1204
+ attribution: dict[str, str],
1205
+ cvar_label: str,
1206
+ ) -> str:
1207
+ """Stress block: conservative envelope plus trimmed-bootstrap models."""
1208
+ parts = [_mc_envelope_attribution_html(envelope, attribution, cvar_label)]
1209
+ if stress_comparison_html:
1210
+ parts.append("<h4>Trimmed Bootstrap</h4>")
1211
+ parts.append(stress_comparison_html)
1212
+ elif not envelope:
1213
+ parts.append('<p class="note">No stress-test models in this run.</p>')
1214
+ return "".join(parts)
1215
+
1216
+
1217
+ def _mc_calibration_html(results):
1218
+ """Per-model calibration diagnostics: one compact row per model.
1219
+
1220
+ Each model exposes a different parameter set, so a wide matrix would be
1221
+ mostly empty. Render Model | inline "key: value" pairs instead.
1222
+ """
1223
+ rows = []
1224
+ for res in results.values():
1225
+ cal = res.calibration_summary()
1226
+ if not cal:
1227
+ continue
1228
+ params = " &nbsp;&bull;&nbsp; ".join(
1229
+ f"{k}: <strong>{v}</strong>" for k, v in cal.items()
1230
+ )
1231
+ rows.append(f'<tr><td>{res.label}</td><td class="params">{params}</td></tr>')
1232
+ if not rows:
1233
+ return '<p class="note">No calibration diagnostics available.</p>'
1234
+ return (
1235
+ "<table><thead><tr><th>Model</th><th>Calibrated Parameters</th>"
1236
+ "</tr></thead><tbody>" + "".join(rows) + "</tbody></table>"
1237
+ )
1238
+
1239
+
1240
+ def html_montecarlo(
1241
+ returns,
1242
+ models=None,
1243
+ horizon=None,
1244
+ sims=1000,
1245
+ bust=None,
1246
+ goal=None,
1247
+ seed=None,
1248
+ rf=0.0,
1249
+ title="Monte Carlo Tearsheet",
1250
+ output=None,
1251
+ periods_per_year=None,
1252
+ download_filename="quantstats-montecarlo.html",
1253
+ figfmt="svg",
1254
+ template_path=None,
1255
+ confidence_level=0.95,
1256
+ drift="historical",
1257
+ match_dates=True,
1258
+ **kwargs,
1259
+ ):
1260
+ """
1261
+ Generate a multi-model Monte Carlo HTML tearsheet for a single asset.
1262
+
1263
+ Characterises the asset with several models (GBM, jump-diffusion, GARCH,
1264
+ Heston, bootstraps, Bayesian, ...) and simulates forward paths from each,
1265
+ producing a cross-model comparison table plus per-model fan charts and
1266
+ terminal-return distributions.
1267
+
1268
+ Parameters
1269
+ ----------
1270
+ returns : pd.Series or pd.DataFrame
1271
+ Daily simple returns of a single asset. A DataFrame uses its first
1272
+ column.
1273
+ models : list[str], optional
1274
+ Subset of model names to run. Defaults to all registered models.
1275
+ horizon : int, optional
1276
+ Periods per simulated path. Defaults to one year (``periods_per_year``
1277
+ trading days). Pass ``len(returns)`` for full-history horizon.
1278
+ sims : int, default 1000
1279
+ Number of simulated paths per model.
1280
+ bust : float, optional
1281
+ Drawdown threshold for bust probability (e.g. ``-0.25``).
1282
+ goal : float, optional
1283
+ Terminal-return threshold for goal probability (e.g. ``0.5``).
1284
+ seed : int, optional
1285
+ Base random seed for reproducibility.
1286
+ title : str, default "Monte Carlo Tearsheet"
1287
+ Report title.
1288
+ output : str or None, default None
1289
+ Output file path. If None, opens in browser / downloads in notebook.
1290
+ periods_per_year : int, optional
1291
+ Periods per year for annualisation. When ``None``, inferred from the
1292
+ return index (252 for weekdays-only, 365 for 24/7 data).
1293
+ figfmt : str, default "svg"
1294
+ Embedded figure format.
1295
+ confidence_level : float, default 0.95
1296
+ Confidence band level for the fan charts.
1297
+ drift : {"historical", "zero", "rf"}, default "historical"
1298
+ Drift handling before calibration (see ``montecarlo.run_models``).
1299
+ """
1300
+ import matplotlib.pyplot as _plt
1301
+
1302
+ from . import montecarlo as _mc
1303
+ from ._reporting import engine
1304
+ from .montecarlo import analytics as _mca
1305
+ from .montecarlo import plotting as _mcplt
1306
+ from .montecarlo.core import infer_periods_per_year
1307
+
1308
+ if match_dates and hasattr(returns, "dropna"):
1309
+ returns = returns.dropna()
1310
+ returns = _get_utils()._prepare_returns(returns)
1311
+ if isinstance(returns, _pd.DataFrame):
1312
+ returns = returns.iloc[:, 0]
1313
+
1314
+ asset_title = kwargs.get("strategy_title")
1315
+ if asset_title is None:
1316
+ asset_title = returns.name if returns.name else "Asset"
1317
+
1318
+ if template_path is None:
1319
+ template_path = Path(__file__).parent / "report_montecarlo.html"
1320
+ else:
1321
+ template_path = Path(template_path)
1322
+ template_path = template_path.resolve()
1323
+ if not template_path.exists():
1324
+ raise FileNotFoundError(f"Template file not found: {template_path}")
1325
+ tpl = template_path.read_text(encoding="utf-8")
1326
+
1327
+ periods = (
1328
+ float(periods_per_year)
1329
+ if periods_per_year is not None
1330
+ else infer_periods_per_year(returns)
1331
+ )
1332
+
1333
+ results = _mc.run_models(
1334
+ returns,
1335
+ models=models,
1336
+ horizon=horizon,
1337
+ sims=sims,
1338
+ bust=bust,
1339
+ goal=goal,
1340
+ seed=seed,
1341
+ periods=periods,
1342
+ drift=drift,
1343
+ rf=rf,
1344
+ )
1345
+
1346
+ mc_results = {k: v for k, v in results.items() if v.category == "montecarlo"}
1347
+ stress_results = {k: v for k, v in results.items() if v.category == "stress"}
1348
+ mc_list = list(mc_results.values())
1349
+
1350
+ used_horizon = next(iter(results.values())).horizon if results else 0
1351
+ # Empirical distribution of realised outcomes: every overlapping
1352
+ # horizon-length window over the full history (not just the last year).
1353
+ hist_windows = _mca.historical_windows(returns, used_horizon)
1354
+ hist_summary = _mca.historical_summary(
1355
+ returns, used_horizon, periods=periods, bust=bust, goal=goal
1356
+ )
1357
+ n_hist_windows = int(hist_windows.shape[1]) if hist_windows.size else 0
1358
+ hist_terminal = (
1359
+ float(_np.median(_mca.terminal_values(hist_windows)))
1360
+ if hist_windows.size
1361
+ else 0.0
1362
+ )
1363
+
1364
+ realism_extra = {}
1365
+ for res in mc_results.values():
1366
+ realism_extra[res.label] = {
1367
+ "realism_pct": _mca.realism_percentile(
1368
+ res.sim_returns, hist_terminal
1369
+ )
1370
+ }
1371
+
1372
+ cvar_label = _mc_cvar_label(used_horizon, periods)
1373
+ table_columns = [
1374
+ (k, cvar_label if k == "cvar_5" else lbl, pct, risk)
1375
+ for k, lbl, pct, risk in _MC_TABLE_COLUMNS
1376
+ ]
1377
+
1378
+ median = _mca.model_median_summary(mc_results)
1379
+ envelope = _mca.conservative_envelope(mc_results)
1380
+ attribution = _mca.envelope_attribution(mc_results, envelope)
1381
+ assessment_html = _mc_risk_summary_html(median, cvar_label)
1382
+
1383
+ mc_rows = _mc_build_rows(mc_results, table_columns, extra=realism_extra)
1384
+ if hist_summary:
1385
+ hist_row = {}
1386
+ for key, label, is_pct, _ in table_columns:
1387
+ if key in hist_summary:
1388
+ hist_row[label] = _mc_format_value(key, hist_summary[key], is_pct)
1389
+ hist_label = f"Historical ({n_hist_windows:,} rolling windows)"
1390
+ mc_rows = {hist_label: hist_row, **mc_rows}
1391
+ comparison_html = _mc_comparison_html(mc_rows, table_columns)
1392
+
1393
+ if stress_results:
1394
+ stress_rows = _mc_build_rows(stress_results, table_columns)
1395
+ stress_comparison_html = _mc_comparison_html(stress_rows, table_columns)
1396
+ else:
1397
+ stress_comparison_html = ""
1398
+ stress_html = _mc_stress_section_html(
1399
+ stress_comparison_html, envelope, attribution, cvar_label
1400
+ )
1401
+
1402
+ calibration_html = _mc_calibration_html(results)
1403
+ model_names = list(results.keys())
1404
+
1405
+ def _embed(fig):
1406
+ figfile = _get_utils()._file_stream()
1407
+ fig.savefig(figfile, format=figfmt, bbox_inches="tight")
1408
+ _plt.close(fig)
1409
+ return _embed_figure(figfile, figfmt)
1410
+
1411
+ overlay_fig = _mcplt.overlay_fan_figure(
1412
+ mc_list, level=confidence_level, historical_windows=hist_windows
1413
+ )
1414
+ maxdd_fig = _mcplt.maxdd_distribution_figure(
1415
+ mc_list, historical_windows=hist_windows
1416
+ )
1417
+ cagr_fig = _mcplt.cagr_quantiles_figure(
1418
+ mc_list, historical_windows=hist_windows
1419
+ )
1420
+
1421
+ fan_parts = []
1422
+ hist_parts = []
1423
+ for res in results.values():
1424
+ fan_fig = _mcplt.fan_chart_figure(
1425
+ res,
1426
+ level=confidence_level,
1427
+ title=res.label,
1428
+ historical_windows=hist_windows,
1429
+ )
1430
+ fan_parts.append(f'<div class="cell">{_embed(fan_fig)}</div>')
1431
+ hist_fig = _mcplt.terminal_hist_figure(
1432
+ res, title=res.label, historical_terminal=hist_terminal
1433
+ )
1434
+ hist_parts.append(f'<div class="cell">{_embed(hist_fig)}</div>')
1435
+
1436
+ date_range = returns.index.strftime("%e %b, %Y")
1437
+ horizon_years = used_horizon / periods if periods else 1.0
1438
+ params_parts = []
1439
+ if bust is not None:
1440
+ params_parts.append(f"Bust: {bust:.0%}")
1441
+ if goal is not None:
1442
+ params_parts.append(f"Goal: {goal:.0%}")
1443
+ params_parts.append(f"Horizon: {used_horizon} periods ({horizon_years:.1f}y)")
1444
+ params_parts.append(f"Periods/year: {periods:.0f}")
1445
+ params_parts.append(f"Sims: {sims}")
1446
+ params_parts.append(f"Asset: {str(asset_title).upper()}")
1447
+ if drift != "historical":
1448
+ params_parts.append(f"Drift: {drift} (stress scenario)")
1449
+ params_str = " &bull; ".join(params_parts)
1450
+ if params_str:
1451
+ params_str += " | "
1452
+
1453
+ seed_str = str(seed) if seed is not None else "random"
1454
+ assumptions = (
1455
+ f"Assumptions: {sims:,} simulations per model &bull; seed {seed_str} "
1456
+ f"&bull; forward horizon {used_horizon} periods ({horizon_years:.1f}y) "
1457
+ f"&bull; {periods:.0f} periods/year &bull; drift={drift} "
1458
+ f"&bull; models: {', '.join(model_names)}"
1459
+ )
1460
+
1461
+ fragments = {
1462
+ "title": title,
1463
+ "date_range": date_range[0] + " - " + date_range[-1],
1464
+ "params": params_str,
1465
+ "v": __version__,
1466
+ "generated_at": _dt.now().strftime("%d %b, %Y %H:%M").lstrip("0"),
1467
+ "assessment": assessment_html,
1468
+ "comparison_table": comparison_html,
1469
+ "calibration_table": calibration_html,
1470
+ "overlay_fan": _embed(overlay_fig),
1471
+ "maxdd_dist": _embed(maxdd_fig),
1472
+ "cagr_quantiles": _embed(cagr_fig),
1473
+ "stress_section": stress_html,
1474
+ "fan_charts": "\n".join(fan_parts),
1475
+ "terminal_hists": "\n".join(hist_parts),
1476
+ "assumptions": assumptions,
1477
+ }
1478
+ rendered = engine.render_report(tpl, fragments)
1479
+
1480
+ if output is None:
1481
+ if _get_utils()._in_notebook():
1482
+ _download_html(rendered, download_filename)
1483
+ else:
1484
+ with tempfile.NamedTemporaryFile(
1485
+ mode="w", suffix=".html", delete=False, encoding="utf-8"
1486
+ ) as f:
1487
+ f.write(rendered)
1488
+ temp_path = f.name
1489
+ webbrowser.open("file://" + temp_path)
1490
+ return
1491
+
1492
+ with open(output, "w", encoding="utf-8") as f:
1493
+ f.write(rendered)
1494
+
1495
+
1496
+ def _ad_status_counts_html(result):
1497
+ counts = {"excellent": 0, "good": 0, "warning": 0, "critical": 0}
1498
+ for mr in result.metrics:
1499
+ for wr in mr.windows.values():
1500
+ counts[wr.status] += 1
1501
+ hints = {
1502
+ "excellent": "well above historical norm",
1503
+ "good": "within acceptable range",
1504
+ "warning": "drifting from historical norm",
1505
+ "critical": "significant deviation from norm",
1506
+ }
1507
+ parts = ['<div class="kpi-grid">']
1508
+ for key, label in (
1509
+ ("excellent", "Excellent"),
1510
+ ("good", "Good"),
1511
+ ("warning", "Warning"),
1512
+ ("critical", "Critical"),
1513
+ ):
1514
+ parts.append(
1515
+ f'<div class="kpi {key}"><div class="label">{label}</div>'
1516
+ f'<div class="value">{counts[key]}</div>'
1517
+ f'<div class="hint">{hints[key]}</div></div>'
1518
+ )
1519
+ parts.append("</div>")
1520
+ return "".join(parts)
1521
+
1522
+
1523
+ def _ad_score_tone(score_pct: float) -> str:
1524
+ """Map aggregate health score to the same status palette as metric cells."""
1525
+ if score_pct >= 75:
1526
+ return "excellent"
1527
+ if score_pct >= 50:
1528
+ return "good"
1529
+ if score_pct >= 25:
1530
+ return "warning"
1531
+ return "critical"
1532
+
1533
+
1534
+ def _ad_summary_table_html(result):
1535
+ from .alphadecay.core import status_label
1536
+
1537
+ windows = result.windows
1538
+ parts = [
1539
+ "<table><thead><tr><th>Metric</th>",
1540
+ *[f"<th>{w}d</th>" for w in windows],
1541
+ "</tr></thead><tbody>",
1542
+ ]
1543
+ for mr in result.metrics:
1544
+ parts.append(f"<tr><td>{mr.spec.label}</td>")
1545
+ for w in windows:
1546
+ wr = mr.windows[w]
1547
+ lbl = status_label(wr.status)
1548
+ z_txt = f"z={wr.z_score:+.2f}" if not _np.isnan(wr.z_score) else ""
1549
+ parts.append(
1550
+ f'<td><span class="badge {wr.status}">{lbl}</span>'
1551
+ f'<br><span class="metric-meta">{z_txt}</span></td>'
1552
+ )
1553
+ parts.append("</tr>")
1554
+ parts.append("</tbody></table>")
1555
+ return "".join(parts)
1556
+
1557
+
1558
+ def _ad_metric_rows_html(result, embed_fn):
1559
+ from .alphadecay import plotting as _adplt
1560
+ from .alphadecay.core import format_value, status_label
1561
+
1562
+ parts = []
1563
+ for mr in result.metrics:
1564
+ parts.append(f'<div class="metric-row" id="metric_{mr.spec.key}">')
1565
+ parts.append(f"<h4>{mr.spec.label}</h4>")
1566
+ parts.append('<div class="grid">')
1567
+ for w in result.windows:
1568
+ wr = mr.windows[w]
1569
+ fig = _adplt.metric_distribution_figure(wr, mr.spec, title=f"{mr.spec.label} — {w}d")
1570
+ meta = (
1571
+ f"Obs: {format_value(mr.spec, wr.observed)} &bull; "
1572
+ f"Mean: {format_value(mr.spec, wr.mean)} &bull; "
1573
+ f"z={wr.z_score:+.2f} &bull; "
1574
+ f"P={wr.percentile:.0f}% &bull; "
1575
+ f'<span class="badge {wr.status}">{status_label(wr.status)}</span>'
1576
+ )
1577
+ parts.append(
1578
+ f'<div class="cell"><div class="metric-meta">{meta}</div>'
1579
+ f"{embed_fn(fig)}</div>"
1580
+ )
1581
+ parts.append("</div></div>")
1582
+ return "\n".join(parts)
1583
+
1584
+
1585
+ def _ad_sota_stats_html(result):
1586
+ from .alphadecay.core import status_label
1587
+
1588
+ cusum = result.cusum
1589
+ tuw = result.time_underwater
1590
+ alarm = "ALARM" if cusum.alarm else "Normal"
1591
+ uw = (
1592
+ f"{tuw.current_days} days underwater"
1593
+ if tuw.is_underwater
1594
+ else "At equity peak"
1595
+ )
1596
+ return (
1597
+ '<table><thead><tr><th>Diagnostic</th><th>Current</th><th>Reference</th>'
1598
+ "<th>Status</th></tr></thead><tbody>"
1599
+ f"<tr><td>CUSUM</td><td>{cusum.current:.4f}</td>"
1600
+ f"<td>Threshold {cusum.threshold:.4f} ({cusum.pct_of_threshold:.0%})</td>"
1601
+ f"<td>{alarm}</td></tr>"
1602
+ f"<tr><td>Time Underwater</td><td>{uw}</td>"
1603
+ f"<td>Mean duration {tuw.mean:.0f}d (z={tuw.z_score:+.2f})</td>"
1604
+ f'<td><span class="badge {tuw.status}">{status_label(tuw.status)}</span></td></tr>'
1605
+ "</tbody></table>"
1606
+ )
1607
+
1608
+
1609
+ def html_alpha_decay(
1610
+ returns,
1611
+ windows=(7, 15, 30),
1612
+ rf=0.0,
1613
+ title="Alpha Decay Tearsheet",
1614
+ output=None,
1615
+ periods_per_year=252,
1616
+ download_filename="quantstats-alpha-decay.html",
1617
+ figfmt="svg",
1618
+ template_path=None,
1619
+ match_dates=True,
1620
+ cusum_k=0.5,
1621
+ cusum_h=4.0,
1622
+ **kwargs,
1623
+ ):
1624
+ """
1625
+ Generate an alpha-decay HTML tearsheet for a single asset.
1626
+
1627
+ Computes rolling risk metrics over short windows (7/15/30 days by default),
1628
+ compares the latest observation against the historical distribution of each
1629
+ metric (z-score traffic light), and adds CUSUM + time-underwater diagnostics.
1630
+
1631
+ Parameters
1632
+ ----------
1633
+ returns : pd.Series or pd.DataFrame
1634
+ Daily simple returns of a single asset. A DataFrame uses its first column.
1635
+ windows : tuple[int], default (7, 15, 30)
1636
+ Rolling window sizes in trading days.
1637
+ rf : float, default 0.0
1638
+ Annual risk-free rate for CAGR.
1639
+ title : str, default "Alpha Decay Tearsheet"
1640
+ Report title.
1641
+ output : str or None, default None
1642
+ Output file path. If None, opens in browser / downloads in notebook.
1643
+ periods_per_year : int, default 252
1644
+ Periods per year for annualisation.
1645
+ figfmt : str, default "svg"
1646
+ Embedded figure format.
1647
+ cusum_k : float, default 0.5
1648
+ CUSUM slack parameter in units of return standard deviation.
1649
+ cusum_h : float, default 4.0
1650
+ CUSUM alarm threshold in units of return standard deviation.
1651
+ """
1652
+ import matplotlib.pyplot as _plt
1653
+
1654
+ from . import alphadecay as _ad
1655
+ from ._reporting import engine
1656
+ from .alphadecay import plotting as _adplt
1657
+
1658
+ if match_dates and hasattr(returns, "dropna"):
1659
+ returns = returns.dropna()
1660
+ returns = _get_utils()._prepare_returns(returns)
1661
+ if isinstance(returns, _pd.DataFrame):
1662
+ returns = returns.iloc[:, 0]
1663
+
1664
+ asset_title = kwargs.get("strategy_title")
1665
+ if asset_title is None:
1666
+ asset_title = returns.name if returns.name else "Asset"
1667
+
1668
+ if template_path is None:
1669
+ template_path = Path(__file__).parent / "report_alpha_decay.html"
1670
+ else:
1671
+ template_path = Path(template_path)
1672
+ template_path = template_path.resolve()
1673
+ if not template_path.exists():
1674
+ raise FileNotFoundError(f"Template file not found: {template_path}")
1675
+ tpl = template_path.read_text(encoding="utf-8")
1676
+
1677
+ result = _ad.analyze(
1678
+ returns,
1679
+ windows=tuple(windows),
1680
+ rf=rf,
1681
+ periods=periods_per_year,
1682
+ cusum_k=cusum_k,
1683
+ cusum_h=cusum_h,
1684
+ asset_label=str(asset_title),
1685
+ )
1686
+
1687
+ def _embed(fig):
1688
+ figfile = _get_utils()._file_stream()
1689
+ fig.savefig(figfile, format=figfmt, bbox_inches="tight")
1690
+ _plt.close(fig)
1691
+ return _embed_figure(figfile, figfmt)
1692
+
1693
+ cusum_fig = _adplt.cusum_figure(result.cusum)
1694
+ tuw_fig = _adplt.time_underwater_figure(result.time_underwater)
1695
+
1696
+ date_range = returns.index.strftime("%e %b, %Y")
1697
+ windows_label = "/".join(str(w) for w in windows)
1698
+ params_parts = [
1699
+ f"Windows: {windows_label}d",
1700
+ f"Asset: {str(asset_title).upper()}",
1701
+ f"Metrics: {len(result.metrics)}",
1702
+ ]
1703
+ params_str = " &bull; ".join(params_parts) + " | "
1704
+
1705
+ score_tone = _ad_score_tone(result.score_pct)
1706
+ score_html = (
1707
+ '<div class="kpi-grid score-grid">'
1708
+ f'<div class="kpi {score_tone}"><div class="label">Health Score</div>'
1709
+ f'<div class="value">{result.score}/{result.total}</div>'
1710
+ f'<div class="hint">metric-window cells rated Good or Excellent '
1711
+ f"({result.score_pct:.0f}%)</div></div></div>"
1712
+ )
1713
+
1714
+ assumptions = (
1715
+ f"Assumptions: windows {windows_label}d &bull; "
1716
+ f"{len(result.metrics)} metrics &bull; "
1717
+ f"CUSUM k={cusum_k}σ h={cusum_h}σ &bull; "
1718
+ f"periods/year={periods_per_year} &bull; rf={rf:.2%}"
1719
+ )
1720
+
1721
+ fragments = {
1722
+ "title": title,
1723
+ "date_range": date_range[0] + " - " + date_range[-1],
1724
+ "params": params_str,
1725
+ "v": __version__,
1726
+ "generated_at": _dt.now().strftime("%d %b, %Y %H:%M").lstrip("0"),
1727
+ "windows_label": windows_label,
1728
+ "score_summary": score_html,
1729
+ "status_counts": _ad_status_counts_html(result),
1730
+ "summary_table": _ad_summary_table_html(result),
1731
+ "metric_rows": _ad_metric_rows_html(result, _embed),
1732
+ "cusum_chart": _embed(cusum_fig),
1733
+ "time_underwater": _embed(tuw_fig),
1734
+ "sota_stats": _ad_sota_stats_html(result),
1735
+ "assumptions": assumptions,
1736
+ }
1737
+ rendered = engine.render_report(tpl, fragments)
1738
+
1739
+ if output is None:
1740
+ if _get_utils()._in_notebook():
1741
+ _download_html(rendered, download_filename)
1742
+ else:
1743
+ with tempfile.NamedTemporaryFile(
1744
+ mode="w", suffix=".html", delete=False, encoding="utf-8"
1745
+ ) as f:
1746
+ f.write(rendered)
1747
+ temp_path = f.name
1748
+ webbrowser.open("file://" + temp_path)
1749
+ return
1750
+
1751
+ with open(output, "w", encoding="utf-8") as f:
1752
+ f.write(rendered)
1753
+
1754
+
1755
+ def full(
1756
+ returns,
1757
+ benchmark=None,
1758
+ rf=0.0,
1759
+ grayscale=False,
1760
+ figsize=(8, 5),
1761
+ display=True,
1762
+ compounded=True,
1763
+ periods_per_year=252,
1764
+ match_dates=True,
1765
+ **kwargs,
1766
+ ):
1767
+ """
1768
+ Generate a comprehensive performance analysis report.
1769
+
1770
+ This function creates a full performance analysis including metrics,
1771
+ worst drawdowns analysis, and complete visualization suite. It's designed
1772
+ for detailed portfolio analysis and can handle both single strategies
1773
+ and multiple strategy comparisons.
1774
+
1775
+ Parameters
1776
+ ----------
1777
+ returns : pd.Series or pd.DataFrame
1778
+ Daily returns data for the strategy/portfolio
1779
+ benchmark : pd.Series, str, or None, default None
1780
+ Benchmark returns for comparison
1781
+ rf : float, default 0.0
1782
+ Risk-free rate for calculations (as decimal)
1783
+ grayscale : bool, default False
1784
+ Whether to generate charts in grayscale
1785
+ figsize : tuple, default (8, 5)
1786
+ Figure size for plots as (width, height)
1787
+ display : bool, default True
1788
+ Whether to display results in notebook/console
1789
+ compounded : bool, default True
1790
+ Whether to compound returns for calculations
1791
+ periods_per_year : int, default 252
1792
+ Number of trading periods per year
1793
+ match_dates : bool, default True
1794
+ Whether to align returns and benchmark start dates
1795
+ **kwargs
1796
+ Additional keyword arguments:
1797
+ - strategy_title: Custom name for the strategy
1798
+ - benchmark_title: Custom name for the benchmark
1799
+ - active_returns: Whether to show active returns vs benchmark
1800
+
1801
+ Returns
1802
+ -------
1803
+ None
1804
+ Displays comprehensive analysis including metrics, drawdowns, and plots
1805
+
1806
+ Examples
1807
+ --------
1808
+ >>> full(returns, benchmark='^GSPC', rf=0.02)
1809
+ >>> full(returns, figsize=(10, 6), grayscale=True)
1810
+ """
1811
+ # prepare timeseries
1812
+ if match_dates:
1813
+ returns = returns.dropna()
1814
+ # Clean and prepare returns data
1815
+ returns = _get_utils()._prepare_returns(returns)
1816
+
1817
+ # Process benchmark if provided
1818
+ if benchmark is not None:
1819
+ benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
1820
+ if match_dates is True:
1821
+ returns, benchmark = _match_dates(returns, benchmark)
1822
+
1823
+ # Extract title parameters from kwargs
1824
+ benchmark_title = None
1825
+ if benchmark is not None:
1826
+ benchmark_title = kwargs.get("benchmark_title", "Benchmark")
1827
+ strategy_title = kwargs.get("strategy_title", "Strategy")
1828
+ active = kwargs.get("active_returns", False)
1829
+
1830
+ # Handle multiple strategy columns
1831
+ if (
1832
+ isinstance(returns, _pd.DataFrame)
1833
+ and len(returns.columns) > 1
1834
+ and isinstance(strategy_title, str)
1835
+ ):
1836
+ strategy_title = list(returns.columns)
1837
+
1838
+ # Set names for display purposes
1839
+ if benchmark is not None:
1840
+ benchmark.name = benchmark_title
1841
+ if isinstance(returns, _pd.Series):
1842
+ returns.name = strategy_title
1843
+ elif isinstance(returns, _pd.DataFrame):
1844
+ returns.columns = strategy_title
1845
+
1846
+ # Calculate drawdown analysis for worst periods display
1847
+ dd = _get_stats().to_drawdown_series(returns)
1848
+
1849
+ # Process drawdown details based on data type
1850
+ if isinstance(dd, _pd.Series):
1851
+ col = _get_stats().drawdown_details(dd).columns[4]
1852
+ dd_info = _get_stats().drawdown_details(dd).sort_values(by=col, ascending=True)[:5]
1853
+ if not dd_info.empty:
1854
+ dd_info.index = range(1, min(6, len(dd_info) + 1))
1855
+ dd_info.columns = map(lambda x: str(x).title(), dd_info.columns)
1856
+ elif isinstance(dd, _pd.DataFrame):
1857
+ # Handle multiple strategy columns
1858
+ col = _get_stats().drawdown_details(dd).columns.get_level_values(1)[4]
1859
+ dd_info_dict = {}
1860
+ for ptf in dd.columns:
1861
+ dd_info = _get_stats().drawdown_details(dd[ptf]).sort_values(
1862
+ by=col, ascending=True
1863
+ )[:5]
1864
+ if not dd_info.empty:
1865
+ dd_info.index = range(1, min(6, len(dd_info) + 1))
1866
+ dd_info.columns = map(lambda x: str(x).title(), dd_info.columns)
1867
+ dd_info_dict[ptf] = dd_info
1868
+
1869
+ # Display results based on environment (notebook vs console)
1870
+ if _get_utils()._in_notebook():
1871
+ # Display in Jupyter notebook with HTML formatting
1872
+ iDisplay(iHTML("<h4>Performance Metrics</h4>"))
1873
+ iDisplay(
1874
+ metrics(
1875
+ returns=returns,
1876
+ benchmark=benchmark,
1877
+ rf=rf,
1878
+ display=display,
1879
+ mode="full",
1880
+ compounded=compounded,
1881
+ periods_per_year=periods_per_year,
1882
+ prepare_returns=False,
1883
+ benchmark_title=benchmark_title,
1884
+ strategy_title=strategy_title,
1885
+ )
1886
+ )
1887
+
1888
+ # Display worst drawdowns analysis
1889
+ if isinstance(dd, _pd.Series):
1890
+ iDisplay(iHTML('<h4 style="margin-bottom:20px">Worst 5 Drawdowns</h4>'))
1891
+ if dd_info.empty:
1892
+ iDisplay(iHTML("<p>(no drawdowns)</p>"))
1893
+ else:
1894
+ iDisplay(dd_info)
1895
+ elif isinstance(dd, _pd.DataFrame):
1896
+ # Display drawdowns for each strategy
1897
+ for ptf, dd_info in dd_info_dict.items():
1898
+ iDisplay(
1899
+ iHTML(
1900
+ f'<h4 style="margin-bottom:20px">{ptf} - Worst 5 Drawdowns</h4>'
1901
+ )
1902
+ )
1903
+ if dd_info.empty:
1904
+ iDisplay(iHTML("<p>(no drawdowns)</p>"))
1905
+ else:
1906
+ iDisplay(dd_info)
1907
+
1908
+ iDisplay(iHTML("<h4>Strategy Visualization</h4>"))
1909
+ else:
1910
+ # Display in console/terminal environment
1911
+ _print_parameters_table(
1912
+ benchmark_title=benchmark_title,
1913
+ periods_per_year=periods_per_year,
1914
+ rf=rf,
1915
+ compounded=compounded,
1916
+ match_dates=match_dates,
1917
+ )
1918
+ print("[Performance Metrics]\n")
1919
+ metrics(
1920
+ returns=returns,
1921
+ benchmark=benchmark,
1922
+ rf=rf,
1923
+ display=display,
1924
+ mode="full",
1925
+ compounded=compounded,
1926
+ periods_per_year=periods_per_year,
1927
+ prepare_returns=False,
1928
+ benchmark_title=benchmark_title,
1929
+ strategy_title=strategy_title,
1930
+ )
1931
+ print("\n\n")
1932
+ print("[Worst 5 Drawdowns]\n")
1933
+
1934
+ # Display drawdowns in tabular format
1935
+ if isinstance(dd, _pd.Series):
1936
+ if dd_info.empty:
1937
+ print("(no drawdowns)")
1938
+ else:
1939
+ print(
1940
+ _tabulate(
1941
+ dd_info, headers="keys", tablefmt="simple", floatfmt=".2f"
1942
+ )
1943
+ )
1944
+ elif isinstance(dd, _pd.DataFrame):
1945
+ for ptf, dd_info in dd_info_dict.items():
1946
+ if dd_info.empty:
1947
+ print("(no drawdowns)")
1948
+ else:
1949
+ print(f"{ptf}\n")
1950
+ print(
1951
+ _tabulate(
1952
+ dd_info, headers="keys", tablefmt="simple", floatfmt=".2f"
1953
+ )
1954
+ )
1955
+
1956
+ print("\n\n")
1957
+ print("[Strategy Visualization]\nvia Matplotlib")
1958
+
1959
+ # Generate comprehensive plots
1960
+ plots(
1961
+ returns=returns,
1962
+ benchmark=benchmark,
1963
+ grayscale=grayscale,
1964
+ figsize=figsize,
1965
+ mode="full",
1966
+ compounded=compounded,
1967
+ periods_per_year=periods_per_year,
1968
+ prepare_returns=False,
1969
+ benchmark_title=benchmark_title,
1970
+ strategy_title=strategy_title,
1971
+ active=active,
1972
+ )
1973
+
1974
+
1975
+ def basic(
1976
+ returns,
1977
+ benchmark=None,
1978
+ rf=0.0,
1979
+ grayscale=False,
1980
+ figsize=(8, 5),
1981
+ display=True,
1982
+ compounded=True,
1983
+ periods_per_year=252,
1984
+ match_dates=True,
1985
+ **kwargs,
1986
+ ):
1987
+ """
1988
+ Generate a basic performance analysis report.
1989
+
1990
+ This function creates a simplified performance analysis with essential
1991
+ metrics and basic visualizations. It's designed for quick portfolio
1992
+ analysis when detailed analysis is not needed.
1993
+
1994
+ Parameters
1995
+ ----------
1996
+ returns : pd.Series or pd.DataFrame
1997
+ Daily returns data for the strategy/portfolio
1998
+ benchmark : pd.Series, str, or None, default None
1999
+ Benchmark returns for comparison
2000
+ rf : float, default 0.0
2001
+ Risk-free rate for calculations (as decimal)
2002
+ grayscale : bool, default False
2003
+ Whether to generate charts in grayscale
2004
+ figsize : tuple, default (8, 5)
2005
+ Figure size for plots as (width, height)
2006
+ display : bool, default True
2007
+ Whether to display results in notebook/console
2008
+ compounded : bool, default True
2009
+ Whether to compound returns for calculations
2010
+ periods_per_year : int, default 252
2011
+ Number of trading periods per year
2012
+ match_dates : bool, default True
2013
+ Whether to align returns and benchmark start dates
2014
+ **kwargs
2015
+ Additional keyword arguments:
2016
+ - strategy_title: Custom name for the strategy
2017
+ - benchmark_title: Custom name for the benchmark
2018
+ - active_returns: Whether to show active returns vs benchmark
2019
+
2020
+ Returns
2021
+ -------
2022
+ None
2023
+ Displays basic analysis including essential metrics and plots
2024
+
2025
+ Examples
2026
+ --------
2027
+ >>> basic(returns, benchmark='^GSPC')
2028
+ >>> basic(returns, figsize=(10, 6), display=False)
2029
+ """
2030
+ # prepare timeseries
2031
+ if match_dates:
2032
+ returns = returns.dropna()
2033
+ # Clean and prepare returns data
2034
+ returns = _get_utils()._prepare_returns(returns)
2035
+
2036
+ # Process benchmark if provided
2037
+ if benchmark is not None:
2038
+ benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
2039
+ if match_dates is True:
2040
+ returns, benchmark = _match_dates(returns, benchmark)
2041
+
2042
+ # Extract title parameters from kwargs
2043
+ benchmark_title = None
2044
+ if benchmark is not None:
2045
+ benchmark_title = kwargs.get("benchmark_title", "Benchmark")
2046
+ strategy_title = kwargs.get("strategy_title", "Strategy")
2047
+ active = kwargs.get("active_returns", False)
2048
+
2049
+ # Handle multiple strategy columns
2050
+ if (
2051
+ isinstance(returns, _pd.DataFrame)
2052
+ and len(returns.columns) > 1
2053
+ and isinstance(strategy_title, str)
2054
+ ):
2055
+ strategy_title = list(returns.columns)
2056
+
2057
+ # Display results based on environment (notebook vs console)
2058
+ if _get_utils()._in_notebook():
2059
+ # Display in Jupyter notebook with HTML formatting
2060
+ iDisplay(iHTML("<h4>Performance Metrics</h4>"))
2061
+ metrics(
2062
+ returns=returns,
2063
+ benchmark=benchmark,
2064
+ rf=rf,
2065
+ display=display,
2066
+ mode="basic",
2067
+ compounded=compounded,
2068
+ periods_per_year=periods_per_year,
2069
+ prepare_returns=False,
2070
+ benchmark_title=benchmark_title,
2071
+ strategy_title=strategy_title,
2072
+ )
2073
+ iDisplay(iHTML("<h4>Strategy Visualization</h4>"))
2074
+ else:
2075
+ # Display in console/terminal environment
2076
+ _print_parameters_table(
2077
+ benchmark_title=benchmark_title,
2078
+ periods_per_year=periods_per_year,
2079
+ rf=rf,
2080
+ compounded=compounded,
2081
+ match_dates=match_dates,
2082
+ )
2083
+ print("[Performance Metrics]\n")
2084
+ metrics(
2085
+ returns=returns,
2086
+ benchmark=benchmark,
2087
+ rf=rf,
2088
+ display=display,
2089
+ mode="basic",
2090
+ compounded=compounded,
2091
+ periods_per_year=periods_per_year,
2092
+ prepare_returns=False,
2093
+ benchmark_title=benchmark_title,
2094
+ strategy_title=strategy_title,
2095
+ )
2096
+
2097
+ print("\n\n")
2098
+ print("[Strategy Visualization]\nvia Matplotlib")
2099
+
2100
+ # Generate basic plots
2101
+ plots(
2102
+ returns=returns,
2103
+ benchmark=benchmark,
2104
+ grayscale=grayscale,
2105
+ figsize=figsize,
2106
+ mode="basic",
2107
+ compounded=compounded,
2108
+ periods_per_year=periods_per_year,
2109
+ prepare_returns=False,
2110
+ benchmark_title=benchmark_title,
2111
+ strategy_title=strategy_title,
2112
+ active=active,
2113
+ )
2114
+
2115
+
2116
+ def metrics(
2117
+ returns,
2118
+ benchmark=None,
2119
+ rf=0.0,
2120
+ display=True,
2121
+ mode="basic",
2122
+ sep=False,
2123
+ compounded=True,
2124
+ periods_per_year=252,
2125
+ prepare_returns=True,
2126
+ match_dates=True,
2127
+ **kwargs,
2128
+ ):
2129
+ """
2130
+ Calculate comprehensive performance metrics for portfolio analysis.
2131
+
2132
+ This function computes a wide range of performance metrics including
2133
+ returns, risk measures, ratios, and statistical measures. It can handle
2134
+ both single strategies and multiple strategy comparisons with optional
2135
+ benchmark analysis.
2136
+
2137
+ Parameters
2138
+ ----------
2139
+ returns : pd.Series or pd.DataFrame
2140
+ Daily returns data for the strategy/portfolio
2141
+ benchmark : pd.Series, str, or None, default None
2142
+ Benchmark returns for comparison
2143
+ rf : float, default 0.0
2144
+ Risk-free rate for calculations (as decimal)
2145
+ display : bool, default True
2146
+ Whether to display results in formatted table
2147
+ mode : str, default "basic"
2148
+ Analysis mode - "basic" for essential metrics, "full" for comprehensive
2149
+ sep : bool, default False
2150
+ Whether to include separator rows in output
2151
+ compounded : bool, default True
2152
+ Whether to compound returns for calculations
2153
+ periods_per_year : int, default 252
2154
+ Number of trading periods per year
2155
+ prepare_returns : bool, default True
2156
+ Whether to prepare/clean returns data
2157
+ match_dates : bool, default True
2158
+ Whether to align returns and benchmark start dates
2159
+ **kwargs
2160
+ Additional keyword arguments:
2161
+ - strategy_title: Custom name for the strategy
2162
+ - benchmark_title: Custom name for the benchmark
2163
+ - as_pct: Whether to return percentages
2164
+ - internal: Internal calculation flag
2165
+
2166
+ Returns
2167
+ -------
2168
+ pd.DataFrame or None
2169
+ DataFrame with performance metrics if display=False, else None
2170
+
2171
+ Examples
2172
+ --------
2173
+ >>> metrics_df = metrics(returns, benchmark='^GSPC', display=False)
2174
+ >>> metrics(returns, mode="full", rf=0.02)
2175
+ """
2176
+ # Clean returns data if date matching is enabled
2177
+ if match_dates:
2178
+ returns = returns.dropna()
2179
+ # Remove timezone information from index for consistent processing
2180
+ returns.index = returns.index.tz_localize(None)
2181
+
2182
+ # Get trading periods for annualization calculations
2183
+ win_year, _ = _get_trading_periods(periods_per_year)
2184
+
2185
+ # Extract column names from kwargs or use defaults
2186
+ benchmark_colname = kwargs.get("benchmark_title", "Benchmark")
2187
+ strategy_colname = kwargs.get("strategy_title", "Strategy")
2188
+
2189
+ # Handle benchmark column naming
2190
+ if benchmark is not None:
2191
+ if isinstance(benchmark, str):
2192
+ benchmark_colname = f"Benchmark ({benchmark.upper()})"
2193
+ elif isinstance(benchmark, _pd.DataFrame) and len(benchmark.columns) > 1:
2194
+ raise ValueError(
2195
+ "`benchmark` must be a pandas Series, "
2196
+ "but a multi-column DataFrame was passed"
2197
+ )
2198
+
2199
+ # Handle strategy column naming for multiple strategies
2200
+ if isinstance(returns, _pd.DataFrame):
2201
+ if len(returns.columns) > 1:
2202
+ blank = [""] * len(returns.columns)
2203
+ if isinstance(strategy_colname, str):
2204
+ strategy_colname = list(returns.columns)
2205
+ else:
2206
+ blank = [""]
2207
+
2208
+ # if isinstance(returns, _pd.DataFrame):
2209
+ # if len(returns.columns) > 1:
2210
+ # raise ValueError("`returns` needs to be a Pandas Series or one column DataFrame. "
2211
+ # "multi colums DataFrame was passed")
2212
+ # returns = returns[returns.columns[0]]
2213
+
2214
+ # Prepare returns data if requested
2215
+ if prepare_returns:
2216
+ df = _get_utils()._prepare_returns(returns)
2217
+
2218
+ # Create main DataFrame for calculations
2219
+ if isinstance(returns, _pd.Series):
2220
+ df = _pd.DataFrame({"returns": returns})
2221
+ elif isinstance(returns, _pd.DataFrame):
2222
+ df = _pd.DataFrame(
2223
+ {
2224
+ "returns_" + str(i + 1): returns[strategy_col]
2225
+ for i, strategy_col in enumerate(returns.columns)
2226
+ }
2227
+ )
2228
+
2229
+ # Process benchmark data if provided
2230
+ if benchmark is not None:
2231
+ benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
2232
+ if match_dates is True:
2233
+ returns, benchmark = _match_dates(returns, benchmark)
2234
+ # Truncate df to the aligned date range to exclude leading zeros
2235
+ df = df.loc[returns.index]
2236
+ df["benchmark"] = benchmark
2237
+ # Update blank list for proper formatting
2238
+ if isinstance(returns, _pd.Series):
2239
+ blank = ["", ""]
2240
+ df["returns"] = returns
2241
+ elif isinstance(returns, _pd.DataFrame):
2242
+ blank = [""] * len(returns.columns) + [""]
2243
+ for i, strategy_col in enumerate(returns.columns):
2244
+ df["returns_" + str(i + 1)] = returns[strategy_col]
2245
+
2246
+ # Calculate start and end dates for each series
2247
+ if isinstance(returns, _pd.Series):
2248
+ s_start = {"returns": df["returns"].index.strftime("%Y-%m-%d")[0]}
2249
+ s_end = {"returns": df["returns"].index.strftime("%Y-%m-%d")[-1]}
2250
+ s_rf = {"returns": rf}
2251
+ elif isinstance(returns, _pd.DataFrame):
2252
+ df_strategy_columns = [col for col in df.columns if col != "benchmark"]
2253
+ s_start = {
2254
+ strategy_col: df[strategy_col].dropna().index.strftime("%Y-%m-%d")[0]
2255
+ for strategy_col in df_strategy_columns
2256
+ }
2257
+ s_end = {
2258
+ strategy_col: df[strategy_col].dropna().index.strftime("%Y-%m-%d")[-1]
2259
+ for strategy_col in df_strategy_columns
2260
+ }
2261
+ s_rf = {strategy_col: rf for strategy_col in df_strategy_columns}
2262
+
2263
+ # Add benchmark dates if present
2264
+ if "benchmark" in df:
2265
+ s_start["benchmark"] = df["benchmark"].index.strftime("%Y-%m-%d")[0]
2266
+ s_end["benchmark"] = df["benchmark"].index.strftime("%Y-%m-%d")[-1]
2267
+ s_rf["benchmark"] = rf
2268
+
2269
+ # Fill missing values with zeros for calculations
2270
+ df = df.fillna(0)
2271
+
2272
+ # Determine percentage multiplier for display
2273
+ # pct multiplier
2274
+ pct = 100 if display or "internal" in kwargs else 1
2275
+ if kwargs.get("as_pct", False):
2276
+ pct = 100
2277
+
2278
+ # Initialize metrics DataFrame with basic information
2279
+ metrics = _pd.DataFrame()
2280
+ metrics["Start Period"] = _pd.Series(s_start)
2281
+ metrics["End Period"] = _pd.Series(s_end)
2282
+ metrics["Risk-Free Rate %"] = _pd.Series(s_rf) * 100
2283
+ metrics["Time in Market %"] = _get_stats().exposure(df, prepare_returns=False) * pct
2284
+
2285
+ # Add separator row
2286
+ metrics["~"] = blank
2287
+
2288
+ # Calculate return metrics based on compounding preference
2289
+ if compounded:
2290
+ metrics["Cumulative Return %"] = (_get_stats().comp(df) * pct).map("{:,.2f}".format)
2291
+ else:
2292
+ metrics["Total Return %"] = (df.sum() * pct).map("{:,.2f}".format)
2293
+
2294
+ # Calculate annualized return (CAGR)
2295
+ metrics["CAGR﹪%"] = _get_stats().cagr(df, rf, compounded, win_year) * pct
2296
+
2297
+ # Add separator row
2298
+ metrics["~~~~~~~~~~~~~~"] = blank
2299
+
2300
+ # Calculate risk-adjusted return ratios
2301
+ metrics["Sharpe"] = _get_stats().sharpe(df, rf, win_year, True)
2302
+ metrics["Prob. Sharpe Ratio %"] = (
2303
+ _get_stats().probabilistic_sharpe_ratio(df, rf, win_year, False) * pct
2304
+ )
2305
+
2306
+ # Add advanced Sharpe metrics for full mode
2307
+ if mode.lower() == "full":
2308
+ metrics["Smart Sharpe"] = _get_stats().smart_sharpe(df, rf, win_year, True)
2309
+ # metrics['Prob. Smart Sharpe Ratio %'] = _get_stats().probabilistic_sharpe_ratio(df, rf, win_year, False, True) * pct
2310
+
2311
+ # Calculate Sortino ratio (downside deviation-based)
2312
+ metrics["Sortino"] = _get_stats().sortino(df, rf, win_year, True)
2313
+ if mode.lower() == "full":
2314
+ # metrics['Prob. Sortino Ratio %'] = _get_stats().probabilistic_sortino_ratio(df, rf, win_year, False) * pct
2315
+ metrics["Smart Sortino"] = _get_stats().smart_sortino(df, rf, win_year, True)
2316
+ # metrics['Prob. Smart Sortino Ratio %'] = _get_stats().probabilistic_sortino_ratio(
2317
+ # df, rf, win_year, False, True) * pct
2318
+
2319
+ # Calculate adjusted Sortino ratio
2320
+ metrics["Sortino/√2"] = metrics["Sortino"] / _sqrt(2)
2321
+ if mode.lower() == "full":
2322
+ # metrics['Prob. Sortino/√2 Ratio %'] = _get_stats().probabilistic_adjusted_sortino_ratio(
2323
+ # df, rf, win_year, False) * pct
2324
+ metrics["Smart Sortino/√2"] = metrics["Smart Sortino"] / _sqrt(2)
2325
+ # metrics['Prob. Smart Sortino/√2 Ratio %'] = _get_stats().probabilistic_adjusted_sortino_ratio(
2326
+ # df, rf, win_year, False, True) * pct
2327
+
2328
+ # Calculate Omega ratio (probability-weighted ratio)
2329
+ if isinstance(returns, _pd.Series):
2330
+ if "benchmark" in df:
2331
+ metrics["Omega"] = [
2332
+ _get_stats().omega(df["returns"], rf, 0.0, win_year),
2333
+ _get_stats().omega(df["benchmark"], rf, 0.0, win_year),
2334
+ ]
2335
+ else:
2336
+ metrics["Omega"] = _get_stats().omega(df["returns"], rf, 0.0, win_year)
2337
+ elif isinstance(returns, _pd.DataFrame):
2338
+ omega_values = [
2339
+ _get_stats().omega(df[strategy_col], rf, 0.0, win_year)
2340
+ for strategy_col in df_strategy_columns
2341
+ ]
2342
+ if "benchmark" in df:
2343
+ omega_values.append(_get_stats().omega(df["benchmark"], rf, 0.0, win_year))
2344
+ metrics["Omega"] = omega_values
2345
+
2346
+ # Add separator and prepare for drawdown metrics
2347
+ metrics["~~~~~~~~"] = blank
2348
+ metrics["Max Drawdown %"] = blank
2349
+ metrics["Max DD Date"] = blank
2350
+ metrics["Max DD Period Start"] = blank
2351
+ metrics["Max DD Period End"] = blank
2352
+ metrics["Longest DD Days"] = blank
2353
+
2354
+ # Add detailed volatility and risk metrics for full mode
2355
+ if mode.lower() == "full":
2356
+ # Calculate annualized volatility
2357
+ if isinstance(returns, _pd.Series):
2358
+ ret_vol = (
2359
+ _get_stats().volatility(df["returns"], win_year, True, prepare_returns=False)
2360
+ * pct
2361
+ )
2362
+ elif isinstance(returns, _pd.DataFrame):
2363
+ ret_vol = [
2364
+ _get_stats().volatility(
2365
+ df[strategy_col], win_year, True, prepare_returns=False
2366
+ )
2367
+ * pct
2368
+ for strategy_col in df_strategy_columns
2369
+ ]
2370
+
2371
+ # Add benchmark volatility if present
2372
+ if "benchmark" in df:
2373
+ bench_vol = (
2374
+ _get_stats().volatility(
2375
+ df["benchmark"], win_year, True, prepare_returns=False
2376
+ )
2377
+ * pct
2378
+ )
2379
+
2380
+ vol_ = [ret_vol, bench_vol]
2381
+ if isinstance(ret_vol, list):
2382
+ metrics["Volatility (ann.) %"] = list(_pd.core.common.flatten(vol_))
2383
+ else:
2384
+ metrics["Volatility (ann.) %"] = vol_
2385
+
2386
+ # Calculate benchmark-relative metrics
2387
+ if isinstance(returns, _pd.Series):
2388
+ metrics["R^2"] = _get_stats().r_squared(
2389
+ df["returns"], df["benchmark"], prepare_returns=False
2390
+ )
2391
+ metrics["Information Ratio"] = _get_stats().information_ratio(
2392
+ df["returns"], df["benchmark"], prepare_returns=False
2393
+ )
2394
+ elif isinstance(returns, _pd.DataFrame):
2395
+ metrics["R^2"] = (
2396
+ [
2397
+ _get_stats().r_squared(
2398
+ df[strategy_col], df["benchmark"], prepare_returns=False
2399
+ ).round(2)
2400
+ for strategy_col in df_strategy_columns
2401
+ ]
2402
+ ) + ["-"]
2403
+ metrics["Information Ratio"] = (
2404
+ [
2405
+ _get_stats().information_ratio(
2406
+ df[strategy_col], df["benchmark"], prepare_returns=False
2407
+ ).round(2)
2408
+ for strategy_col in df_strategy_columns
2409
+ ]
2410
+ ) + ["-"]
2411
+ else:
2412
+ # No benchmark case
2413
+ if isinstance(returns, _pd.Series):
2414
+ metrics["Volatility (ann.) %"] = [ret_vol]
2415
+ elif isinstance(returns, _pd.DataFrame):
2416
+ metrics["Volatility (ann.) %"] = ret_vol
2417
+
2418
+ # Additional risk and return metrics
2419
+ metrics["Calmar"] = _get_stats().calmar(df, prepare_returns=False, periods=win_year)
2420
+ metrics["Skew"] = _get_stats().skew(df, prepare_returns=False)
2421
+ metrics["Kurtosis"] = _get_stats().kurtosis(df, prepare_returns=False)
2422
+
2423
+ # Additional ratios
2424
+ metrics["Ulcer Performance Index"] = _get_stats().ulcer_performance_index(df, rf)
2425
+ metrics["Risk-Adjusted Return %"] = _get_stats().rar(df, rf, periods=win_year) * pct
2426
+ metrics["Risk-Return Ratio"] = _get_stats().risk_return_ratio(df, prepare_returns=False)
2427
+
2428
+ # Add separator
2429
+ metrics["~~~~~~~~~~"] = blank
2430
+
2431
+ # Average return metrics
2432
+ metrics["Avg. Return %"] = _get_stats().avg_return(df, prepare_returns=False) * pct
2433
+ metrics["Avg. Win %"] = _get_stats().avg_win(df, prepare_returns=False) * pct
2434
+ metrics["Avg. Loss %"] = _get_stats().avg_loss(df, prepare_returns=False) * pct
2435
+ metrics["Win/Loss Ratio"] = _get_stats().win_loss_ratio(df, prepare_returns=False)
2436
+ metrics["Profit Ratio"] = _get_stats().profit_ratio(df, prepare_returns=False)
2437
+
2438
+ # Add separator
2439
+ metrics["~~~~~~~~~~~"] = blank
2440
+
2441
+ # Expected returns at different frequencies
2442
+ metrics["Expected Daily %%"] = (
2443
+ _get_stats().expected_return(df, compounded=compounded, prepare_returns=False)
2444
+ * pct
2445
+ )
2446
+ metrics["Expected Monthly %%"] = (
2447
+ _get_stats().expected_return(
2448
+ df, compounded=compounded, aggregate="ME", prepare_returns=False
2449
+ )
2450
+ * pct
2451
+ )
2452
+ metrics["Expected Yearly %%"] = (
2453
+ _get_stats().expected_return(
2454
+ df, compounded=compounded, aggregate="YE", prepare_returns=False
2455
+ )
2456
+ * pct
2457
+ )
2458
+
2459
+ # Risk management metrics
2460
+ metrics["Kelly Criterion %"] = (
2461
+ _get_stats().kelly_criterion(df, prepare_returns=False) * pct
2462
+ )
2463
+ metrics["Risk of Ruin %"] = _get_stats().risk_of_ruin(df, prepare_returns=False)
2464
+
2465
+ # Value at Risk metrics
2466
+ metrics["Daily Value-at-Risk %"] = -abs(
2467
+ _get_stats().var(df, prepare_returns=False) * pct
2468
+ )
2469
+ metrics["Expected Shortfall (cVaR) %"] = -abs(
2470
+ _get_stats().cvar(df, prepare_returns=False) * pct
2471
+ )
2472
+
2473
+ # Add separator
2474
+ metrics["~~~~~~"] = blank
2475
+
2476
+ # Consecutive wins/losses analysis (full mode only)
2477
+ if mode.lower() == "full":
2478
+ metrics["Max Consecutive Wins *int"] = _get_stats().consecutive_wins(df)
2479
+ metrics["Max Consecutive Losses *int"] = _get_stats().consecutive_losses(df)
2480
+
2481
+ # Pain-based metrics (Gain/Pain ratio)
2482
+ metrics["Gain/Pain Ratio"] = _get_stats().gain_to_pain_ratio(df, rf)
2483
+ metrics["Gain/Pain (1M)"] = _get_stats().gain_to_pain_ratio(df, rf, "ME")
2484
+ # if mode.lower() == 'full':
2485
+ # metrics['GPR (3M)'] = _get_stats().gain_to_pain_ratio(df, rf, "QE")
2486
+ # metrics['GPR (6M)'] = _get_stats().gain_to_pain_ratio(df, rf, "2Q")
2487
+ # metrics['GPR (1Y)'] = _get_stats().gain_to_pain_ratio(df, rf, "YE")
2488
+
2489
+ # Add separator
2490
+ metrics["~~~~~~~"] = blank
2491
+
2492
+ # Trading-based performance metrics
2493
+ metrics["Payoff Ratio"] = _get_stats().payoff_ratio(df, prepare_returns=False)
2494
+ metrics["Profit Factor"] = _get_stats().profit_factor(df, prepare_returns=False)
2495
+ metrics["Common Sense Ratio"] = _get_stats().common_sense_ratio(df, prepare_returns=False)
2496
+ metrics["CPC Index"] = _get_stats().cpc_index(df, prepare_returns=False)
2497
+ metrics["Tail Ratio"] = _get_stats().tail_ratio(df, prepare_returns=False)
2498
+ metrics["Outlier Win Ratio"] = _get_stats().outlier_win_ratio(df, prepare_returns=False)
2499
+ metrics["Outlier Loss Ratio"] = _get_stats().outlier_loss_ratio(df, prepare_returns=False)
2500
+
2501
+ # # returns
2502
+ metrics["~~"] = blank
2503
+
2504
+ # Time-based return analysis
2505
+ today = df.index[-1] # _dt.today()
2506
+ m3 = today - relativedelta(months=3)
2507
+ m6 = today - relativedelta(months=6)
2508
+ y1 = today - relativedelta(years=1)
2509
+
2510
+ # Calculate period returns based on compounding preference
2511
+ if compounded:
2512
+ metrics["MTD %"] = (
2513
+ _get_stats().comp(df[df.index >= _dt(today.year, today.month, 1)]) * pct
2514
+ )
2515
+ metrics["3M %"] = _get_stats().comp(df[df.index >= m3]) * pct
2516
+ metrics["6M %"] = _get_stats().comp(df[df.index >= m6]) * pct
2517
+ metrics["YTD %"] = _get_stats().comp(df[df.index >= _dt(today.year, 1, 1)]) * pct
2518
+ metrics["1Y %"] = _get_stats().comp(df[df.index >= y1]) * pct
2519
+ else:
2520
+ metrics["MTD %"] = (
2521
+ _np.sum(df[df.index >= _dt(today.year, today.month, 1)], axis=0) * pct
2522
+ )
2523
+ metrics["3M %"] = _np.sum(df[df.index >= m3], axis=0) * pct
2524
+ metrics["6M %"] = _np.sum(df[df.index >= m6], axis=0) * pct
2525
+ metrics["YTD %"] = _np.sum(df[df.index >= _dt(today.year, 1, 1)], axis=0) * pct
2526
+ metrics["1Y %"] = _np.sum(df[df.index >= y1], axis=0) * pct
2527
+
2528
+ # Multi-year annualized returns
2529
+ d = today - relativedelta(months=35)
2530
+ metrics["3Y (ann.) %"] = (
2531
+ _get_stats().cagr(df[df.index >= d], 0.0, compounded, win_year) * pct
2532
+ )
2533
+
2534
+ d = today - relativedelta(months=59)
2535
+ metrics["5Y (ann.) %"] = (
2536
+ _get_stats().cagr(df[df.index >= d], 0.0, compounded, win_year) * pct
2537
+ )
2538
+
2539
+ d = today - relativedelta(years=10)
2540
+ metrics["10Y (ann.) %"] = (
2541
+ _get_stats().cagr(df[df.index >= d], 0.0, compounded, win_year) * pct
2542
+ )
2543
+
2544
+ metrics["All-time (ann.) %"] = _get_stats().cagr(df, 0.0, compounded, win_year) * pct
2545
+
2546
+ # Best/worst period analysis (full mode only)
2547
+ # best/worst
2548
+ if mode.lower() == "full":
2549
+ metrics["~~~"] = blank
2550
+ metrics["Best Day %"] = (
2551
+ _get_stats().best(df, compounded=compounded, prepare_returns=False) * pct
2552
+ )
2553
+ metrics["Worst Day %"] = _get_stats().worst(df, prepare_returns=False) * pct
2554
+ metrics["Best Month %"] = (
2555
+ _get_stats().best(
2556
+ df, compounded=compounded, aggregate="ME", prepare_returns=False
2557
+ )
2558
+ * pct
2559
+ )
2560
+ metrics["Worst Month %"] = (
2561
+ _get_stats().worst(df, aggregate="ME", prepare_returns=False) * pct
2562
+ )
2563
+ metrics["Best Year %"] = (
2564
+ _get_stats().best(
2565
+ df, compounded=compounded, aggregate="YE", prepare_returns=False
2566
+ )
2567
+ * pct
2568
+ )
2569
+ metrics["Worst Year %"] = (
2570
+ _get_stats().worst(
2571
+ df, compounded=compounded, aggregate="YE", prepare_returns=False
2572
+ )
2573
+ * pct
2574
+ )
2575
+
2576
+ # Calculate and integrate drawdown metrics
2577
+ # return drawdown (dd) df
2578
+ dd = _calc_dd(
2579
+ df,
2580
+ display=(display or "internal" in kwargs),
2581
+ as_pct=kwargs.get("as_pct", False),
2582
+ )
2583
+
2584
+ # Add drawdown metrics to main metrics DataFrame
2585
+ # drawdown (dd) detail
2586
+ metrics["~~~~"] = blank
2587
+ # Properly integrate drawdown data into metrics
2588
+ for metric_name in dd.index:
2589
+ metrics[metric_name] = dd.loc[metric_name].values
2590
+
2591
+ # Additional drawdown-based metrics
2592
+ metrics["Recovery Factor"] = _get_stats().recovery_factor(df)
2593
+ metrics["Ulcer Index"] = _get_stats().ulcer_index(df)
2594
+ metrics["Serenity Index"] = _get_stats().serenity_index(df, rf)
2595
+
2596
+ # Win rate analysis (full mode only)
2597
+ # win rate
2598
+ if mode.lower() == "full":
2599
+ metrics["~~~~~"] = blank
2600
+ metrics["Avg. Up Month %"] = (
2601
+ _get_stats().avg_win(
2602
+ df, compounded=compounded, aggregate="ME", prepare_returns=False
2603
+ )
2604
+ * pct
2605
+ )
2606
+ metrics["Avg. Down Month %"] = (
2607
+ _get_stats().avg_loss(
2608
+ df, compounded=compounded, aggregate="ME", prepare_returns=False
2609
+ )
2610
+ * pct
2611
+ )
2612
+ metrics["Win Days %%"] = _get_stats().win_rate(df, prepare_returns=False) * pct
2613
+ metrics["Win Month %%"] = (
2614
+ _get_stats().win_rate(
2615
+ df, compounded=compounded, aggregate="ME", prepare_returns=False
2616
+ )
2617
+ * pct
2618
+ )
2619
+ metrics["Win Quarter %%"] = (
2620
+ _get_stats().win_rate(
2621
+ df, compounded=compounded, aggregate="QE", prepare_returns=False
2622
+ )
2623
+ * pct
2624
+ )
2625
+ metrics["Win Year %%"] = (
2626
+ _get_stats().win_rate(
2627
+ df, compounded=compounded, aggregate="YE", prepare_returns=False
2628
+ )
2629
+ * pct
2630
+ )
2631
+
2632
+ # Greek letters and correlation analysis (if benchmark exists)
2633
+ if "benchmark" in df:
2634
+ metrics["~~~~~~~~~~~~"] = blank
2635
+ if isinstance(returns, _pd.Series):
2636
+ # Calculate Greek letters (Beta, Alpha) for single strategy
2637
+ greeks = _get_stats().greeks(
2638
+ df["returns"], df["benchmark"], win_year, prepare_returns=False
2639
+ )
2640
+ metrics["Beta"] = [str(round(greeks["beta"], 2)), "-"]
2641
+ metrics["Alpha"] = [str(round(greeks["alpha"], 2)), "-"]
2642
+ metrics["Correlation"] = [
2643
+ str(round(df["benchmark"].corr(df["returns"]) * pct, 2)) + "%",
2644
+ "-",
2645
+ ]
2646
+ metrics["Treynor Ratio"] = [
2647
+ str(
2648
+ round(
2649
+ _get_stats().treynor_ratio(
2650
+ df["returns"], df["benchmark"], win_year, rf
2651
+ )
2652
+ * pct,
2653
+ 2,
2654
+ )
2655
+ )
2656
+ + "%",
2657
+ "-",
2658
+ ]
2659
+ elif isinstance(returns, _pd.DataFrame):
2660
+ # Calculate Greek letters for multiple strategies
2661
+ greeks = [
2662
+ _get_stats().greeks(
2663
+ df[strategy_col],
2664
+ df["benchmark"],
2665
+ win_year,
2666
+ prepare_returns=False,
2667
+ )
2668
+ for strategy_col in df_strategy_columns
2669
+ ]
2670
+ metrics["Beta"] = [str(round(g["beta"], 2)) for g in greeks] + ["-"]
2671
+ metrics["Alpha"] = [str(round(g["alpha"], 2)) for g in greeks] + ["-"]
2672
+ metrics["Correlation"] = (
2673
+ [
2674
+ str(round(df["benchmark"].corr(df[strategy_col]) * pct, 2))
2675
+ + "%"
2676
+ for strategy_col in df_strategy_columns
2677
+ ]
2678
+ ) + ["-"]
2679
+ metrics["Treynor Ratio"] = (
2680
+ [
2681
+ str(
2682
+ round(
2683
+ _get_stats().treynor_ratio(
2684
+ df[strategy_col], df["benchmark"], win_year, rf
2685
+ )
2686
+ * pct,
2687
+ 2,
2688
+ )
2689
+ )
2690
+ + "%"
2691
+ for strategy_col in df_strategy_columns
2692
+ ]
2693
+ ) + ["-"]
2694
+
2695
+ # Format metrics for display
2696
+ # prepare for display
2697
+ for col in metrics.columns:
2698
+ try:
2699
+ # Try to convert to float and round
2700
+ metrics[col] = metrics[col].astype(float).round(2)
2701
+ if display or "internal" in kwargs:
2702
+ metrics[col] = metrics[col].astype(str)
2703
+ except (ValueError, TypeError, AttributeError):
2704
+ pass
2705
+ # Handle integer columns (marked with *int)
2706
+ if (display or "internal" in kwargs) and "*int" in col:
2707
+ metrics[col] = metrics[col].str.replace(".0", "", regex=False)
2708
+ metrics.rename({col: col.replace("*int", "")}, axis=1, inplace=True)
2709
+ # Add percentage signs to percentage columns
2710
+ if (display or "internal" in kwargs) and "%" in col:
2711
+ metrics[col] = metrics[col] + "%"
2712
+
2713
+ # Format drawdown days as integers
2714
+ try:
2715
+ metrics["Longest DD Days"] = _pd.to_numeric(metrics["Longest DD Days"]).astype(
2716
+ "int"
2717
+ )
2718
+ metrics["Avg. Drawdown Days"] = _pd.to_numeric(
2719
+ metrics["Avg. Drawdown Days"]
2720
+ ).astype("int")
2721
+
2722
+ if display or "internal" in kwargs:
2723
+ metrics["Longest DD Days"] = metrics["Longest DD Days"].astype(str)
2724
+ metrics["Avg. Drawdown Days"] = metrics["Avg. Drawdown Days"].astype(str)
2725
+ except Exception:
2726
+ metrics["Longest DD Days"] = "-"
2727
+ metrics["Avg. Drawdown Days"] = "-"
2728
+ if display or "internal" in kwargs:
2729
+ metrics["Longest DD Days"] = "-"
2730
+ metrics["Avg. Drawdown Days"] = "-"
2731
+
2732
+ # Clean up column names (remove separators and percentage signs)
2733
+ metrics.columns = [col if "~" not in col else "" for col in metrics.columns]
2734
+ metrics.columns = [col[:-1] if "%" in col else col for col in metrics.columns]
2735
+ metrics = metrics.T
2736
+
2737
+ # Set appropriate column names
2738
+ if "benchmark" in df:
2739
+ column_names = [strategy_colname, benchmark_colname]
2740
+ if isinstance(strategy_colname, list):
2741
+ metrics.columns = list(_pd.core.common.flatten(column_names))
2742
+ else:
2743
+ metrics.columns = column_names
2744
+ else:
2745
+ if isinstance(strategy_colname, list):
2746
+ metrics.columns = strategy_colname
2747
+ else:
2748
+ metrics.columns = [strategy_colname]
2749
+
2750
+ # Final data cleaning
2751
+ # cleanups
2752
+ metrics.replace([-0, "-0"], 0, inplace=True)
2753
+ metrics.replace(
2754
+ [
2755
+ _np.nan,
2756
+ -_np.nan,
2757
+ _np.inf,
2758
+ -_np.inf,
2759
+ "-nan%",
2760
+ "nan%",
2761
+ "-nan",
2762
+ "nan",
2763
+ "-inf%",
2764
+ "inf%",
2765
+ "-inf",
2766
+ "inf",
2767
+ ],
2768
+ "-",
2769
+ inplace=True,
2770
+ )
2771
+
2772
+ # Reorder columns to put benchmark first if present
2773
+ # move benchmark to be the first column always if present
2774
+ if "benchmark" in df:
2775
+ metrics = metrics[
2776
+ [benchmark_colname]
2777
+ + [col for col in metrics.columns if col != benchmark_colname]
2778
+ ]
2779
+
2780
+ # Handle display vs return
2781
+ if display:
2782
+ # Build and display parameters table (feature #472)
2783
+ params_data = {
2784
+ "Parameter": ["Risk-Free Rate", "Periods/Year", "Compounded", "Match Dates"],
2785
+ "Value": [
2786
+ f"{rf:.1%}" if rf != 0 else "0.0%",
2787
+ str(periods_per_year),
2788
+ "Yes" if compounded else "No",
2789
+ "Yes" if match_dates else "No",
2790
+ ],
2791
+ }
2792
+ if benchmark is not None:
2793
+ params_data["Parameter"].insert(0, "Benchmark")
2794
+ params_data["Value"].insert(0, benchmark_colname)
2795
+ params_df = _pd.DataFrame(params_data)
2796
+ print("\n" + _tabulate(params_df, headers="keys", tablefmt="simple", showindex=False))
2797
+ print("\n")
2798
+ print(_tabulate(metrics, headers="keys", tablefmt="simple"))
2799
+ return None
2800
+
2801
+ # Remove separator rows if not requested
2802
+ if not sep:
2803
+ metrics = metrics[metrics.index != ""]
2804
+
2805
+ # Final formatting for programmatic use
2806
+ # remove spaces from column names
2807
+ metrics = metrics.T
2808
+ metrics.columns = [
2809
+ c.replace(" %", "").replace(" *int", "").strip() for c in metrics.columns
2810
+ ]
2811
+ metrics = metrics.T
2812
+
2813
+ return metrics
2814
+
2815
+
2816
+ def plots(
2817
+ returns,
2818
+ benchmark=None,
2819
+ grayscale=False,
2820
+ figsize=(8, 5),
2821
+ mode="basic",
2822
+ compounded=True,
2823
+ periods_per_year=252,
2824
+ prepare_returns=True,
2825
+ match_dates=True,
2826
+ **kwargs,
2827
+ ):
2828
+ """
2829
+ Generate comprehensive visualization plots for portfolio performance.
2830
+
2831
+ This function creates a complete set of performance visualization plots
2832
+ including returns, drawdowns, distributions, and rolling metrics. It can
2833
+ generate either basic plots or a full comprehensive suite.
2834
+
2835
+ Parameters
2836
+ ----------
2837
+ returns : pd.Series or pd.DataFrame
2838
+ Daily returns data for the strategy/portfolio
2839
+ benchmark : pd.Series, str, or None, default None
2840
+ Benchmark returns for comparison
2841
+ grayscale : bool, default False
2842
+ Whether to generate charts in grayscale
2843
+ figsize : tuple, default (8, 5)
2844
+ Figure size for plots as (width, height)
2845
+ mode : str, default "basic"
2846
+ Plot mode - "basic" for essential plots, "full" for comprehensive suite
2847
+ compounded : bool, default True
2848
+ Whether to compound returns for calculations
2849
+ periods_per_year : int, default 252
2850
+ Number of trading periods per year
2851
+ prepare_returns : bool, default True
2852
+ Whether to prepare/clean returns data
2853
+ match_dates : bool, default True
2854
+ Whether to align returns and benchmark start dates
2855
+ **kwargs
2856
+ Additional keyword arguments:
2857
+ - strategy_title: Custom name for the strategy
2858
+ - benchmark_title: Custom name for the benchmark
2859
+ - active: Whether to show active returns vs benchmark
2860
+
2861
+ Returns
2862
+ -------
2863
+ None
2864
+ Displays various performance plots
2865
+
2866
+ Examples
2867
+ --------
2868
+ >>> plots(returns, benchmark='^GSPC', mode="full")
2869
+ >>> plots(returns, grayscale=True, figsize=(10, 6))
2870
+ """
2871
+ # Extract title parameters from kwargs
2872
+ benchmark_colname = kwargs.get("benchmark_title", "Benchmark")
2873
+ strategy_colname = kwargs.get("strategy_title", "Strategy")
2874
+ active = kwargs.get("active", False)
2875
+
2876
+ # Handle multiple strategy columns
2877
+ if (
2878
+ isinstance(returns, _pd.DataFrame)
2879
+ and len(returns.columns) > 1
2880
+ and isinstance(strategy_colname, str)
2881
+ ):
2882
+ strategy_colname = list(returns.columns)
2883
+
2884
+ # Get trading periods for rolling window calculations
2885
+ win_year, win_half_year = _get_trading_periods(periods_per_year)
2886
+
2887
+ # Clean returns data if date matching is enabled
2888
+ if match_dates is True:
2889
+ returns = returns.dropna()
2890
+
2891
+ # Prepare returns data if requested
2892
+ if prepare_returns:
2893
+ returns = _get_utils()._prepare_returns(returns)
2894
+
2895
+ # Set names for display in plots
2896
+ if isinstance(returns, _pd.Series):
2897
+ returns.name = strategy_colname
2898
+ elif isinstance(returns, _pd.DataFrame):
2899
+ returns.columns = strategy_colname
2900
+
2901
+ # Generate basic plots (snapshot and heatmap)
2902
+ if mode.lower() != "full":
2903
+ # Performance snapshot plot
2904
+ _get_plots().snapshot(
2905
+ returns,
2906
+ grayscale=grayscale,
2907
+ figsize=(figsize[0], figsize[0]),
2908
+ show=True,
2909
+ mode=("comp" if compounded else "sum"),
2910
+ benchmark_title=benchmark_colname,
2911
+ strategy_title=strategy_colname,
2912
+ )
2913
+
2914
+ # Monthly returns heatmap
2915
+ if isinstance(returns, _pd.Series):
2916
+ _get_plots().monthly_heatmap(
2917
+ returns,
2918
+ benchmark,
2919
+ grayscale=grayscale,
2920
+ figsize=(figsize[0], figsize[0] * 0.5),
2921
+ show=True,
2922
+ ylabel="",
2923
+ compounded=compounded,
2924
+ active=active,
2925
+ )
2926
+ elif isinstance(returns, _pd.DataFrame):
2927
+ # Generate heatmap for each strategy column
2928
+ for col in returns.columns:
2929
+ _get_plots().monthly_heatmap(
2930
+ returns[col].dropna(),
2931
+ benchmark,
2932
+ grayscale=grayscale,
2933
+ figsize=(figsize[0], figsize[0] * 0.5),
2934
+ show=True,
2935
+ ylabel="",
2936
+ returns_label=col,
2937
+ compounded=compounded,
2938
+ active=active,
2939
+ )
2940
+
2941
+ return
2942
+
2943
+ # prepare timeseries
2944
+ if benchmark is not None:
2945
+ benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index)
2946
+ benchmark.name = benchmark_colname
2947
+ if match_dates is True:
2948
+ returns, benchmark = _match_dates(returns, benchmark)
2949
+
2950
+ # Generate comprehensive plot suite
2951
+ # Cumulative returns plot
2952
+ _get_plots().returns(
2953
+ returns,
2954
+ benchmark,
2955
+ grayscale=grayscale,
2956
+ figsize=(figsize[0], figsize[0] * 0.6),
2957
+ show=True,
2958
+ ylabel="",
2959
+ prepare_returns=False,
2960
+ compound=compounded,
2961
+ )
2962
+
2963
+ # Log returns plot for better visualization
2964
+ _get_plots().log_returns(
2965
+ returns,
2966
+ benchmark,
2967
+ grayscale=grayscale,
2968
+ figsize=(figsize[0], figsize[0] * 0.5),
2969
+ show=True,
2970
+ ylabel="",
2971
+ prepare_returns=False,
2972
+ compound=compounded,
2973
+ )
2974
+
2975
+ # Volatility-matched returns (if benchmark exists)
2976
+ if benchmark is not None:
2977
+ _get_plots().returns(
2978
+ returns,
2979
+ benchmark,
2980
+ match_volatility=True,
2981
+ grayscale=grayscale,
2982
+ figsize=(figsize[0], figsize[0] * 0.5),
2983
+ show=True,
2984
+ ylabel="",
2985
+ prepare_returns=False,
2986
+ compound=compounded,
2987
+ )
2988
+
2989
+ # Yearly returns comparison
2990
+ _get_plots().yearly_returns(
2991
+ returns,
2992
+ benchmark,
2993
+ grayscale=grayscale,
2994
+ figsize=(figsize[0], figsize[0] * 0.5),
2995
+ show=True,
2996
+ ylabel="",
2997
+ prepare_returns=False,
2998
+ compounded=compounded,
2999
+ )
3000
+
3001
+ # Returns distribution histogram
3002
+ _get_plots().histogram(
3003
+ returns,
3004
+ benchmark,
3005
+ grayscale=grayscale,
3006
+ figsize=(figsize[0], figsize[0] * 0.5),
3007
+ show=True,
3008
+ ylabel="",
3009
+ prepare_returns=False,
3010
+ compounded=compounded,
3011
+ )
3012
+
3013
+ # Calculate figure size for smaller plots
3014
+ small_fig_size = (figsize[0], figsize[0] * 0.35)
3015
+ if isinstance(returns, _pd.DataFrame) and len(returns.columns) > 1:
3016
+ small_fig_size = (
3017
+ figsize[0],
3018
+ figsize[0] * (0.33 * (len(returns.columns) * 0.66)),
3019
+ )
3020
+
3021
+ # Daily returns scatter plot
3022
+ _get_plots().daily_returns(
3023
+ returns,
3024
+ benchmark,
3025
+ grayscale=grayscale,
3026
+ figsize=small_fig_size,
3027
+ show=True,
3028
+ ylabel="",
3029
+ prepare_returns=False,
3030
+ active=active,
3031
+ )
3032
+
3033
+ # Rolling beta analysis (if benchmark exists)
3034
+ if benchmark is not None:
3035
+ _get_plots().rolling_beta(
3036
+ returns,
3037
+ benchmark,
3038
+ grayscale=grayscale,
3039
+ window1=win_half_year,
3040
+ window2=win_year,
3041
+ figsize=small_fig_size,
3042
+ show=True,
3043
+ ylabel="",
3044
+ prepare_returns=False,
3045
+ )
3046
+
3047
+ # Rolling volatility analysis
3048
+ _get_plots().rolling_volatility(
3049
+ returns,
3050
+ benchmark,
3051
+ grayscale=grayscale,
3052
+ figsize=small_fig_size,
3053
+ show=True,
3054
+ ylabel="",
3055
+ period=win_half_year,
3056
+ )
3057
+
3058
+ # Rolling Sharpe ratio analysis
3059
+ _get_plots().rolling_sharpe(
3060
+ returns,
3061
+ grayscale=grayscale,
3062
+ figsize=small_fig_size,
3063
+ show=True,
3064
+ ylabel="",
3065
+ period=win_half_year,
3066
+ )
3067
+
3068
+ # Rolling Sortino ratio analysis
3069
+ _get_plots().rolling_sortino(
3070
+ returns,
3071
+ grayscale=grayscale,
3072
+ figsize=small_fig_size,
3073
+ show=True,
3074
+ ylabel="",
3075
+ period=win_half_year,
3076
+ )
3077
+
3078
+ # Drawdown periods analysis
3079
+ if isinstance(returns, _pd.Series):
3080
+ _get_plots().drawdowns_periods(
3081
+ returns,
3082
+ grayscale=grayscale,
3083
+ figsize=(figsize[0], figsize[0] * 0.5),
3084
+ show=True,
3085
+ ylabel="",
3086
+ prepare_returns=False,
3087
+ compounded=compounded,
3088
+ )
3089
+ elif isinstance(returns, _pd.DataFrame):
3090
+ # Handle multiple strategy columns
3091
+ for col in returns.columns:
3092
+ _get_plots().drawdowns_periods(
3093
+ returns[col],
3094
+ grayscale=grayscale,
3095
+ figsize=(figsize[0], figsize[0] * 0.5),
3096
+ show=True,
3097
+ ylabel="",
3098
+ title=col,
3099
+ prepare_returns=False,
3100
+ compounded=compounded,
3101
+ )
3102
+
3103
+ # Underwater (drawdown) plot
3104
+ _get_plots().drawdown(
3105
+ returns,
3106
+ grayscale=grayscale,
3107
+ figsize=(figsize[0], figsize[0] * 0.4),
3108
+ show=True,
3109
+ ylabel="",
3110
+ compound=compounded,
3111
+ )
3112
+
3113
+ # Monthly returns heatmap
3114
+ if isinstance(returns, _pd.Series):
3115
+ _get_plots().monthly_heatmap(
3116
+ returns,
3117
+ benchmark,
3118
+ grayscale=grayscale,
3119
+ figsize=(figsize[0], figsize[0] * 0.5),
3120
+ returns_label=returns.name,
3121
+ show=True,
3122
+ ylabel="",
3123
+ compounded=compounded,
3124
+ active=active,
3125
+ )
3126
+ elif isinstance(returns, _pd.DataFrame):
3127
+ # Handle multiple strategy columns
3128
+ for col in returns.columns:
3129
+ _get_plots().monthly_heatmap(
3130
+ returns[col],
3131
+ benchmark,
3132
+ grayscale=grayscale,
3133
+ figsize=(figsize[0], figsize[0] * 0.5),
3134
+ show=True,
3135
+ ylabel="",
3136
+ returns_label=col,
3137
+ compounded=compounded,
3138
+ active=active,
3139
+ )
3140
+
3141
+ # Returns distribution analysis
3142
+ if isinstance(returns, _pd.Series):
3143
+ _get_plots().distribution(
3144
+ returns,
3145
+ grayscale=grayscale,
3146
+ figsize=(figsize[0], figsize[0] * 0.5),
3147
+ show=True,
3148
+ title=returns.name,
3149
+ ylabel="",
3150
+ prepare_returns=False,
3151
+ compounded=compounded,
3152
+ )
3153
+ elif isinstance(returns, _pd.DataFrame):
3154
+ # Handle multiple strategy columns
3155
+ for col in returns.columns:
3156
+ _get_plots().distribution(
3157
+ returns[col],
3158
+ grayscale=grayscale,
3159
+ figsize=(figsize[0], figsize[0] * 0.5),
3160
+ show=True,
3161
+ title=col,
3162
+ ylabel="",
3163
+ prepare_returns=False,
3164
+ compounded=compounded,
3165
+ )
3166
+
3167
+
3168
+ def _calc_dd(df, display=True, as_pct=False):
3169
+ """
3170
+ Calculate drawdown statistics for performance analysis.
3171
+
3172
+ This helper function computes comprehensive drawdown statistics including
3173
+ maximum drawdown, drawdown dates, recovery periods, and average drawdown
3174
+ metrics. It handles both single strategy and multiple strategy analysis.
3175
+
3176
+ Parameters
3177
+ ----------
3178
+ df : pd.DataFrame
3179
+ DataFrame containing returns data with columns for strategies
3180
+ and optionally benchmark
3181
+ display : bool, default True
3182
+ Whether the output is for display purposes (affects formatting)
3183
+ as_pct : bool, default False
3184
+ Whether to return percentages instead of decimals
3185
+
3186
+ Returns
3187
+ -------
3188
+ pd.DataFrame
3189
+ DataFrame with drawdown statistics including:
3190
+ - Max Drawdown %: Maximum drawdown percentage
3191
+ - Max DD Date: Date of maximum drawdown
3192
+ - Max DD Period Start: Start date of worst drawdown period
3193
+ - Max DD Period End: End date of worst drawdown period
3194
+ - Longest DD Days: Duration of longest drawdown in days
3195
+ - Avg. Drawdown %: Average drawdown percentage
3196
+ - Avg. Drawdown Days: Average drawdown duration in days
3197
+
3198
+ Examples
3199
+ --------
3200
+ >>> dd_stats = _calc_dd(returns_df, display=False)
3201
+ >>> dd_stats = _calc_dd(returns_df, as_pct=True)
3202
+ """
3203
+ # Convert returns to drawdown series
3204
+ dd = _get_stats().to_drawdown_series(df)
3205
+ dd_info = _get_stats().drawdown_details(dd)
3206
+
3207
+ # Return empty DataFrame if no drawdowns found
3208
+ if dd_info.empty:
3209
+ return _pd.DataFrame()
3210
+
3211
+ # Handle different column structures based on data type
3212
+ if "returns" in dd_info:
3213
+ ret_dd = dd_info["returns"]
3214
+ # to match multiple columns like returns_1, returns_2, ...
3215
+ elif (
3216
+ any(dd_info.columns.get_level_values(0).str.contains("returns"))
3217
+ and dd_info.columns.get_level_values(0).nunique() > 1
3218
+ ):
3219
+ ret_dd = dd_info.loc[
3220
+ :, dd_info.columns.get_level_values(0).str.contains("returns")
3221
+ ]
3222
+ else:
3223
+ ret_dd = dd_info
3224
+
3225
+ # Calculate drawdown statistics based on data structure
3226
+ if (
3227
+ any(ret_dd.columns.get_level_values(0).str.contains("returns"))
3228
+ and ret_dd.columns.get_level_values(0).nunique() > 1
3229
+ ):
3230
+ # Multiple strategy columns case
3231
+ dd_stats = {
3232
+ col: {
3233
+ "Max Drawdown %": ret_dd[col]
3234
+ .sort_values(by="max drawdown", ascending=True)["max drawdown"]
3235
+ .values[0]
3236
+ / 100,
3237
+ "Max DD Date": ret_dd[col]
3238
+ .sort_values(by="max drawdown", ascending=True)["valley"]
3239
+ .values[0],
3240
+ "Max DD Period Start": ret_dd[col]
3241
+ .sort_values(by="max drawdown", ascending=True)["start"]
3242
+ .values[0],
3243
+ "Max DD Period End": ret_dd[col]
3244
+ .sort_values(by="max drawdown", ascending=True)["end"]
3245
+ .values[0],
3246
+ "Longest DD Days": str(
3247
+ _np.round(
3248
+ ret_dd[col]
3249
+ .sort_values(by="days", ascending=False)["days"]
3250
+ .values[0]
3251
+ )
3252
+ ),
3253
+ "Avg. Drawdown %": ret_dd[col]["max drawdown"].mean() / 100,
3254
+ "Avg. Drawdown Days": str(_np.round(ret_dd[col]["days"].mean())),
3255
+ }
3256
+ for col in ret_dd.columns.get_level_values(0)
3257
+ }
3258
+ else:
3259
+ # Single strategy case. A single-column DataFrame input arrives here
3260
+ # with MultiIndex columns (level 0 = the strategy column); flatten it
3261
+ # so the per-field access below works on flat column labels.
3262
+ if isinstance(ret_dd.columns, _pd.MultiIndex):
3263
+ ret_dd = ret_dd.droplevel(0, axis=1)
3264
+ max_dd = ret_dd.sort_values(by="max drawdown", ascending=True)
3265
+ dd_stats = {
3266
+ "returns": {
3267
+ "Max Drawdown %": max_dd["max drawdown"].values[0] / 100,
3268
+ "Max DD Date": max_dd["valley"].values[0],
3269
+ "Max DD Period Start": max_dd["start"].values[0],
3270
+ "Max DD Period End": max_dd["end"].values[0],
3271
+ "Longest DD Days": str(
3272
+ _np.round(
3273
+ ret_dd.sort_values(by="days", ascending=False)["days"].values[0]
3274
+ )
3275
+ ),
3276
+ "Avg. Drawdown %": ret_dd["max drawdown"].mean() / 100,
3277
+ "Avg. Drawdown Days": str(_np.round(ret_dd["days"].mean())),
3278
+ }
3279
+ }
3280
+
3281
+ # Add benchmark drawdown statistics if present
3282
+ if "benchmark" in df and (dd_info.columns, _pd.MultiIndex):
3283
+ bench_dd = dd_info["benchmark"].sort_values(by="max drawdown")
3284
+ dd_stats["benchmark"] = {
3285
+ "Max Drawdown %": bench_dd.sort_values(by="max drawdown", ascending=True)[
3286
+ "max drawdown"
3287
+ ].values[0]
3288
+ / 100,
3289
+ "Max DD Date": bench_dd.sort_values(
3290
+ by="max drawdown", ascending=True
3291
+ )["valley"].values[0],
3292
+ "Max DD Period Start": bench_dd.sort_values(
3293
+ by="max drawdown", ascending=True
3294
+ )["start"].values[0],
3295
+ "Max DD Period End": bench_dd.sort_values(
3296
+ by="max drawdown", ascending=True
3297
+ )["end"].values[0],
3298
+ "Longest DD Days": str(
3299
+ _np.round(
3300
+ bench_dd.sort_values(by="days", ascending=False)["days"].values[0]
3301
+ )
3302
+ ),
3303
+ "Avg. Drawdown %": bench_dd["max drawdown"].mean() / 100,
3304
+ "Avg. Drawdown Days": str(_np.round(bench_dd["days"].mean())),
3305
+ }
3306
+
3307
+ # Apply percentage multiplier based on display settings
3308
+ # pct multiplier
3309
+ pct = 100 if display or as_pct else 1
3310
+
3311
+ # Convert to DataFrame and apply percentage formatting
3312
+ dd_stats = _pd.DataFrame(dd_stats).T
3313
+ dd_stats["Max Drawdown %"] = dd_stats["Max Drawdown %"].astype(float) * pct
3314
+ dd_stats["Avg. Drawdown %"] = dd_stats["Avg. Drawdown %"].astype(float) * pct
3315
+
3316
+ return dd_stats.T
3317
+
3318
+
3319
+ def _html_table(obj, showindex="default"):
3320
+ """
3321
+ Convert DataFrame to HTML table format for report generation.
3322
+
3323
+ This helper function converts pandas DataFrames to clean HTML table format
3324
+ suitable for embedding in HTML reports. It removes default tabulate styling
3325
+ and cleans up spacing for better presentation.
3326
+
3327
+ Parameters
3328
+ ----------
3329
+ obj : pd.DataFrame
3330
+ DataFrame to convert to HTML table
3331
+ showindex : str or bool, default "default"
3332
+ Whether to show the DataFrame index in the HTML table.
3333
+ "default" uses tabulate's default behavior
3334
+
3335
+ Returns
3336
+ -------
3337
+ str
3338
+ HTML string containing the formatted table
3339
+
3340
+ Examples
3341
+ --------
3342
+ >>> html_str = _html_table(metrics_df)
3343
+ >>> html_str = _html_table(metrics_df, showindex=False)
3344
+ """
3345
+ # Convert DataFrame to HTML table using tabulate
3346
+ obj = _tabulate(
3347
+ obj, headers="keys", tablefmt="html", floatfmt=".2f", showindex=showindex
3348
+ )
3349
+
3350
+ # Remove default tabulate styling attributes
3351
+ obj = obj.replace(' style="text-align: right;"', "")
3352
+ obj = obj.replace(' style="text-align: left;"', "")
3353
+ obj = obj.replace(' style="text-align: center;"', "")
3354
+
3355
+ # Clean up spacing in table cells
3356
+ obj = _regex.sub("<td> +", "<td>", obj)
3357
+ obj = _regex.sub(" +</td>", "</td>", obj)
3358
+ obj = _regex.sub("<th> +", "<th>", obj)
3359
+ obj = _regex.sub(" +</th>", "</th>", obj)
3360
+
3361
+ return obj
3362
+
3363
+
3364
+ def _download_html(html, filename="quantstats-tearsheet.html"):
3365
+ """
3366
+ Generate JavaScript code to download HTML content in browser.
3367
+
3368
+ This helper function creates JavaScript code that triggers a download
3369
+ of HTML content in the browser. It's used for downloading tearsheet
3370
+ reports directly from Jupyter notebooks.
3371
+
3372
+ Parameters
3373
+ ----------
3374
+ html : str
3375
+ HTML content to be downloaded
3376
+ filename : str, default "quantstats-tearsheet.html"
3377
+ Filename for the downloaded file
3378
+
3379
+ Returns
3380
+ -------
3381
+ None
3382
+ Displays JavaScript code in notebook to trigger download
3383
+
3384
+ Examples
3385
+ --------
3386
+ >>> _download_html(html_content, "my_report.html")
3387
+ """
3388
+ # Create JavaScript code for file download
3389
+ jscode = _regex.sub(
3390
+ " +",
3391
+ " ",
3392
+ """<script>
3393
+ var bl=new Blob(['{{html}}'],{type:"text/html"});
3394
+ var a=document.createElement("a");
3395
+ a.href=URL.createObjectURL(bl);
3396
+ a.download="{{filename}}";
3397
+ a.hidden=true;document.body.appendChild(a);
3398
+ a.innerHTML="download report";
3399
+ a.click();</script>""".replace(
3400
+ "\n", ""
3401
+ ),
3402
+ )
3403
+
3404
+ # Insert HTML content and clean up formatting
3405
+ jscode = jscode.replace("{{html}}", _regex.sub(" +", " ", html.replace("\n", "")))
3406
+
3407
+ # Execute JavaScript in notebook if in notebook environment
3408
+ if _get_utils()._in_notebook():
3409
+ iDisplay(iHTML(jscode.replace("{{filename}}", filename)))
3410
+
3411
+
3412
+ def _open_html(html):
3413
+ """
3414
+ Generate JavaScript code to open HTML content in new browser window.
3415
+
3416
+ This helper function creates JavaScript code that opens HTML content
3417
+ in a new browser window. It's used for displaying tearsheet reports
3418
+ directly in the browser from Jupyter notebooks.
3419
+
3420
+ Parameters
3421
+ ----------
3422
+ html : str
3423
+ HTML content to be displayed in new window
3424
+
3425
+ Returns
3426
+ -------
3427
+ None
3428
+ Displays JavaScript code in notebook to open new window
3429
+
3430
+ Examples
3431
+ --------
3432
+ >>> _open_html(html_content)
3433
+ """
3434
+ # Create JavaScript code to open new window with HTML content
3435
+ jscode = _regex.sub(
3436
+ " +",
3437
+ " ",
3438
+ """<script>
3439
+ var win=window.open();win.document.body.innerHTML='{{html}}';
3440
+ </script>""".replace(
3441
+ "\n", ""
3442
+ ),
3443
+ )
3444
+
3445
+ # Insert HTML content and clean up formatting
3446
+ jscode = jscode.replace("{{html}}", _regex.sub(" +", " ", html.replace("\n", "")))
3447
+
3448
+ # Execute JavaScript in notebook if in notebook environment
3449
+ if _get_utils()._in_notebook():
3450
+ iDisplay(iHTML(jscode))
3451
+
3452
+
3453
+ def _embed_figure(figfiles, figfmt):
3454
+ """
3455
+ Embed matplotlib figures in HTML format for reports.
3456
+
3457
+ This helper function converts matplotlib figure objects to embedded
3458
+ HTML format suitable for inclusion in HTML reports. It handles both
3459
+ SVG and base64-encoded image formats.
3460
+
3461
+ Parameters
3462
+ ----------
3463
+ figfiles : io.StringIO or list of io.StringIO
3464
+ File-like objects containing figure data. Can be single figure
3465
+ or list of figures for multiple plots
3466
+ figfmt : str
3467
+ Format for the figures ('svg', 'png', 'jpg', etc.)
3468
+
3469
+ Returns
3470
+ -------
3471
+ str
3472
+ HTML string with embedded figure(s) ready for inclusion in report
3473
+
3474
+ Examples
3475
+ --------
3476
+ >>> embed_str = _embed_figure(figfile, 'svg')
3477
+ >>> embed_str = _embed_figure([fig1, fig2], 'png')
3478
+ """
3479
+ # Handle multiple figures
3480
+ if isinstance(figfiles, list):
3481
+ embed_string = "\n"
3482
+ for figfile in figfiles:
3483
+ figbytes = figfile.getvalue()
3484
+ if figfmt == "svg":
3485
+ # SVG can be embedded directly as text
3486
+ return figbytes.decode()
3487
+ # For other formats, encode as base64 data URI
3488
+ data_uri = _b64encode(figbytes).decode()
3489
+ embed_string.join(
3490
+ f'<img src="data:image/{figfmt};base64,{data_uri}" />'
3491
+ )
3492
+ else:
3493
+ # Handle single figure
3494
+ figbytes = figfiles.getvalue()
3495
+ if figfmt == "svg":
3496
+ # SVG can be embedded directly as text
3497
+ return figbytes.decode()
3498
+ # For other formats, encode as base64 data URI
3499
+ data_uri = _b64encode(figbytes).decode()
3500
+ embed_string = f'<img src="data:image/{figfmt};base64,{data_uri}" />'
3501
+
3502
+ return embed_string