pyalloq-viz 0.1.22__tar.gz
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.
- pyalloq_viz-0.1.22/PKG-INFO +350 -0
- pyalloq_viz-0.1.22/README.md +331 -0
- pyalloq_viz-0.1.22/pyproject.toml +36 -0
- pyalloq_viz-0.1.22/pyproject.toml.orig +30 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/__init__.py +79 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/allocation.py +850 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/py.typed +0 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/regime.py +482 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/robustness.py +439 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/simulation.py +524 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/tearsheets/__init__.py +13 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/tearsheets/allocation_ts.py +278 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/tearsheets/base.py +218 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/tearsheets/regime_ts.py +170 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/tearsheets/robustness_ts.py +146 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/tearsheets/simulation_ts.py +166 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/themes.py +211 -0
- pyalloq_viz-0.1.22/src/pyalloq_viz/utils.py +284 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: pyalloq-viz
|
|
3
|
+
Version: 0.1.22
|
|
4
|
+
Summary: Interactive and static visualization tear sheets for PyAlloq portfolio optimization, backtesting, and simulation.
|
|
5
|
+
Author: Siddeshkanth
|
|
6
|
+
Author-email: Siddeshkanth <pyalloq-info@alloq-alpha.com>
|
|
7
|
+
Requires-Dist: numpy>=1.24
|
|
8
|
+
Requires-Dist: pandas>=2.0
|
|
9
|
+
Requires-Dist: scipy>=1.11
|
|
10
|
+
Requires-Dist: plotly>=5.18.0
|
|
11
|
+
Requires-Dist: matplotlib>=3.7
|
|
12
|
+
Requires-Dist: seaborn>=0.13
|
|
13
|
+
Requires-Dist: jinja2>=3.1
|
|
14
|
+
Requires-Dist: pyalloq-core
|
|
15
|
+
Requires-Dist: pyalloq-backtest
|
|
16
|
+
Requires-Dist: pyalloq-simulation
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# `pyalloq-viz` — Visualization & Tear Sheet Suite for PyAlloq
|
|
21
|
+
|
|
22
|
+
`pyalloq-viz` provides interactive Plotly visualizations, publication-ready charts, and self-contained HTML Tear Sheet dashboards for portfolio optimization, walk-forward backtesting, Monte Carlo simulations, and macroeconomic regime analysis.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Overview & Design Philosophy
|
|
27
|
+
|
|
28
|
+
`pyalloq-viz` supports **two complementary ways** to visualize your quantitative workflows:
|
|
29
|
+
|
|
30
|
+
1. **Modular Plot Functions (`plot_*`)**:
|
|
31
|
+
Every visualization is available as a standalone function that returns a styled `plotly.graph_objects.Figure` (supporting both `"alloq_dark"` and `"alloq_light"` institutional themes).
|
|
32
|
+
2. **Unified Tear Sheet Classes (`*TearSheet`)**:
|
|
33
|
+
Four specialized tear sheet builders combine related charts and summary KPIs into either:
|
|
34
|
+
- A multi-subplot interactive figure via `.to_figure()` / `.show()`
|
|
35
|
+
- A self-contained, responsive HTML dashboard via `.to_html("report.html")`
|
|
36
|
+
- A high-DPI static image via `.save_image("report.png")`
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Quickstart: End-to-End Workflow
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import numpy as np
|
|
44
|
+
import pandas as pd
|
|
45
|
+
|
|
46
|
+
from pyalloq_core.data import MarketData
|
|
47
|
+
from pyalloq_core.pipeline import StrategyPipeline
|
|
48
|
+
from pyalloq_backtest.engine import WalkForwardEngine
|
|
49
|
+
from pyalloq_backtest.splitters import RollingWindowSplitter
|
|
50
|
+
from pyalloq.classical.estimators.covariance.empirical import EmpiricalCovariance
|
|
51
|
+
from pyalloq.ml.optimizers.hrp import HRPAllocator
|
|
52
|
+
from pyalloq_simulation import (
|
|
53
|
+
GMMRegimeGenerator,
|
|
54
|
+
ViewBuilder,
|
|
55
|
+
AbsoluteView,
|
|
56
|
+
EntropyPooler,
|
|
57
|
+
)
|
|
58
|
+
import pyalloq_viz as viz
|
|
59
|
+
|
|
60
|
+
# 1. Prepare MarketData (with optional sector/hierarchy metadata)
|
|
61
|
+
dates = pd.bdate_range("2022-01-03", periods=500)
|
|
62
|
+
assets = ["AAPL", "MSFT", "TLT", "GLD"]
|
|
63
|
+
prices = pd.DataFrame(
|
|
64
|
+
100.0 * np.cumprod(1.0 + np.random.normal(0.0005, 0.012, (500, 4)), axis=0),
|
|
65
|
+
index=dates,
|
|
66
|
+
columns=assets,
|
|
67
|
+
)
|
|
68
|
+
cross_sectional = pd.DataFrame(
|
|
69
|
+
{"sector": ["Equities - Tech", "Equities - Tech", "Fixed Income", "Commodities"]},
|
|
70
|
+
index=assets,
|
|
71
|
+
)
|
|
72
|
+
market_data = MarketData(prices=prices, cross_sectional=cross_sectional, risk_free_rate=0.02)
|
|
73
|
+
|
|
74
|
+
# 2. Run Walk-Forward Historical Backtest
|
|
75
|
+
cov_est = EmpiricalCovariance()
|
|
76
|
+
allocator = HRPAllocator(tickers=assets)
|
|
77
|
+
pipeline = StrategyPipeline(allocator=allocator, cov_estimator=cov_est)
|
|
78
|
+
bt_engine = WalkForwardEngine(
|
|
79
|
+
pipeline=pipeline,
|
|
80
|
+
splitter=RollingWindowSplitter(lookback_window=126),
|
|
81
|
+
rebalance_freq="ME",
|
|
82
|
+
)
|
|
83
|
+
bt_result = bt_engine.run(market_data)
|
|
84
|
+
|
|
85
|
+
# 3. Fit GMM Regime Generator, Simulate Synthetic Futures & Apply Entropy Pooling Views
|
|
86
|
+
gmm_gen = GMMRegimeGenerator(n_regimes=2, random_state=42)
|
|
87
|
+
gmm_gen.fit(market_data)
|
|
88
|
+
scenarios = gmm_gen.generate(n_paths=500, horizon=63)
|
|
89
|
+
|
|
90
|
+
builder = ViewBuilder(scenarios)
|
|
91
|
+
A_ineq, b_ineq, C_eq, d_eq = builder.build([
|
|
92
|
+
AbsoluteView(asset="AAPL", operator=">=", target=0.02)
|
|
93
|
+
])
|
|
94
|
+
entropy_res = EntropyPooler(n_scenarios=scenarios.n_paths).fit(
|
|
95
|
+
A_ineq=A_ineq, b_ineq=b_ineq, C_eq=C_eq, d_eq=d_eq
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# 4. Generate Interactive HTML Tear Sheets!
|
|
99
|
+
viz.SimulationTearSheet(
|
|
100
|
+
scenarios,
|
|
101
|
+
entropy_result=entropy_res,
|
|
102
|
+
ruin_threshold=-0.15,
|
|
103
|
+
benchmark=bt_result,
|
|
104
|
+
).to_html("simulation_tearsheet.html")
|
|
105
|
+
|
|
106
|
+
viz.RobustnessTearSheet(bt_result).to_html("robustness_tearsheet.html")
|
|
107
|
+
|
|
108
|
+
viz.MacroRegimeTearSheet(
|
|
109
|
+
entropy_result=entropy_res,
|
|
110
|
+
equity_or_scenarios=bt_result,
|
|
111
|
+
gmm_or_probs=gmm_gen,
|
|
112
|
+
scenario_data=scenarios,
|
|
113
|
+
market_data=market_data,
|
|
114
|
+
).to_html("macro_regime_tearsheet.html")
|
|
115
|
+
|
|
116
|
+
viz.AllocationTearSheet(
|
|
117
|
+
backtest_result=bt_result,
|
|
118
|
+
market_data=market_data,
|
|
119
|
+
scenario_data=scenarios,
|
|
120
|
+
allocator_or_pipeline=allocator,
|
|
121
|
+
).to_html("allocation_tearsheet.html")
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Detailed Guide by Tear Sheet
|
|
127
|
+
|
|
128
|
+
### 1. The Multiverse & Simulation Tear Sheet
|
|
129
|
+
|
|
130
|
+
Visualizes synthetic price/return paths (`ScenarioMarketData` or `MonteCarloResult`), optionally weighted by posterior probabilities from `EntropyResult`.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from pyalloq_viz import (
|
|
134
|
+
SimulationTearSheet,
|
|
135
|
+
plot_fan_chart,
|
|
136
|
+
plot_terminal_wealth_ruin,
|
|
137
|
+
plot_cvar_tail_risk,
|
|
138
|
+
plot_drawdown_fan_chart,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# Individual plots:
|
|
142
|
+
fig_fan = plot_fan_chart(
|
|
143
|
+
scenarios,
|
|
144
|
+
asset_weights=bt_result.weights.iloc[-1],
|
|
145
|
+
entropy_result=entropy_res, # Optional: weights quantiles by posterior x*
|
|
146
|
+
percentiles=((5, 95), (10, 90), (25, 75)),
|
|
147
|
+
benchmark=bt_result, # Optional: overlay realized equity curve
|
|
148
|
+
theme="alloq_dark",
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
fig_ruin = plot_terminal_wealth_ruin(
|
|
152
|
+
scenarios,
|
|
153
|
+
entropy_result=entropy_res,
|
|
154
|
+
ruin_threshold=-0.20, # Highlights wealth dropping below 0.80 (-20%)
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
fig_cvar = plot_cvar_tail_risk(
|
|
158
|
+
scenarios, # Accepts ScenarioMarketData, MonteCarloResult, or BacktestResult
|
|
159
|
+
entropy_result=entropy_res,
|
|
160
|
+
alpha=0.05, # 95% VaR and CVaR (Expected Shortfall) left-tail shading
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
fig_dd = plot_drawdown_fan_chart(
|
|
164
|
+
scenarios,
|
|
165
|
+
entropy_result=entropy_res, # Underwater drawdown probability cones across all paths
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
# Combined Tear Sheet:
|
|
169
|
+
sim_ts = SimulationTearSheet(
|
|
170
|
+
scenarios,
|
|
171
|
+
asset_weights=bt_result.weights.iloc[-1],
|
|
172
|
+
entropy_result=entropy_res,
|
|
173
|
+
ruin_threshold=-0.20,
|
|
174
|
+
cvar_alpha=0.05,
|
|
175
|
+
benchmark=bt_result,
|
|
176
|
+
)
|
|
177
|
+
sim_ts.show() # Display 2x2 multi-subplot figure in Jupyter/IDE
|
|
178
|
+
sim_ts.to_html("multiverse_report.html") # Standalone HTML report with KPI summary cards
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
### 2. Robustness & Overfitting Tear Sheet
|
|
184
|
+
|
|
185
|
+
Integrates directly with `PBOEvaluator` and `CPCVSplitter` in `pyalloq_backtest` to test whether a strategy is genuinely robust or historically overfit.
|
|
186
|
+
|
|
187
|
+
#### Mode A: Single-Strategy Combinatorial Scrambling (CPCV) & Benchmark PBO
|
|
188
|
+
Recombines historical return blocks into scrambled chronological sequences of market regimes to test path-dependent survival:
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
from pyalloq_backtest import CPCVSplitter, PBOEvaluator
|
|
192
|
+
from pyalloq_viz import RobustnessTearSheet, plot_pbo_distribution, plot_cpcv_paths
|
|
193
|
+
|
|
194
|
+
# Scramble historical returns across 6 regime blocks
|
|
195
|
+
splitter = CPCVSplitter(n_groups=6, k_test_groups=2, max_paths=120)
|
|
196
|
+
cpcv_res = splitter.scramble_timelines(bt_result)
|
|
197
|
+
|
|
198
|
+
# Plot scrambled equity paths & Sharpe vs. Max Drawdown scatter
|
|
199
|
+
fig_cpcv = plot_cpcv_paths(cpcv_res)
|
|
200
|
+
|
|
201
|
+
# Compare historical Sharpe against the scrambled/synthetic Sharpe distribution
|
|
202
|
+
fig_pbo = plot_pbo_distribution(bt_result, synthetic_comparison=cpcv_res)
|
|
203
|
+
|
|
204
|
+
# Or generate the full Robustness Tear Sheet in one line:
|
|
205
|
+
rob_ts = RobustnessTearSheet(bt_result, cpcv_or_synthetic=cpcv_res)
|
|
206
|
+
rob_ts.to_html("robustness_report.html")
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
#### Mode B: Multi-Strategy Combinatorial Symmetric Cross-Validation (CSCV)
|
|
210
|
+
Implements Bailey & Lopez de Prado's exact CSCV algorithm across a $(T \times M)$ matrix of $M$ candidate strategy configurations (or a list of `BacktestResult` objects):
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
# trial_returns_df has shape (T_days, M_strategies)
|
|
214
|
+
pbo_eval = PBOEvaluator(n_partitions=8)
|
|
215
|
+
pbo_result = pbo_eval.evaluate_cscv(trial_returns_df)
|
|
216
|
+
|
|
217
|
+
# Plots Rank Logit (lambda) distribution (shaded for lambda <= 0) + IS vs. OOS Sharpe degradation
|
|
218
|
+
fig_cscv = plot_pbo_distribution(pbo_result)
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
### 3. Macro Regime & Entropy Tear Sheet
|
|
224
|
+
|
|
225
|
+
Visualizes subjective macroeconomic view adjustments (`EntropyPooler`) and Gaussian Mixture Model Markov regimes (`GMMRegimeGenerator`).
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
from pyalloq_viz import (
|
|
229
|
+
MacroRegimeTearSheet,
|
|
230
|
+
plot_entropy_pooling,
|
|
231
|
+
plot_regime_transitions,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
# 1. Prior vs. Posterior Density (Entropy Pooling)
|
|
235
|
+
# Left panel: Uniform prior 1/M vs. sorted posterior x* with KL-divergence & Effective Scenarios (ENS)
|
|
236
|
+
# Right panel: Prior vs. Posterior view-shifted return distribution
|
|
237
|
+
fig_ep = plot_entropy_pooling(
|
|
238
|
+
entropy_res,
|
|
239
|
+
scenario_data=scenarios,
|
|
240
|
+
asset_weights=bt_result.weights.iloc[-1],
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
# 2A. Historical Regime Transition Overlay
|
|
244
|
+
# Plots historical equity curve with background Bull/Bear regime shading + real-time p_k(t) stack
|
|
245
|
+
fig_reg_hist = plot_regime_transitions(
|
|
246
|
+
bt_result,
|
|
247
|
+
gmm_or_probs=gmm_gen,
|
|
248
|
+
market_data=market_data,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
# 2B. Synthetic Multiverse Regime Proportion Overlay
|
|
252
|
+
# Plots simulated equity fan cone + cross-sectional proportion of paths in each regime at step t
|
|
253
|
+
fig_reg_sim = plot_regime_transitions(
|
|
254
|
+
scenarios,
|
|
255
|
+
gmm_or_probs=gmm_gen,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# Combined Tear Sheet:
|
|
259
|
+
macro_ts = MacroRegimeTearSheet(
|
|
260
|
+
entropy_result=entropy_res,
|
|
261
|
+
equity_or_scenarios=bt_result,
|
|
262
|
+
gmm_or_probs=gmm_gen,
|
|
263
|
+
scenario_data=scenarios,
|
|
264
|
+
market_data=market_data,
|
|
265
|
+
)
|
|
266
|
+
macro_ts.to_html("macro_regime_report.html")
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
### 4. Allocation Mechanics & Risk Tear Sheet
|
|
272
|
+
|
|
273
|
+
Inspects how optimizers allocate capital and risk across assets, how weights drift between rebalances, and how asset correlations and seasonal returns behave.
|
|
274
|
+
|
|
275
|
+
```python
|
|
276
|
+
from pyalloq.classical.optimizers.risk_budgeting import RiskBudgetingAllocator
|
|
277
|
+
from pyalloq_viz import (
|
|
278
|
+
AllocationTearSheet,
|
|
279
|
+
plot_multi_universe_frontier,
|
|
280
|
+
plot_weight_drift_turnover,
|
|
281
|
+
plot_hierarchical_composition,
|
|
282
|
+
plot_risk_contributions,
|
|
283
|
+
plot_correlation_and_periodic_returns,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
cov_matrix = market_data.get_returns().cov() * 252.0
|
|
287
|
+
exp_returns = market_data.get_returns().mean() * 252.0
|
|
288
|
+
|
|
289
|
+
hrp_res = allocator.allocate(market_data, cov_matrix=cov_matrix)
|
|
290
|
+
rb_res = RiskBudgetingAllocator(tickers=assets).allocate(market_data, cov_matrix=cov_matrix)
|
|
291
|
+
|
|
292
|
+
# 1. Multi-Universe Efficient Frontier
|
|
293
|
+
# Renders Parametric Markowitz Frontier + Random Dirichlet Cloud + Optimal Allocations across synthetic paths
|
|
294
|
+
fig_ef = plot_multi_universe_frontier(
|
|
295
|
+
expected_returns=exp_returns,
|
|
296
|
+
cov_matrix=cov_matrix,
|
|
297
|
+
scenario_data=scenarios,
|
|
298
|
+
allocator_or_pipeline=allocator,
|
|
299
|
+
optimal_portfolios=[hrp_res, rb_res],
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# 2. Weight Drift & Rebalance Turnover Dynamics
|
|
303
|
+
# Reconstructs daily intra-period price drift (sawtooth pattern) and rebalance snap-backs + turnover bars
|
|
304
|
+
fig_drift = plot_weight_drift_turnover(bt_result, market_data=market_data)
|
|
305
|
+
|
|
306
|
+
# 3. Hierarchical Composition Treemap & Target vs. Current Comparison
|
|
307
|
+
# Resolves hierarchy from MarketData.cross_sectional, HRP/HERC/NCO clusters, or explicit dict
|
|
308
|
+
fig_tree = plot_hierarchical_composition(
|
|
309
|
+
hrp_res,
|
|
310
|
+
target_or_benchmark_weights=rb_res,
|
|
311
|
+
market_data=market_data,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
# 4. Capital Weights vs. Component Risk Contributions (PCRC) vs. Target Risk Budgets
|
|
315
|
+
fig_rc = plot_risk_contributions(rb_res, cov_matrix=cov_matrix)
|
|
316
|
+
|
|
317
|
+
# 5. Quasi-Diagonalized Asset Correlation Heatmap + Monthly Periodic Return Heatmap (Jan-Dec x Year)
|
|
318
|
+
fig_corr = plot_correlation_and_periodic_returns(
|
|
319
|
+
market_data,
|
|
320
|
+
portfolio_returns=bt_result,
|
|
321
|
+
cluster_order=True,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
# Combined Tear Sheet:
|
|
325
|
+
alloc_ts = AllocationTearSheet(
|
|
326
|
+
optimization_result=hrp_res,
|
|
327
|
+
backtest_result=bt_result,
|
|
328
|
+
market_data=market_data,
|
|
329
|
+
cov_matrix=cov_matrix,
|
|
330
|
+
expected_returns=exp_returns,
|
|
331
|
+
scenario_data=scenarios,
|
|
332
|
+
allocator_or_pipeline=allocator,
|
|
333
|
+
target_weights=rb_res,
|
|
334
|
+
)
|
|
335
|
+
alloc_ts.to_html("allocation_report.html")
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
---
|
|
339
|
+
|
|
340
|
+
## Themes & Styling (`alloq_dark` & `alloq_light`)
|
|
341
|
+
|
|
342
|
+
Every plotting function and TearSheet method accepts `theme="alloq_dark"` (default) or `theme="alloq_light"`:
|
|
343
|
+
|
|
344
|
+
```python
|
|
345
|
+
# Render light-mode publication chart
|
|
346
|
+
fig = plot_fan_chart(scenarios, theme="alloq_light")
|
|
347
|
+
|
|
348
|
+
# Export light-mode HTML dashboard
|
|
349
|
+
sim_ts.to_html("light_report.html", theme="alloq_light")
|
|
350
|
+
```
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
# `pyalloq-viz` — Visualization & Tear Sheet Suite for PyAlloq
|
|
2
|
+
|
|
3
|
+
`pyalloq-viz` provides interactive Plotly visualizations, publication-ready charts, and self-contained HTML Tear Sheet dashboards for portfolio optimization, walk-forward backtesting, Monte Carlo simulations, and macroeconomic regime analysis.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Overview & Design Philosophy
|
|
8
|
+
|
|
9
|
+
`pyalloq-viz` supports **two complementary ways** to visualize your quantitative workflows:
|
|
10
|
+
|
|
11
|
+
1. **Modular Plot Functions (`plot_*`)**:
|
|
12
|
+
Every visualization is available as a standalone function that returns a styled `plotly.graph_objects.Figure` (supporting both `"alloq_dark"` and `"alloq_light"` institutional themes).
|
|
13
|
+
2. **Unified Tear Sheet Classes (`*TearSheet`)**:
|
|
14
|
+
Four specialized tear sheet builders combine related charts and summary KPIs into either:
|
|
15
|
+
- A multi-subplot interactive figure via `.to_figure()` / `.show()`
|
|
16
|
+
- A self-contained, responsive HTML dashboard via `.to_html("report.html")`
|
|
17
|
+
- A high-DPI static image via `.save_image("report.png")`
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Quickstart: End-to-End Workflow
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
|
|
27
|
+
from pyalloq_core.data import MarketData
|
|
28
|
+
from pyalloq_core.pipeline import StrategyPipeline
|
|
29
|
+
from pyalloq_backtest.engine import WalkForwardEngine
|
|
30
|
+
from pyalloq_backtest.splitters import RollingWindowSplitter
|
|
31
|
+
from pyalloq.classical.estimators.covariance.empirical import EmpiricalCovariance
|
|
32
|
+
from pyalloq.ml.optimizers.hrp import HRPAllocator
|
|
33
|
+
from pyalloq_simulation import (
|
|
34
|
+
GMMRegimeGenerator,
|
|
35
|
+
ViewBuilder,
|
|
36
|
+
AbsoluteView,
|
|
37
|
+
EntropyPooler,
|
|
38
|
+
)
|
|
39
|
+
import pyalloq_viz as viz
|
|
40
|
+
|
|
41
|
+
# 1. Prepare MarketData (with optional sector/hierarchy metadata)
|
|
42
|
+
dates = pd.bdate_range("2022-01-03", periods=500)
|
|
43
|
+
assets = ["AAPL", "MSFT", "TLT", "GLD"]
|
|
44
|
+
prices = pd.DataFrame(
|
|
45
|
+
100.0 * np.cumprod(1.0 + np.random.normal(0.0005, 0.012, (500, 4)), axis=0),
|
|
46
|
+
index=dates,
|
|
47
|
+
columns=assets,
|
|
48
|
+
)
|
|
49
|
+
cross_sectional = pd.DataFrame(
|
|
50
|
+
{"sector": ["Equities - Tech", "Equities - Tech", "Fixed Income", "Commodities"]},
|
|
51
|
+
index=assets,
|
|
52
|
+
)
|
|
53
|
+
market_data = MarketData(prices=prices, cross_sectional=cross_sectional, risk_free_rate=0.02)
|
|
54
|
+
|
|
55
|
+
# 2. Run Walk-Forward Historical Backtest
|
|
56
|
+
cov_est = EmpiricalCovariance()
|
|
57
|
+
allocator = HRPAllocator(tickers=assets)
|
|
58
|
+
pipeline = StrategyPipeline(allocator=allocator, cov_estimator=cov_est)
|
|
59
|
+
bt_engine = WalkForwardEngine(
|
|
60
|
+
pipeline=pipeline,
|
|
61
|
+
splitter=RollingWindowSplitter(lookback_window=126),
|
|
62
|
+
rebalance_freq="ME",
|
|
63
|
+
)
|
|
64
|
+
bt_result = bt_engine.run(market_data)
|
|
65
|
+
|
|
66
|
+
# 3. Fit GMM Regime Generator, Simulate Synthetic Futures & Apply Entropy Pooling Views
|
|
67
|
+
gmm_gen = GMMRegimeGenerator(n_regimes=2, random_state=42)
|
|
68
|
+
gmm_gen.fit(market_data)
|
|
69
|
+
scenarios = gmm_gen.generate(n_paths=500, horizon=63)
|
|
70
|
+
|
|
71
|
+
builder = ViewBuilder(scenarios)
|
|
72
|
+
A_ineq, b_ineq, C_eq, d_eq = builder.build([
|
|
73
|
+
AbsoluteView(asset="AAPL", operator=">=", target=0.02)
|
|
74
|
+
])
|
|
75
|
+
entropy_res = EntropyPooler(n_scenarios=scenarios.n_paths).fit(
|
|
76
|
+
A_ineq=A_ineq, b_ineq=b_ineq, C_eq=C_eq, d_eq=d_eq
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# 4. Generate Interactive HTML Tear Sheets!
|
|
80
|
+
viz.SimulationTearSheet(
|
|
81
|
+
scenarios,
|
|
82
|
+
entropy_result=entropy_res,
|
|
83
|
+
ruin_threshold=-0.15,
|
|
84
|
+
benchmark=bt_result,
|
|
85
|
+
).to_html("simulation_tearsheet.html")
|
|
86
|
+
|
|
87
|
+
viz.RobustnessTearSheet(bt_result).to_html("robustness_tearsheet.html")
|
|
88
|
+
|
|
89
|
+
viz.MacroRegimeTearSheet(
|
|
90
|
+
entropy_result=entropy_res,
|
|
91
|
+
equity_or_scenarios=bt_result,
|
|
92
|
+
gmm_or_probs=gmm_gen,
|
|
93
|
+
scenario_data=scenarios,
|
|
94
|
+
market_data=market_data,
|
|
95
|
+
).to_html("macro_regime_tearsheet.html")
|
|
96
|
+
|
|
97
|
+
viz.AllocationTearSheet(
|
|
98
|
+
backtest_result=bt_result,
|
|
99
|
+
market_data=market_data,
|
|
100
|
+
scenario_data=scenarios,
|
|
101
|
+
allocator_or_pipeline=allocator,
|
|
102
|
+
).to_html("allocation_tearsheet.html")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## Detailed Guide by Tear Sheet
|
|
108
|
+
|
|
109
|
+
### 1. The Multiverse & Simulation Tear Sheet
|
|
110
|
+
|
|
111
|
+
Visualizes synthetic price/return paths (`ScenarioMarketData` or `MonteCarloResult`), optionally weighted by posterior probabilities from `EntropyResult`.
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from pyalloq_viz import (
|
|
115
|
+
SimulationTearSheet,
|
|
116
|
+
plot_fan_chart,
|
|
117
|
+
plot_terminal_wealth_ruin,
|
|
118
|
+
plot_cvar_tail_risk,
|
|
119
|
+
plot_drawdown_fan_chart,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
# Individual plots:
|
|
123
|
+
fig_fan = plot_fan_chart(
|
|
124
|
+
scenarios,
|
|
125
|
+
asset_weights=bt_result.weights.iloc[-1],
|
|
126
|
+
entropy_result=entropy_res, # Optional: weights quantiles by posterior x*
|
|
127
|
+
percentiles=((5, 95), (10, 90), (25, 75)),
|
|
128
|
+
benchmark=bt_result, # Optional: overlay realized equity curve
|
|
129
|
+
theme="alloq_dark",
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
fig_ruin = plot_terminal_wealth_ruin(
|
|
133
|
+
scenarios,
|
|
134
|
+
entropy_result=entropy_res,
|
|
135
|
+
ruin_threshold=-0.20, # Highlights wealth dropping below 0.80 (-20%)
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
fig_cvar = plot_cvar_tail_risk(
|
|
139
|
+
scenarios, # Accepts ScenarioMarketData, MonteCarloResult, or BacktestResult
|
|
140
|
+
entropy_result=entropy_res,
|
|
141
|
+
alpha=0.05, # 95% VaR and CVaR (Expected Shortfall) left-tail shading
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
fig_dd = plot_drawdown_fan_chart(
|
|
145
|
+
scenarios,
|
|
146
|
+
entropy_result=entropy_res, # Underwater drawdown probability cones across all paths
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Combined Tear Sheet:
|
|
150
|
+
sim_ts = SimulationTearSheet(
|
|
151
|
+
scenarios,
|
|
152
|
+
asset_weights=bt_result.weights.iloc[-1],
|
|
153
|
+
entropy_result=entropy_res,
|
|
154
|
+
ruin_threshold=-0.20,
|
|
155
|
+
cvar_alpha=0.05,
|
|
156
|
+
benchmark=bt_result,
|
|
157
|
+
)
|
|
158
|
+
sim_ts.show() # Display 2x2 multi-subplot figure in Jupyter/IDE
|
|
159
|
+
sim_ts.to_html("multiverse_report.html") # Standalone HTML report with KPI summary cards
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
### 2. Robustness & Overfitting Tear Sheet
|
|
165
|
+
|
|
166
|
+
Integrates directly with `PBOEvaluator` and `CPCVSplitter` in `pyalloq_backtest` to test whether a strategy is genuinely robust or historically overfit.
|
|
167
|
+
|
|
168
|
+
#### Mode A: Single-Strategy Combinatorial Scrambling (CPCV) & Benchmark PBO
|
|
169
|
+
Recombines historical return blocks into scrambled chronological sequences of market regimes to test path-dependent survival:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from pyalloq_backtest import CPCVSplitter, PBOEvaluator
|
|
173
|
+
from pyalloq_viz import RobustnessTearSheet, plot_pbo_distribution, plot_cpcv_paths
|
|
174
|
+
|
|
175
|
+
# Scramble historical returns across 6 regime blocks
|
|
176
|
+
splitter = CPCVSplitter(n_groups=6, k_test_groups=2, max_paths=120)
|
|
177
|
+
cpcv_res = splitter.scramble_timelines(bt_result)
|
|
178
|
+
|
|
179
|
+
# Plot scrambled equity paths & Sharpe vs. Max Drawdown scatter
|
|
180
|
+
fig_cpcv = plot_cpcv_paths(cpcv_res)
|
|
181
|
+
|
|
182
|
+
# Compare historical Sharpe against the scrambled/synthetic Sharpe distribution
|
|
183
|
+
fig_pbo = plot_pbo_distribution(bt_result, synthetic_comparison=cpcv_res)
|
|
184
|
+
|
|
185
|
+
# Or generate the full Robustness Tear Sheet in one line:
|
|
186
|
+
rob_ts = RobustnessTearSheet(bt_result, cpcv_or_synthetic=cpcv_res)
|
|
187
|
+
rob_ts.to_html("robustness_report.html")
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### Mode B: Multi-Strategy Combinatorial Symmetric Cross-Validation (CSCV)
|
|
191
|
+
Implements Bailey & Lopez de Prado's exact CSCV algorithm across a $(T \times M)$ matrix of $M$ candidate strategy configurations (or a list of `BacktestResult` objects):
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
# trial_returns_df has shape (T_days, M_strategies)
|
|
195
|
+
pbo_eval = PBOEvaluator(n_partitions=8)
|
|
196
|
+
pbo_result = pbo_eval.evaluate_cscv(trial_returns_df)
|
|
197
|
+
|
|
198
|
+
# Plots Rank Logit (lambda) distribution (shaded for lambda <= 0) + IS vs. OOS Sharpe degradation
|
|
199
|
+
fig_cscv = plot_pbo_distribution(pbo_result)
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
### 3. Macro Regime & Entropy Tear Sheet
|
|
205
|
+
|
|
206
|
+
Visualizes subjective macroeconomic view adjustments (`EntropyPooler`) and Gaussian Mixture Model Markov regimes (`GMMRegimeGenerator`).
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
from pyalloq_viz import (
|
|
210
|
+
MacroRegimeTearSheet,
|
|
211
|
+
plot_entropy_pooling,
|
|
212
|
+
plot_regime_transitions,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
# 1. Prior vs. Posterior Density (Entropy Pooling)
|
|
216
|
+
# Left panel: Uniform prior 1/M vs. sorted posterior x* with KL-divergence & Effective Scenarios (ENS)
|
|
217
|
+
# Right panel: Prior vs. Posterior view-shifted return distribution
|
|
218
|
+
fig_ep = plot_entropy_pooling(
|
|
219
|
+
entropy_res,
|
|
220
|
+
scenario_data=scenarios,
|
|
221
|
+
asset_weights=bt_result.weights.iloc[-1],
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# 2A. Historical Regime Transition Overlay
|
|
225
|
+
# Plots historical equity curve with background Bull/Bear regime shading + real-time p_k(t) stack
|
|
226
|
+
fig_reg_hist = plot_regime_transitions(
|
|
227
|
+
bt_result,
|
|
228
|
+
gmm_or_probs=gmm_gen,
|
|
229
|
+
market_data=market_data,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
# 2B. Synthetic Multiverse Regime Proportion Overlay
|
|
233
|
+
# Plots simulated equity fan cone + cross-sectional proportion of paths in each regime at step t
|
|
234
|
+
fig_reg_sim = plot_regime_transitions(
|
|
235
|
+
scenarios,
|
|
236
|
+
gmm_or_probs=gmm_gen,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# Combined Tear Sheet:
|
|
240
|
+
macro_ts = MacroRegimeTearSheet(
|
|
241
|
+
entropy_result=entropy_res,
|
|
242
|
+
equity_or_scenarios=bt_result,
|
|
243
|
+
gmm_or_probs=gmm_gen,
|
|
244
|
+
scenario_data=scenarios,
|
|
245
|
+
market_data=market_data,
|
|
246
|
+
)
|
|
247
|
+
macro_ts.to_html("macro_regime_report.html")
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
### 4. Allocation Mechanics & Risk Tear Sheet
|
|
253
|
+
|
|
254
|
+
Inspects how optimizers allocate capital and risk across assets, how weights drift between rebalances, and how asset correlations and seasonal returns behave.
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
from pyalloq.classical.optimizers.risk_budgeting import RiskBudgetingAllocator
|
|
258
|
+
from pyalloq_viz import (
|
|
259
|
+
AllocationTearSheet,
|
|
260
|
+
plot_multi_universe_frontier,
|
|
261
|
+
plot_weight_drift_turnover,
|
|
262
|
+
plot_hierarchical_composition,
|
|
263
|
+
plot_risk_contributions,
|
|
264
|
+
plot_correlation_and_periodic_returns,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
cov_matrix = market_data.get_returns().cov() * 252.0
|
|
268
|
+
exp_returns = market_data.get_returns().mean() * 252.0
|
|
269
|
+
|
|
270
|
+
hrp_res = allocator.allocate(market_data, cov_matrix=cov_matrix)
|
|
271
|
+
rb_res = RiskBudgetingAllocator(tickers=assets).allocate(market_data, cov_matrix=cov_matrix)
|
|
272
|
+
|
|
273
|
+
# 1. Multi-Universe Efficient Frontier
|
|
274
|
+
# Renders Parametric Markowitz Frontier + Random Dirichlet Cloud + Optimal Allocations across synthetic paths
|
|
275
|
+
fig_ef = plot_multi_universe_frontier(
|
|
276
|
+
expected_returns=exp_returns,
|
|
277
|
+
cov_matrix=cov_matrix,
|
|
278
|
+
scenario_data=scenarios,
|
|
279
|
+
allocator_or_pipeline=allocator,
|
|
280
|
+
optimal_portfolios=[hrp_res, rb_res],
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
# 2. Weight Drift & Rebalance Turnover Dynamics
|
|
284
|
+
# Reconstructs daily intra-period price drift (sawtooth pattern) and rebalance snap-backs + turnover bars
|
|
285
|
+
fig_drift = plot_weight_drift_turnover(bt_result, market_data=market_data)
|
|
286
|
+
|
|
287
|
+
# 3. Hierarchical Composition Treemap & Target vs. Current Comparison
|
|
288
|
+
# Resolves hierarchy from MarketData.cross_sectional, HRP/HERC/NCO clusters, or explicit dict
|
|
289
|
+
fig_tree = plot_hierarchical_composition(
|
|
290
|
+
hrp_res,
|
|
291
|
+
target_or_benchmark_weights=rb_res,
|
|
292
|
+
market_data=market_data,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
# 4. Capital Weights vs. Component Risk Contributions (PCRC) vs. Target Risk Budgets
|
|
296
|
+
fig_rc = plot_risk_contributions(rb_res, cov_matrix=cov_matrix)
|
|
297
|
+
|
|
298
|
+
# 5. Quasi-Diagonalized Asset Correlation Heatmap + Monthly Periodic Return Heatmap (Jan-Dec x Year)
|
|
299
|
+
fig_corr = plot_correlation_and_periodic_returns(
|
|
300
|
+
market_data,
|
|
301
|
+
portfolio_returns=bt_result,
|
|
302
|
+
cluster_order=True,
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# Combined Tear Sheet:
|
|
306
|
+
alloc_ts = AllocationTearSheet(
|
|
307
|
+
optimization_result=hrp_res,
|
|
308
|
+
backtest_result=bt_result,
|
|
309
|
+
market_data=market_data,
|
|
310
|
+
cov_matrix=cov_matrix,
|
|
311
|
+
expected_returns=exp_returns,
|
|
312
|
+
scenario_data=scenarios,
|
|
313
|
+
allocator_or_pipeline=allocator,
|
|
314
|
+
target_weights=rb_res,
|
|
315
|
+
)
|
|
316
|
+
alloc_ts.to_html("allocation_report.html")
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
## Themes & Styling (`alloq_dark` & `alloq_light`)
|
|
322
|
+
|
|
323
|
+
Every plotting function and TearSheet method accepts `theme="alloq_dark"` (default) or `theme="alloq_light"`:
|
|
324
|
+
|
|
325
|
+
```python
|
|
326
|
+
# Render light-mode publication chart
|
|
327
|
+
fig = plot_fan_chart(scenarios, theme="alloq_light")
|
|
328
|
+
|
|
329
|
+
# Export light-mode HTML dashboard
|
|
330
|
+
sim_ts.to_html("light_report.html", theme="alloq_light")
|
|
331
|
+
```
|