Skip to main content

Financial modeling for widget manufacturers with ergodic insurance limits

Project description

Ergodic Insurance Limits

Rationalizing and optimizing insurance purchasing decisions.

Repo Banner

This research model applies Ole Petersโ€™ ergodic economics framework to insurance optimization for a widget manufacturing company, demonstrating that traditional expected value approaches systematically mislead insurance decisions. By optimizing time-average growth rates (for a single company) rather than ensemble averages (across many companies), the model aims to demonstrate that insurance premiums can significantly exceed expected losses while still enhancing long-term growth, transforming insurance from a cost center to a growth enabler. The implementation features:

  • A comprehensive Monte Carlo simulation engine with stochastic processes (GBM, mean-reversion)
  • Multi-layer insurance programs with collateral management
  • Extensive configuration architecture
  • CPU-optimized parallel processing

Documentation Status Ask DeepWiki

Introduction - Why Do Companies Buy Insurance?

Ergodic theory transforms insurance optimization fundamentally

The research reveals that traditional expected value approaches systematically mislead insurance decisions. Ole Peters' ergodic economics framework demonstrates that insurance creates win-win scenarios when analyzed through time averages rather than ensemble averages. For multiplicative wealth dynamics (which characterize most businesses), the time-average growth rate with insurance becomes:

$$g = \lim_{T\to\infty}{\frac{1}{T}\ln{\frac{x(T)}{x(0)}}}$$

This framework resolves the fundamental insurance puzzle: while insurance appears zero-sum in expected value terms, both parties benefit when optimizing time-average growth rates. For our widget manufacturing model with $10M starting assets, the hypothesis is that optimal insurance premiums can exceed expected losses by 200-500% while still enhancing long-term growth. This package is being built to validate this hypothesis.

Value Proposition

Ergodic Distinction Between Averages

The framework fundamentally reframes insurance from a cost center to growth enabler. By optimizing time-average growth rates rather than expected values, widget manufacturers can achieve 30-50% better long-term performance while maintaining acceptable ruin probabilities. The key insight: maximizing ergodic growth rates naturally balances profitability with survival, eliminating the need for arbitrary risk preferences or utility functions.

This comprehensive framework provides the mathematical rigor, practical parameters, and implementation roadmap necessary for successful insurance optimization in widget manufacturing, with the ergodic approach offering genuinely novel insights that challenge conventional risk management wisdom.

Key Features

flowchart LR
    MODEL["<b>๐Ÿญ Financial Model</b><br/>Widget Manufacturer<br/>Double-Entry Accounting<br/>Multi-Layer Insurance<br/>Stochastic Loss Processes"]

    SIM["<b>๐ŸŽฒ Simulation Engine</b><br/>Parallel Monte Carlo<br/>100K+ Paths<br/>Convergence Monitoring"]

    ERGODIC["<b>โšก Ergodic Optimization</b><br/>Time-Average vs Ensemble<br/>8 Optimization Algorithms<br/>HJB Optimal Control<br/>Pareto Frontier Analysis"]

    OUTPUT["<b>๐Ÿ“Š Insights & Reports</b><br/>40+ Visualization Types<br/>VaR ยท TVaR ยท Ruin Metrics<br/>Walk-Forward Validation<br/>Excel & HTML Reports"]

    MODEL ==> SIM ==> ERGODIC ==> OUTPUT
    ERGODIC -.->|"โ™ป๏ธ Strategy Refinement"| MODEL

    classDef default fill:#f8f9fa,stroke:#dee2e6,stroke-width:2px,color:#212529
    classDef hero fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#1b5e20

    class ERGODIC hero

Ergodic Analysis

  • Time-average vs ensemble-average growth โ€” the core framework for evaluating insurance decisions
  • Scenario comparison with statistical significance testing (insured vs uninsured trajectories)
  • Convergence validation to ensure time-average estimates are reliable
  • Loss-integrated ergodic analysis connecting loss processes to growth rate impacts

Monte Carlo Simulation

  • Single-trajectory simulation engine for detailed time-series analysis
  • Parallel Monte Carlo engine with convergence monitoring and checkpoint support
  • Bootstrap confidence intervals for ruin probability and key metrics
  • CPU-optimized parallel executor designed for budget hardware (4-8 cores, 100K+ simulations in <4GB RAM)

Financial Modeling

  • Widget manufacturer model with 75+ methods for revenue, expenses, and balance sheet management
  • Double-entry ledger with event-sourced accounting and trial balance generation
  • Full financial statement generation โ€” balance sheets, income statements, cash flow statements with GAAP compliance
  • Stochastic processes including geometric Brownian motion, mean-reversion, and lognormal volatility
  • Multi-year claim liability scheduling and collateral/letter of credit tracking

Insurance Modeling

  • Multi-layer insurance programs with attachment points, limits, and reinstatement provisions
  • Market cycle-aware pricing (soft/normal/hard markets) with cycle transition simulation
  • Multiple limit types and aggregate limit tracking with layer utilization monitoring
  • Actuarial claim development patterns (standard, slow, fast) with cash flow projection

Optimization

  • 8 optimization algorithms โ€” SLSQP, Differential Evolution, Trust Region, Penalty Method, Augmented Lagrangian, Multi-Start, and more
  • Business outcome optimizer โ€” maximize ROE, minimize bankruptcy risk, optimize capital efficiency
  • HJB optimal control solver โ€” stochastic control via Hamilton-Jacobi-Bellman PDE with multiple utility functions
  • Multi-objective Pareto frontier generation (weighted-sum, epsilon-constraint, evolutionary methods)

Risk Metrics & Validation

  • Comprehensive risk metrics โ€” VaR, TVaR, Expected Shortfall, PML, maximum drawdown, economic capital
  • Ruin probability analysis with multi-horizon support and bootstrap confidence intervals
  • Walk-forward validation with out-of-sample testing across rolling windows
  • Strategy backtesting with pre-built strategies (conservative, aggressive, adaptive, optimized)

Visualization & Reporting

Sample Analytics: Optimal Insurance Configuration by Company Size

  • 40+ executive and technical plots โ€” ROE-ruin frontiers, ruin cliffs, tornado diagrams, convergence diagnostics, Pareto frontiers
  • Interactive dashboards (Plotly-based) for exploration
  • Excel report generation with cover sheets, financial statements, metrics dashboards, and pivot data
  • Automated insight extraction โ€” performance, trend, outlier, threshold, and correlation insights
  • 30+ Jupyter notebooks for interactive analysis and exploration

Configuration System

  • 3-tier architecture โ€” profiles, modules, and presets with inheritance
  • ConfigManager with profile loading, module composition, and runtime overrides
  • Industry-specific configs (manufacturing, service, retail) and market condition presets

Professional Standards and Disclaimers

This framework provides actuarial research tools subject to ASOP No. 41: Actuarial Communications and ASOP No. 56: Modeling. Full compliance disclosures are in ergodic_insurance/docs/user_guide/actuarial_standards.rst.

Research Use Only. This is an early-stage research tool. It does not constitute an actuarial opinion or rate filing. Outputs are intended for qualified actuaries who can independently validate the methodology and results.

Responsible Actuary: Alex Filiakov, ACAS. Review is ongoing; the responsible actuary does not currently take responsibility for the accuracy of the methodology or results. See the full Actuarial Standards Compliance document.

Key Limitations:

  • Outputs should not be used for regulatory filings, rate opinions, or reserve opinions without independent actuarial analysis.
  • Results are illustrative and depend on input assumptions. Treat them as directional guidance, not prescriptive recommendations.
  • The framework embeds simplifying assumptions (Poisson frequency, log-normal severity, no regulatory capital, deterministic margins) documented in the compliance disclosures.
  • Development involved extensive reliance on Large Language Models for research and code generation.

Conflict of Interest: The responsible actuary is employed by an insurance broker. See the compliance document for full disclosure and mitigation measures.

Published Results

Reproducible Research

Ergodic Insurance Under Volatility

Traditional insurance analysis says companies should self-insure whenever premiums exceed expected losses. A 250,000-path Monte Carlo simulation over 50-year horizons shows this advice is directionally wrong: the strategy that minimizes expected costs (no insurance) produces the worst actual compound growth, while guaranteed cost insurance achieves the highest growth despite costing the most. The mechanism is the Volatility Tax: large losses destroy more growth than their expected value suggests because wealth compounds multiplicatively. Without insurance, 37.8% of simulated firms go insolvent; with full coverage, just 0.01% do. The entire experiment is reproducible on Google Colab for ~$25. See the project README for setup instructions and parameters to tweak.


Installation

Prerequisites

  • Python 3.12 or higher
  • Git

Setup

  1. Clone the repository:
git clone https://github.com/AlexFiliakov/Ergodic-Insurance-Limits.git
cd Ergodic-Insurance-Limits
  1. Install dependencies using uv (recommended) or pip:
# Using uv
uv sync

# Or using pip
pip install -e .

Developer Setup

If you plan to contribute, run the one-time setup script to install dev dependencies and pre-commit hooks (black, isort, mypy, pylint, conventional commit enforcement):

python ergodic_insurance/scripts/setup_dev.py

Or do it manually:

pip install -e ".[dev]"
pre-commit install
pre-commit install --hook-type commit-msg

Quick Start

from ergodic_insurance import run_analysis

results = run_analysis(
    initial_assets=10_000_000,
    loss_frequency=2.5,
    loss_severity_mean=1_000_000,
    deductible=500_000,
    coverage_limit=10_000_000,
    premium_rate=0.025,
    n_simulations=1000,
    time_horizon=20,
)
print(results.summary())   # human-readable comparison
results.plot()              # 2ร—2 insured-vs-uninsured chart
df = results.to_dataframe() # per-simulation metrics

Verify Installation

# test_installation.py
from ergodic_insurance import run_analysis

print("Framework imported successfully!")

# Quick smoke test with minimal simulations
results = run_analysis(n_simulations=5, time_horizon=5, seed=42)
print(results.summary())
print("Installation successful!")

Exploratory Notebooks

Documentation

See Getting Started for starter examples.

Project Structure

Ergodic-Insurance-Limits/
โ”œโ”€โ”€ ergodic_insurance/          # Main Python package (60+ modules)
โ”‚   โ”œโ”€โ”€ manufacturer.py        # Widget manufacturer financial model with balance sheet management
โ”‚   โ”œโ”€โ”€ simulation.py          # Main simulation orchestrator
โ”‚   โ”œโ”€โ”€ monte_carlo.py         # Enhanced Monte Carlo engine with parallel processing
โ”‚   โ”œโ”€โ”€ ergodic_analyzer.py    # Ergodic theory implementation for time-average growth analysis
โ”‚   โ”œโ”€โ”€ insurance.py           # Core insurance policy and layer definitions
โ”‚   โ”œโ”€โ”€ insurance_program.py   # Multi-layer insurance program management
โ”‚   โ”œโ”€โ”€ insurance_pricing.py   # Insurance pricing models
โ”‚   โ”œโ”€โ”€ loss_distributions.py  # Statistical loss modeling (lognormal, pareto, etc.)
โ”‚   โ”œโ”€โ”€ config.py              # Configuration system - 3-tier architecture with profiles/modules/presets
โ”‚   โ”œโ”€โ”€ risk_metrics.py        # VaR, CVaR, tail risk, and ruin probability calculations
โ”‚   โ”œโ”€โ”€ optimization.py        # Core optimization algorithms and solvers
โ”‚   โ”œโ”€โ”€ business_optimizer.py  # Business-specific optimization strategies
โ”‚   โ”œโ”€โ”€ decision_engine.py     # Decision framework for insurance purchasing
โ”‚   โ”œโ”€โ”€ financial_statements.py # Full financial statement generation
โ”‚   โ”œโ”€โ”€ stochastic_processes.py # GBM, mean-reversion, and volatility models
โ”‚   โ”œโ”€โ”€ parallel_executor.py   # CPU-optimized parallel processing for budget hardware
โ”‚   โ”œโ”€โ”€ walk_forward_validator.py # Walk-forward validation framework
โ”‚   โ”œโ”€โ”€ strategy_backtester.py # Insurance strategy backtesting
โ”‚   โ”œโ”€โ”€ ...                    # + convergence, sensitivity, bootstrap, reporting modules
โ”‚   โ”œโ”€โ”€ visualization/         # Plotting package (executive, technical, batch, interactive)
โ”‚   โ”œโ”€โ”€ visualization_infra/   # Visualization infrastructure (figure factory, style manager)
โ”‚   โ”œโ”€โ”€ reporting/             # Report generation (executive, technical, scenario comparator)
โ”‚   โ”œโ”€โ”€ tests/                 # Test suite (100+ test files)
โ”‚   โ”œโ”€โ”€ notebooks/             # Jupyter notebooks (30+) for analysis and exploration
โ”‚   โ”œโ”€โ”€ examples/              # Demo scripts showing framework usage
โ”‚   โ”œโ”€โ”€ data/                  # Configuration and parameter files
โ”‚   โ”‚   โ””โ”€โ”€ config/            # 3-tier configuration system
โ”‚   โ”‚       โ”œโ”€โ”€ profiles/      # Complete configuration profiles (default, conservative, aggressive)
โ”‚   โ”‚       โ”œโ”€โ”€ modules/       # Reusable configuration components
โ”‚   โ”‚       โ””โ”€โ”€ presets/       # Quick-apply market condition templates
โ”‚   โ”œโ”€โ”€ docs/                  # Sphinx documentation source (API reference, tutorials, theory)
โ”‚   โ””โ”€โ”€ scripts/               # Utility and migration scripts
โ”œโ”€โ”€ docs/                      # GitHub Pages documentation
โ”œโ”€โ”€ tutorials/                 # Published tutorial pages
โ”œโ”€โ”€ assets/                    # Images, diagrams, and visual resources
โ”œโ”€โ”€ results/                   # Simulation outputs and analysis reports
โ”œโ”€โ”€ simone/                    # AI project management engine
โ”œโ”€โ”€ .github/workflows/         # CI/CD pipelines for docs and testing
โ”œโ”€โ”€ pyproject.toml             # Python project configuration and dependencies
โ”œโ”€โ”€ uv.lock                   # Locked dependency versions for reproducibility
โ”œโ”€โ”€ README.md                 # Project overview and documentation (this file)
โ”œโ”€โ”€ CLAUDE.md                 # AI assistant development instructions
โ””โ”€โ”€ LICENSE                   # MIT open source license

Contributing

See the Codebase Onboarding Guide for the project preliminaries.

See the list of Open Issues for improvement ideas.

Refer to this Wiki for code questions: Ask DeepWiki

First-Time Setup

After cloning, run the developer setup script to install dependencies and pre-commit hooks:

python ergodic_insurance/scripts/setup_dev.py

This installs the package in editable mode with dev extras, and configures pre-commit and commit-msg hooks so that black, isort, mypy, pylint, and conventional commit checks run automatically on every commit.

Code Quality Tools

This project uses several tools to maintain code quality:

  • Black: Code formatting (line length: 100)
  • isort: Import sorting
  • mypy: Static type checking
  • pylint: Code linting
  • pytest-cov: Test coverage reporting (minimum: 80%)

Running Tests

# Run all tests with coverage
pytest

# Run specific test file
pytest ergodic_insurance/tests/test_manufacturer.py

# Run with coverage report
pytest --cov=ergodic_insurance --cov-report=html

Pre-commit Hooks

Pre-commit hooks run automatically on commit. To run manually:

# Run on all files
pre-commit run --all-files

# Run specific hook
pre-commit run black --all-files

Type Checking

# Run mypy
mypy ergodic_insurance

# Run with specific file
mypy ergodic_insurance/manufacturer.py

Code Formatting

# Format with black
black ergodic_insurance

# Sort imports with isort
isort ergodic_insurance

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ergodic_insurance-0.13.0.tar.gz (1.6 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ergodic_insurance-0.13.0-py3-none-any.whl (1.8 MB view details)

Uploaded Python 3

File details

Details for the file ergodic_insurance-0.13.0.tar.gz.

File metadata

  • Download URL: ergodic_insurance-0.13.0.tar.gz
  • Upload date:
  • Size: 1.6 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ergodic_insurance-0.13.0.tar.gz
Algorithm Hash digest
SHA256 541ee9c22180fa3be8a1732f77953f539558e6069001d8e3009176b767de2957
MD5 b80fe1b00ac1f1eb79230d4d2a56da26
BLAKE2b-256 a5246889b34f295b232be073b386930b8c4c1f7704147fc1cd119fd80ffbefe7

See more details on using hashes here.

File details

Details for the file ergodic_insurance-0.13.0-py3-none-any.whl.

File metadata

File hashes

Hashes for ergodic_insurance-0.13.0-py3-none-any.whl
Algorithm Hash digest
SHA256 babb5f23f0ce6888d27910ec75730c5db17f18f71c68d6dcf1fca13c30957de0
MD5 b79c76e9695b7306f57f996fa8af3fd5
BLAKE2b-256 d146da01c551e6c4d120c69aa83a8baecc80e3ffe192ede81803ee8e412d8b00

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page