Skip to main content

Crate reserving_kernels

Crate reserving_kernels 

Source
Expand description

reserving-kernels — Actuarial computing in Rust

Pure Rust numeric kernels for P&C actuarial reserving and reserve-risk capital modeling.

CI Rust 1.97+ License: MIT or Apache-2.0 No unsafe code Dependencies: serde only WebAssembly target

Quick Start  ·  Modules  ·  Performance  ·  Verification  ·  Build & Test  ·  Literature


reserving-kernels covers retrospective loss development, stochastic reserving, and the reserve risk module of capital modeling (1-year CDR, multi-line dependence, and capital allocation). Every method is implemented from peer-reviewed actuarial literature (docs/SOURCES.md) and verified against published benchmark triangles (tests/source_benchmarks.rs).

§Why reserving-kernels?

  • Zero heavy dependencies: Pure Rust with no BLAS, LAPACK, FFTW, or ndarray. Linear algebra, IRLS, and FFT routines are built in and compile cleanly to wasm32 (--features wasm).
  • Validated flat triangles: Row-major f64 grids using NaN for unobserved cells, with explicit monotonicity validation and support for negative development in incurred or reinsurance triangles.
  • Deterministic by design: Fixed-seed PRNG streams and custom samplers keep ODP bootstraps, multi-line correlations, and Monte Carlo runs reproducible across native and browser targets.

§Quick Start

Add reserving-kernels to your Cargo.toml:

[dependencies]
reserving-kernels = { git = "https://github.com/SinisterRob/reserving-kernels" }

Basic triangle reserving and aggregate loss convolution:

use reserving_kernels::prelude::*;

fn main() -> Result<(), ValidationError> {
    // Build from upper-triangle rows (no manual NaN padding needed)
    let triangle = Triangle::try_from_upper_rows(&[
        &[100.0, 160.0, 195.0, 205.0],
        &[120.0, 190.0, 232.0],
        &[135.0, 218.0],
        &[150.0],
    ])?;

    // Mack ultimate reserve & standard error
    let mack = triangle.mack(1.0)?;
    println!(
        "Mack reserve: {:.2} (SE: {:.2}, CV: {:.1}%)",
        mack.total_reserve,
        mack.total_standard_error,
        mack.total_cv * 100.0,
    );

    // Merz–Wüthrich 1-year Claims Development Result (Solvency II)
    let cdr = triangle.merz_wuthrich()?;
    println!("1-yr CDR SE:  {:.2}", cdr.total_cdr_standard_error);
    assert!(cdr.total_cdr_standard_error <= mack.total_standard_error);

    // Aggregate loss: Panjer recursion vs. FFT
    let freq = FrequencyDistribution::Poisson { lambda: 3.0 };
    let severity_pmf = [0.0, 0.5, 0.3, 0.2];
    let panjer = panjer_recursion(freq, &severity_pmf, 100.0, 128)?;
    let fft = fft_aggregate_loss(freq, &severity_pmf, 100.0, 128, None)?;
    assert!((panjer.mean - fft.mean).abs() < 1e-8);

    Ok(())
}

§Implemented Modules

reserving-kernels is organized into four areas covering 54 public modules (plus optional wasm_exports behind --features wasm).

AreaHighlights
1. Loss Development & Point EstimatorsChain Ladder, Bornhuetter–Ferguson, Benktander, Cape Cod (standard & generalized), Berquist–Sherman, Munich & Double Chain Ladder, Separation, sub-annual grids
2. Stochastic Reserving, 1-Year Risk & GLMsMack (uni/multivariate & BF), Merz–Wüthrich 1-year CDR, ODP/Gamma/Tweedie GLMs, ODP Bootstrap, Paid–Incurred Chain, Kalman & individual-claim reserving
3. Dependence, Aggregate Loss & Capital AllocationIman–Conover rank correlation, synchronized multi-line bootstrap, Panjer & FFT aggregate loss convolution, VaR/TVaR/RVaR, Euler & Myers–Read allocation
4. Excess Layering, Severity & DiagnosticsParametric severity & LEV/excess ratios, excess-layer development, Mack diagnostic tests, backtesting, roll-forwards, and preprocessing utilities
Full module directory (54 public modules)

§1. Loss Development & Point Estimators

ModuleCapabilities
types, triangle, validateFlat row-major Triangle / TriangleView, monotonicity policies, and validation errors
ldfVolume-weighted, simple, geometric, median, trimmed, last-N, and masked LDFs/CDFs
tailBondy, Generalized Bondy, Exponential, Inverse Power, Weibull, Clark growth-curve, and Mack tail variance
chain_ladderUnchecked hot-path kernels and checked ChainLadderEngine
bfBornhuetter–Ferguson reserve indications with scalar, vector, or a priori inputs
benktanderClosed-form m-iteration credibility recursion and MSE-optimal weights
cape_cod, generalized_cape_codStandard and decay-weighted Cape Cod ELR estimation
case_outstandingPaid-to-case and case-to-case development from aligned triangles
incremental_additiveExposure-weighted incremental loss ratios with optional trend
berquist_shermanCase-reserve adequacy restatement and paid disposal-rate interpolation
brosius, murphyCentered OLS credibility and generalized weighted-regression CL with exact MSE
separationArithmetic and geometric separation of delay patterns and calendar inflation
credibility_clBühlmann–Straub shrinkage of LDFs toward collective priors with analytical MSEP
munich_chain_ladderBivariate paid/incurred CL closing the paid-vs-incurred gap
schnieperTwo-triangle True IBNR vs. IBNER separation with Mack-style MSEP
double_chain_ladderPaid + count deconvolution into reporting/payment delays, severity inflation, and RBNS/IBNR
subannualAsymmetric grids (2:1/4:1/12:1), 7 CDF/LDF interpolators, Bloom stubs, asymmetric CL/BF/Cape Cod/Clark/ODP, and parity checks
datasetsZero-I/O benchmark triangles (RAA, GenIns, Quarg & Mack, Friedland Auto)
ragged, triangle_algebraLow-level ragged link selectors and allocation-free slice transforms

§2. Stochastic Reserving, 1-Year Risk & GLMs

ModuleCapabilities
mack, multivariate_mackDistribution-free CL standard errors (single & correlated multi-line) with stochastic tails
mack_bfAnalytical BF MSEP decomposing process, prior, pattern, and interaction variance
merz_wuthrich1-year Solvency II CDR analytical MSEP and multi-year run-off decomposition
multivariate_clJoint K-line Diagonal MCL and General GMCL with full cross-line covariance
paid_incurred_chainBayesian log-normal joint paid/incurred model with closed-form posterior & MSEP
hertigExact closed-form log-normal link-ratio moments and quantiles
kalman_reservingRecursive Kalman filter over calendar diagonals for dynamic inflation shifts
micro_reservingIndividual-claim reserving (NHPP, reporting delay, multi-state RBNS + IBNR simulation)
clark_mleLoglogistic & Weibull growth-curve ODP MLE with Cramér–Rao standard errors
ptf_regressionProbabilistic Trend Family log-linear regression for accident, dev, and calendar trends
glm_reservingBuilt-in QR IRLS engine for ODP, Gamma, Tweedie, and Log-normal GLMs
bootstrap_odpODP GLM bootstrap with hat-matrix leverages, process variance, and 1-year CDR re-reserving

§3. Dependence, Aggregate Loss & Capital Allocation

ModuleCapabilities
dependenceIman–Conover rank reordering and synchronized multi-line ODP bootstrap
reserve_distributionEmpirical moments, VaR, coherent TVaR, and RVaR
aggregate_lossPanjer (a, b, 0) recursion, exponentially tilted FFT, and severity discretization
capital_allocationEuler allocation (TVaR, RVaR, SD) and Myers–Read marginal default-put allocation

§4. Excess Layering, Severity & Diagnostics

ModuleCapabilities
severityClosed-form LEV, survival/PDF, layer losses, and excess ratios (Lognormal, Pareto, Exponential, Mixed Exp, GPD)
excess_layersParametric layering, exceedance probabilities, and antithetic Monte Carlo simulation
excess_developmentExcess-of-L, limited-to-L, and bounded-layer CDFs/LDFs with exact conservation
diagnosticsMack Spearman & calendar-year tests, actual vs. expected, leave-one-out fragility, and paid/incurred reconciliation
selection, reserve_rollforward, exhibitHoldout LDF backtesting, valuation roll-forwards, and JSON exhibit DTOs
large_loss, trend, onlevelLarge-loss capping, loss trending, and parallelogram rate on-leveling
count_development, apriori, aggregateClaim-count development, a priori loss-ratio builders, and triangle aggregation

§Performance

Single-threaded benchmarks on an Intel Core i9-14900K comparing reserving-kernels (--release) against mages/ChainLadder 0.2.21 (R) and casact/chainladder-python 0.10.1 (Python) on identical triangles:

reserving-kernels vs R ChainLadder and chainladder-python benchmark comparison

Benchmarkreserving-kernelsR ChainLadderchainladder-pythonvs. Rvs. Python
Volume-Weighted LDFs (40×40)0.28 µs840 µs5,710 µs3,030×20,610×
Mack Chain Ladder (RAA 10×10)0.26 µs5,840 µs25,446 µs22,090×96,270×
Mack Chain Ladder (40×40)3.07 µs24,650 µs30,077 µs8,020×9,790×
Merz–Wüthrich 1-Yr CDR (RAA)0.39 µs9,420 µs—23,890×—
Clark Loglogistic MLE (GenIns)11.5 µs8,300 µs12,026 µs720×1,040×
ODP GLM Reserve (GenIns)42.9 µs5,300 µs219.6 ms124×5,120×
ODP Bootstrap (GenIns, 1k sims)0.19 ms216.5 ms76.8 ms1,150×409×
ODP Bootstrap (GenIns, 10k sims)1.91 ms2,223 ms416.2 ms1,160×218×

Note: reserving-kernels operates directly on validated f64 slices with reusable scratch space, whereas the R and Python libraries carry DataFrame and S3/S4 object overhead. All point estimates and Mack / Merz–Wüthrich standard errors were verified for numerical parity before timing.

§Verification

Kernels are tested against published actuarial datasets and closed-form mathematical identities:

  • Benchmark triangles: Mack (1993) RAA, Taylor & Ashe / England & Verrall GenIns, Friedland US Industry Auto, and Quarg & Mack (2004).
  • Exact identities: Merz–Wüthrich multi-year run-off summing to Mack ultimate MSEP; ODP GLM matching exact analytical leverages and dispersion; Panjer vs. FFT aggregate loss agreement; and full-allocation conservation for Euler TVaR and Myers–Read.

Full citations and equation mappings live in docs/SOURCES.md; parity tests live in tests/source_benchmarks.rs.

§Building and Testing

# Run unit, integration, doctest, and benchmark-parity tests
cargo test --all-targets --all-features
cargo test --doc --all-features

# Run the JSON exhibit example
cargo run --example export_exhibit

# Run Criterion benchmarks (benches/kernels.rs & benches/triangle_algebra.rs)
cargo bench --bench kernels -- --save-baseline main
cargo bench --bench kernels -- --baseline main

# Profile a specific kernel under release optimization (requires samply)
samply record cargo bench --bench kernels -- glm_odp_genins --profile-time 5

# Build for WebAssembly
cargo build --release --target wasm32-unknown-unknown --features wasm

§License

Licensed under either of MIT or Apache-2.0 at your option.

Re-exports§

pub use types::Triangle;
pub use types::TriangleView;

Modules§

aggregate
Portfolio-level slice reducers.
aggregate_loss
Compound aggregate loss distributions via Panjer (1981) recursion and Robertson (1992) tilted radix-2 FFT characteristic-function inversion.
apriori
Shared a priori expected-ultimate builders for BF-style methods.
benktander
Benktander–Hovinen iterated Bornhuetter–Ferguson credibility reserving method.
berquist_sherman
Berquist & Sherman (1977) operational loss-reserve adjustments.
bf
Bornhuetter–Ferguson reserving method.
bootstrap_odp
Over-Dispersed Poisson (ODP) GLM and residual bootstrap reserving kernel.
brosius
Brosius least-squares development.
cape_cod
Cape Cod / Stanard–Bühlmann method.
capital_allocation
Coherent capital allocation via Tasche’s (2008) Euler principle and Myers & Read’s (2001) marginal default-put allocation.
case_outstanding
Case Outstanding (Paid-to-Case & Case-to-Case) reserving kernel.
chain_ladder
Chain-ladder projection.
clark_mle
Clark (2003) LDF & Cape Cod parametric growth-curve MLE and stochastic reserving kernel.
count_development
Claim-count development kernels.
credibility_cl
Bühlmann–Straub credibility for the Chain-Ladder reserving method.
datasets
Canonical published P&C actuarial benchmark datasets.
dependence
Multi-line portfolio dependence: Iman–Conover rank reordering and synchronized multi-line ODP bootstrapping.
diagnostics
Diagnostic kernels that audit triangles and factor behavior without crossing into product-level actuarial judgment.
double_chain_ladder
Martínez-Miranda, Nielsen & Verrall (2012) Double Chain Ladder (DCL).
excess_development
Excess-of-loss and limited-loss development factors.
excess_layers
Lognormal severity layering and Limited Expected Values (LEV).
exhibit
Typed actuarial exhibit DTOs over the reserving kernels.
generalized_cape_cod
Generalized (Decay-Weighted) Cape Cod reserving method — Gluck (1997).
glm_reserving
Generalized Linear Model (GLM) stochastic loss reserving via Iteratively Reweighted Least Squares (IRLS) — Taylor & McGuire (2016).
hertig
Hertig (1985) exact closed-form log-normal link-ratio reserving model.
incremental_additive
Incremental Additive reserving kernel (Schmidt 2006 / Friedland).
kalman_reserving
State-Space & Kalman Filter Loss Reserving.
large_loss
Large-loss triangle transforms.
ldf
Age-to-age development factors and CDF construction.
mack
Mack’s distribution-free chain-ladder standard error.
mack_bf
Mack (2008) distribution-free analytical MSEP for Bornhuetter–Ferguson.
merz_wuthrich
Merz & Wüthrich (2008) 1-year Claims Development Result (CDR) analytical MSEP for Solvency II / 1-year capital horizons.
micro_reserving
Antonio & Plat (2014) micro-level individual-claim stochastic reserving.
multivariate_cl
Multivariate Chain Ladder (Zhang 2010 / Pröhl & Schmidt 2005).
multivariate_mack
Multivariate Chain-Ladder analytical MSEP for correlated run-off triangles.
munich_chain_ladder
Munich Chain Ladder (MCL) bivariate paid/incurred reserving method.
murphy
Murphy (1994) generalized weighted-regression loss development factors.
onlevel
Premium on-level transforms.
paid_incurred_chain
Merz & Wüthrich (2010) Paid-Incurred Chain (PIC) Bayesian log-normal joint paid/incurred reserving model.
prelude
Convenient re-exports of the most commonly used reserving types and engines.
ptf_regression
Barnett & Zehnwirth (2000) Probabilistic Trend Family (PTF) log-linear regression reserving kernel.
ragged
Factor selection for rectangular cumulative triangles.
reserve_distribution
Shared summary math and coherent risk measures for reserve-simulation output.
reserve_rollforward
Reserve roll-forward kernels.
schnieper
Schnieper (1991) & Liu–Verrall (2009) True IBNR / IBNER Separation.
selection
Selection and backtesting kernels for deterministic factor choices.
separation
Taylor (1977) Arithmetic and Geometric Separation Methods.
severity
Severity kernels: empirical claim-count ratios and parametric severity distributions for Limited Expected Values (LEV), excess ratios, and layer loss development.
subannual
Sub-annual development (semiannual/quarterly/monthly), asymmetric grids, and pre-12-month stub-period reserving kernels.
tail
Parametric and heuristic tail-factor fitting kernels.
trend
Deterministic trend transforms for vectors and triangles.
triangle
Triangle helpers: cumulative ↔ incremental conversion, latest-diagonal extraction, individual age-to-age ratios.
triangle_algebra
Allocation-free numeric kernels for triangle algebra.
types
Prevalidated columnar triangle inputs.
validate
Input validation — kept deliberately off the compute hot path.