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: Enum

Supported 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: object

Configuration 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

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 = 'local'
backend_config: Dict[str, Any]
__post_init__()[source]

Validate and initialize configuration.

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: object

Statistics 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

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
update_hit_rate()[source]

Update the cache hit rate.

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: object

Cache 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

hash_key: str
params: Dict[str, Any]
timestamp: datetime
size_bytes: int = 0
access_count: int = 0
last_accessed: datetime
to_dict() Dict[str, Any][source]

Convert to dictionary for serialization.

Return type:

Dict[str, Any]

classmethod from_dict(data: Dict[str, Any]) CacheKey[source]

Create from dictionary.

Return type:

CacheKey

class BaseStorageBackend[source]

Bases: ABC

Abstract base class for storage backends.

abstractmethod exists(path: Path) bool[source]

Check if path exists.

Return type:

bool

abstractmethod save(path: Path, data: Any, file_format: str = 'pickle') int[source]

Save data to path, return size in bytes.

Return type:

int

abstractmethod load(path: Path, file_format: str = 'pickle') Any[source]

Load data from path.

Return type:

Any

abstractmethod delete(path: Path) bool[source]

Delete data at path.

Return type:

bool

abstractmethod list_files(pattern: str = '*') List[Path][source]

List files matching pattern.

Return type:

List[Path]

abstractmethod get_size(path: Path) int[source]

Get size of file in bytes.

Return type:

int

class LocalStorageBackend(root_dir: Path)[source]

Bases: BaseStorageBackend

Local filesystem storage backend.

exists(path: Path) bool[source]

Check if path exists.

Return type:

bool

save(path: Path, data: Any, file_format: str = 'pickle') int[source]

Save data to path.

Return type:

int

load(path: Path, file_format: str = 'pickle') Any[source]

Load data from path.

Return type:

Any

delete(path: Path) bool[source]

Delete data at path.

Return type:

bool

list_files(pattern: str = '*') List[Path][source]

List files matching pattern.

Return type:

List[Path]

get_size(path: Path) int[source]

Get size of file in bytes.

Return type:

int

class CacheManager(config: CacheConfig | None = None)[source]

Bases: object

High-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:
  • params (Dict[str, Any]) – Simulation parameters (used for cache key)

  • paths (ndarray) – Numpy array of simulation paths (n_simulations, n_years)

  • metadata (Optional[Dict[str, Any]]) – Optional metadata to store with paths

Return type:

str

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:
  • params (Dict[str, Any]) – Simulation parameters (must match cached params)

  • memory_map (Optional[bool]) – Use memory mapping for large files (None=auto)

Return type:

Optional[ndarray]

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:
  • params (Dict[str, Any]) – Processing parameters (used for cache key)

  • results (DataFrame) – Pandas DataFrame with results

  • result_type (str) – Type of results (e.g., ‘efficient_frontier’)

Return type:

str

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:
  • params (Dict[str, Any]) – Processing parameters (must match cached params)

  • result_type (str) – Type of results to load

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:
  • params (Dict[str, Any]) – Figure parameters (used for cache key)

  • figure (Any) – Matplotlib or Plotly figure object

  • figure_name (str) – Name of the figure

  • figure_type (str) – ‘executive’ or ‘technical’

  • file_format (str) – Storage format (‘pickle’, ‘json’ for plotly)

Return type:

str

Returns:

Cache key for retrieval

invalidate_cache(params: Dict[str, Any] | None = None)[source]

Invalidate cache entries.

Parameters:

params (Optional[Dict[str, Any]]) – If provided, only invalidate entries matching these params. If None, invalidate all cache.

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:

CacheStats

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:
  • scenarios (List[Dict[str, Any]]) – List of parameter dictionaries to compute

  • compute_func (Callable[[Dict[str, Any]], Any]) – Function that takes params and returns results

  • result_type (str) – Type of results being cached

Return type:

int

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)
... )
validate_cache() Dict[str, Any][source]

Validate cache integrity and consistency.

Return type:

Dict[str, Any]

Returns:

Dictionary with validation results

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: BaseModel

Configuration 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.

name: str
caption: str
source: str | Path
width: float
height: float
dpi: int
position: str
cache_key: str | None
classmethod validate_source(v)[source]

Validate that source is a valid path or callable name.

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: BaseModel

Configuration 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.

name: str
caption: str
data_source: str | Path
format: Literal['markdown', 'html', 'latex']
columns: List[str] | None
index: bool
precision: int
style: Dict[str, Any]
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: BaseModel

Configuration 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.

title: str
level: int
content: str | None
figures: List[FigureConfig]
tables: List[TableConfig]
subsections: List[SectionConfig]
page_break: bool
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: BaseModel

Metadata 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.

title: str
subtitle: str | None
authors: List[str]
date: datetime
version: str
organization: str
confidentiality: Literal['Public', 'Internal', 'Confidential']
keywords: List[str]
abstract: str | None
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: BaseModel

Styling 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.

font_family: str
font_size: int
line_spacing: float
margins: Dict[str, float]
page_size: Literal['A4', 'Letter', 'Legal']
orientation: Literal['portrait', 'landscape']
header_footer: bool
page_numbers: bool
color_scheme: str
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: BaseModel

Complete 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]
template: Literal['executive', 'technical', 'full', 'custom']
output_formats: List[Literal['pdf', 'html', 'markdown']]
output_dir: Path
cache_dir: Path
debug: bool
classmethod create_directories(v)[source]

Ensure output directories exist.

to_yaml(path: Path | None = None) str[source]

Export configuration to YAML format.

Parameters:

path (Optional[Path]) – Optional path to save YAML file.

Return type:

str

Returns:

YAML string representation.

classmethod from_yaml(path: str | Path) ReportConfig[source]

Load configuration from YAML file.

Parameters:

path (Union[str, Path]) – Path to YAML configuration file.

Return type:

ReportConfig

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:

ReportConfig

Returns:

ReportConfig for executive summary.

create_technical_config() ReportConfig[source]

Create default configuration for technical report.

Return type:

ReportConfig

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: ReportBuilder

Generate 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:

Path

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:

Figure

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:

Figure

Returns:

Matplotlib figure.

generate_convergence_table() DataFrame[source]

Generate convergence metrics table.

Return type:

DataFrame

Returns:

Convergence metrics DataFrame.

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: object

Format 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:
  • value (Union[float, int, Decimal]) – Numeric value to format.

  • decimals (Optional[int]) – Number of decimal places (uses default if None).

  • abbreviate (bool) – Whether to abbreviate large numbers (e.g., $1.5M).

Return type:

str

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:
  • value (Union[float, int]) – Numeric value to format.

  • decimals (Optional[int]) – Number of decimal places (default 1).

  • multiply_by_100 (bool) – Whether to multiply by 100 (default True).

Return type:

str

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:
  • value (Union[float, int]) – Numeric value to format.

  • decimals (Optional[int]) – Number of decimal places.

  • scientific (bool) – Use scientific notation for large/small numbers.

  • abbreviate (bool) – Abbreviate large numbers (K, M, B).

Return type:

str

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'
format_ratio(value: float | int, decimals: int = 2) str[source]

Format a ratio value.

Parameters:
  • value (Union[float, int]) – Ratio value to format.

  • decimals (int) – Number of decimal places.

Return type:

str

Returns:

Formatted ratio string.

Examples

>>> formatter = NumberFormatter()
>>> formatter.format_ratio(1.5)
'1.50x'
class ColorCoder(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', color_scheme: Dict[str, str] | None = None)[source]

Bases: object

Apply 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:

str

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:
  • value (Union[float, int]) – Numeric value to color.

  • min_val (float) – Minimum value in range.

  • max_val (float) – Maximum value in range.

  • text (Optional[str]) – Text to display (uses value if None).

Return type:

str

Returns:

Formatted string with heatmap coloring.

Examples

>>> coder = ColorCoder(output_format="html")
>>> coder.heatmap(50, 0, 100)
'<span style="background-color: #42a5f5;">50</span>'
threshold_color(value: float | int, threshold: float, above_color: str = '#28a745', below_color: str = '#dc3545', text: str | None = None) str[source]

Apply binary coloring based on threshold.

Parameters:
  • value (Union[float, int]) – Numeric value to evaluate.

  • threshold (float) – Threshold value.

  • above_color (str) – Color for values above threshold.

  • below_color (str) – Color for values below threshold.

  • text (Optional[str]) – Text to display.

Return type:

str

Returns:

Formatted string with threshold-based coloring.

class TableFormatter(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', currency_symbol: str = '$', decimal_places: int = 2)[source]

Bases: object

High-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:
  • df (DataFrame) – Input DataFrame.

  • column_formats (Optional[Dict[str, Dict[str, Any]]]) – Format specifications per column.

  • row_colors (Optional[Dict[int, str]]) – Colors for specific rows.

  • alternating_rows (bool) – Whether to use alternating row colors.

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.

Parameters:
  • df (DataFrame) – Input DataFrame.

  • columns (Optional[List[str]]) – Columns to total (None for all numeric).

  • label (str) – Label for totals row.

  • operation (Literal['sum', 'mean', 'median']) – Aggregation operation.

Return type:

DataFrame

Returns:

DataFrame with totals row added.

add_footnotes(table_str: str, footnotes: List[str], output_format: str | None = None) str[source]

Add footnotes to a table string.

Parameters:
  • table_str (str) – Table string.

  • footnotes (List[str]) – List of footnote texts.

  • output_format (Optional[str]) – Output format (uses instance format if None).

Return type:

str

Returns:

Table with footnotes added.

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:
  • df (DataFrame) – DataFrame to export.

  • export_format (Literal['csv', 'excel', 'latex', 'html', 'markdown']) – Export format.

  • include_index (bool) – Whether to include row index.

  • **kwargs – Additional format-specific arguments.

Return type:

Optional[str]

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: object

Container 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)

category: str
importance: float
title: str
description: str
data: Dict[str, Any]
metrics: List[str]
confidence: float = 1.0
to_bullet_point() str[source]

Convert insight to bullet point format.

Return type:

str

Returns:

Formatted bullet point string

to_executive_summary() str[source]

Convert to executive summary format.

Return type:

str

Returns:

Executive-friendly description

class InsightExtractor[source]

Bases: object

Extract 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}%'}
insights: List[Insight]
data: Any | None
extract_insights(data: Any, focus_metrics: List[str] | None = None, threshold_importance: float = 50.0) List[Insight][source]

Extract insights from simulation data.

Parameters:
  • data (Any) – Simulation results or comparison data

  • focus_metrics (Optional[List[str]]) – Metrics to focus on

  • threshold_importance (float) – Minimum importance threshold

Return type:

List[Insight]

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.

Parameters:
  • max_points (int) – Maximum number of points

  • focus_positive (bool) – Focus on positive insights

Return type:

str

Returns:

Executive summary text

generate_technical_notes() List[str][source]

Generate technical notes from insights.

Return type:

List[str]

Returns:

List of technical observation strings

export_insights(output_path: str, output_format: str = 'markdown') str[source]

Export insights to file.

Parameters:
  • output_path (str) – Path for output file

  • output_format (str) – Output format (markdown, json, csv)

Return type:

str

Returns:

Path to exported file

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: ABC

Base 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:

Path

Returns:

Path to generated report file.

build_section(section: SectionConfig) str[source]

Build a report section.

Parameters:

section (SectionConfig) – Section configuration.

Return type:

str

Returns:

Formatted section content.

compile_report() str[source]

Compile all sections into complete report.

Return type:

str

Returns:

Complete report content as string.

save(output_format: str = 'markdown') Path[source]

Save report in specified format.

Parameters:

output_format (str) – Output format (markdown, html, pdf).

Return type:

Path

Returns:

Path to saved report.

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: object

Container 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

scenarios: List[str]
metrics: Dict[str, Dict[str, float]]
parameters: Dict[str, Dict[str, Any]]
statistics: Dict[str, Any]
diffs: Dict[str, Dict[str, Any]]
rankings: Dict[str, List[Tuple[str, float]]]
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

get_top_performers(metric: str, n: int = 3, ascending: bool = False) List[Tuple[str, float]][source]

Get top performing scenarios for a metric.

Parameters:
  • metric (str) – Metric name

  • n (int) – Number of top performers

  • ascending (bool) – If True, lower values are better

Return type:

List[Tuple[str, float]]

Returns:

List of (scenario, value) tuples

class ScenarioComparator[source]

Bases: object

Framework for comparing multiple simulation scenarios.

baseline_scenario: str | None
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:
  • results (Dict[str, Any]) – Dictionary of scenario results

  • baseline (Optional[str]) – Baseline scenario name for comparison

  • metrics (Optional[List[str]]) – Metrics to compare (default: all numeric)

  • parameters (Optional[List[str]]) – Parameters to track (default: all)

Return type:

ScenarioComparison

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.

Parameters:
Return type:

Figure

Returns:

Matplotlib figure with comparison grid

create_parameter_diff_table(scenario: str, threshold: float = 5.0) DataFrame[source]

Create table showing parameter differences from baseline.

Parameters:
  • scenario (str) – Scenario to compare

  • threshold (float) – Minimum percentage change to highlight

Return type:

DataFrame

Returns:

DataFrame with parameter differences

export_comparison_report(output_path: str, include_plots: bool = True) Dict[str, Any][source]

Export comprehensive comparison report.

Parameters:
  • output_path (str) – Base path for output files

  • include_plots (bool) – Whether to generate and save plots

Return type:

Dict[str, Any]

Returns:

Dictionary with paths to generated files

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: object

Generate 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:

str

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.

Parameters:
  • df (DataFrame) – Input DataFrame.

  • metrics (Optional[List[str]]) – List of metrics to compute.

  • output_format (Optional[str]) – Output format.

Return type:

str

Returns:

Formatted 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.

Parameters:
  • data (Dict[str, Series]) – Dictionary mapping names to series.

  • caption (str) – Table caption.

  • output_format (Optional[str]) – Output format.

Return type:

str

Returns:

Formatted comparison table.

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:
  • alternatives (List[str]) – List of alternative names.

  • criteria (List[str]) – List of criteria names.

  • scores (ndarray) – Score matrix (alternatives x criteria).

  • weights (Optional[List[float]]) – Optional criteria weights.

  • output_format (Optional[str]) – Output format.

Return type:

str

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:
  • company_sizes (List[float]) – List of company asset sizes in dollars.

  • optimal_limits (Dict[float, Dict[str, float]]) – Dict mapping size to limits structure.

  • output_format (Optional[str]) – Output format (uses default if None).

  • include_percentages (bool) – Whether to include % of assets columns.

Return type:

str

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:
  • characteristics (List[str]) – List of company characteristic names.

  • recommendations (Dict[str, Dict[str, Any]]) – Dict mapping characteristics to recommendations.

  • output_format (Optional[str]) – Output format.

  • use_traffic_lights (bool) – Whether to apply traffic light coloring.

Return type:

str

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:

str

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:
  • loss_types (List[str]) – List of loss type names.

  • distribution_params (Dict[str, Dict[str, Any]]) – Parameters for each loss type.

  • output_format (Optional[str]) – Output format.

  • include_correlations (bool) – Whether to include correlation matrix.

Return type:

str

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:

str

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.

Parameters:
  • metrics (Dict[str, Dict[str, float]]) – Dictionary of metric categories and values.

  • output_format (Optional[str]) – Output format.

  • include_thresholds (bool) – Whether to include pass/fail thresholds.

Return type:

str

Returns:

Formatted statistical validation table.

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:
  • results (List[Dict[str, Any]]) – List of result dictionaries from optimization.

  • ranking_metric (str) – Metric to use for ranking.

  • output_format (Optional[str]) – Output format.

  • top_n (Optional[int]) – Show only top N results (None for all).

Return type:

str

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.

Parameters:
  • validation_results (List[Dict[str, Any]]) – List of validation period results.

  • output_format (Optional[str]) – Output format.

Return type:

str

Returns:

Formatted walk-forward validation table.

export_to_file(df: DataFrame, file_path: str, output_format: Literal['csv', 'excel', 'latex', 'html'], **kwargs) None[source]

Export DataFrame to file in specified format.

Parameters:
  • df (DataFrame) – DataFrame to export.

  • file_path (str) – Path to save file.

  • output_format (Literal['csv', 'excel', 'latex', 'html']) – Export format.

  • **kwargs – Additional format-specific arguments.

Return type:

None

create_performance_table(results: Dict[str, Any]) str[source]

Create a performance metrics table from simulation results.

Parameters:

results (Dict[str, Any]) – Dictionary of performance metrics.

Return type:

str

Returns:

Formatted performance table.

create_parameter_table(params: Dict[str, Any]) str[source]

Create a parameter summary table.

Parameters:

params (Dict[str, Any]) – Dictionary of parameters.

Return type:

str

Returns:

Formatted parameter table.

create_sensitivity_table(base_case: float, sensitivities: Dict[str, List[float]], parameter_ranges: Dict[str, List[float]]) str[source]

Create a sensitivity analysis table.

Parameters:
  • base_case (float) – Base case value.

  • sensitivities (Dict[str, List[float]]) – Sensitivity results by parameter.

  • parameter_ranges (Dict[str, List[float]]) – Parameter test ranges.

Return type:

str

Returns:

Formatted sensitivity table.

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: ReportBuilder

Generate 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:

Path

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:

Figure

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:

Figure

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:

Figure

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: object

Validate 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.

validate() Tuple[bool, List[str], List[str]][source]

Run complete validation suite.

Return type:

Tuple[bool, List[str], List[str]]

Returns:

Tuple of (is_valid, errors, warnings).

validate_results_data(results: Dict[str, Any]) Tuple[bool, List[str]][source]

Validate results data for report generation.

Parameters:

results (Dict[str, Any]) – Results dictionary to validate.

Return type:

Tuple[bool, List[str]]

Returns:

Tuple of (is_valid, error_messages).

validate_parameters(params: Dict[str, Any]) Tuple[bool, List[str]][source]

Validate model parameters.

Parameters:

params (Dict[str, Any]) – Parameters dictionary to validate.

Return type:

Tuple[bool, List[str]]

Returns:

Tuple of (is_valid, error_messages).

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: object

High-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:
  • params (Dict[str, Any]) – Simulation parameters (used for cache key)

  • paths (ndarray) – Numpy array of simulation paths (n_simulations, n_years)

  • metadata (Optional[Dict[str, Any]]) – Optional metadata to store with paths

Return type:

str

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:
  • params (Dict[str, Any]) – Simulation parameters (must match cached params)

  • memory_map (Optional[bool]) – Use memory mapping for large files (None=auto)

Return type:

Optional[ndarray]

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:
  • params (Dict[str, Any]) – Processing parameters (used for cache key)

  • results (DataFrame) – Pandas DataFrame with results

  • result_type (str) – Type of results (e.g., ‘efficient_frontier’)

Return type:

str

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:
  • params (Dict[str, Any]) – Processing parameters (must match cached params)

  • result_type (str) – Type of results to load

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:
  • params (Dict[str, Any]) – Figure parameters (used for cache key)

  • figure (Any) – Matplotlib or Plotly figure object

  • figure_name (str) – Name of the figure

  • figure_type (str) – ‘executive’ or ‘technical’

  • file_format (str) – Storage format (‘pickle’, ‘json’ for plotly)

Return type:

str

Returns:

Cache key for retrieval

invalidate_cache(params: Dict[str, Any] | None = None)[source]

Invalidate cache entries.

Parameters:

params (Optional[Dict[str, Any]]) – If provided, only invalidate entries matching these params. If None, invalidate all cache.

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:

CacheStats

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:
  • scenarios (List[Dict[str, Any]]) – List of parameter dictionaries to compute

  • compute_func (Callable[[Dict[str, Any]], Any]) – Function that takes params and returns results

  • result_type (str) – Type of results being cached

Return type:

int

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)
... )
validate_cache() Dict[str, Any][source]

Validate cache integrity and consistency.

Return type:

Dict[str, Any]

Returns:

Dictionary with validation results

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: object

Configuration 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

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 = 'local'
backend_config: Dict[str, Any]
__post_init__()[source]

Validate and initialize configuration.

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: object

Statistics 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

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
update_hit_rate()[source]

Update the cache hit rate.

class StorageBackend(*values)[source]

Bases: Enum

Supported 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: object

Cache 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

hash_key: str
params: Dict[str, Any]
timestamp: datetime
size_bytes: int = 0
access_count: int = 0
last_accessed: datetime
to_dict() Dict[str, Any][source]

Convert to dictionary for serialization.

Return type:

Dict[str, Any]

classmethod from_dict(data: Dict[str, Any]) CacheKey[source]

Create from dictionary.

Return type:

CacheKey

class ReportConfig(**data: Any) None[source]

Bases: BaseModel

Complete 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]
template: Literal['executive', 'technical', 'full', 'custom']
output_formats: List[Literal['pdf', 'html', 'markdown']]
output_dir: Path
cache_dir: Path
debug: bool
classmethod create_directories(v)[source]

Ensure output directories exist.

to_yaml(path: Path | None = None) str[source]

Export configuration to YAML format.

Parameters:

path (Optional[Path]) – Optional path to save YAML file.

Return type:

str

Returns:

YAML string representation.

classmethod from_yaml(path: str | Path) ReportConfig[source]

Load configuration from YAML file.

Parameters:

path (Union[str, Path]) – Path to YAML configuration file.

Return type:

ReportConfig

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: BaseModel

Metadata 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.

title: str
subtitle: str | None
authors: List[str]
date: datetime
version: str
organization: str
confidentiality: Literal['Public', 'Internal', 'Confidential']
keywords: List[str]
abstract: str | None
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: BaseModel

Styling 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.

font_family: str
font_size: int
line_spacing: float
margins: Dict[str, float]
page_size: Literal['A4', 'Letter', 'Legal']
orientation: Literal['portrait', 'landscape']
header_footer: bool
page_numbers: bool
color_scheme: str
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: BaseModel

Configuration 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.

title: str
level: int
content: str | None
figures: List[FigureConfig]
tables: List[TableConfig]
subsections: List[SectionConfig]
page_break: bool
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: BaseModel

Configuration 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.

name: str
caption: str
source: str | Path
width: float
height: float
dpi: int
position: str
cache_key: str | None
classmethod validate_source(v)[source]

Validate that source is a valid path or callable name.

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: BaseModel

Configuration 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.

name: str
caption: str
data_source: str | Path
format: Literal['markdown', 'html', 'latex']
columns: List[str] | None
index: bool
precision: int
style: Dict[str, Any]
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:

ReportConfig

Returns:

ReportConfig for executive summary.

create_technical_config() ReportConfig[source]

Create default configuration for technical report.

Return type:

ReportConfig

Returns:

ReportConfig for technical appendix.

class NumberFormatter(currency_symbol: str = '$', decimal_places: int = 2, thousands_separator: str = ',', decimal_separator: str = '.')[source]

Bases: object

Format 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:
  • value (Union[float, int, Decimal]) – Numeric value to format.

  • decimals (Optional[int]) – Number of decimal places (uses default if None).

  • abbreviate (bool) – Whether to abbreviate large numbers (e.g., $1.5M).

Return type:

str

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:
  • value (Union[float, int]) – Numeric value to format.

  • decimals (Optional[int]) – Number of decimal places (default 1).

  • multiply_by_100 (bool) – Whether to multiply by 100 (default True).

Return type:

str

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:
  • value (Union[float, int]) – Numeric value to format.

  • decimals (Optional[int]) – Number of decimal places.

  • scientific (bool) – Use scientific notation for large/small numbers.

  • abbreviate (bool) – Abbreviate large numbers (K, M, B).

Return type:

str

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'
format_ratio(value: float | int, decimals: int = 2) str[source]

Format a ratio value.

Parameters:
  • value (Union[float, int]) – Ratio value to format.

  • decimals (int) – Number of decimal places.

Return type:

str

Returns:

Formatted ratio string.

Examples

>>> formatter = NumberFormatter()
>>> formatter.format_ratio(1.5)
'1.50x'
class ColorCoder(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', color_scheme: Dict[str, str] | None = None)[source]

Bases: object

Apply 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:

str

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:
  • value (Union[float, int]) – Numeric value to color.

  • min_val (float) – Minimum value in range.

  • max_val (float) – Maximum value in range.

  • text (Optional[str]) – Text to display (uses value if None).

Return type:

str

Returns:

Formatted string with heatmap coloring.

Examples

>>> coder = ColorCoder(output_format="html")
>>> coder.heatmap(50, 0, 100)
'<span style="background-color: #42a5f5;">50</span>'
threshold_color(value: float | int, threshold: float, above_color: str = '#28a745', below_color: str = '#dc3545', text: str | None = None) str[source]

Apply binary coloring based on threshold.

Parameters:
  • value (Union[float, int]) – Numeric value to evaluate.

  • threshold (float) – Threshold value.

  • above_color (str) – Color for values above threshold.

  • below_color (str) – Color for values below threshold.

  • text (Optional[str]) – Text to display.

Return type:

str

Returns:

Formatted string with threshold-based coloring.

class TableFormatter(output_format: Literal['html', 'latex', 'terminal', 'none'] = 'none', currency_symbol: str = '$', decimal_places: int = 2)[source]

Bases: object

High-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:
  • df (DataFrame) – Input DataFrame.

  • column_formats (Optional[Dict[str, Dict[str, Any]]]) – Format specifications per column.

  • row_colors (Optional[Dict[int, str]]) – Colors for specific rows.

  • alternating_rows (bool) – Whether to use alternating row colors.

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.

Parameters:
  • df (DataFrame) – Input DataFrame.

  • columns (Optional[List[str]]) – Columns to total (None for all numeric).

  • label (str) – Label for totals row.

  • operation (Literal['sum', 'mean', 'median']) – Aggregation operation.

Return type:

DataFrame

Returns:

DataFrame with totals row added.

add_footnotes(table_str: str, footnotes: List[str], output_format: str | None = None) str[source]

Add footnotes to a table string.

Parameters:
  • table_str (str) – Table string.

  • footnotes (List[str]) – List of footnote texts.

  • output_format (Optional[str]) – Output format (uses instance format if None).

Return type:

str

Returns:

Table with footnotes added.

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:
  • df (DataFrame) – DataFrame to export.

  • export_format (Literal['csv', 'excel', 'latex', 'html', 'markdown']) – Export format.

  • include_index (bool) – Whether to include row index.

  • **kwargs – Additional format-specific arguments.

Return type:

Optional[str]

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: object

Generate 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:

str

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.

Parameters:
  • df (DataFrame) – Input DataFrame.

  • metrics (Optional[List[str]]) – List of metrics to compute.

  • output_format (Optional[str]) – Output format.

Return type:

str

Returns:

Formatted 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.

Parameters:
  • data (Dict[str, Series]) – Dictionary mapping names to series.

  • caption (str) – Table caption.

  • output_format (Optional[str]) – Output format.

Return type:

str

Returns:

Formatted comparison table.

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:
  • alternatives (List[str]) – List of alternative names.

  • criteria (List[str]) – List of criteria names.

  • scores (ndarray) – Score matrix (alternatives x criteria).

  • weights (Optional[List[float]]) – Optional criteria weights.

  • output_format (Optional[str]) – Output format.

Return type:

str

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:
  • company_sizes (List[float]) – List of company asset sizes in dollars.

  • optimal_limits (Dict[float, Dict[str, float]]) – Dict mapping size to limits structure.

  • output_format (Optional[str]) – Output format (uses default if None).

  • include_percentages (bool) – Whether to include % of assets columns.

Return type:

str

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:
  • characteristics (List[str]) – List of company characteristic names.

  • recommendations (Dict[str, Dict[str, Any]]) – Dict mapping characteristics to recommendations.

  • output_format (Optional[str]) – Output format.

  • use_traffic_lights (bool) – Whether to apply traffic light coloring.

Return type:

str

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:

str

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:
  • loss_types (List[str]) – List of loss type names.

  • distribution_params (Dict[str, Dict[str, Any]]) – Parameters for each loss type.

  • output_format (Optional[str]) – Output format.

  • include_correlations (bool) – Whether to include correlation matrix.

Return type:

str

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:

str

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.

Parameters:
  • metrics (Dict[str, Dict[str, float]]) – Dictionary of metric categories and values.

  • output_format (Optional[str]) – Output format.

  • include_thresholds (bool) – Whether to include pass/fail thresholds.

Return type:

str

Returns:

Formatted statistical validation table.

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:
  • results (List[Dict[str, Any]]) – List of result dictionaries from optimization.

  • ranking_metric (str) – Metric to use for ranking.

  • output_format (Optional[str]) – Output format.

  • top_n (Optional[int]) – Show only top N results (None for all).

Return type:

str

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.

Parameters:
  • validation_results (List[Dict[str, Any]]) – List of validation period results.

  • output_format (Optional[str]) – Output format.

Return type:

str

Returns:

Formatted walk-forward validation table.

export_to_file(df: DataFrame, file_path: str, output_format: Literal['csv', 'excel', 'latex', 'html'], **kwargs) None[source]

Export DataFrame to file in specified format.

Parameters:
  • df (DataFrame) – DataFrame to export.

  • file_path (str) – Path to save file.

  • output_format (Literal['csv', 'excel', 'latex', 'html']) – Export format.

  • **kwargs – Additional format-specific arguments.

Return type:

None

create_performance_table(results: Dict[str, Any]) str[source]

Create a performance metrics table from simulation results.

Parameters:

results (Dict[str, Any]) – Dictionary of performance metrics.

Return type:

str

Returns:

Formatted performance table.

create_parameter_table(params: Dict[str, Any]) str[source]

Create a parameter summary table.

Parameters:

params (Dict[str, Any]) – Dictionary of parameters.

Return type:

str

Returns:

Formatted parameter table.

create_sensitivity_table(base_case: float, sensitivities: Dict[str, List[float]], parameter_ranges: Dict[str, List[float]]) str[source]

Create a sensitivity analysis table.

Parameters:
  • base_case (float) – Base case value.

  • sensitivities (Dict[str, List[float]]) – Sensitivity results by parameter.

  • parameter_ranges (Dict[str, List[float]]) – Parameter test ranges.

Return type:

str

Returns:

Formatted sensitivity table.

class ReportBuilder(config: ReportConfig, cache_dir: Path | None = None)[source]

Bases: ABC

Base 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:

Path

Returns:

Path to generated report file.

build_section(section: SectionConfig) str[source]

Build a report section.

Parameters:

section (SectionConfig) – Section configuration.

Return type:

str

Returns:

Formatted section content.

compile_report() str[source]

Compile all sections into complete report.

Return type:

str

Returns:

Complete report content as string.

save(output_format: str = 'markdown') Path[source]

Save report in specified format.

Parameters:

output_format (str) – Output format (markdown, html, pdf).

Return type:

Path

Returns:

Path to saved report.

class ExecutiveReport(results: Dict[str, Any], config: ReportConfig | None = None, cache_dir: Path | None = None)[source]

Bases: ReportBuilder

Generate 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:

Path

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:

Figure

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:

Figure

Returns:

Matplotlib figure.

generate_convergence_table() DataFrame[source]

Generate convergence metrics table.

Return type:

DataFrame

Returns:

Convergence metrics DataFrame.

class TechnicalReport(results: Dict[str, Any], parameters: Dict[str, Any], config: ReportConfig | None = None, cache_dir: Path | None = None)[source]

Bases: ReportBuilder

Generate 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:

Path

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:

Figure

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:

Figure

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:

Figure

Returns:

Matplotlib figure.

class ReportValidator(config: ReportConfig)[source]

Bases: object

Validate 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.

validate() Tuple[bool, List[str], List[str]][source]

Run complete validation suite.

Return type:

Tuple[bool, List[str], List[str]]

Returns:

Tuple of (is_valid, errors, warnings).

validate_results_data(results: Dict[str, Any]) Tuple[bool, List[str]][source]

Validate results data for report generation.

Parameters:

results (Dict[str, Any]) – Results dictionary to validate.

Return type:

Tuple[bool, List[str]]

Returns:

Tuple of (is_valid, error_messages).

validate_parameters(params: Dict[str, Any]) Tuple[bool, List[str]][source]

Validate model parameters.

Parameters:

params (Dict[str, Any]) – Parameters dictionary to validate.

Return type:

Tuple[bool, List[str]]

Returns:

Tuple of (is_valid, error_messages).