ergodic_insurance.visualization package
Submodules
ergodic_insurance.visualization.annotations module
Annotation and labeling utilities for visualizations.
This module provides utilities for adding professional annotations, labels, and callouts to plots with smart placement and leader line routing.
- add_value_labels(ax: Axes, bars, format_func=None, fontsize: int = 9, va: str = 'bottom', ha: str = 'center', offset: float = 0.01, color: str | None = None, bold: bool = False) None[source]
Add value labels to bar chart.
Adds formatted value labels on top of or inside bars in a bar chart.
- Parameters:
ax (
Axes) – Matplotlib axesbars – Bar container from ax.bar()
format_func – Optional function to format values
fontsize (
int) – Font size for labelsva (
str) – Vertical alignment (‘bottom’, ‘center’, ‘top’)ha (
str) – Horizontal alignment (‘left’, ‘center’, ‘right’)offset (
float) – Vertical offset as fraction of y-rangebold (
bool) – Whether to make text bold
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> bars = ax.bar(range(5), [10, 20, 15, 25, 30]) >>> add_value_labels(ax, bars)
- add_trend_annotation(ax: Axes, x_pos: float, y_pos: float, trend: float, period: str = 'YoY', fontsize: int = 10) None[source]
Add trend annotation with arrow.
Adds a trend annotation showing percentage change with an up/down arrow.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> add_trend_annotation(ax, 0.8, 0.9, 0.15, "YoY")
- add_callout(ax: Axes, text: str, xy: Tuple[float, float], xytext: Tuple[float, float], fontsize: int = 9, color: str | None = None, arrow_color: str | None = None, bbox_props: dict | None = None) None[source]
Add a callout annotation with arrow.
Creates a professional callout annotation with customizable styling.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> add_callout(ax, "Peak value", xy=(2, 4), xytext=(2.5, 4.5))
- add_benchmark_line(ax: Axes, value: float, label: str, color: str | None = None, linestyle: str = '--', linewidth: float = 1.5, fontsize: int = 9, position: str = 'right') None[source]
Add a horizontal benchmark line with label.
Draws a horizontal reference line with an integrated label.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot(range(10), np.random.randn(10)) >>> add_benchmark_line(ax, 0, "Average", color="red")
- add_shaded_region(ax: Axes, x_start: float, x_end: float, label: str | None = None, color: str | None = None, alpha: float = 0.2) None[source]
Add a shaded vertical region.
Creates a shaded vertical band to highlight a specific time period or range.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot(range(10), np.random.randn(10)) >>> add_shaded_region(ax, 3, 6, label="Recession", color="gray")
- add_data_source(fig, source: str, x: float = 0.99, y: float = 0.01, fontsize: int = 8, color: str | None = None) None[source]
Add data source attribution.
Adds a data source note to the figure, typically at the bottom right.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> add_data_source(fig, "Source: Internal Analysis")
- add_footnote(fig, text: str, x: float = 0.5, y: float = 0.02, fontsize: int = 8, color: str | None = None) None[source]
Add footnote to figure.
Adds a footnote or explanatory text to the bottom of the figure.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> add_footnote(fig, "* Preliminary data subject to revision")
- class AnnotationBox(text: str, position: Tuple[float, float], width: float = 0.15, height: float = 0.08, priority: int = 50) None[source]
Bases:
objectContainer for annotation box properties.
- text
Annotation text
- position
(x, y) position in data coordinates
- width
Box width in axes fraction
- height
Box height in axes fraction
- priority
Priority for placement (higher = more important)
- overlaps(other: AnnotationBox, margin: float = 0.01) bool[source]
Check if this box overlaps with another.
- Parameters:
other (
AnnotationBox) – Another annotation boxmargin (
float) – Additional margin to consider
- Return type:
- Returns:
True if boxes overlap
- class SmartAnnotationPlacer(ax: Axes)[source]
Bases:
objectSmart placement system for annotations without overlaps.
- placed_annotations: List[AnnotationBox]
- find_best_position(target_point: Tuple[float, float], text: str, priority: int = 50, preferred_quadrant: str | None = None) Tuple[float, float][source]
Find best position for annotation near target point.
- Parameters:
- Return type:
- Returns:
Best position in axes fraction coordinates
- add_smart_callout(text: str, target_point: Tuple[float, float], fontsize: int = 9, priority: int = 50, preferred_quadrant: str | None = None, color: str | None = None, arrow_color: str | None = None) None[source]
Add callout with smart placement.
- add_smart_annotations(annotations: List[Dict[str, Any]], fontsize: int = 9) None[source]
Add multiple annotations with smart placement.
- Parameters:
- Return type:
Examples
>>> placer = SmartAnnotationPlacer(ax) >>> annotations = [ ... {'text': 'Peak', 'point': (2, 4), 'priority': 80, 'color': 'green'}, ... {'text': 'Valley', 'point': (5, 1), 'priority': 60, 'color': 'red'} ... ] >>> placer.add_smart_annotations(annotations)
- create_leader_line(ax: Axes, start: Tuple[float, float], end: Tuple[float, float], style: str = 'curved', color: str | None = None, linewidth: float = 1.0, alpha: float = 0.7) None[source]
Create a leader line with intelligent routing.
- auto_annotate_peaks_valleys(ax: Axes, x_data: ndarray, y_data: ndarray, n_peaks: int = 3, n_valleys: int = 2, peak_color: str | None = None, valley_color: str | None = None, fontsize: int = 9, placer: SmartAnnotationPlacer | None = None) SmartAnnotationPlacer[source]
Automatically annotate peaks and valleys in data.
- Parameters:
ax (
Axes) – Matplotlib axesx_data (
ndarray) – X coordinatesy_data (
ndarray) – Y coordinatesn_peaks (
int) – Number of peaks to annotaten_valleys (
int) – Number of valleys to annotatefontsize (
int) – Font sizeplacer (
Optional[SmartAnnotationPlacer]) – Existing SmartAnnotationPlacer to use (creates new if None)
- Return type:
- Returns:
The SmartAnnotationPlacer instance used
ergodic_insurance.visualization.batch_plots module
Batch processing and scenario comparison visualizations.
This module provides visualization functions for batch simulation results, scenario comparisons, and sensitivity analyses.
- plot_scenario_comparison(aggregated_results: Any, metrics: List[str] | None = None, figsize: Tuple[float, float] = (14, 8), save_path: str | None = None) Figure[source]
Create comprehensive scenario comparison visualization.
Compares multiple scenarios across different metrics with bar charts highlighting the best performer for each metric.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with scenario comparisons
Examples
>>> from ergodic_insurance.batch_processor import AggregatedResults >>> results = AggregatedResults(batch_results) >>> fig = plot_scenario_comparison(results, metrics=["mean_growth_rate"])
- plot_sensitivity_heatmap(aggregated_results: Any, metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (10, 8), save_path: str | None = None) Figure[source]
Create sensitivity analysis heatmap.
Visualizes sensitivity of outcomes to parameter changes using a horizontal bar chart color-coded by impact direction.
- plot_parameter_sweep_3d(aggregated_results: Any, param1: str, param2: str, metric: str = 'mean_growth_rate', height: int = 600, save_path: str | None = None) Figure[source]
Create 3D surface plot for parameter sweep results.
Visualizes how a metric varies across two parameter dimensions using an interactive 3D scatter plot.
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with 3D parameter sweep
- plot_scenario_convergence(batch_results: List[Any], metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (12, 6), save_path: str | None = None) Figure[source]
Plot convergence of metric across scenarios.
Shows how a metric converges as more scenarios are processed, with execution time distribution.
- plot_parallel_scenarios(batch_results: List[Any], metrics: List[str], figsize: Tuple[float, float] = (12, 8), normalize: bool = True) Figure[source]
Create parallel coordinates plot for scenario comparison.
Visualizes multiple scenarios across multiple metrics using parallel coordinates for comprehensive comparison.
ergodic_insurance.visualization.core module
Core visualization utilities and constants.
This module provides the foundational elements for visualization including WSJ-style color palettes, formatters, and base configuration settings.
- set_wsj_style()[source]
Set matplotlib to use WSJ-style formatting.
This function applies Wall Street Journal aesthetic styling to matplotlib plots including font choices, spine visibility, grid settings, and colors.
- format_currency(value: float, decimals: int = 0, abbreviate: bool = False) str[source]
Format value as currency.
- Parameters:
- Return type:
- Returns:
Formatted string (e.g., “$1,000” or “$1K” if abbreviate=True)
Examples
>>> format_currency(1000) '$1,000' >>> format_currency(1500000, abbreviate=True) '$1.5M' >>> format_currency(2500.50, decimals=2) '$2,500.50'
- format_percentage(value: float, decimals: int = 1) str[source]
Format value as percentage.
- Parameters:
- Return type:
- Returns:
Formatted string (e.g., “5.0%”)
Examples
>>> format_percentage(0.05) '5.0%' >>> format_percentage(0.1234, decimals=2) '12.34%'
- class WSJFormatter[source]
Bases:
objectFormatter for WSJ-style axis labels.
This class provides static methods for formatting axis values in various styles consistent with Wall Street Journal publication standards.
- static currency_formatter(x, pos)[source]
Format axis values as currency.
- Parameters:
x – The value to format
pos – The position (unused but required by matplotlib)
- Returns:
Formatted currency string
- static currency(x: float, decimals: int = 1) str[source]
Format value as currency (shortened method name).
- static percentage_formatter(x, pos)[source]
Format axis values as percentage.
- Parameters:
x – The value to format
pos – The position (unused but required by matplotlib)
- Returns:
Formatted percentage string
- static percentage(x: float, decimals: int = 1) str[source]
Format value as percentage (shortened method name).
ergodic_insurance.visualization.executive_plots module
Executive-level visualization functions.
This module provides high-level visualization functions for executive reporting including loss distributions, return period curves, and insurance layer diagrams.
- plot_loss_distribution(losses: ndarray | DataFrame, title: str = 'Loss Distribution', bins: int = 50, show_metrics: bool = True, var_levels: List[float] | None = None, figsize: Tuple[int, int] = (12, 6), show_stats: bool = False, log_scale: bool = False, use_factory: bool = False, theme: Any | None = None) Figure[source]
Create WSJ-style loss distribution plot.
Creates a two-panel visualization showing loss distribution histogram and Q-Q plot for normality assessment.
- Parameters:
losses (
Union[ndarray,DataFrame]) – Array of loss values or DataFrame with ‘amount’ columntitle (
str) – Plot titlebins (
int) – Number of histogram binsshow_metrics (
bool) – Whether to show VaR/TVaR linesvar_levels (
Optional[List[float]]) – VaR confidence levels to show (default: [0.95, 0.99])show_stats (
bool) – Whether to show statisticslog_scale (
bool) – Whether to use log scaleuse_factory (
bool) – Whether to use new visualization factory if available
- Return type:
- Returns:
Matplotlib figure with distribution plots
Examples
>>> losses = np.random.lognormal(10, 2, 1000) >>> fig = plot_loss_distribution(losses, title="Annual Loss Distribution")
- plot_return_period_curve(losses: ndarray | DataFrame, return_periods: ndarray | None = None, scenarios: Dict[str, ndarray] | None = None, title: str = 'Return Period Curves', figsize: Tuple[int, int] = (10, 6), confidence_level: float = 0.95, show_grid: bool = True) Figure[source]
Create WSJ-style return period curve.
Visualizes the relationship between return periods and loss magnitudes, commonly used in catastrophe modeling and risk assessment.
- Parameters:
losses (
Union[ndarray,DataFrame]) – Loss amounts (array or DataFrame)return_periods (
Optional[ndarray]) – Array of return periods (years), optionalscenarios (
Optional[Dict[str,ndarray]]) – Optional dict of scenario names to loss arraystitle (
str) – Plot titleconfidence_level (
float) – Confidence level for bandsshow_grid (
bool) – Whether to show grid
- Return type:
- Returns:
Matplotlib figure with return period curve
Examples
>>> losses = np.random.lognormal(10, 2, 1000) >>> fig = plot_return_period_curve(losses)
- plot_insurance_layers(layers: List[Dict[str, float]] | DataFrame, total_limit: float | None = None, title: str = 'Insurance Program Structure', figsize: Tuple[int, int] = (10, 6), losses: ndarray | DataFrame | None = None, loss_data: ndarray | DataFrame | None = None, show_expected_loss: bool = False) Figure[source]
Create WSJ-style insurance layer visualization.
Visualizes insurance program structure with layer attachments, limits, and premium distribution in a two-panel display.
- Parameters:
layers (
Union[List[Dict[str,float]],DataFrame]) – List of layer dictionaries or DataFrame with ‘attachment’, ‘limit’ columnstotal_limit (
Optional[float]) – Total program limit (calculated from layers if not provided)title (
str) – Plot titlelosses (
Union[ndarray,DataFrame,None]) – Optional loss data for overlayloss_data (
Union[ndarray,DataFrame,None]) – Alias for losses parametershow_expected_loss (
bool) – Whether to show expected loss line
- Return type:
- Returns:
Matplotlib figure with layer structure and premium distribution
Examples
>>> layers = [ ... {"attachment": 0, "limit": 5e6, "premium": 0.015}, ... {"attachment": 5e6, "limit": 10e6, "premium": 0.008}, ... ] >>> fig = plot_insurance_layers(layers)
- plot_roe_ruin_frontier(results: Dict[float, DataFrame] | DataFrame, company_sizes: List[float] | None = None, title: str = 'ROE-Ruin Efficient Frontier', figsize: Tuple[int, int] = (12, 8), highlight_sweet_spots: bool = True, show_optimal_zones: bool = True, export_dpi: int | None = None, log_scale_y: bool = True, grid: bool = True, annotations: bool = True, color_scheme: List[str] | None = None) Figure[source]
Create ROE-Ruin efficient frontier visualization.
Visualizes the Pareto frontier showing trade-offs between Return on Equity (ROE) and Ruin Probability for different company sizes. This helps executives understand optimal insurance purchasing decisions.
- Parameters:
results (
Union[Dict[float,DataFrame],DataFrame]) – Either a dict of company_size (float) -> optimization results DataFrame, or a single DataFrame with ‘company_size’ columncompany_sizes (
Optional[List[float]]) – List of company sizes to plot (e.g., [1e6, 1e7, 1e8]) If None, will use all available sizes in resultstitle (
str) – Plot titlehighlight_sweet_spots (
bool) – Whether to highlight knee points on curvesshow_optimal_zones (
bool) – Whether to show shaded optimal zonesexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print, None for screen)log_scale_y (
bool) – Whether to use log scale for ruin probability axisgrid (
bool) – Whether to show grid linesannotations (
bool) – Whether to show annotations for key pointscolor_scheme (
Optional[List[str]]) – List of colors for different company sizes
- Return type:
- Returns:
Matplotlib figure with ROE-Ruin efficient frontier plots
- Raises:
ValueError – If results format is invalid or no data available
Examples
>>> # With dictionary of results >>> results = { ... 1e6: pd.DataFrame({'roe': [0.1, 0.15, 0.2], ... 'ruin_prob': [0.05, 0.02, 0.01]}), ... 1e7: pd.DataFrame({'roe': [0.08, 0.12, 0.18], ... 'ruin_prob': [0.03, 0.015, 0.008]}) ... } >>> fig = plot_roe_ruin_frontier(results)
>>> # With single DataFrame >>> df = pd.DataFrame({ ... 'company_size': [1e6, 1e6, 1e7, 1e7], ... 'roe': [0.1, 0.15, 0.08, 0.12], ... 'ruin_prob': [0.05, 0.02, 0.03, 0.015] ... }) >>> fig = plot_roe_ruin_frontier(df)
- plot_ruin_cliff(retention_range: Tuple[float, float] | None = None, n_points: int = 50, company_size: float = 10000000, simulation_data: Dict[str, Any] | None = None, title: str = 'The Ruin Cliff: Retention vs Failure Risk', figsize: Tuple[int, int] = (14, 8), show_inset: bool = True, show_warnings: bool = True, show_3d_effect: bool = True, export_dpi: int | None = None) Figure[source]
Create dramatic ruin cliff visualization with 3D effects.
Visualizes the relationship between insurance retention (deductible) levels and ruin probability, highlighting the “cliff edge” where risk dramatically increases. Features 3D-style gradient effects and warning zones.
- Parameters:
retention_range (
Optional[Tuple[float,float]]) – Tuple of (min, max) retention values in dollars. Default: (10_000, 10_000_000)n_points (
int) – Number of points to calculate along retention axiscompany_size (
float) – Company asset size for scaling retention levelssimulation_data (
Optional[Dict[str,Any]]) – Optional pre-computed simulation results with keys: ‘retentions’, ‘ruin_probs’, ‘confidence_intervals’title (
str) – Plot titleshow_inset (
bool) – Whether to show zoomed inset of critical regionshow_warnings (
bool) – Whether to show warning callouts and annotationsshow_3d_effect (
bool) – Whether to add 3D gradient background effectsexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with ruin cliff visualization
Examples
>>> # Basic usage with synthetic data >>> fig = plot_ruin_cliff()
>>> # With custom retention range >>> fig = plot_ruin_cliff(retention_range=(5000, 5_000_000))
>>> # With pre-computed simulation data >>> data = { ... 'retentions': np.logspace(4, 7, 50), ... 'ruin_probs': np.array([...]), ... } >>> fig = plot_ruin_cliff(simulation_data=data)
Notes
The visualization uses a log scale for retention values to show the full range from small to large deductibles. The cliff edge is detected using derivative analysis to find the steepest point of increase in ruin probability.
- plot_simulation_architecture(title: str = 'Simulation Architecture Flow', figsize: Tuple[int, int] = (14, 8), export_dpi: int | None = None, show_icons: bool = True) Figure[source]
Create simulation architecture flow diagram.
Visualizes the data flow from parameters through simulation to insights using a clean flowchart style with boxes and arrows.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with architecture diagram
Examples
>>> fig = plot_simulation_architecture() >>> fig.savefig("architecture.png", dpi=150)
- plot_sample_paths(simulation_data: Dict[str, Any] | None = None, n_paths: int = 5, short_horizon: int = 10, long_horizon: int = 100, company_size: float = 10000000, title: str = 'Sample Path Visualization', figsize: Tuple[int, int] = (14, 8), show_failures: bool = True, export_dpi: int | None = None) Figure[source]
Create sample path visualization showing trajectory evolution.
Displays representative paths over short and long time horizons, highlighting survivors vs failed companies with transparency effects.
- Parameters:
simulation_data (
Optional[Dict[str,Any]]) – Optional pre-computed simulation results with pathsn_paths (
int) – Number of paths to display (default 5)short_horizon (
int) – Years for short-term view (default 10)long_horizon (
int) – Years for long-term view (default 100)company_size (
float) – Starting company sizetitle (
str) – Plot titleshow_failures (
bool) – Whether to highlight failed pathsexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with dual-panel path visualization
Examples
>>> fig = plot_sample_paths(n_paths=5) >>> fig.savefig("sample_paths.png", dpi=150)
- plot_optimal_coverage_heatmap(optimization_results: Dict[str, Any] | None = None, company_sizes: List[float] | None = None, title: str = 'Optimal Coverage Heatmap', figsize: Tuple[int, int] = (16, 6), show_contours: bool = True, export_dpi: int | None = None) Figure[source]
Create optimal insurance coverage heatmap for different company sizes.
Visualizes the relationship between retention, limit, and growth rate using color intensity to show optimal configurations.
- Parameters:
optimization_results (
Optional[Dict[str,Any]]) – Optional pre-computed optimization datacompany_sizes (
Optional[List[float]]) – List of company sizes (default: [1e6, 1e7, 1e8])title (
str) – Plot titleshow_contours (
bool) – Whether to show contour linesexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with 3-panel heatmap
Examples
>>> fig = plot_optimal_coverage_heatmap( ... company_sizes=[1e6, 1e7, 1e8] ... ) >>> fig.savefig("coverage_heatmap.png", dpi=150)
- plot_sensitivity_tornado(sensitivity_data: Dict[str, float] | None = None, baseline_value: float | None = None, title: str = 'Sensitivity Analysis - Tornado Chart', figsize: Tuple[int, int] = (10, 8), show_percentages: bool = True, export_dpi: int | None = None) Figure[source]
Create tornado chart showing parameter sensitivity analysis.
Visualizes the impact of parameter variations on key metrics using horizontal bars sorted by influence magnitude.
- Parameters:
sensitivity_data (
Optional[Dict[str,float]]) – Dict of parameter names to impact valuesbaseline_value (
Optional[float]) – Baseline metric value for referencetitle (
str) – Plot titleshow_percentages (
bool) – Whether to show percentage labelsexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with tornado chart
Examples
>>> sensitivity = { ... "Premium Rate": 0.15, ... "Loss Frequency": -0.12, ... "Loss Severity": -0.08, ... } >>> fig = plot_sensitivity_tornado(sensitivity)
- plot_robustness_heatmap(robustness_data: ndarray | None = None, frequency_range: Tuple[float, float] | None = None, severity_range: Tuple[float, float] | None = None, title: str = 'Insurance Program Robustness Analysis', figsize: Tuple[int, int] = (10, 8), show_reference: bool = True, export_dpi: int | None = None) Figure[source]
Create robustness heatmap showing stability across parameter variations.
Visualizes how optimal coverage changes with variations in loss frequency and severity parameters.
- Parameters:
robustness_data (
Optional[ndarray]) – 2D array of stability metricsfrequency_range (
Optional[Tuple[float,float]]) – Tuple of (min, max) frequency variation (default 0.7-1.3)severity_range (
Optional[Tuple[float,float]]) – Tuple of (min, max) severity variation (default 0.7-1.3)title (
str) – Plot titleshow_reference (
bool) – Whether to show reference point at 100%/100%export_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with robustness heatmap
Examples
>>> fig = plot_robustness_heatmap() >>> fig.savefig("robustness.png", dpi=150)
Create premium multiplier analysis visualization.
Visualizes the optimal premium as a multiple of expected loss for different company sizes, demonstrating why premiums 2-5× expected losses are optimal from an ergodic perspective.
- Parameters:
optimization_results (
Optional[Dict[float,Dict[str,Any]]]) – Dict of company_size -> optimization data containing ‘expected_loss’, ‘optimal_premium’, and optionally ‘confidence_bounds’ for each company sizecompany_sizes (
Optional[List[float]]) – List of company sizes to analyze (default: [1e6, 1e7, 1e8])title (
str) – Plot titleshow_confidence (
bool) – Whether to show confidence intervalsshow_reference_lines (
bool) – Whether to show horizontal reference linesshow_annotations (
bool) – Whether to add explanatory annotationsexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with premium multiplier analysis
Examples
>>> results = { ... 1e6: {'expected_loss': 50000, 'optimal_premium': 150000}, ... 1e7: {'expected_loss': 200000, 'optimal_premium': 600000} ... } >>> fig = plot_premium_multiplier(results)
- plot_breakeven_timeline(simulation_results: Dict[float, Dict[str, Any]] | None = None, company_sizes: List[float] | None = None, time_horizon: int = 30, title: str = 'Insurance Break-even Timeline Analysis', figsize: Tuple[int, int] = (14, 8), show_percentiles: bool = True, show_breakeven_markers: bool = True, export_dpi: int | None = None) Figure[source]
Create break-even timeline visualization.
Shows when the cumulative benefits of optimal insurance exceed the cumulative excess premiums paid (premiums above expected losses), demonstrating the long-term value proposition.
- Parameters:
simulation_results (
Optional[Dict[float,Dict[str,Any]]]) – Dict of company_size -> simulation data containing ‘cumulative_benefit’, ‘cumulative_excess_premium’, and optionally percentile datacompany_sizes (
Optional[List[float]]) – List of company sizes to analyze (default: [1e6, 1e7, 1e8])time_horizon (
int) – Years to simulate (default: 30)title (
str) – Plot titleshow_percentiles (
bool) – Whether to show 25th/75th percentile bandsshow_breakeven_markers (
bool) – Whether to mark break-even pointsexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with break-even timeline analysis
Examples
>>> results = { ... 1e6: { ... 'cumulative_benefit': np.array([...]), ... 'cumulative_excess_premium': np.array([...]) ... } ... } >>> fig = plot_breakeven_timeline(results)
ergodic_insurance.visualization.export module
Export utilities for saving visualizations in various formats.
This module provides functions to export visualizations to different formats including high-resolution images, PDFs, and web-ready formats.
- save_figure(fig: Figure | Figure, filename: str, dpi: int = 300, bbox_inches: str = 'tight', transparent: bool = False, formats: List[str] | None = None, metadata: Dict[str, Any] | None = None) List[str][source]
Save figure in multiple formats.
Saves a matplotlib or plotly figure to disk in one or more formats with professional quality settings.
- Parameters:
fig (
Union[Figure,Figure]) – Matplotlib Figure or Plotly Figure to savefilename (
str) – Base filename (without extension)dpi (
int) – Resolution for raster formatsbbox_inches (
str) – How to handle figure boundstransparent (
bool) – Whether to use transparent backgroundformats (
Optional[List[str]]) – List of formats to save (default: [‘png’])metadata (
Optional[Dict[str,Any]]) – Optional metadata to embed in files
- Return type:
- Returns:
List of saved file paths
- Raises:
ValueError – If unsupported format is requested
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> save_figure(fig, "my_plot", formats=["png", "pdf"]) ['my_plot.png', 'my_plot.pdf']
- save_for_publication(fig: Figure, filename: str, width: float = 7, height: float = 5, dpi: int = 600) str[source]
Save figure with publication-quality settings.
Exports a figure with settings optimized for academic publication or professional reports.
- Parameters:
- Return type:
- Returns:
Path to saved PDF file
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> save_for_publication(fig, "figure_1") 'figure_1.pdf'
- save_for_presentation(fig: Figure | Figure, filename: str, width: int = 1920, height: int = 1080) str[source]
Save figure optimized for presentations.
Exports a figure with settings optimized for PowerPoint or other presentation software.
- Parameters:
- Return type:
- Returns:
Path to saved file
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> save_for_presentation(fig, "slide_1") 'slide_1.png'
- save_for_web(fig: Figure | Figure, filename: str, optimize: bool = True) Dict[str, str][source]
Save figure optimized for web display.
Creates web-optimized versions of the figure including responsive formats and multiple resolutions.
- Parameters:
- Return type:
- Returns:
Dictionary of format to file path mappings
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> files = save_for_web(fig, "chart") >>> print(files) {'thumbnail': 'chart_thumb.png', 'full': 'chart.png', 'svg': 'chart.svg'}
- batch_export(figures: Dict[str, Figure | Figure], output_dir: str, formats: List[str] | None = None, dpi: int = 300) Dict[str, List[str]][source]
Export multiple figures in batch.
Saves multiple figures to a directory with consistent settings.
- Parameters:
- Return type:
- Returns:
Dictionary mapping figure names to lists of saved files
Examples
>>> fig1, ax1 = plt.subplots() >>> fig2, ax2 = plt.subplots() >>> figures = {"chart1": fig1, "chart2": fig2} >>> batch_export(figures, "output/", formats=["png"])
ergodic_insurance.visualization.figure_factory module
Figure factory for creating standardized plots with consistent styling.
This module provides a factory class for creating various types of plots with automatic styling, spacing, and formatting applied consistently.
- class FigureFactory(style_manager: StyleManager | None = None, theme: Theme = Theme.DEFAULT, auto_apply: bool = True)[source]
Bases:
objectFactory for creating standardized figures with consistent styling.
This class provides methods to create various types of plots with automatic application of themes, consistent formatting, and proper spacing.
Example
>>> factory = FigureFactory(theme=Theme.PRESENTATION) >>> fig, ax = factory.create_line_plot( ... x_data=[1, 2, 3, 4], ... y_data=[10, 20, 15, 25], ... title="Revenue Growth", ... x_label="Quarter", ... y_label="Revenue ($M)" ... )
>>> # Create multiple subplots >>> fig, axes = factory.create_subplots( ... rows=2, cols=2, ... size_type="large", ... subplot_titles=["Q1", "Q2", "Q3", "Q4"] ... )
- create_figure(size_type: str = 'medium', orientation: str = 'landscape', dpi_type: str = 'screen', title: str | None = None) Tuple[Figure, Axes][source]
Create a basic figure with styling applied.
- Parameters:
- Return type:
- Returns:
Tuple of (figure, axes)
- create_subplots(rows: int = 1, cols: int = 1, size_type: str = 'large', dpi_type: str = 'screen', title: str | None = None, subplot_titles: List[str] | None = None, **kwargs) Tuple[Figure, Axes | ndarray][source]
Create subplots with consistent styling.
- Parameters:
- Return type:
- Returns:
Tuple of (figure, axes array)
- create_line_plot(x_data: List | ndarray | Series, y_data: List | ndarray | Series | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', show_legend: bool = True, show_grid: bool = True, markers: bool = False, **kwargs) Tuple[Figure, Axes][source]
Create a line plot with automatic formatting.
- Parameters:
y_data (
Union[List,ndarray,Series,Dict[str,Union[List,ndarray]]]) – Y-axis data (can be multiple series as dict)size_type (
str) – Figure size presetdpi_type (
str) – DPI typeshow_legend (
bool) – Whether to show legendshow_grid (
bool) – Whether to show gridmarkers (
bool) – Whether to add markers to lines**kwargs – Additional arguments for plot
- Return type:
- Returns:
Tuple of (figure, axes)
- create_bar_plot(categories: List | ndarray, values: List | ndarray | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_values: bool = False, value_format: str = '.1f', **kwargs) Tuple[Figure, Axes][source]
Create a bar plot with automatic formatting.
- Parameters:
values (
Union[List,ndarray,Dict[str,Union[List,ndarray]]]) – Values to plot (can be multiple series as dict)size_type (
str) – Figure size presetdpi_type (
str) – DPI typeorientation (
str) – Bar orientation (vertical or horizontal)show_values (
bool) – Whether to show value labels on barsvalue_format (
str) – Format string for value labels**kwargs – Additional arguments for bar plot
- Return type:
- Returns:
Tuple of (figure, axes)
- create_scatter_plot(x_data: List | ndarray, y_data: List | ndarray, title: str | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', colors: List | ndarray | None = None, sizes: List | ndarray | None = None, labels: List[str] | None = None, show_colorbar: bool = False, **kwargs) Tuple[Figure, Axes][source]
Create a scatter plot with automatic formatting.
- Parameters:
size_type (
str) – Figure size presetdpi_type (
str) – DPI typecolors (
Union[List,ndarray,None]) – Optional colors for points (for continuous coloring)sizes (
Union[List,ndarray,None]) – Optional sizes for pointsshow_colorbar (
bool) – Whether to show colorbar when colors provided**kwargs – Additional arguments for scatter
- Return type:
- Returns:
Tuple of (figure, axes)
- create_histogram(data: List | ndarray | Series, title: str | None = None, x_label: str | None = None, y_label: str = 'Frequency', bins: int | str = 'auto', size_type: str = 'medium', dpi_type: str = 'screen', show_statistics: bool = False, show_kde: bool = False, **kwargs) Tuple[Figure, Axes][source]
Create a histogram with automatic formatting.
- create_heatmap(data: ndarray | DataFrame, title: str | None = None, x_labels: List[str] | None = None, y_labels: List[str] | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', cmap: str = 'RdBu_r', show_values: bool = True, value_format: str = '.2f', **kwargs) Tuple[Figure, Axes][source]
Create a heatmap with automatic formatting.
- Parameters:
- Return type:
- Returns:
Tuple of (figure, axes)
- create_box_plot(data: List[List] | Dict[str, List] | DataFrame, title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_means: bool = True, **kwargs) Tuple[Figure, Axes][source]
Create a box plot with automatic formatting.
- Parameters:
data (
Union[List[List],Dict[str,List],DataFrame]) – Data for box plot (list of lists, dict, or DataFrame)size_type (
str) – Figure size presetdpi_type (
str) – DPI typeorientation (
str) – Plot orientation (vertical or horizontal)show_means (
bool) – Whether to show mean markers**kwargs – Additional arguments for boxplot
- Return type:
- Returns:
Tuple of (figure, axes)
- format_axis_currency(ax: Axes, axis: str = 'y', abbreviate: bool = True, decimals: int = 0) None[source]
Format axis labels as currency.
- format_axis_percentage(ax: Axes, axis: str = 'y', decimals: int = 0) None[source]
Format axis labels as percentages.
- add_annotations(ax: Axes, x: float, y: float, text: str, arrow: bool = True, offset: Tuple[float, float] = (10, 10), **kwargs) None[source]
Add styled annotation to plot.
ergodic_insurance.visualization.improved_tower_plot module
Improved insurance tower visualization with stacked bar chart and smart annotations.
- plot_insurance_tower(layers: List[Dict[str, float]] | DataFrame, title: str = 'Insurance Tower Structure', figsize: Tuple[int, int] = (10, 12), min_height_for_text: float = 0.02, color_scheme: str = 'viridis', show_summary: bool = True, log_scale: bool = True) Figure[source]
Create an improved insurance tower visualization with stacked bars and smart annotations.
- Parameters:
layers (
Union[List[Dict[str,float]],DataFrame]) – List of layer dictionaries or DataFrame with columns: - attachment: Layer attachment point - limit: Layer limit - premium: Premium amount or rate - expected_loss (optional): Expected loss for the layer - rate_on_line (optional): Rate on line for the layertitle (
str) – Plot titlemin_height_for_text (
float) – Minimum relative height (as fraction of total) to display text inside barcolor_scheme (
str) – Matplotlib colormap nameshow_summary (
bool) – Whether to show summary statisticslog_scale (
bool) – Use logarithmic scale for y-axis to better show layers of different sizes
- Return type:
- Returns:
Matplotlib figure with improved tower visualization
ergodic_insurance.visualization.interactive_plots module
Interactive visualization functions using Plotly.
This module provides functions for creating interactive dashboards and visualizations for Monte Carlo simulations and analysis results.
- create_interactive_dashboard(results: Dict[str, Any] | DataFrame, title: str = 'Monte Carlo Simulation Dashboard', height: int = 600, show_distributions: bool = False) Figure[source]
Create interactive Plotly dashboard with WSJ styling.
Creates a comprehensive interactive dashboard with multiple panels showing simulation results, convergence, and risk metrics.
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with interactive dashboard
Examples
>>> results = { ... "growth_rates": np.random.normal(0.05, 0.02, 1000), ... "losses": np.random.lognormal(10, 2, 1000), ... "metrics": {"var_95": 100000, "var_99": 150000} ... } >>> fig = create_interactive_dashboard(results)
- create_time_series_dashboard(data: DataFrame, value_col: str, time_col: str = 'date', title: str = 'Time Series Analysis', height: int = 600, show_forecast: bool = False) Figure[source]
Create interactive time series visualization.
Creates an interactive time series plot with optional forecast bands and statistical overlays.
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with time series visualization
- create_correlation_heatmap(data: DataFrame, title: str = 'Correlation Matrix', height: int = 600, show_values: bool = True) Figure[source]
Create interactive correlation heatmap.
Creates an interactive heatmap showing correlations between variables with customizable color scheme and annotations.
ergodic_insurance.visualization.style_manager module
Style management for consistent visualization across all reports.
This module provides centralized style configuration for all visualizations, including color palettes, fonts, figure sizes, and DPI settings.
- class Theme(*values)[source]
Bases:
EnumAvailable visualization themes.
- DEFAULT = 'default'
- COLORBLIND = 'colorblind'
- PRESENTATION = 'presentation'
- MINIMAL = 'minimal'
- PRINT = 'print'
- class ColorPalette(primary: str = '#0080C7', secondary: str = '#003F5C', accent: str = '#FF9800', warning: str = '#D32F2F', success: str = '#4CAF50', neutral: str = '#666666', background: str = '#FFFFFF', text: str = '#000000', grid: str = '#E0E0E0', series: List[str] = <factory>) None[source]
Bases:
objectColor palette configuration for a theme.
- primary
Main color for primary elements
- secondary
Secondary color for supporting elements
- accent
Accent color for highlights
- warning
Color for warnings or negative values
- success
Color for positive values or success states
- neutral
Neutral gray tones
- background
Background color
- text
Text color
- grid
Grid line color
- series
List of colors for multiple data series
- class FontConfig(family: str = 'Arial', size_base: int = 11, size_title: int = 14, size_label: int = 12, size_tick: int = 10, size_legend: int = 10, weight_normal: str = 'normal', weight_bold: str = 'bold') None[source]
Bases:
objectFont configuration for a theme.
- family
Font family name
- size_base
Base font size
- size_title
Title font size
- size_label
Label font size
- size_tick
Tick label font size
- size_legend
Legend font size
- weight_normal
Normal font weight
- weight_bold
Bold font weight
- class FigureConfig(size_small: Tuple[float, float] = (6, 4), size_medium: Tuple[float, float] = (8, 6), size_large: Tuple[float, float] = (12, 8), size_blog: Tuple[float, float] = (8, 6), size_technical: Tuple[float, float] = (10, 8), size_presentation: Tuple[float, float] = (10, 7.5), dpi_screen: int = 100, dpi_web: int = 150, dpi_print: int = 300) None[source]
Bases:
objectFigure size and DPI configuration.
- size_small
Small figure size (width, height) in inches
- size_medium
Medium figure size
- size_large
Large figure size
- size_blog
Blog-optimized size (8x6)
- size_technical
Technical appendix size (10x8)
- size_presentation
Presentation slide size
- dpi_screen
DPI for screen display
- dpi_web
DPI for web publishing (150)
- dpi_print
DPI for print quality (300)
- class GridConfig(show_grid: bool = True, grid_alpha: float = 0.3, grid_linewidth: float = 0.5, spine_top: bool = False, spine_right: bool = False, spine_bottom: bool = True, spine_left: bool = True, spine_linewidth: float = 0.8, tick_major_width: float = 0.8, tick_minor_width: float = 0.4) None[source]
Bases:
objectGrid and axis configuration.
- show_grid
Whether to show grid lines
- grid_alpha
Grid transparency
- grid_linewidth
Grid line width
- spine_top
Show top spine
- spine_right
Show right spine
- spine_bottom
Show bottom spine
- spine_left
Show left spine
- spine_linewidth
Spine line width
- tick_major_width
Major tick width
- tick_minor_width
Minor tick width
- class StyleManager(theme: Theme = Theme.DEFAULT, config_path: str | Path | None = None, custom_colors: Dict[str, str] | None = None, custom_fonts: Dict[str, Any] | None = None)[source]
Bases:
objectManages visualization styles and themes.
This class provides centralized style management for all visualizations, supporting multiple themes, custom configurations, and style inheritance.
Example
>>> style_mgr = StyleManager() >>> style_mgr.set_theme(Theme.PRESENTATION) >>> style_mgr.apply_style() >>> # Create plots with consistent styling
>>> # Or with custom configuration >>> style_mgr = StyleManager(config_path="custom_style.yaml") >>> style_mgr.apply_style()
- get_colors() ColorPalette[source]
Get current color palette.
- Return type:
- Returns:
Current theme’s color palette
- get_fonts() FontConfig[source]
Get current font configuration.
- Return type:
- Returns:
Current theme’s font configuration
- get_figure_config() FigureConfig[source]
Get current figure configuration.
- Return type:
- Returns:
Current theme’s figure configuration
- get_grid_config() GridConfig[source]
Get current grid configuration.
- Return type:
- Returns:
Current theme’s grid configuration
- apply_style() None[source]
Apply current theme to matplotlib.
This updates matplotlib’s rcParams to match the current theme settings.
- Return type:
- get_figure_size(size_type: str = 'medium', orientation: str = 'landscape') Tuple[float, float][source]
Get figure size for a given type.
ergodic_insurance.visualization.technical_plots module
Technical appendix visualization functions.
This module provides detailed technical visualization functions for convergence diagnostics, Pareto frontier analysis, loss distribution validation, and Monte Carlo convergence analysis.
- plot_convergence_diagnostics(convergence_stats: Dict[str, Any], title: str = 'Convergence Diagnostics', figsize: Tuple[int, int] = (12, 8), r_hat_threshold: float = 1.1, show_threshold: bool = False) Figure[source]
Create comprehensive convergence diagnostics plot.
Visualizes convergence metrics including R-hat statistics, effective sample size, autocorrelation, and Monte Carlo standard errors.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with convergence diagnostics
Examples
>>> stats = { ... "r_hat_history": [1.5, 1.3, 1.15, 1.05], ... "iterations": [100, 200, 300, 400], ... "ess_history": [500, 800, 1200, 1500] ... } >>> fig = plot_convergence_diagnostics(stats)
- plot_pareto_frontier_2d(frontier_points: List[Any], x_objective: str, y_objective: str, x_label: str | None = None, y_label: str | None = None, title: str = 'Pareto Frontier', highlight_knees: bool = True, show_trade_offs: bool = False, figsize: Tuple[float, float] = (10, 6)) Figure[source]
Plot 2D Pareto frontier with WSJ styling.
Visualizes the trade-off between two objectives with optional knee point highlighting and dominated region shading.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with 2D Pareto frontier
Examples
>>> points = [ParetoPoint(objectives={"cost": 100, "quality": 0.8})] >>> fig = plot_pareto_frontier_2d(points, "cost", "quality")
- plot_pareto_frontier_3d(frontier_points: List[Any], x_objective: str, y_objective: str, z_objective: str, x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, title: str = '3D Pareto Frontier', figsize: Tuple[float, float] = (12, 8)) Figure[source]
Plot 3D Pareto frontier surface.
Creates a 3D visualization of the Pareto frontier with optional surface interpolation when sufficient points are available.
- create_interactive_pareto_frontier(frontier_points: List[Any], objectives: List[str], title: str = 'Interactive Pareto Frontier', height: int = 600, show_dominated: bool = True) Figure[source]
Create interactive Plotly Pareto frontier visualization.
Creates an interactive visualization that automatically adapts to the number of objectives (2D scatter, 3D scatter, or parallel coordinates).
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with interactive Pareto frontier
- plot_trace_plots(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Trace Plots', figsize: Tuple[int, int] = (12, 8)) Figure[source]
Create trace plots for MCMC chains with burn-in indicators.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with trace plots
Examples
>>> chains = np.random.randn(4, 1000, 3) # 4 chains, 1000 iterations, 3 parameters >>> fig = plot_trace_plots(chains, ["param1", "param2", "param3"], burn_in=200)
- plot_loss_distribution_validation(attritional_losses: ndarray, large_losses: ndarray, attritional_dist: Dict[str, Any] | None = None, large_dist: Dict[str, Any] | None = None, title: str = 'Loss Distribution Validation', figsize: Tuple[int, int] = (12, 10)) Figure[source]
Create comprehensive loss distribution validation plots (Figure B1).
Generates Q-Q plots and CDF comparisons for attritional and large losses, with K-S test statistics and goodness-of-fit metrics.
- Parameters:
attritional_losses (
ndarray) – Empirical attritional loss datalarge_losses (
ndarray) – Empirical large loss dataattritional_dist (
Optional[Dict[str,Any]]) – Theoretical distribution parameters for attritional losseslarge_dist (
Optional[Dict[str,Any]]) – Theoretical distribution parameters for large lossestitle (
str) – Overall plot title
- Return type:
- Returns:
Matplotlib figure with validation plots
Examples
>>> attritional = np.random.lognormal(10, 1, 1000) >>> large = np.random.lognormal(15, 2, 100) >>> fig = plot_loss_distribution_validation(attritional, large)
- plot_monte_carlo_convergence(metrics_history: Dict[str, List[float]], iterations: ndarray | None = None, convergence_thresholds: Dict[str, float] | None = None, title: str = 'Monte Carlo Convergence Analysis', figsize: Tuple[int, int] = (14, 10), log_scale: bool = True) Figure[source]
Create Monte Carlo convergence analysis plots (Figure C3).
Visualizes convergence of key metrics (ROE, ruin probability, etc.) as a function of Monte Carlo iterations, with running statistics and thresholds.
- Parameters:
metrics_history (
Dict[str,List[float]]) – Dictionary of metric names to lists of values over iterationsiterations (
Optional[ndarray]) – Array of iteration counts (optional, will be inferred)convergence_thresholds (
Optional[Dict[str,float]]) – Dictionary of metric names to convergence thresholdstitle (
str) – Overall plot titlelog_scale (
bool) – Whether to use log scale for x-axis
- Return type:
- Returns:
Matplotlib figure with convergence analysis
Examples
>>> history = { ... "ROE": [0.08, 0.082, 0.081, 0.0805], ... "Ruin Probability": [0.05, 0.048, 0.049, 0.0495] ... } >>> fig = plot_monte_carlo_convergence(history)
- plot_enhanced_convergence_diagnostics(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Enhanced Convergence Diagnostics', figsize: Tuple[int, int] = (14, 10)) Figure[source]
Create comprehensive convergence diagnostics with trace plots and statistics.
Enhanced version of plot_convergence_diagnostics that includes trace plots, R-hat evolution, ESS calculations, and autocorrelation analysis.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with enhanced diagnostics
Examples
>>> chains = np.random.randn(4, 1000, 2) >>> fig = plot_enhanced_convergence_diagnostics( ... chains, ... parameter_names=["mu", "sigma"], ... burn_in=200 ... )
- plot_ergodic_divergence(time_horizons: ndarray, time_averages: ndarray, ensemble_averages: ndarray, standard_errors: ndarray | None = None, parameter_scenarios: Dict[str, Dict[str, Any]] | None = None, title: str = 'Ergodic vs Ensemble Average Divergence', figsize: Tuple[float, float] = (14, 8), add_formulas: bool = True) Figure[source]
Create ergodic vs ensemble divergence visualization (Figure C1).
Demonstrates the fundamental difference between time-average (ergodic) and ensemble-average growth rates as time horizon increases, showing why insurance decisions must consider individual path dynamics rather than expected values.
- Parameters:
time_horizons (
ndarray) – Array of time horizons (e.g., 1 to 1000 years)time_averages (
ndarray) – Time-average growth rates for each horizonensemble_averages (
ndarray) – Ensemble-average growth rates for each horizonstandard_errors (
Optional[ndarray]) – Optional standard errors for confidence bandsparameter_scenarios (
Optional[Dict[str,Dict[str,Any]]]) – Optional dict of scenario name to parameter valuestitle (
str) – Plot titleadd_formulas (
bool) – Whether to add LaTeX formula annotations
- Return type:
- Returns:
Matplotlib figure showing divergence visualization
Examples
>>> horizons = np.logspace(0, 3, 50) # 1 to 1000 years >>> time_avg = np.array([0.05 * (1 - 0.1 * np.log10(t)) for t in horizons]) >>> ensemble_avg = np.array([0.08] * len(horizons)) >>> fig = plot_ergodic_divergence(horizons, time_avg, ensemble_avg)
- plot_path_dependent_wealth(trajectories: ndarray, time_points: ndarray | None = None, ruin_threshold: float = 0.0, percentiles: List[int] | None = None, highlight_ruined: bool = True, add_survivor_bias_inset: bool = True, title: str = 'Path-Dependent Wealth Evolution', figsize: Tuple[float, float] = (14, 8), log_scale: bool = True) Figure[source]
Create path-dependent wealth evolution visualization (Figure C2).
Shows multiple wealth trajectories over time with percentile bands, highlighting paths that hit ruin and demonstrating survivor bias effects. This visualization makes clear why ensemble averages mislead decision-making.
- Parameters:
trajectories (
ndarray) – Array of shape (n_paths, n_time_points) with wealth valuestime_points (
Optional[ndarray]) – Optional array of time points (defaults to years)ruin_threshold (
float) – Wealth level considered as ruin (default 0)percentiles (
Optional[List[int]]) – List of percentiles to show (default [5, 25, 50, 75, 95])highlight_ruined (
bool) – Whether to highlight paths that hit ruinadd_survivor_bias_inset (
bool) – Whether to add survivor bias analysis insettitle (
str) – Plot titlelog_scale (
bool) – Whether to use log scale for wealth axis
- Return type:
- Returns:
Matplotlib figure showing path evolution
Examples
>>> n_paths, n_years = 1000, 100 >>> trajectories = np.random.lognormal(0, 0.2, (n_paths, n_years)).cumprod(axis=1) >>> fig = plot_path_dependent_wealth(trajectories)
- plot_correlation_structure(data: Dict[str, ndarray], correlation_type: str = 'pearson', risk_types: List[str] | None = None, title: str = 'Risk Correlation Structure', figsize: Tuple[float, float] = (14, 10), show_copula: bool = True) Figure[source]
Create correlation structure visualization with copula analysis (Figure B2).
Visualizes correlation matrices, copula density plots, and scatter plots with fitted copulas to show dependencies between different risk types.
- Parameters:
data (
Dict[str,ndarray]) – Dictionary mapping risk type names to data arrays (n_samples, n_variables)correlation_type (
str) – Type of correlation (‘pearson’, ‘spearman’, ‘kendall’)risk_types (
Optional[List[str]]) – List of risk types to analyze (defaults to all in data)title (
str) – Plot titleshow_copula (
bool) – Whether to show copula density plots
- Return type:
- Returns:
Matplotlib figure with correlation structure visualization
Examples
>>> data = { ... "operational": np.random.randn(1000, 3), ... "financial": np.random.randn(1000, 3) ... } >>> fig = plot_correlation_structure(data)
Create premium loading decomposition visualization (Figure C4).
Shows stacked bar charts breaking down insurance premium into components: expected loss (base), volatility load, tail load, expense load, and profit margin.
- Parameters:
premium_components (
Dict[str,Dict[str,Dict[str,float]]]) – Nested dict with structure: {company_size: {layer: {component: value}}} Components: ‘expected_loss’, ‘volatility_load’, ‘tail_load’, ‘expense_load’, ‘profit_margin’company_sizes (
Optional[List[str]]) – List of company sizes to show (defaults to all)layers (
Optional[List[str]]) – List of insurance layers to show (defaults to all)title (
str) – Plot titleshow_percentages (
bool) – Whether to show percentage labels on segmentscolor_scheme (
Optional[Dict[str,str]]) – Dict mapping component names to colors
- Return type:
- Returns:
Matplotlib figure with premium decomposition
Examples
>>> components = { ... "Small": { ... "Primary": {"expected_loss": 100, "volatility_load": 20, ... "tail_load": 15, "expense_load": 10, "profit_margin": 5} ... } ... } >>> fig = plot_premium_decomposition(components)
- plot_capital_efficiency_frontier_3d(efficiency_data: Dict[str, Dict[str, ndarray]], company_sizes: List[str] | None = None, optimal_paths: Dict[str, ndarray] | None = None, title: str = 'Capital Efficiency Frontier', figsize: Tuple[float, float] = (14, 10), view_angles: Tuple[float, float] | None = None, export_views: bool = False) Figure | List[Figure][source]
Create 3D capital efficiency frontier visualization (Figure C5).
Shows 3D surface plot with ROE, Ruin Probability, and Insurance Spend axes, with separate surfaces for each company size and highlighted optimal paths.
- Parameters:
efficiency_data (
Dict[str,Dict[str,ndarray]]) – Nested dict with structure:{company_size: {'roe': 2D array (n_ruin x n_spend), 'ruin_prob': 1D array (n_ruin), 'insurance_spend': 1D array (n_spend)}}company_sizes (
Optional[List[str]]) – List of company sizes to show (defaults to all)optimal_paths (
Optional[Dict[str,ndarray]]) – Dict mapping company size to optimal path coordinates:{company_size: array of shape (n_points, 3) with [roe, ruin, spend]}title (
str) – Plot titleview_angles (
Optional[Tuple[float,float]]) – Tuple of (elevation, azimuth) angles for 3D viewexport_views (
bool) – Whether to return multiple figures with different view angles
- Return type:
- Returns:
Single figure or list of figures with different viewing angles if export_views=True
Examples
>>> data = { ... "Small": { ... "roe": np.random.rand(20, 30), ... "ruin_prob": np.linspace(0, 0.1, 20), ... "insurance_spend": np.linspace(0, 1e6, 30) ... } ... } >>> fig = plot_capital_efficiency_frontier_3d(data)
Module contents
Unified visualization infrastructure for ergodic insurance analysis.
This package provides a comprehensive visualization toolkit with: - Professional Wall Street Journal styling - Executive-level and technical visualizations - Interactive dashboards - Export utilities for various formats
- set_wsj_style()[source]
Set matplotlib to use WSJ-style formatting.
This function applies Wall Street Journal aesthetic styling to matplotlib plots including font choices, spine visibility, grid settings, and colors.
- format_currency(value: float, decimals: int = 0, abbreviate: bool = False) str[source]
Format value as currency.
- Parameters:
- Return type:
- Returns:
Formatted string (e.g., “$1,000” or “$1K” if abbreviate=True)
Examples
>>> format_currency(1000) '$1,000' >>> format_currency(1500000, abbreviate=True) '$1.5M' >>> format_currency(2500.50, decimals=2) '$2,500.50'
- format_percentage(value: float, decimals: int = 1) str[source]
Format value as percentage.
- Parameters:
- Return type:
- Returns:
Formatted string (e.g., “5.0%”)
Examples
>>> format_percentage(0.05) '5.0%' >>> format_percentage(0.1234, decimals=2) '12.34%'
- class WSJFormatter[source]
Bases:
objectFormatter for WSJ-style axis labels.
This class provides static methods for formatting axis values in various styles consistent with Wall Street Journal publication standards.
- static currency_formatter(x, pos)[source]
Format axis values as currency.
- Parameters:
x – The value to format
pos – The position (unused but required by matplotlib)
- Returns:
Formatted currency string
- static currency(x: float, decimals: int = 1) str[source]
Format value as currency (shortened method name).
- static percentage_formatter(x, pos)[source]
Format axis values as percentage.
- Parameters:
x – The value to format
pos – The position (unused but required by matplotlib)
- Returns:
Formatted percentage string
- static percentage(x: float, decimals: int = 1) str[source]
Format value as percentage (shortened method name).
- plot_loss_distribution(losses: ndarray | DataFrame, title: str = 'Loss Distribution', bins: int = 50, show_metrics: bool = True, var_levels: List[float] | None = None, figsize: Tuple[int, int] = (12, 6), show_stats: bool = False, log_scale: bool = False, use_factory: bool = False, theme: Any | None = None) Figure[source]
Create WSJ-style loss distribution plot.
Creates a two-panel visualization showing loss distribution histogram and Q-Q plot for normality assessment.
- Parameters:
losses (
Union[ndarray,DataFrame]) – Array of loss values or DataFrame with ‘amount’ columntitle (
str) – Plot titlebins (
int) – Number of histogram binsshow_metrics (
bool) – Whether to show VaR/TVaR linesvar_levels (
Optional[List[float]]) – VaR confidence levels to show (default: [0.95, 0.99])show_stats (
bool) – Whether to show statisticslog_scale (
bool) – Whether to use log scaleuse_factory (
bool) – Whether to use new visualization factory if available
- Return type:
- Returns:
Matplotlib figure with distribution plots
Examples
>>> losses = np.random.lognormal(10, 2, 1000) >>> fig = plot_loss_distribution(losses, title="Annual Loss Distribution")
- plot_return_period_curve(losses: ndarray | DataFrame, return_periods: ndarray | None = None, scenarios: Dict[str, ndarray] | None = None, title: str = 'Return Period Curves', figsize: Tuple[int, int] = (10, 6), confidence_level: float = 0.95, show_grid: bool = True) Figure[source]
Create WSJ-style return period curve.
Visualizes the relationship between return periods and loss magnitudes, commonly used in catastrophe modeling and risk assessment.
- Parameters:
losses (
Union[ndarray,DataFrame]) – Loss amounts (array or DataFrame)return_periods (
Optional[ndarray]) – Array of return periods (years), optionalscenarios (
Optional[Dict[str,ndarray]]) – Optional dict of scenario names to loss arraystitle (
str) – Plot titleconfidence_level (
float) – Confidence level for bandsshow_grid (
bool) – Whether to show grid
- Return type:
- Returns:
Matplotlib figure with return period curve
Examples
>>> losses = np.random.lognormal(10, 2, 1000) >>> fig = plot_return_period_curve(losses)
- plot_insurance_layers(layers: List[Dict[str, float]] | DataFrame, total_limit: float | None = None, title: str = 'Insurance Program Structure', figsize: Tuple[int, int] = (10, 6), losses: ndarray | DataFrame | None = None, loss_data: ndarray | DataFrame | None = None, show_expected_loss: bool = False) Figure[source]
Create WSJ-style insurance layer visualization.
Visualizes insurance program structure with layer attachments, limits, and premium distribution in a two-panel display.
- Parameters:
layers (
Union[List[Dict[str,float]],DataFrame]) – List of layer dictionaries or DataFrame with ‘attachment’, ‘limit’ columnstotal_limit (
Optional[float]) – Total program limit (calculated from layers if not provided)title (
str) – Plot titlelosses (
Union[ndarray,DataFrame,None]) – Optional loss data for overlayloss_data (
Union[ndarray,DataFrame,None]) – Alias for losses parametershow_expected_loss (
bool) – Whether to show expected loss line
- Return type:
- Returns:
Matplotlib figure with layer structure and premium distribution
Examples
>>> layers = [ ... {"attachment": 0, "limit": 5e6, "premium": 0.015}, ... {"attachment": 5e6, "limit": 10e6, "premium": 0.008}, ... ] >>> fig = plot_insurance_layers(layers)
- plot_roe_ruin_frontier(results: Dict[float, DataFrame] | DataFrame, company_sizes: List[float] | None = None, title: str = 'ROE-Ruin Efficient Frontier', figsize: Tuple[int, int] = (12, 8), highlight_sweet_spots: bool = True, show_optimal_zones: bool = True, export_dpi: int | None = None, log_scale_y: bool = True, grid: bool = True, annotations: bool = True, color_scheme: List[str] | None = None) Figure[source]
Create ROE-Ruin efficient frontier visualization.
Visualizes the Pareto frontier showing trade-offs between Return on Equity (ROE) and Ruin Probability for different company sizes. This helps executives understand optimal insurance purchasing decisions.
- Parameters:
results (
Union[Dict[float,DataFrame],DataFrame]) – Either a dict of company_size (float) -> optimization results DataFrame, or a single DataFrame with ‘company_size’ columncompany_sizes (
Optional[List[float]]) – List of company sizes to plot (e.g., [1e6, 1e7, 1e8]) If None, will use all available sizes in resultstitle (
str) – Plot titlehighlight_sweet_spots (
bool) – Whether to highlight knee points on curvesshow_optimal_zones (
bool) – Whether to show shaded optimal zonesexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print, None for screen)log_scale_y (
bool) – Whether to use log scale for ruin probability axisgrid (
bool) – Whether to show grid linesannotations (
bool) – Whether to show annotations for key pointscolor_scheme (
Optional[List[str]]) – List of colors for different company sizes
- Return type:
- Returns:
Matplotlib figure with ROE-Ruin efficient frontier plots
- Raises:
ValueError – If results format is invalid or no data available
Examples
>>> # With dictionary of results >>> results = { ... 1e6: pd.DataFrame({'roe': [0.1, 0.15, 0.2], ... 'ruin_prob': [0.05, 0.02, 0.01]}), ... 1e7: pd.DataFrame({'roe': [0.08, 0.12, 0.18], ... 'ruin_prob': [0.03, 0.015, 0.008]}) ... } >>> fig = plot_roe_ruin_frontier(results)
>>> # With single DataFrame >>> df = pd.DataFrame({ ... 'company_size': [1e6, 1e6, 1e7, 1e7], ... 'roe': [0.1, 0.15, 0.08, 0.12], ... 'ruin_prob': [0.05, 0.02, 0.03, 0.015] ... }) >>> fig = plot_roe_ruin_frontier(df)
- plot_ruin_cliff(retention_range: Tuple[float, float] | None = None, n_points: int = 50, company_size: float = 10000000, simulation_data: Dict[str, Any] | None = None, title: str = 'The Ruin Cliff: Retention vs Failure Risk', figsize: Tuple[int, int] = (14, 8), show_inset: bool = True, show_warnings: bool = True, show_3d_effect: bool = True, export_dpi: int | None = None) Figure[source]
Create dramatic ruin cliff visualization with 3D effects.
Visualizes the relationship between insurance retention (deductible) levels and ruin probability, highlighting the “cliff edge” where risk dramatically increases. Features 3D-style gradient effects and warning zones.
- Parameters:
retention_range (
Optional[Tuple[float,float]]) – Tuple of (min, max) retention values in dollars. Default: (10_000, 10_000_000)n_points (
int) – Number of points to calculate along retention axiscompany_size (
float) – Company asset size for scaling retention levelssimulation_data (
Optional[Dict[str,Any]]) – Optional pre-computed simulation results with keys: ‘retentions’, ‘ruin_probs’, ‘confidence_intervals’title (
str) – Plot titleshow_inset (
bool) – Whether to show zoomed inset of critical regionshow_warnings (
bool) – Whether to show warning callouts and annotationsshow_3d_effect (
bool) – Whether to add 3D gradient background effectsexport_dpi (
Optional[int]) – DPI for export (150 for web, 300 for print)
- Return type:
- Returns:
Matplotlib figure with ruin cliff visualization
Examples
>>> # Basic usage with synthetic data >>> fig = plot_ruin_cliff()
>>> # With custom retention range >>> fig = plot_ruin_cliff(retention_range=(5000, 5_000_000))
>>> # With pre-computed simulation data >>> data = { ... 'retentions': np.logspace(4, 7, 50), ... 'ruin_probs': np.array([...]), ... } >>> fig = plot_ruin_cliff(simulation_data=data)
Notes
The visualization uses a log scale for retention values to show the full range from small to large deductibles. The cliff edge is detected using derivative analysis to find the steepest point of increase in ruin probability.
- plot_convergence_diagnostics(convergence_stats: Dict[str, Any], title: str = 'Convergence Diagnostics', figsize: Tuple[int, int] = (12, 8), r_hat_threshold: float = 1.1, show_threshold: bool = False) Figure[source]
Create comprehensive convergence diagnostics plot.
Visualizes convergence metrics including R-hat statistics, effective sample size, autocorrelation, and Monte Carlo standard errors.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with convergence diagnostics
Examples
>>> stats = { ... "r_hat_history": [1.5, 1.3, 1.15, 1.05], ... "iterations": [100, 200, 300, 400], ... "ess_history": [500, 800, 1200, 1500] ... } >>> fig = plot_convergence_diagnostics(stats)
- plot_enhanced_convergence_diagnostics(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Enhanced Convergence Diagnostics', figsize: Tuple[int, int] = (14, 10)) Figure[source]
Create comprehensive convergence diagnostics with trace plots and statistics.
Enhanced version of plot_convergence_diagnostics that includes trace plots, R-hat evolution, ESS calculations, and autocorrelation analysis.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with enhanced diagnostics
Examples
>>> chains = np.random.randn(4, 1000, 2) >>> fig = plot_enhanced_convergence_diagnostics( ... chains, ... parameter_names=["mu", "sigma"], ... burn_in=200 ... )
- plot_ergodic_divergence(time_horizons: ndarray, time_averages: ndarray, ensemble_averages: ndarray, standard_errors: ndarray | None = None, parameter_scenarios: Dict[str, Dict[str, Any]] | None = None, title: str = 'Ergodic vs Ensemble Average Divergence', figsize: Tuple[float, float] = (14, 8), add_formulas: bool = True) Figure[source]
Create ergodic vs ensemble divergence visualization (Figure C1).
Demonstrates the fundamental difference between time-average (ergodic) and ensemble-average growth rates as time horizon increases, showing why insurance decisions must consider individual path dynamics rather than expected values.
- Parameters:
time_horizons (
ndarray) – Array of time horizons (e.g., 1 to 1000 years)time_averages (
ndarray) – Time-average growth rates for each horizonensemble_averages (
ndarray) – Ensemble-average growth rates for each horizonstandard_errors (
Optional[ndarray]) – Optional standard errors for confidence bandsparameter_scenarios (
Optional[Dict[str,Dict[str,Any]]]) – Optional dict of scenario name to parameter valuestitle (
str) – Plot titleadd_formulas (
bool) – Whether to add LaTeX formula annotations
- Return type:
- Returns:
Matplotlib figure showing divergence visualization
Examples
>>> horizons = np.logspace(0, 3, 50) # 1 to 1000 years >>> time_avg = np.array([0.05 * (1 - 0.1 * np.log10(t)) for t in horizons]) >>> ensemble_avg = np.array([0.08] * len(horizons)) >>> fig = plot_ergodic_divergence(horizons, time_avg, ensemble_avg)
- plot_trace_plots(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Trace Plots', figsize: Tuple[int, int] = (12, 8)) Figure[source]
Create trace plots for MCMC chains with burn-in indicators.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with trace plots
Examples
>>> chains = np.random.randn(4, 1000, 3) # 4 chains, 1000 iterations, 3 parameters >>> fig = plot_trace_plots(chains, ["param1", "param2", "param3"], burn_in=200)
- plot_loss_distribution_validation(attritional_losses: ndarray, large_losses: ndarray, attritional_dist: Dict[str, Any] | None = None, large_dist: Dict[str, Any] | None = None, title: str = 'Loss Distribution Validation', figsize: Tuple[int, int] = (12, 10)) Figure[source]
Create comprehensive loss distribution validation plots (Figure B1).
Generates Q-Q plots and CDF comparisons for attritional and large losses, with K-S test statistics and goodness-of-fit metrics.
- Parameters:
attritional_losses (
ndarray) – Empirical attritional loss datalarge_losses (
ndarray) – Empirical large loss dataattritional_dist (
Optional[Dict[str,Any]]) – Theoretical distribution parameters for attritional losseslarge_dist (
Optional[Dict[str,Any]]) – Theoretical distribution parameters for large lossestitle (
str) – Overall plot title
- Return type:
- Returns:
Matplotlib figure with validation plots
Examples
>>> attritional = np.random.lognormal(10, 1, 1000) >>> large = np.random.lognormal(15, 2, 100) >>> fig = plot_loss_distribution_validation(attritional, large)
- plot_monte_carlo_convergence(metrics_history: Dict[str, List[float]], iterations: ndarray | None = None, convergence_thresholds: Dict[str, float] | None = None, title: str = 'Monte Carlo Convergence Analysis', figsize: Tuple[int, int] = (14, 10), log_scale: bool = True) Figure[source]
Create Monte Carlo convergence analysis plots (Figure C3).
Visualizes convergence of key metrics (ROE, ruin probability, etc.) as a function of Monte Carlo iterations, with running statistics and thresholds.
- Parameters:
metrics_history (
Dict[str,List[float]]) – Dictionary of metric names to lists of values over iterationsiterations (
Optional[ndarray]) – Array of iteration counts (optional, will be inferred)convergence_thresholds (
Optional[Dict[str,float]]) – Dictionary of metric names to convergence thresholdstitle (
str) – Overall plot titlelog_scale (
bool) – Whether to use log scale for x-axis
- Return type:
- Returns:
Matplotlib figure with convergence analysis
Examples
>>> history = { ... "ROE": [0.08, 0.082, 0.081, 0.0805], ... "Ruin Probability": [0.05, 0.048, 0.049, 0.0495] ... } >>> fig = plot_monte_carlo_convergence(history)
- plot_pareto_frontier_2d(frontier_points: List[Any], x_objective: str, y_objective: str, x_label: str | None = None, y_label: str | None = None, title: str = 'Pareto Frontier', highlight_knees: bool = True, show_trade_offs: bool = False, figsize: Tuple[float, float] = (10, 6)) Figure[source]
Plot 2D Pareto frontier with WSJ styling.
Visualizes the trade-off between two objectives with optional knee point highlighting and dominated region shading.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with 2D Pareto frontier
Examples
>>> points = [ParetoPoint(objectives={"cost": 100, "quality": 0.8})] >>> fig = plot_pareto_frontier_2d(points, "cost", "quality")
- plot_pareto_frontier_3d(frontier_points: List[Any], x_objective: str, y_objective: str, z_objective: str, x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, title: str = '3D Pareto Frontier', figsize: Tuple[float, float] = (12, 8)) Figure[source]
Plot 3D Pareto frontier surface.
Creates a 3D visualization of the Pareto frontier with optional surface interpolation when sufficient points are available.
- plot_path_dependent_wealth(trajectories: ndarray, time_points: ndarray | None = None, ruin_threshold: float = 0.0, percentiles: List[int] | None = None, highlight_ruined: bool = True, add_survivor_bias_inset: bool = True, title: str = 'Path-Dependent Wealth Evolution', figsize: Tuple[float, float] = (14, 8), log_scale: bool = True) Figure[source]
Create path-dependent wealth evolution visualization (Figure C2).
Shows multiple wealth trajectories over time with percentile bands, highlighting paths that hit ruin and demonstrating survivor bias effects. This visualization makes clear why ensemble averages mislead decision-making.
- Parameters:
trajectories (
ndarray) – Array of shape (n_paths, n_time_points) with wealth valuestime_points (
Optional[ndarray]) – Optional array of time points (defaults to years)ruin_threshold (
float) – Wealth level considered as ruin (default 0)percentiles (
Optional[List[int]]) – List of percentiles to show (default [5, 25, 50, 75, 95])highlight_ruined (
bool) – Whether to highlight paths that hit ruinadd_survivor_bias_inset (
bool) – Whether to add survivor bias analysis insettitle (
str) – Plot titlelog_scale (
bool) – Whether to use log scale for wealth axis
- Return type:
- Returns:
Matplotlib figure showing path evolution
Examples
>>> n_paths, n_years = 1000, 100 >>> trajectories = np.random.lognormal(0, 0.2, (n_paths, n_years)).cumprod(axis=1) >>> fig = plot_path_dependent_wealth(trajectories)
- create_interactive_pareto_frontier(frontier_points: List[Any], objectives: List[str], title: str = 'Interactive Pareto Frontier', height: int = 600, show_dominated: bool = True) Figure[source]
Create interactive Plotly Pareto frontier visualization.
Creates an interactive visualization that automatically adapts to the number of objectives (2D scatter, 3D scatter, or parallel coordinates).
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with interactive Pareto frontier
- plot_correlation_structure(data: Dict[str, ndarray], correlation_type: str = 'pearson', risk_types: List[str] | None = None, title: str = 'Risk Correlation Structure', figsize: Tuple[float, float] = (14, 10), show_copula: bool = True) Figure[source]
Create correlation structure visualization with copula analysis (Figure B2).
Visualizes correlation matrices, copula density plots, and scatter plots with fitted copulas to show dependencies between different risk types.
- Parameters:
data (
Dict[str,ndarray]) – Dictionary mapping risk type names to data arrays (n_samples, n_variables)correlation_type (
str) – Type of correlation (‘pearson’, ‘spearman’, ‘kendall’)risk_types (
Optional[List[str]]) – List of risk types to analyze (defaults to all in data)title (
str) – Plot titleshow_copula (
bool) – Whether to show copula density plots
- Return type:
- Returns:
Matplotlib figure with correlation structure visualization
Examples
>>> data = { ... "operational": np.random.randn(1000, 3), ... "financial": np.random.randn(1000, 3) ... } >>> fig = plot_correlation_structure(data)
Create premium loading decomposition visualization (Figure C4).
Shows stacked bar charts breaking down insurance premium into components: expected loss (base), volatility load, tail load, expense load, and profit margin.
- Parameters:
premium_components (
Dict[str,Dict[str,Dict[str,float]]]) – Nested dict with structure: {company_size: {layer: {component: value}}} Components: ‘expected_loss’, ‘volatility_load’, ‘tail_load’, ‘expense_load’, ‘profit_margin’company_sizes (
Optional[List[str]]) – List of company sizes to show (defaults to all)layers (
Optional[List[str]]) – List of insurance layers to show (defaults to all)title (
str) – Plot titleshow_percentages (
bool) – Whether to show percentage labels on segmentscolor_scheme (
Optional[Dict[str,str]]) – Dict mapping component names to colors
- Return type:
- Returns:
Matplotlib figure with premium decomposition
Examples
>>> components = { ... "Small": { ... "Primary": {"expected_loss": 100, "volatility_load": 20, ... "tail_load": 15, "expense_load": 10, "profit_margin": 5} ... } ... } >>> fig = plot_premium_decomposition(components)
- plot_capital_efficiency_frontier_3d(efficiency_data: Dict[str, Dict[str, ndarray]], company_sizes: List[str] | None = None, optimal_paths: Dict[str, ndarray] | None = None, title: str = 'Capital Efficiency Frontier', figsize: Tuple[float, float] = (14, 10), view_angles: Tuple[float, float] | None = None, export_views: bool = False) Figure | List[Figure][source]
Create 3D capital efficiency frontier visualization (Figure C5).
Shows 3D surface plot with ROE, Ruin Probability, and Insurance Spend axes, with separate surfaces for each company size and highlighted optimal paths.
- Parameters:
efficiency_data (
Dict[str,Dict[str,ndarray]]) – Nested dict with structure:{company_size: {'roe': 2D array (n_ruin x n_spend), 'ruin_prob': 1D array (n_ruin), 'insurance_spend': 1D array (n_spend)}}company_sizes (
Optional[List[str]]) – List of company sizes to show (defaults to all)optimal_paths (
Optional[Dict[str,ndarray]]) – Dict mapping company size to optimal path coordinates:{company_size: array of shape (n_points, 3) with [roe, ruin, spend]}title (
str) – Plot titleview_angles (
Optional[Tuple[float,float]]) – Tuple of (elevation, azimuth) angles for 3D viewexport_views (
bool) – Whether to return multiple figures with different view angles
- Return type:
- Returns:
Single figure or list of figures with different viewing angles if export_views=True
Examples
>>> data = { ... "Small": { ... "roe": np.random.rand(20, 30), ... "ruin_prob": np.linspace(0, 0.1, 20), ... "insurance_spend": np.linspace(0, 1e6, 30) ... } ... } >>> fig = plot_capital_efficiency_frontier_3d(data)
- create_interactive_dashboard(results: Dict[str, Any] | DataFrame, title: str = 'Monte Carlo Simulation Dashboard', height: int = 600, show_distributions: bool = False) Figure[source]
Create interactive Plotly dashboard with WSJ styling.
Creates a comprehensive interactive dashboard with multiple panels showing simulation results, convergence, and risk metrics.
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with interactive dashboard
Examples
>>> results = { ... "growth_rates": np.random.normal(0.05, 0.02, 1000), ... "losses": np.random.lognormal(10, 2, 1000), ... "metrics": {"var_95": 100000, "var_99": 150000} ... } >>> fig = create_interactive_dashboard(results)
- create_time_series_dashboard(data: DataFrame, value_col: str, time_col: str = 'date', title: str = 'Time Series Analysis', height: int = 600, show_forecast: bool = False) Figure[source]
Create interactive time series visualization.
Creates an interactive time series plot with optional forecast bands and statistical overlays.
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with time series visualization
- create_correlation_heatmap(data: DataFrame, title: str = 'Correlation Matrix', height: int = 600, show_values: bool = True) Figure[source]
Create interactive correlation heatmap.
Creates an interactive heatmap showing correlations between variables with customizable color scheme and annotations.
- create_risk_dashboard(risk_metrics: Dict[str, Any], title: str = 'Risk Analytics Dashboard', height: int = 800) Figure[source]
Create comprehensive risk analytics dashboard.
Creates a multi-panel dashboard showing various risk metrics and distributions for comprehensive risk assessment.
- plot_scenario_comparison(aggregated_results: Any, metrics: List[str] | None = None, figsize: Tuple[float, float] = (14, 8), save_path: str | None = None) Figure[source]
Create comprehensive scenario comparison visualization.
Compares multiple scenarios across different metrics with bar charts highlighting the best performer for each metric.
- Parameters:
- Return type:
- Returns:
Matplotlib figure with scenario comparisons
Examples
>>> from ergodic_insurance.batch_processor import AggregatedResults >>> results = AggregatedResults(batch_results) >>> fig = plot_scenario_comparison(results, metrics=["mean_growth_rate"])
- plot_sensitivity_heatmap(aggregated_results: Any, metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (10, 8), save_path: str | None = None) Figure[source]
Create sensitivity analysis heatmap.
Visualizes sensitivity of outcomes to parameter changes using a horizontal bar chart color-coded by impact direction.
- plot_parameter_sweep_3d(aggregated_results: Any, param1: str, param2: str, metric: str = 'mean_growth_rate', height: int = 600, save_path: str | None = None) Figure[source]
Create 3D surface plot for parameter sweep results.
Visualizes how a metric varies across two parameter dimensions using an interactive 3D scatter plot.
- Parameters:
- Return type:
Figure- Returns:
Plotly figure with 3D parameter sweep
- plot_scenario_convergence(batch_results: List[Any], metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (12, 6), save_path: str | None = None) Figure[source]
Plot convergence of metric across scenarios.
Shows how a metric converges as more scenarios are processed, with execution time distribution.
- plot_parallel_scenarios(batch_results: List[Any], metrics: List[str], figsize: Tuple[float, float] = (12, 8), normalize: bool = True) Figure[source]
Create parallel coordinates plot for scenario comparison.
Visualizes multiple scenarios across multiple metrics using parallel coordinates for comprehensive comparison.
- add_value_labels(ax: Axes, bars, format_func=None, fontsize: int = 9, va: str = 'bottom', ha: str = 'center', offset: float = 0.01, color: str | None = None, bold: bool = False) None[source]
Add value labels to bar chart.
Adds formatted value labels on top of or inside bars in a bar chart.
- Parameters:
ax (
Axes) – Matplotlib axesbars – Bar container from ax.bar()
format_func – Optional function to format values
fontsize (
int) – Font size for labelsva (
str) – Vertical alignment (‘bottom’, ‘center’, ‘top’)ha (
str) – Horizontal alignment (‘left’, ‘center’, ‘right’)offset (
float) – Vertical offset as fraction of y-rangebold (
bool) – Whether to make text bold
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> bars = ax.bar(range(5), [10, 20, 15, 25, 30]) >>> add_value_labels(ax, bars)
- add_trend_annotation(ax: Axes, x_pos: float, y_pos: float, trend: float, period: str = 'YoY', fontsize: int = 10) None[source]
Add trend annotation with arrow.
Adds a trend annotation showing percentage change with an up/down arrow.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> add_trend_annotation(ax, 0.8, 0.9, 0.15, "YoY")
- add_callout(ax: Axes, text: str, xy: Tuple[float, float], xytext: Tuple[float, float], fontsize: int = 9, color: str | None = None, arrow_color: str | None = None, bbox_props: dict | None = None) None[source]
Add a callout annotation with arrow.
Creates a professional callout annotation with customizable styling.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> add_callout(ax, "Peak value", xy=(2, 4), xytext=(2.5, 4.5))
- add_benchmark_line(ax: Axes, value: float, label: str, color: str | None = None, linestyle: str = '--', linewidth: float = 1.5, fontsize: int = 9, position: str = 'right') None[source]
Add a horizontal benchmark line with label.
Draws a horizontal reference line with an integrated label.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot(range(10), np.random.randn(10)) >>> add_benchmark_line(ax, 0, "Average", color="red")
- add_shaded_region(ax: Axes, x_start: float, x_end: float, label: str | None = None, color: str | None = None, alpha: float = 0.2) None[source]
Add a shaded vertical region.
Creates a shaded vertical band to highlight a specific time period or range.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot(range(10), np.random.randn(10)) >>> add_shaded_region(ax, 3, 6, label="Recession", color="gray")
- add_data_source(fig, source: str, x: float = 0.99, y: float = 0.01, fontsize: int = 8, color: str | None = None) None[source]
Add data source attribution.
Adds a data source note to the figure, typically at the bottom right.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> add_data_source(fig, "Source: Internal Analysis")
- add_footnote(fig, text: str, x: float = 0.5, y: float = 0.02, fontsize: int = 8, color: str | None = None) None[source]
Add footnote to figure.
Adds a footnote or explanatory text to the bottom of the figure.
- Parameters:
- Return type:
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> add_footnote(fig, "* Preliminary data subject to revision")
- save_figure(fig: Figure | Figure, filename: str, dpi: int = 300, bbox_inches: str = 'tight', transparent: bool = False, formats: List[str] | None = None, metadata: Dict[str, Any] | None = None) List[str][source]
Save figure in multiple formats.
Saves a matplotlib or plotly figure to disk in one or more formats with professional quality settings.
- Parameters:
fig (
Union[Figure,Figure]) – Matplotlib Figure or Plotly Figure to savefilename (
str) – Base filename (without extension)dpi (
int) – Resolution for raster formatsbbox_inches (
str) – How to handle figure boundstransparent (
bool) – Whether to use transparent backgroundformats (
Optional[List[str]]) – List of formats to save (default: [‘png’])metadata (
Optional[Dict[str,Any]]) – Optional metadata to embed in files
- Return type:
- Returns:
List of saved file paths
- Raises:
ValueError – If unsupported format is requested
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> save_figure(fig, "my_plot", formats=["png", "pdf"]) ['my_plot.png', 'my_plot.pdf']
- save_for_publication(fig: Figure, filename: str, width: float = 7, height: float = 5, dpi: int = 600) str[source]
Save figure with publication-quality settings.
Exports a figure with settings optimized for academic publication or professional reports.
- Parameters:
- Return type:
- Returns:
Path to saved PDF file
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> save_for_publication(fig, "figure_1") 'figure_1.pdf'
- save_for_presentation(fig: Figure | Figure, filename: str, width: int = 1920, height: int = 1080) str[source]
Save figure optimized for presentations.
Exports a figure with settings optimized for PowerPoint or other presentation software.
- Parameters:
- Return type:
- Returns:
Path to saved file
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> save_for_presentation(fig, "slide_1") 'slide_1.png'
- save_for_web(fig: Figure | Figure, filename: str, optimize: bool = True) Dict[str, str][source]
Save figure optimized for web display.
Creates web-optimized versions of the figure including responsive formats and multiple resolutions.
- Parameters:
- Return type:
- Returns:
Dictionary of format to file path mappings
Examples
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 4, 2]) >>> files = save_for_web(fig, "chart") >>> print(files) {'thumbnail': 'chart_thumb.png', 'full': 'chart.png', 'svg': 'chart.svg'}
- batch_export(figures: Dict[str, Figure | Figure], output_dir: str, formats: List[str] | None = None, dpi: int = 300) Dict[str, List[str]][source]
Export multiple figures in batch.
Saves multiple figures to a directory with consistent settings.
- Parameters:
- Return type:
- Returns:
Dictionary mapping figure names to lists of saved files
Examples
>>> fig1, ax1 = plt.subplots() >>> fig2, ax2 = plt.subplots() >>> figures = {"chart1": fig1, "chart2": fig2} >>> batch_export(figures, "output/", formats=["png"])
- class FigureFactory(style_manager: StyleManager | None = None, theme: Theme = Theme.DEFAULT, auto_apply: bool = True)[source]
Bases:
objectFactory for creating standardized figures with consistent styling.
This class provides methods to create various types of plots with automatic application of themes, consistent formatting, and proper spacing.
Example
>>> factory = FigureFactory(theme=Theme.PRESENTATION) >>> fig, ax = factory.create_line_plot( ... x_data=[1, 2, 3, 4], ... y_data=[10, 20, 15, 25], ... title="Revenue Growth", ... x_label="Quarter", ... y_label="Revenue ($M)" ... )
>>> # Create multiple subplots >>> fig, axes = factory.create_subplots( ... rows=2, cols=2, ... size_type="large", ... subplot_titles=["Q1", "Q2", "Q3", "Q4"] ... )
- create_figure(size_type: str = 'medium', orientation: str = 'landscape', dpi_type: str = 'screen', title: str | None = None) Tuple[Figure, Axes][source]
Create a basic figure with styling applied.
- Parameters:
- Return type:
- Returns:
Tuple of (figure, axes)
- create_subplots(rows: int = 1, cols: int = 1, size_type: str = 'large', dpi_type: str = 'screen', title: str | None = None, subplot_titles: List[str] | None = None, **kwargs) Tuple[Figure, Axes | ndarray][source]
Create subplots with consistent styling.
- Parameters:
- Return type:
- Returns:
Tuple of (figure, axes array)
- create_line_plot(x_data: List | ndarray | Series, y_data: List | ndarray | Series | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', show_legend: bool = True, show_grid: bool = True, markers: bool = False, **kwargs) Tuple[Figure, Axes][source]
Create a line plot with automatic formatting.
- Parameters:
y_data (
Union[List,ndarray,Series,Dict[str,Union[List,ndarray]]]) – Y-axis data (can be multiple series as dict)size_type (
str) – Figure size presetdpi_type (
str) – DPI typeshow_legend (
bool) – Whether to show legendshow_grid (
bool) – Whether to show gridmarkers (
bool) – Whether to add markers to lines**kwargs – Additional arguments for plot
- Return type:
- Returns:
Tuple of (figure, axes)
- create_bar_plot(categories: List | ndarray, values: List | ndarray | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_values: bool = False, value_format: str = '.1f', **kwargs) Tuple[Figure, Axes][source]
Create a bar plot with automatic formatting.
- Parameters:
values (
Union[List,ndarray,Dict[str,Union[List,ndarray]]]) – Values to plot (can be multiple series as dict)size_type (
str) – Figure size presetdpi_type (
str) – DPI typeorientation (
str) – Bar orientation (vertical or horizontal)show_values (
bool) – Whether to show value labels on barsvalue_format (
str) – Format string for value labels**kwargs – Additional arguments for bar plot
- Return type:
- Returns:
Tuple of (figure, axes)
- create_scatter_plot(x_data: List | ndarray, y_data: List | ndarray, title: str | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', colors: List | ndarray | None = None, sizes: List | ndarray | None = None, labels: List[str] | None = None, show_colorbar: bool = False, **kwargs) Tuple[Figure, Axes][source]
Create a scatter plot with automatic formatting.
- Parameters:
size_type (
str) – Figure size presetdpi_type (
str) – DPI typecolors (
Union[List,ndarray,None]) – Optional colors for points (for continuous coloring)sizes (
Union[List,ndarray,None]) – Optional sizes for pointsshow_colorbar (
bool) – Whether to show colorbar when colors provided**kwargs – Additional arguments for scatter
- Return type:
- Returns:
Tuple of (figure, axes)
- create_histogram(data: List | ndarray | Series, title: str | None = None, x_label: str | None = None, y_label: str = 'Frequency', bins: int | str = 'auto', size_type: str = 'medium', dpi_type: str = 'screen', show_statistics: bool = False, show_kde: bool = False, **kwargs) Tuple[Figure, Axes][source]
Create a histogram with automatic formatting.
- create_heatmap(data: ndarray | DataFrame, title: str | None = None, x_labels: List[str] | None = None, y_labels: List[str] | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', cmap: str = 'RdBu_r', show_values: bool = True, value_format: str = '.2f', **kwargs) Tuple[Figure, Axes][source]
Create a heatmap with automatic formatting.
- Parameters:
- Return type:
- Returns:
Tuple of (figure, axes)
- create_box_plot(data: List[List] | Dict[str, List] | DataFrame, title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_means: bool = True, **kwargs) Tuple[Figure, Axes][source]
Create a box plot with automatic formatting.
- Parameters:
data (
Union[List[List],Dict[str,List],DataFrame]) – Data for box plot (list of lists, dict, or DataFrame)size_type (
str) – Figure size presetdpi_type (
str) – DPI typeorientation (
str) – Plot orientation (vertical or horizontal)show_means (
bool) – Whether to show mean markers**kwargs – Additional arguments for boxplot
- Return type:
- Returns:
Tuple of (figure, axes)
- format_axis_currency(ax: Axes, axis: str = 'y', abbreviate: bool = True, decimals: int = 0) None[source]
Format axis labels as currency.
- format_axis_percentage(ax: Axes, axis: str = 'y', decimals: int = 0) None[source]
Format axis labels as percentages.
- add_annotations(ax: Axes, x: float, y: float, text: str, arrow: bool = True, offset: Tuple[float, float] = (10, 10), **kwargs) None[source]
Add styled annotation to plot.
- class StyleManager(theme: Theme = Theme.DEFAULT, config_path: str | Path | None = None, custom_colors: Dict[str, str] | None = None, custom_fonts: Dict[str, Any] | None = None)[source]
Bases:
objectManages visualization styles and themes.
This class provides centralized style management for all visualizations, supporting multiple themes, custom configurations, and style inheritance.
Example
>>> style_mgr = StyleManager() >>> style_mgr.set_theme(Theme.PRESENTATION) >>> style_mgr.apply_style() >>> # Create plots with consistent styling
>>> # Or with custom configuration >>> style_mgr = StyleManager(config_path="custom_style.yaml") >>> style_mgr.apply_style()
- get_colors() ColorPalette[source]
Get current color palette.
- Return type:
- Returns:
Current theme’s color palette
- get_fonts() FontConfig[source]
Get current font configuration.
- Return type:
- Returns:
Current theme’s font configuration
- get_figure_config() FigureConfig[source]
Get current figure configuration.
- Return type:
- Returns:
Current theme’s figure configuration
- get_grid_config() GridConfig[source]
Get current grid configuration.
- Return type:
- Returns:
Current theme’s grid configuration
- apply_style() None[source]
Apply current theme to matplotlib.
This updates matplotlib’s rcParams to match the current theme settings.
- Return type:
- get_figure_size(size_type: str = 'medium', orientation: str = 'landscape') Tuple[float, float][source]
Get figure size for a given type.