ergodic_insurance.reporting package
Submodules
ergodic_insurance.reporting.cache_manager module
High-performance caching system for expensive Monte Carlo computations.
This module implements a robust caching system that stores Monte Carlo simulation results and processed data using efficient storage formats (HDF5, Parquet) with hash-based invalidation and memory-mapped loading for optimal performance.
- The caching system achieves:
<1 second load time for 10,000 paths × 1,000 years
Automatic cache invalidation on parameter changes
Memory-efficient loading with memory mapping
Support for both local and cloud storage backends
Example
>>> from ergodic_insurance.reporting import CacheManager
>>> cache = CacheManager()
>>> # Cache expensive simulation
>>> key = cache.cache_simulation_paths(
... params={'n_sims': 10000, 'n_years': 1000},
... paths=simulation_data,
... metadata={'seed': 42}
... )
>>> # Load from cache (100x faster)
>>> cached_paths = cache.load_simulation_paths(params)
- class StorageBackend(*values)[source]
Bases:
EnumSupported storage backend types.
- LOCAL = 'local'
- S3 = 's3'
- AZURE = 'azure'
- GCS = 'gcs'
- class CacheConfig(cache_dir: Path = PosixPath('cache'), max_cache_size_gb: float = 10.0, ttl_hours: int | None = None, compression: str | None = 'gzip', compression_level: int = 4, enable_memory_mapping: bool = True, backend: StorageBackend = StorageBackend.LOCAL, backend_config: Dict[str, ~typing.Any]=<factory>) None[source]
Bases:
objectConfiguration for the cache manager.
- cache_dir
Root directory for cache storage
- max_cache_size_gb
Maximum cache size in gigabytes
- ttl_hours
Time-to-live for cache entries in hours
- compression
Compression algorithm for HDF5 (‘gzip’, ‘lzf’, None)
- compression_level
Compression level (1-9 for gzip)
- enable_memory_mapping
Use memory mapping for large files
- backend
Storage backend type
- backend_config
Backend-specific configuration
- backend: StorageBackend = 'local'
- class CacheStats(total_size_bytes: int = 0, n_entries: int = 0, n_hits: int = 0, n_misses: int = 0, hit_rate: float = 0.0, avg_load_time_ms: float = 0.0, avg_save_time_ms: float = 0.0, oldest_entry: datetime | None = None, newest_entry: datetime | None = None) None[source]
Bases:
objectStatistics about cache usage and performance.
- total_size_bytes
Total size of cached data
- n_entries
Number of cache entries
- n_hits
Number of cache hits
- n_misses
Number of cache misses
- hit_rate
Cache hit rate (0-1)
- avg_load_time_ms
Average load time in milliseconds
- avg_save_time_ms
Average save time in milliseconds
- oldest_entry
Timestamp of oldest cache entry
- newest_entry
Timestamp of newest cache entry
- class CacheKey(hash_key: str, params: ~typing.Dict[str, ~typing.Any], timestamp: ~datetime.datetime = <factory>, size_bytes: int = 0, access_count: int = 0, last_accessed: ~datetime.datetime = <factory>) None[source]
Bases:
objectCache key with metadata for cache entries.
- hash_key
SHA256 hash of parameters
- params
Original parameters dictionary
- timestamp
Creation timestamp
- size_bytes
Size of cached data
- access_count
Number of times accessed
- last_accessed
Last access timestamp
- class BaseStorageBackend[source]
Bases:
ABCAbstract base class for storage backends.
- abstractmethod save(path: Path, data: Any, file_format: str = 'pickle') int[source]
Save data to path, return size in bytes.
- Return type:
- abstractmethod load(path: Path, file_format: str = 'pickle') Any[source]
Load data from path.
- Return type:
- class LocalStorageBackend(root_dir: Path)[source]
Bases:
BaseStorageBackendLocal filesystem storage backend.
- save(path: Path, data: Any, file_format: str = 'pickle') int[source]
Save data to path.
- Return type:
- class CacheManager(config: CacheConfig | None = None)[source]
Bases:
objectHigh-performance cache manager for Monte Carlo simulations.
This class provides efficient caching of simulation results with automatic invalidation, memory-mapped loading, and configurable storage backends.
- config
Cache configuration
- stats
Cache statistics
- backend
Storage backend instance
Example
>>> cache = CacheManager(config=CacheConfig(cache_dir="./cache")) >>> # Cache simulation results >>> cache.cache_simulation_paths( ... params={'n_sims': 10000}, ... paths=np.random.randn(10000, 100) ... ) >>> # Load from cache >>> paths = cache.load_simulation_paths({'n_sims': 10000})
- cache_simulation_paths(params: Dict[str, Any], paths: ndarray, metadata: Dict[str, Any] | None = None) str[source]
Cache Monte Carlo simulation paths to HDF5.
Stores large simulation arrays efficiently using HDF5 with optional compression. Supports arrays up to 10,000 x 1,000 dimensions.
- Parameters:
- Return type:
- Returns:
Cache key for retrieval
Example
>>> paths = np.random.randn(10000, 1000) >>> key = cache.cache_simulation_paths( ... params={'n_sims': 10000, 'seed': 42}, ... paths=paths, ... metadata={'generator': 'numpy'} ... )
- load_simulation_paths(params: Dict[str, Any], memory_map: bool | None = None) ndarray | None[source]
Load simulation paths from cache.
Retrieves cached simulation data with optional memory mapping for efficient loading of large arrays.
- Parameters:
- Return type:
- Returns:
Numpy array of paths or None if not cached
Example
>>> paths = cache.load_simulation_paths( ... params={'n_sims': 10000, 'seed': 42} ... ) >>> if paths is not None: ... print(f"Loaded {paths.shape} from cache")
- cache_processed_results(params: Dict[str, Any], results: DataFrame, result_type: str = 'generic') str[source]
Cache processed results as Parquet.
Stores tabular results efficiently using Parquet format with columnar compression for fast queries.
- Parameters:
- Return type:
- Returns:
Cache key for retrieval
Example
>>> df = pd.DataFrame({'limit': [1e6, 2e6], 'premium': [1e4, 2e4]}) >>> key = cache.cache_processed_results( ... params={'optimization': 'pareto'}, ... results=df, ... result_type='efficient_frontier' ... )
- load_processed_results(params: Dict[str, Any], result_type: str = 'generic') DataFrame | None[source]
Load processed results from cache.
Retrieves cached tabular results from Parquet storage.
- Parameters:
- Return type:
Optional[DataFrame]- Returns:
DataFrame with results or None if not cached
Example
>>> df = cache.load_processed_results( ... params={'optimization': 'pareto'}, ... result_type='efficient_frontier' ... )
- cache_figure(params: Dict[str, Any], figure: Any, figure_name: str, figure_type: str = 'technical', file_format: str = 'pickle') str[source]
Cache matplotlib or plotly figure.
Stores figure objects with metadata for fast regeneration.
- Parameters:
- Return type:
- Returns:
Cache key for retrieval
- clear_cache(confirm: bool = True)[source]
Clear all cached data.
- Parameters:
confirm (
bool) – Require confirmation before clearing
- get_cache_stats() CacheStats[source]
Get current cache statistics.
- Return type:
- Returns:
CacheStats object with usage information
- warm_cache(scenarios: List[Dict[str, Any]], compute_func: Callable[[Dict[str, Any]], Any], result_type: str = 'simulation') int[source]
Pre-compute and cache results for common scenarios.
- Parameters:
- Return type:
- Returns:
Number of scenarios cached
Example
>>> scenarios = [ ... {'n_sims': 1000, 'seed': i} for i in range(10) ... ] >>> n_cached = cache.warm_cache( ... scenarios, ... lambda p: np.random.randn(p['n_sims'], 100) ... )
ergodic_insurance.reporting.config module
Configuration schema for report generation system.
This module defines Pydantic models for configuring various types of reports, including sections, figures, tables, and formatting options.
- class FigureConfig(**data: Any) None[source]
Bases:
BaseModelConfiguration for a figure in a report.
- name
Figure identifier name.
- caption
Caption text for the figure.
- source
Source file path or generation function.
- width
Figure width in inches.
- height
Figure height in inches.
- dpi
Resolution in dots per inch.
- position
LaTeX-style position hint.
- cache_key
Optional cache key for pre-generated figures.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class TableConfig(**data: Any) None[source]
Bases:
BaseModelConfiguration for a table in a report.
- name
Table identifier name.
- caption
Caption text for the table.
- data_source
Source of data (file path or function).
- format
Output format for the table.
- columns
List of columns to include.
- index
Whether to include row index.
- precision
Number of decimal places for numeric values.
- style
Table styling options.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class SectionConfig(**data: Any) None[source]
Bases:
BaseModelConfiguration for a report section.
- title
Section title.
- level
Heading level (1-4).
- content
Text content or template name.
- figures
List of figures to include.
- tables
List of tables to include.
- subsections
Nested subsections.
- page_break
Whether to start on new page.
- figures: List[FigureConfig]
- tables: List[TableConfig]
- subsections: List[SectionConfig]
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class ReportMetadata(**data: Any) None[source]
Bases:
BaseModelMetadata for a report.
- title
Report title.
- subtitle
Optional subtitle.
- authors
List of author names.
- date
Report generation date.
- version
Report version.
- organization
Organization name.
- confidentiality
Confidentiality level.
- keywords
List of keywords.
- abstract
Brief abstract or summary.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class ReportStyle(**data: Any) None[source]
Bases:
BaseModelStyling configuration for reports.
- font_family
Main font family.
- font_size
Base font size in points.
- line_spacing
Line spacing multiplier.
- margins
Page margins in inches.
- page_size
Paper size.
- orientation
Page orientation.
Include headers and footers.
- page_numbers
Include page numbers.
- color_scheme
Color scheme for charts.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class ReportConfig(**data: Any) None[source]
Bases:
BaseModelComplete configuration for a report.
- metadata
Report metadata.
- style
Report styling.
- sections
List of report sections.
- template
Template type to use.
- output_formats
List of output formats to generate.
- output_dir
Directory for output files.
- cache_dir
Directory for cached figures.
- debug
Enable debug mode.
- metadata: ReportMetadata
- style: ReportStyle
- sections: List[SectionConfig]
- classmethod from_yaml(path: str | Path) ReportConfig[source]
Load configuration from YAML file.
- Parameters:
- Return type:
- Returns:
ReportConfig instance.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- create_executive_config() ReportConfig[source]
Create default configuration for executive report.
- Return type:
- Returns:
ReportConfig for executive summary.
- create_technical_config() ReportConfig[source]
Create default configuration for technical report.
- Return type:
- Returns:
ReportConfig for technical appendix.
ergodic_insurance.reporting.executive_report module
Executive report generation for insurance optimization analysis.
This module provides the ExecutiveReport class that generates concise, high-level reports targeted at executive audiences.
- class ExecutiveReport(results: Dict[str, Any], config: ReportConfig | None = None, cache_dir: Path | None = None)[source]
Bases:
ReportBuilderGenerate executive summary reports.
This class creates concise, visually-rich reports designed for executive audiences, focusing on key findings, recommendations, and decision-critical information.
- results
Simulation or analysis results.
- style_manager
Visualization style manager.
- key_metrics
Dictionary of key performance metrics.
- generate() Path[source]
Generate the executive report.
- Return type:
- Returns:
Path to generated report file.
- generate_roe_frontier(fig_config: FigureConfig) Figure[source]
Generate ROE-Ruin frontier plot.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- generate_performance_table() DataFrame[source]
Generate performance metrics table.
- Return type:
DataFrame- Returns:
Performance metrics DataFrame.
- generate_decision_matrix() DataFrame[source]
Generate decision matrix table.
- Return type:
DataFrame- Returns:
Decision matrix DataFrame.
- generate_convergence_plot(fig_config: FigureConfig) Figure[source]
Generate convergence diagnostics plot.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
ergodic_insurance.reporting.formatters module
Formatting utilities for table generation and report creation.
This module provides comprehensive formatting functions for numbers, currency, percentages, and color coding for tables in various output formats.
Google-style docstrings are used throughout for consistency.
- class NumberFormatter(currency_symbol: str = '$', decimal_places: int = 2, thousands_separator: str = ',', decimal_separator: str = '.')[source]
Bases:
objectFormat numbers for display in tables and reports.
This class provides methods to format various numeric types including currency, percentages, and scientific notation with consistent precision and locale-aware formatting.
- currency_symbol
Symbol to use for currency formatting.
- decimal_places
Default number of decimal places.
- thousands_separator
Character for thousands separation.
- decimal_separator
Character for decimal separation.
- format_currency(value: float | int | Decimal, decimals: int | None = None, abbreviate: bool = False) str[source]
Format a number as currency.
- Parameters:
- Return type:
- Returns:
Formatted currency string.
Examples
>>> formatter = NumberFormatter() >>> formatter.format_currency(1234567.89) '$1,234,567.89' >>> formatter.format_currency(1234567.89, abbreviate=True) '$1.23M'
- format_percentage(value: float | int, decimals: int | None = None, multiply_by_100: bool = True) str[source]
Format a number as percentage.
- Parameters:
- Return type:
- Returns:
Formatted percentage string.
Examples
>>> formatter = NumberFormatter() >>> formatter.format_percentage(0.1234) '12.34%' >>> formatter.format_percentage(12.34, multiply_by_100=False) '12.34%'
- format_number(value: float | int, decimals: int | None = None, scientific: bool = False, abbreviate: bool = False) str[source]
Format a general number.
- Parameters:
- Return type:
- Returns:
Formatted number string.
Examples
>>> formatter = NumberFormatter() >>> formatter.format_number(1234567.89) '1,234,567.89' >>> formatter.format_number(0.00001234, scientific=True) '1.23e-05'
- class ColorCoder(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', color_scheme: Dict[str, str] | None = None)[source]
Bases:
objectApply color coding to values for visual indicators.
This class provides methods for traffic light coloring, heatmaps, and threshold-based coloring for different output formats.
- output_format
Target output format (html, latex, terminal).
- color_scheme
Color scheme to use.
- TRAFFIC_LIGHT = {'bad': '#dc3545', 'good': '#28a745', 'warning': '#ffc107'}
- HEATMAP_COLORS = {'high': '#ef5350', 'low': '#e3f2fd', 'medium': '#42a5f5', 'medium_high': '#ffb74d', 'medium_low': '#90caf9'}
- traffic_light(value: float | int, thresholds: Dict[str, Tuple[float | None, float | None]], text: str | None = None) str[source]
Apply traffic light coloring based on thresholds.
- Parameters:
- Return type:
- Returns:
Formatted string with appropriate coloring.
Examples
>>> coder = ColorCoder(output_format="html") >>> thresholds = { ... 'good': (0.15, None), ... 'warning': (0.10, 0.15), ... 'bad': (None, 0.10) ... } >>> coder.traffic_light(0.18, thresholds) '<span style="color: #28a745;">0.18</span>'
- heatmap(value: float | int, min_val: float, max_val: float, text: str | None = None) str[source]
Apply heatmap coloring based on value range.
- Parameters:
- Return type:
- Returns:
Formatted string with heatmap coloring.
Examples
>>> coder = ColorCoder(output_format="html") >>> coder.heatmap(50, 0, 100) '<span style="background-color: #42a5f5;">50</span>'
- class TableFormatter(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', currency_symbol: str = '$', decimal_places: int = 2)[source]
Bases:
objectHigh-level table formatting utilities.
This class combines number formatting and color coding to provide comprehensive table formatting capabilities.
- number_formatter
NumberFormatter instance.
- color_coder
ColorCoder instance.
- format_dataframe(df: DataFrame, column_formats: Dict[str, Dict[str, Any]] | None = None, row_colors: Dict[int, str] | None = None, alternating_rows: bool = False) DataFrame[source]
Apply formatting to entire DataFrame.
- Parameters:
- Return type:
DataFrame- Returns:
Formatted DataFrame.
Examples
>>> formatter = TableFormatter() >>> formats = { ... 'Revenue': {'type': 'currency', 'abbreviate': True}, ... 'Growth': {'type': 'percentage'}, ... 'Risk': {'type': 'traffic_light', 'thresholds': {...}} ... } >>> formatted_df = formatter.format_dataframe(df, formats)
- add_totals_row(df: DataFrame, columns: List[str] | None = None, label: str = 'Total', operation: Literal['sum', 'mean', 'median'] = 'sum') DataFrame[source]
Add a totals row to DataFrame.
- format_for_export(df: DataFrame, export_format: Literal['csv', 'excel', 'latex', 'html', 'markdown'], include_index: bool = False, **kwargs) str | None[source]
Format DataFrame for export to various formats.
- Parameters:
- Return type:
- Returns:
Formatted string or None for file-based exports.
Examples
>>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) >>> csv_str = format_for_export(df, 'csv') >>> latex_str = format_for_export(df, 'latex', caption='My Table')
ergodic_insurance.reporting.insight_extractor module
Insight extraction and natural language generation for analysis results.
This module provides tools for automatically extracting key insights from simulation results and generating natural language descriptions.
- class Insight(category: str, importance: float, title: str, description: str, data: Dict[str, ~typing.Any]=<factory>, metrics: List[str] = <factory>, confidence: float = 1.0) None[source]
Bases:
objectContainer for a single insight.
- category
Type of insight (trend, outlier, correlation, etc.)
- importance
Importance score (0-100)
- title
Short title for the insight
- description
Detailed description
- data
Supporting data for the insight
- metrics
Related metrics
- confidence
Confidence level (0-1)
- class InsightExtractor[source]
Bases:
objectExtract and generate insights from simulation results.
- TEMPLATES = {'best_performer': 'The {scenario} scenario achieved the best {metric} at {value}, outperforming the baseline by {improvement}%', 'convergence': '{metric} converges to {value} after {period} periods, indicating stability', 'correlation': 'Strong {direction} correlation ({corr}) detected between {metric1} and {metric2}', 'dominance': '{scenario} dominates on {count} out of {total} metrics, suggesting overall superiority', 'inflection': 'Key inflection point identified at period {period} where {metric} shifts from {before} to {after}', 'outlier_high': '{scenario} exhibits exceptionally high {metric} ({value}), {std_dev} standard deviations above mean', 'outlier_low': '{scenario} shows unusually low {metric} ({value}), {std_dev} standard deviations below mean', 'threshold_exceeded': '{metric} exceeded the critical threshold of {threshold} in {count} scenarios', 'trend_negative': '{metric} displays concerning decline, decreasing by {change}% from {start} to {end}', 'trend_positive': '{metric} shows a strong positive trend, increasing by {change}% from {start} to {end}', 'volatility_high': '{scenario} demonstrates high volatility in {metric} with coefficient of variation {cv}', 'worst_performer': 'The {scenario} scenario showed the weakest {metric} at {value}, underperforming by {decline}%'}
- extract_insights(data: Any, focus_metrics: List[str] | None = None, threshold_importance: float = 50.0) List[Insight][source]
Extract insights from simulation data.
- Parameters:
- Return type:
- Returns:
List of extracted insights
Examples
>>> extractor = InsightExtractor() >>> insights = extractor.extract_insights(results) >>> for insight in insights[:3]: ... print(insight.to_bullet_point())
- generate_executive_summary(max_points: int = 5, focus_positive: bool = True) str[source]
Generate executive summary from insights.
ergodic_insurance.reporting.report_builder module
Base report builder class for automated report generation.
This module provides the core ReportBuilder class that handles report compilation, figure embedding, section management, and content generation.
- class ReportBuilder(config: ReportConfig, cache_dir: Path | None = None)[source]
Bases:
ABCBase class for building automated reports.
This abstract base class provides common functionality for generating different types of reports, including section management, figure embedding, and template rendering.
- config
Report configuration object.
- cache_manager
Cache manager for figures and data.
- table_generator
Table generation utility.
- content
Accumulated report content.
- figures
List of generated figures.
- tables
List of generated tables.
- abstractmethod generate() Path[source]
Generate the complete report.
- Return type:
- Returns:
Path to generated report file.
- build_section(section: SectionConfig) str[source]
Build a report section.
- Parameters:
section (
SectionConfig) – Section configuration.- Return type:
- Returns:
Formatted section content.
ergodic_insurance.reporting.scenario_comparator module
Scenario comparison framework for analyzing multiple simulation results.
This module provides comprehensive tools for comparing different scenarios, highlighting parameter differences, and performing statistical comparisons.
- class ScenarioComparison(scenarios: ~typing.List[str], metrics: ~typing.Dict[str, ~typing.Dict[str, float]], parameters: ~typing.Dict[str, ~typing.Dict[str, ~typing.Any]], statistics: ~typing.Dict[str, ~typing.Any] = <factory>, diffs: ~typing.Dict[str, ~typing.Dict[str, ~typing.Any]] = <factory>, rankings: ~typing.Dict[str, ~typing.List[~typing.Tuple[str, float]]] = <factory>) None[source]
Bases:
objectContainer for scenario comparison results.
- scenarios
List of scenario names
- metrics
Dictionary of metric values by scenario
- parameters
Dictionary of parameter values by scenario
- statistics
Statistical comparison results
- diffs
Parameter differences from baseline
- rankings
Scenario rankings by metric
- get_metric_df(metric: str) DataFrame[source]
Get metric values as DataFrame.
- Parameters:
metric (
str) – Metric name- Return type:
DataFrame- Returns:
DataFrame with scenarios and metric values
- class ScenarioComparator[source]
Bases:
objectFramework for comparing multiple simulation scenarios.
- comparison_data: ScenarioComparison | None
- compare_scenarios(results: Dict[str, Any], baseline: str | None = None, metrics: List[str] | None = None, parameters: List[str] | None = None) ScenarioComparison[source]
Compare multiple scenarios with comprehensive analysis.
- Parameters:
- Return type:
- Returns:
ScenarioComparison object with analysis results
Examples
>>> comparator = ScenarioComparator() >>> results = {'base': {...}, 'optimized': {...}} >>> comparison = comparator.compare_scenarios(results)
- create_comparison_grid(metrics: List[str] | None = None, figsize: Tuple[float, float] = (16, 10), show_diff: bool = True) Figure[source]
Create comprehensive comparison visualization grid.
- create_parameter_diff_table(scenario: str, threshold: float = 5.0) DataFrame[source]
Create table showing parameter differences from baseline.
ergodic_insurance.reporting.table_generator module
Table generation utilities for report creation.
This module provides functions to generate and format tables from various data sources, supporting multiple output formats including Markdown, HTML, and LaTeX.
- class TableGenerator(default_format: Literal['markdown', 'html', 'latex', 'grid', 'csv', 'excel'] = 'markdown', precision: int = 2, max_width: int = 50, currency_symbol: str = '$')[source]
Bases:
objectGenerate formatted tables for reports.
This class provides methods to create professionally formatted tables from pandas DataFrames or raw data, supporting various output formats and styling options. Enhanced with comprehensive table generation methods for executive and technical reports.
- default_format
Default output format for tables.
- precision
Default precision for numeric values.
- max_width
Maximum width for text columns.
- number_formatter
NumberFormatter instance for formatting.
- color_coder
ColorCoder instance for color coding.
- table_formatter
TableFormatter instance for comprehensive formatting.
- generate(data: DataFrame | Dict | List, caption: str = '', columns: List[str] | None = None, index: bool = False, output_format: str | None = None, precision: int | None = None, style: Dict[str, Any] | None = None) str[source]
Generate a formatted table from data.
- Parameters:
data (
Union[DataFrame,Dict,List]) – Input data (DataFrame, dict, or list).caption (
str) – Table caption.columns (
Optional[List[str]]) – Columns to include (None for all).index (
bool) – Whether to include row index.output_format (
Optional[str]) – Output format (uses default if None).precision (
Optional[int]) – Decimal precision (uses default if None).style (
Optional[Dict[str,Any]]) – Additional styling options.
- Return type:
- Returns:
Formatted table string.
Examples
>>> gen = TableGenerator() >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) >>> print(gen.generate(df, caption="Sample Table"))
- generate_summary_statistics(df: DataFrame, metrics: List[str] | None = None, output_format: str | None = None) str[source]
Generate summary statistics table.
- generate_comparison_table(data: Dict[str, Series], caption: str = 'Comparison Table', output_format: str | None = None) str[source]
Generate comparison table from multiple series.
- generate_decision_matrix(alternatives: List[str], criteria: List[str], scores: ndarray, weights: List[float] | None = None, output_format: str | None = None) str[source]
Generate a decision matrix table.
- Parameters:
- Return type:
- Returns:
Formatted decision matrix.
- generate_optimal_limits_by_size(company_sizes: List[float], optimal_limits: Dict[float, Dict[str, float]], output_format: str | None = None, include_percentages: bool = True) str[source]
Generate Table 1: Optimal Insurance Limits by Company Size.
Creates a comprehensive table showing optimal insurance structures for different company sizes, including retention, primary limits, excess limits, and total premiums.
- Parameters:
- Return type:
- Returns:
Formatted table string.
Examples
>>> gen = TableGenerator() >>> sizes = [1_000_000, 10_000_000, 100_000_000] >>> limits = { ... 1_000_000: {'retention': 50000, 'primary': 500000, ... 'excess': 1000000, 'premium': 25000}, ... # ... more sizes ... } >>> table = gen.generate_optimal_limits_by_size(sizes, limits)
- generate_quick_reference_matrix(characteristics: List[str], recommendations: Dict[str, Dict[str, Any]], output_format: str | None = None, use_traffic_lights: bool = True) str[source]
Generate Table 2: Quick Reference Decision Matrix.
Creates a decision matrix with company characteristics as rows and recommended insurance structures as columns, with optional traffic light coloring for visual indicators.
- Parameters:
- Return type:
- Returns:
Formatted decision matrix table.
Examples
>>> gen = TableGenerator() >>> chars = ['High Growth', 'Stable', 'Distressed'] >>> recs = { ... 'High Growth': {'retention': 'Low', 'coverage': 'High', ... 'premium_budget': '2-3%', 'risk_level': 'good'}, ... # ... more recommendations ... } >>> table = gen.generate_quick_reference_matrix(chars, recs)
- generate_parameter_grid(parameters: Dict[str, Dict[str, Any]], scenarios: List[str] | None = None, output_format: str | None = None) str[source]
Generate Table A1: Complete Parameter Grid.
Creates a comprehensive parameter grid showing all simulation parameters with ranges for different scenarios.
- Parameters:
- Return type:
- Returns:
Formatted parameter grid table.
Examples
>>> gen = TableGenerator() >>> params = { ... 'Growth': {'mean': [0.05, 0.08, 0.12], 'volatility': [0.15, 0.20, 0.30]}, ... 'Losses': {'frequency': [3, 5, 8], 'severity': [50000, 100000, 200000]} ... } >>> table = gen.generate_parameter_grid(params)
- generate_loss_distribution_params(loss_types: List[str], distribution_params: Dict[str, Dict[str, Any]], output_format: str | None = None, include_correlations: bool = True) str[source]
Generate Table A2: Loss Distribution Parameters.
Creates a table showing frequency and severity parameters for different loss types, including correlation coefficients and development patterns.
- Parameters:
- Return type:
- Returns:
Formatted loss distribution parameters table.
- generate_insurance_pricing_grid(layers: List[Tuple[float, float]], pricing_params: Dict[Tuple[float, float], Dict[str, float]], output_format: str | None = None) str[source]
Generate Table A3: Insurance Pricing Grid.
Creates a pricing grid showing premium rates by layer and attachment point, including loading factors.
- Parameters:
- Return type:
- Returns:
Formatted insurance pricing grid.
Examples
>>> gen = TableGenerator() >>> layers = [(0, 1_000_000), (1_000_000, 5_000_000)] >>> pricing = { ... (0, 1_000_000): {'rate': 0.015, 'loading': 1.3}, ... (1_000_000, 5_000_000): {'rate': 0.008, 'loading': 1.2} ... } >>> table = gen.generate_insurance_pricing_grid(layers, pricing)
- generate_statistical_validation(metrics: Dict[str, Dict[str, float]], output_format: str | None = None, include_thresholds: bool = True) str[source]
Generate Table B1: Statistical Validation Metrics.
Creates a table of statistical validation metrics including goodness-of-fit tests, convergence statistics, and out-of-sample performance.
- generate_comprehensive_results(results: List[Dict[str, Any]], ranking_metric: str = 'roe', output_format: str | None = None, top_n: int | None = None) str[source]
Generate Table C1: Comprehensive Optimization Results.
Creates a comprehensive results table showing all parameter combinations tested with ranking by specified metric.
- Parameters:
- Return type:
- Returns:
Formatted comprehensive results table.
- generate_walk_forward_validation(validation_results: List[Dict[str, Any]], output_format: str | None = None) str[source]
Generate Table C2: Walk-Forward Validation Results.
Creates a table showing rolling window analysis results and strategy stability metrics over time.
- create_performance_table(results: Dict[str, Any]) str[source]
Create a performance metrics table from simulation results.
ergodic_insurance.reporting.technical_report module
Technical report generation for detailed analysis documentation.
This module provides the TechnicalReport class that generates comprehensive technical appendices with methodology, validation, and detailed results.
- class TechnicalReport(results: Dict[str, Any], parameters: Dict[str, Any], config: ReportConfig | None = None, cache_dir: Path | None = None)[source]
Bases:
ReportBuilderGenerate detailed technical reports.
This class creates comprehensive technical documentation including methodology, mathematical proofs, statistical validation, and detailed analysis results.
- results
Complete analysis results.
- parameters
Model parameters used.
- validation_metrics
Validation and convergence metrics.
- generate() Path[source]
Generate the technical report.
- Return type:
- Returns:
Path to generated report file.
- generate_parameter_sensitivity_plot(fig_config: FigureConfig) Figure[source]
Generate parameter sensitivity tornado plot.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- generate_qq_plot(fig_config: FigureConfig) Figure[source]
Generate Q-Q plot for distribution validation.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- generate_model_parameters_table() DataFrame[source]
Generate comprehensive model parameters table.
- Return type:
DataFrame- Returns:
Parameters DataFrame.
- generate_correlation_matrix_plot(fig_config: FigureConfig) Figure[source]
Generate correlation matrix heatmap.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
ergodic_insurance.reporting.validator module
Report validation and quality control utilities.
This module provides validation functions to ensure report completeness, accuracy, and quality before generation.
- class ReportValidator(config: ReportConfig)[source]
Bases:
objectValidate report configuration and content.
This class provides comprehensive validation for report configurations, ensuring all references are valid, data is complete, and quality standards are met.
- config
Report configuration to validate.
- errors
List of validation errors.
- warnings
List of validation warnings.
Module contents
Reporting and caching infrastructure with automated report generation.
This module provides comprehensive report generation capabilities along with high-performance caching for Monte Carlo simulations and analysis results.
- Key Features:
Automated report generation (Executive & Technical)
Configurable report structures
Table generation utilities
Multi-format output (Markdown, HTML, PDF)
Report validation and quality checks
HDF5 storage for large simulation data
Parquet support for structured results
Hash-based cache invalidation
Memory-mapped reading for efficiency
Configurable storage backends
Example
>>> from ergodic_insurance.reporting import ExecutiveReport, CacheManager
>>> # Generate executive report
>>> report = ExecutiveReport(results={'roe': 0.18, 'ruin_probability': 0.01})
>>> report_path = report.generate()
>>>
>>> # Use caching for simulations
>>> cache = CacheManager(cache_dir="./cache")
>>> cache.cache_simulation_paths(params, paths, metadata={'n_sims': 10000})
- class CacheManager(config: CacheConfig | None = None)[source]
Bases:
objectHigh-performance cache manager for Monte Carlo simulations.
This class provides efficient caching of simulation results with automatic invalidation, memory-mapped loading, and configurable storage backends.
- config
Cache configuration
- stats
Cache statistics
- backend
Storage backend instance
Example
>>> cache = CacheManager(config=CacheConfig(cache_dir="./cache")) >>> # Cache simulation results >>> cache.cache_simulation_paths( ... params={'n_sims': 10000}, ... paths=np.random.randn(10000, 100) ... ) >>> # Load from cache >>> paths = cache.load_simulation_paths({'n_sims': 10000})
- cache_simulation_paths(params: Dict[str, Any], paths: ndarray, metadata: Dict[str, Any] | None = None) str[source]
Cache Monte Carlo simulation paths to HDF5.
Stores large simulation arrays efficiently using HDF5 with optional compression. Supports arrays up to 10,000 x 1,000 dimensions.
- Parameters:
- Return type:
- Returns:
Cache key for retrieval
Example
>>> paths = np.random.randn(10000, 1000) >>> key = cache.cache_simulation_paths( ... params={'n_sims': 10000, 'seed': 42}, ... paths=paths, ... metadata={'generator': 'numpy'} ... )
- load_simulation_paths(params: Dict[str, Any], memory_map: bool | None = None) ndarray | None[source]
Load simulation paths from cache.
Retrieves cached simulation data with optional memory mapping for efficient loading of large arrays.
- Parameters:
- Return type:
- Returns:
Numpy array of paths or None if not cached
Example
>>> paths = cache.load_simulation_paths( ... params={'n_sims': 10000, 'seed': 42} ... ) >>> if paths is not None: ... print(f"Loaded {paths.shape} from cache")
- cache_processed_results(params: Dict[str, Any], results: DataFrame, result_type: str = 'generic') str[source]
Cache processed results as Parquet.
Stores tabular results efficiently using Parquet format with columnar compression for fast queries.
- Parameters:
- Return type:
- Returns:
Cache key for retrieval
Example
>>> df = pd.DataFrame({'limit': [1e6, 2e6], 'premium': [1e4, 2e4]}) >>> key = cache.cache_processed_results( ... params={'optimization': 'pareto'}, ... results=df, ... result_type='efficient_frontier' ... )
- load_processed_results(params: Dict[str, Any], result_type: str = 'generic') DataFrame | None[source]
Load processed results from cache.
Retrieves cached tabular results from Parquet storage.
- Parameters:
- Return type:
Optional[DataFrame]- Returns:
DataFrame with results or None if not cached
Example
>>> df = cache.load_processed_results( ... params={'optimization': 'pareto'}, ... result_type='efficient_frontier' ... )
- cache_figure(params: Dict[str, Any], figure: Any, figure_name: str, figure_type: str = 'technical', file_format: str = 'pickle') str[source]
Cache matplotlib or plotly figure.
Stores figure objects with metadata for fast regeneration.
- Parameters:
- Return type:
- Returns:
Cache key for retrieval
- clear_cache(confirm: bool = True)[source]
Clear all cached data.
- Parameters:
confirm (
bool) – Require confirmation before clearing
- get_cache_stats() CacheStats[source]
Get current cache statistics.
- Return type:
- Returns:
CacheStats object with usage information
- warm_cache(scenarios: List[Dict[str, Any]], compute_func: Callable[[Dict[str, Any]], Any], result_type: str = 'simulation') int[source]
Pre-compute and cache results for common scenarios.
- Parameters:
- Return type:
- Returns:
Number of scenarios cached
Example
>>> scenarios = [ ... {'n_sims': 1000, 'seed': i} for i in range(10) ... ] >>> n_cached = cache.warm_cache( ... scenarios, ... lambda p: np.random.randn(p['n_sims'], 100) ... )
- class CacheConfig(cache_dir: Path = PosixPath('cache'), max_cache_size_gb: float = 10.0, ttl_hours: int | None = None, compression: str | None = 'gzip', compression_level: int = 4, enable_memory_mapping: bool = True, backend: StorageBackend = StorageBackend.LOCAL, backend_config: Dict[str, ~typing.Any]=<factory>) None[source]
Bases:
objectConfiguration for the cache manager.
- cache_dir
Root directory for cache storage
- max_cache_size_gb
Maximum cache size in gigabytes
- ttl_hours
Time-to-live for cache entries in hours
- compression
Compression algorithm for HDF5 (‘gzip’, ‘lzf’, None)
- compression_level
Compression level (1-9 for gzip)
- enable_memory_mapping
Use memory mapping for large files
- backend
Storage backend type
- backend_config
Backend-specific configuration
- backend: StorageBackend = 'local'
- class CacheStats(total_size_bytes: int = 0, n_entries: int = 0, n_hits: int = 0, n_misses: int = 0, hit_rate: float = 0.0, avg_load_time_ms: float = 0.0, avg_save_time_ms: float = 0.0, oldest_entry: datetime | None = None, newest_entry: datetime | None = None) None[source]
Bases:
objectStatistics about cache usage and performance.
- total_size_bytes
Total size of cached data
- n_entries
Number of cache entries
- n_hits
Number of cache hits
- n_misses
Number of cache misses
- hit_rate
Cache hit rate (0-1)
- avg_load_time_ms
Average load time in milliseconds
- avg_save_time_ms
Average save time in milliseconds
- oldest_entry
Timestamp of oldest cache entry
- newest_entry
Timestamp of newest cache entry
- class StorageBackend(*values)[source]
Bases:
EnumSupported storage backend types.
- LOCAL = 'local'
- S3 = 's3'
- AZURE = 'azure'
- GCS = 'gcs'
- class CacheKey(hash_key: str, params: ~typing.Dict[str, ~typing.Any], timestamp: ~datetime.datetime = <factory>, size_bytes: int = 0, access_count: int = 0, last_accessed: ~datetime.datetime = <factory>) None[source]
Bases:
objectCache key with metadata for cache entries.
- hash_key
SHA256 hash of parameters
- params
Original parameters dictionary
- timestamp
Creation timestamp
- size_bytes
Size of cached data
- access_count
Number of times accessed
- last_accessed
Last access timestamp
- class ReportConfig(**data: Any) None[source]
Bases:
BaseModelComplete configuration for a report.
- metadata
Report metadata.
- style
Report styling.
- sections
List of report sections.
- template
Template type to use.
- output_formats
List of output formats to generate.
- output_dir
Directory for output files.
- cache_dir
Directory for cached figures.
- debug
Enable debug mode.
- metadata: ReportMetadata
- style: ReportStyle
- sections: List[SectionConfig]
- classmethod from_yaml(path: str | Path) ReportConfig[source]
Load configuration from YAML file.
- Parameters:
- Return type:
- Returns:
ReportConfig instance.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class ReportMetadata(**data: Any) None[source]
Bases:
BaseModelMetadata for a report.
- title
Report title.
- subtitle
Optional subtitle.
- authors
List of author names.
- date
Report generation date.
- version
Report version.
- organization
Organization name.
- confidentiality
Confidentiality level.
- keywords
List of keywords.
- abstract
Brief abstract or summary.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class ReportStyle(**data: Any) None[source]
Bases:
BaseModelStyling configuration for reports.
- font_family
Main font family.
- font_size
Base font size in points.
- line_spacing
Line spacing multiplier.
- margins
Page margins in inches.
- page_size
Paper size.
- orientation
Page orientation.
Include headers and footers.
- page_numbers
Include page numbers.
- color_scheme
Color scheme for charts.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class SectionConfig(**data: Any) None[source]
Bases:
BaseModelConfiguration for a report section.
- title
Section title.
- level
Heading level (1-4).
- content
Text content or template name.
- figures
List of figures to include.
- tables
List of tables to include.
- subsections
Nested subsections.
- page_break
Whether to start on new page.
- figures: List[FigureConfig]
- tables: List[TableConfig]
- subsections: List[SectionConfig]
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class FigureConfig(**data: Any) None[source]
Bases:
BaseModelConfiguration for a figure in a report.
- name
Figure identifier name.
- caption
Caption text for the figure.
- source
Source file path or generation function.
- width
Figure width in inches.
- height
Figure height in inches.
- dpi
Resolution in dots per inch.
- position
LaTeX-style position hint.
- cache_key
Optional cache key for pre-generated figures.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class TableConfig(**data: Any) None[source]
Bases:
BaseModelConfiguration for a table in a report.
- name
Table identifier name.
- caption
Caption text for the table.
- data_source
Source of data (file path or function).
- format
Output format for the table.
- columns
List of columns to include.
- index
Whether to include row index.
- precision
Number of decimal places for numeric values.
- style
Table styling options.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- create_executive_config() ReportConfig[source]
Create default configuration for executive report.
- Return type:
- Returns:
ReportConfig for executive summary.
- create_technical_config() ReportConfig[source]
Create default configuration for technical report.
- Return type:
- Returns:
ReportConfig for technical appendix.
- class NumberFormatter(currency_symbol: str = '$', decimal_places: int = 2, thousands_separator: str = ',', decimal_separator: str = '.')[source]
Bases:
objectFormat numbers for display in tables and reports.
This class provides methods to format various numeric types including currency, percentages, and scientific notation with consistent precision and locale-aware formatting.
- currency_symbol
Symbol to use for currency formatting.
- decimal_places
Default number of decimal places.
- thousands_separator
Character for thousands separation.
- decimal_separator
Character for decimal separation.
- format_currency(value: float | int | Decimal, decimals: int | None = None, abbreviate: bool = False) str[source]
Format a number as currency.
- Parameters:
- Return type:
- Returns:
Formatted currency string.
Examples
>>> formatter = NumberFormatter() >>> formatter.format_currency(1234567.89) '$1,234,567.89' >>> formatter.format_currency(1234567.89, abbreviate=True) '$1.23M'
- format_percentage(value: float | int, decimals: int | None = None, multiply_by_100: bool = True) str[source]
Format a number as percentage.
- Parameters:
- Return type:
- Returns:
Formatted percentage string.
Examples
>>> formatter = NumberFormatter() >>> formatter.format_percentage(0.1234) '12.34%' >>> formatter.format_percentage(12.34, multiply_by_100=False) '12.34%'
- format_number(value: float | int, decimals: int | None = None, scientific: bool = False, abbreviate: bool = False) str[source]
Format a general number.
- Parameters:
- Return type:
- Returns:
Formatted number string.
Examples
>>> formatter = NumberFormatter() >>> formatter.format_number(1234567.89) '1,234,567.89' >>> formatter.format_number(0.00001234, scientific=True) '1.23e-05'
- class ColorCoder(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', color_scheme: Dict[str, str] | None = None)[source]
Bases:
objectApply color coding to values for visual indicators.
This class provides methods for traffic light coloring, heatmaps, and threshold-based coloring for different output formats.
- output_format
Target output format (html, latex, terminal).
- color_scheme
Color scheme to use.
- TRAFFIC_LIGHT = {'bad': '#dc3545', 'good': '#28a745', 'warning': '#ffc107'}
- HEATMAP_COLORS = {'high': '#ef5350', 'low': '#e3f2fd', 'medium': '#42a5f5', 'medium_high': '#ffb74d', 'medium_low': '#90caf9'}
- traffic_light(value: float | int, thresholds: Dict[str, Tuple[float | None, float | None]], text: str | None = None) str[source]
Apply traffic light coloring based on thresholds.
- Parameters:
- Return type:
- Returns:
Formatted string with appropriate coloring.
Examples
>>> coder = ColorCoder(output_format="html") >>> thresholds = { ... 'good': (0.15, None), ... 'warning': (0.10, 0.15), ... 'bad': (None, 0.10) ... } >>> coder.traffic_light(0.18, thresholds) '<span style="color: #28a745;">0.18</span>'
- heatmap(value: float | int, min_val: float, max_val: float, text: str | None = None) str[source]
Apply heatmap coloring based on value range.
- Parameters:
- Return type:
- Returns:
Formatted string with heatmap coloring.
Examples
>>> coder = ColorCoder(output_format="html") >>> coder.heatmap(50, 0, 100) '<span style="background-color: #42a5f5;">50</span>'
- class TableFormatter(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', currency_symbol: str = '$', decimal_places: int = 2)[source]
Bases:
objectHigh-level table formatting utilities.
This class combines number formatting and color coding to provide comprehensive table formatting capabilities.
- number_formatter
NumberFormatter instance.
- color_coder
ColorCoder instance.
- format_dataframe(df: DataFrame, column_formats: Dict[str, Dict[str, Any]] | None = None, row_colors: Dict[int, str] | None = None, alternating_rows: bool = False) DataFrame[source]
Apply formatting to entire DataFrame.
- Parameters:
- Return type:
DataFrame- Returns:
Formatted DataFrame.
Examples
>>> formatter = TableFormatter() >>> formats = { ... 'Revenue': {'type': 'currency', 'abbreviate': True}, ... 'Growth': {'type': 'percentage'}, ... 'Risk': {'type': 'traffic_light', 'thresholds': {...}} ... } >>> formatted_df = formatter.format_dataframe(df, formats)
- add_totals_row(df: DataFrame, columns: List[str] | None = None, label: str = 'Total', operation: Literal['sum', 'mean', 'median'] = 'sum') DataFrame[source]
Add a totals row to DataFrame.
- format_for_export(df: DataFrame, export_format: Literal['csv', 'excel', 'latex', 'html', 'markdown'], include_index: bool = False, **kwargs) str | None[source]
Format DataFrame for export to various formats.
- Parameters:
- Return type:
- Returns:
Formatted string or None for file-based exports.
Examples
>>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) >>> csv_str = format_for_export(df, 'csv') >>> latex_str = format_for_export(df, 'latex', caption='My Table')
- class TableGenerator(default_format: Literal['markdown', 'html', 'latex', 'grid', 'csv', 'excel'] = 'markdown', precision: int = 2, max_width: int = 50, currency_symbol: str = '$')[source]
Bases:
objectGenerate formatted tables for reports.
This class provides methods to create professionally formatted tables from pandas DataFrames or raw data, supporting various output formats and styling options. Enhanced with comprehensive table generation methods for executive and technical reports.
- default_format
Default output format for tables.
- precision
Default precision for numeric values.
- max_width
Maximum width for text columns.
- number_formatter
NumberFormatter instance for formatting.
- color_coder
ColorCoder instance for color coding.
- table_formatter
TableFormatter instance for comprehensive formatting.
- generate(data: DataFrame | Dict | List, caption: str = '', columns: List[str] | None = None, index: bool = False, output_format: str | None = None, precision: int | None = None, style: Dict[str, Any] | None = None) str[source]
Generate a formatted table from data.
- Parameters:
data (
Union[DataFrame,Dict,List]) – Input data (DataFrame, dict, or list).caption (
str) – Table caption.columns (
Optional[List[str]]) – Columns to include (None for all).index (
bool) – Whether to include row index.output_format (
Optional[str]) – Output format (uses default if None).precision (
Optional[int]) – Decimal precision (uses default if None).style (
Optional[Dict[str,Any]]) – Additional styling options.
- Return type:
- Returns:
Formatted table string.
Examples
>>> gen = TableGenerator() >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) >>> print(gen.generate(df, caption="Sample Table"))
- generate_summary_statistics(df: DataFrame, metrics: List[str] | None = None, output_format: str | None = None) str[source]
Generate summary statistics table.
- generate_comparison_table(data: Dict[str, Series], caption: str = 'Comparison Table', output_format: str | None = None) str[source]
Generate comparison table from multiple series.
- generate_decision_matrix(alternatives: List[str], criteria: List[str], scores: ndarray, weights: List[float] | None = None, output_format: str | None = None) str[source]
Generate a decision matrix table.
- Parameters:
- Return type:
- Returns:
Formatted decision matrix.
- generate_optimal_limits_by_size(company_sizes: List[float], optimal_limits: Dict[float, Dict[str, float]], output_format: str | None = None, include_percentages: bool = True) str[source]
Generate Table 1: Optimal Insurance Limits by Company Size.
Creates a comprehensive table showing optimal insurance structures for different company sizes, including retention, primary limits, excess limits, and total premiums.
- Parameters:
- Return type:
- Returns:
Formatted table string.
Examples
>>> gen = TableGenerator() >>> sizes = [1_000_000, 10_000_000, 100_000_000] >>> limits = { ... 1_000_000: {'retention': 50000, 'primary': 500000, ... 'excess': 1000000, 'premium': 25000}, ... # ... more sizes ... } >>> table = gen.generate_optimal_limits_by_size(sizes, limits)
- generate_quick_reference_matrix(characteristics: List[str], recommendations: Dict[str, Dict[str, Any]], output_format: str | None = None, use_traffic_lights: bool = True) str[source]
Generate Table 2: Quick Reference Decision Matrix.
Creates a decision matrix with company characteristics as rows and recommended insurance structures as columns, with optional traffic light coloring for visual indicators.
- Parameters:
- Return type:
- Returns:
Formatted decision matrix table.
Examples
>>> gen = TableGenerator() >>> chars = ['High Growth', 'Stable', 'Distressed'] >>> recs = { ... 'High Growth': {'retention': 'Low', 'coverage': 'High', ... 'premium_budget': '2-3%', 'risk_level': 'good'}, ... # ... more recommendations ... } >>> table = gen.generate_quick_reference_matrix(chars, recs)
- generate_parameter_grid(parameters: Dict[str, Dict[str, Any]], scenarios: List[str] | None = None, output_format: str | None = None) str[source]
Generate Table A1: Complete Parameter Grid.
Creates a comprehensive parameter grid showing all simulation parameters with ranges for different scenarios.
- Parameters:
- Return type:
- Returns:
Formatted parameter grid table.
Examples
>>> gen = TableGenerator() >>> params = { ... 'Growth': {'mean': [0.05, 0.08, 0.12], 'volatility': [0.15, 0.20, 0.30]}, ... 'Losses': {'frequency': [3, 5, 8], 'severity': [50000, 100000, 200000]} ... } >>> table = gen.generate_parameter_grid(params)
- generate_loss_distribution_params(loss_types: List[str], distribution_params: Dict[str, Dict[str, Any]], output_format: str | None = None, include_correlations: bool = True) str[source]
Generate Table A2: Loss Distribution Parameters.
Creates a table showing frequency and severity parameters for different loss types, including correlation coefficients and development patterns.
- Parameters:
- Return type:
- Returns:
Formatted loss distribution parameters table.
- generate_insurance_pricing_grid(layers: List[Tuple[float, float]], pricing_params: Dict[Tuple[float, float], Dict[str, float]], output_format: str | None = None) str[source]
Generate Table A3: Insurance Pricing Grid.
Creates a pricing grid showing premium rates by layer and attachment point, including loading factors.
- Parameters:
- Return type:
- Returns:
Formatted insurance pricing grid.
Examples
>>> gen = TableGenerator() >>> layers = [(0, 1_000_000), (1_000_000, 5_000_000)] >>> pricing = { ... (0, 1_000_000): {'rate': 0.015, 'loading': 1.3}, ... (1_000_000, 5_000_000): {'rate': 0.008, 'loading': 1.2} ... } >>> table = gen.generate_insurance_pricing_grid(layers, pricing)
- generate_statistical_validation(metrics: Dict[str, Dict[str, float]], output_format: str | None = None, include_thresholds: bool = True) str[source]
Generate Table B1: Statistical Validation Metrics.
Creates a table of statistical validation metrics including goodness-of-fit tests, convergence statistics, and out-of-sample performance.
- generate_comprehensive_results(results: List[Dict[str, Any]], ranking_metric: str = 'roe', output_format: str | None = None, top_n: int | None = None) str[source]
Generate Table C1: Comprehensive Optimization Results.
Creates a comprehensive results table showing all parameter combinations tested with ranking by specified metric.
- Parameters:
- Return type:
- Returns:
Formatted comprehensive results table.
- generate_walk_forward_validation(validation_results: List[Dict[str, Any]], output_format: str | None = None) str[source]
Generate Table C2: Walk-Forward Validation Results.
Creates a table showing rolling window analysis results and strategy stability metrics over time.
- create_performance_table(results: Dict[str, Any]) str[source]
Create a performance metrics table from simulation results.
- create_sensitivity_table(base_case: float, sensitivities: Dict[str, List[float]], parameter_ranges: Dict[str, List[float]]) str[source]
Create a sensitivity analysis table.
- class ReportBuilder(config: ReportConfig, cache_dir: Path | None = None)[source]
Bases:
ABCBase class for building automated reports.
This abstract base class provides common functionality for generating different types of reports, including section management, figure embedding, and template rendering.
- config
Report configuration object.
- cache_manager
Cache manager for figures and data.
- table_generator
Table generation utility.
- content
Accumulated report content.
- figures
List of generated figures.
- tables
List of generated tables.
- abstractmethod generate() Path[source]
Generate the complete report.
- Return type:
- Returns:
Path to generated report file.
- build_section(section: SectionConfig) str[source]
Build a report section.
- Parameters:
section (
SectionConfig) – Section configuration.- Return type:
- Returns:
Formatted section content.
- class ExecutiveReport(results: Dict[str, Any], config: ReportConfig | None = None, cache_dir: Path | None = None)[source]
Bases:
ReportBuilderGenerate executive summary reports.
This class creates concise, visually-rich reports designed for executive audiences, focusing on key findings, recommendations, and decision-critical information.
- results
Simulation or analysis results.
- style_manager
Visualization style manager.
- key_metrics
Dictionary of key performance metrics.
- generate() Path[source]
Generate the executive report.
- Return type:
- Returns:
Path to generated report file.
- generate_roe_frontier(fig_config: FigureConfig) Figure[source]
Generate ROE-Ruin frontier plot.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- generate_performance_table() DataFrame[source]
Generate performance metrics table.
- Return type:
DataFrame- Returns:
Performance metrics DataFrame.
- generate_decision_matrix() DataFrame[source]
Generate decision matrix table.
- Return type:
DataFrame- Returns:
Decision matrix DataFrame.
- generate_convergence_plot(fig_config: FigureConfig) Figure[source]
Generate convergence diagnostics plot.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- class TechnicalReport(results: Dict[str, Any], parameters: Dict[str, Any], config: ReportConfig | None = None, cache_dir: Path | None = None)[source]
Bases:
ReportBuilderGenerate detailed technical reports.
This class creates comprehensive technical documentation including methodology, mathematical proofs, statistical validation, and detailed analysis results.
- results
Complete analysis results.
- parameters
Model parameters used.
- validation_metrics
Validation and convergence metrics.
- generate() Path[source]
Generate the technical report.
- Return type:
- Returns:
Path to generated report file.
- generate_parameter_sensitivity_plot(fig_config: FigureConfig) Figure[source]
Generate parameter sensitivity tornado plot.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- generate_qq_plot(fig_config: FigureConfig) Figure[source]
Generate Q-Q plot for distribution validation.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- generate_model_parameters_table() DataFrame[source]
Generate comprehensive model parameters table.
- Return type:
DataFrame- Returns:
Parameters DataFrame.
- generate_correlation_matrix_plot(fig_config: FigureConfig) Figure[source]
Generate correlation matrix heatmap.
- Parameters:
fig_config (
FigureConfig) – Figure configuration.- Return type:
- Returns:
Matplotlib figure.
- class ReportValidator(config: ReportConfig)[source]
Bases:
objectValidate report configuration and content.
This class provides comprehensive validation for report configurations, ensuring all references are valid, data is complete, and quality standards are met.
- config
Report configuration to validate.
- errors
List of validation errors.
- warnings
List of validation warnings.