# An ILS deal analysis with prospicio

An investment fund gets an offer of a share of a cedant's 2026 premium as a **collateralised reinsurance** deal. The insurance-linked securities (ILS) market writes this kind of deal. The fund puts collateral in a trust, and the cedant pays premium into the trust. The trust pays the losses, and the fund gets the remainder when the deal commutes.

The fund asks about the return to its investors, not about the technical price. What return does the deal give, how likely is a loss, and how do the alternative structures compare? This notebook answers these questions in `prospicio`, in six steps:

1.  read a submission and build the cedant's loss triangle,
2.  show the historical exhibits and test how well a Bayesian model forecasts the cedant's history,
3.  estimate an industry prior from peer triangles, and fit the cedant's ultimates against it,
4.  draw the 2026 loss ratio from the fit, and apply the reinsurance structure, the collateral and the cash flows to it,
5.  read the investor's IRR, MOIC and downside from the simulations, and compare two structures,
6.  after binding, compare the next diagonal of actual losses with the one-year forecast.

The workflow is generic: a data submission, a loss model, a contract, a collateral rule and an investor.

**The data.** The submission is the synthetic one of `submission_evaluation.ipynb`. `examples/data/make_submission.py` wrote it from known parameters. Here the cedant offers a **20% quota share** of its commercial property book for 2026, not the per-risk layers of that notebook. Thus the loss to the fund is a share of the loss ratio of the cedant's whole book. All the deal terms below (the share, the commission, the collateral rule, the yield) are assumptions for the demonstration, not values in the files. Change them and run the notebook again.

To run the notebook, clone the repository and start Jupyter with prospicio built from source, which needs Rust. From the repository root, run `uv run --project python --group examples jupyter lab` (see `examples/README.md`). Set `PROSPICIO_EXAMPLE_SIMS` to run fewer simulations. The docs site publishes the results, and the repository keeps only the code.

``` python
import csv
import math
import os
from statistics import NormalDist
from pathlib import Path

try:
    from prospicio.distributions import Sampled
    from prospicio.pricing import (CashflowTerms, CollateralRequirement, DealBook, DealRun, Period, PaymentPattern,
                                   RateHistory, deal_ave, year_fraction)
    from prospicio.reinsurance import Layer, Tower
    from prospicio.reserving import (BayesBfNormalised, BayesOdp, ChainLadder, IndustryPrior, Triangle,
                                     UnderwritingBasis, diagonal_backtest)
    from prospicio.risk import risk_ratios, statistics
except ImportError as error:
    raise ImportError("this notebook needs prospicio 0.1.0 or later (`pip install -U prospicio`), or a build from "
                      "source, `uv run --project python --group examples jupyter lab` from the repository root") from error

N_SIMS = int(os.environ.get("PROSPICIO_EXAMPLE_SIMS", "10000"))
N_ONE_YEAR = min(N_SIMS, 1000)  # one-year simulations for the monitoring section
SAMPLER = dict(chains=4, tune=600, draws=600)  # small on purpose: the demo runs in a few minutes
SEED = 20261023

DATA = next((p / sub for p in [Path.cwd(), *Path.cwd().parents]
             for sub in ("examples/data/submission", "data/submission") if (p / sub).is_dir()), None)
if DATA is None:
    raise FileNotFoundError(
        f"examples/data/submission not found in {Path.cwd()} or above it: open this notebook from inside a clone "
        "of the repository (examples/data/make_submission.py writes the files)")


def read_csv(name):
    with open(DATA / name) as f:
        return list(csv.DictReader(f))


def when(text):
    y, m, d = map(int, text.split("-"))
    return year_fraction(y, m, d)


def money(x):
    return f"{x / 1e6:,.1f}m"


def show(rows, header):
    # A small text table: rows of strings under a header row.
    widths = [max(len(str(r[i])) for r in [header, *rows]) for i in range(len(header))]
    for r in [header, *rows]:
        print("  ".join(str(c).rjust(w) for c, w in zip(r, widths)))


def uniform(i):
    # The i-th point of a low-discrepancy sequence on (0, 1): the same numbers in the R twin, with no generator to differ.
    return (0.5 + i * 0.6180339887498949) % 1.0


def normal(i):
    return NormalDist().inv_cdf(uniform(i))


def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs)


def sd(xs):
    xs = list(xs)
    m = mean(xs)
    return math.sqrt(sum((x - m) ** 2 for x in xs) / len(xs))


print(f"submission files in {DATA.parent.name}/{DATA.name}; {N_SIMS} simulations, seed {SEED}")
```

    submission files in data/submission; 10000 simulations, seed 20261023


# 1. The submission and the cedant's triangle

A real submission comes as spreadsheets, and here it is CSV files. The analysis needs three items from it:

- the loss triangle (paid and incurred by accident year and age),
- the premium by year,
- the rate changes.

The rate changes restate the premium of each year at the **current rate level** (the *on-level* premium). Loss ratios are comparable across years only on that basis. The 2026 loss ratio forecast is on the 2026 on-level premium.

``` python
program = {r["item"]: r["value"] for r in read_csv("treaty_program.csv")}
SUBJECT_PREMIUM = {int(r["calendar_year"]): float(r["subject_premium"]) for r in read_csv("subject_premium.csv")}
YEARS = sorted(SUBJECT_PREMIUM)
P_2026 = float(program["estimated_subject_premium_income"])

rate_rows = read_csv("rate_changes.csv")
history = RateHistory([when(r["effective_date"]) for r in rate_rows],
                      [float(r["average_rate_change"]) for r in rate_rows])
onlevel = {y: SUBJECT_PREMIUM[y] * history.rate_level(Period.calendar(y, y + 1), 1.0).on_level_factor for y in YEARS}

tri_rows = read_csv("triangle.csv")
triangle = Triangle.from_long(
    [int(r["accident_year"]) for r in tri_rows],
    [int(r["development_months"]) for r in tri_rows],
    {"paid": [float(r["paid"]) for r in tri_rows],
     "incurred": [float(r["incurred"]) for r in tri_rows],
     "onlevel": [onlevel[int(r["accident_year"])] for r in tri_rows]},
)
print(f"cedant {program['cedant']}; {program['line_of_business']}; treaty year {program['period_start']} to {program['period_end']}")
print(f"estimated 2026 subject premium {money(P_2026)}; triangle origins {triangle.origins[0]} to {triangle.origins[-1]}, "
      f"{len(triangle.development)} ages")
```

    cedant Northgate Mutual (synthetic); commercial property, per risk excess of loss; treaty year 2026-01-01 to 2026-12-31
    estimated 2026 subject premium 179.9m; triangle origins 2016 to 2025, 10 ages


# 2. Historical exhibits and a backtest

Two exhibits show the history to the fund before it trusts a model. The **paid chain ladder** gives the cedant's payment pattern (the share of the ultimate loss paid by each age), a check on the pattern the model fits in section 4. The **loss ratio by accident year** at its latest age, on on-level premium, shows the level and the spread to compare with the prior.

``` python
chain = ChainLadder().fit(triangle, "paid")
CDF = list(chain.cdf)
AGES = [12 * (i + 1) for i in range(len(CDF))]
latest = {int(r["accident_year"]): (float(r["paid"]), float(r["incurred"]))  # last row per year is the latest age
          for r in tri_rows}
loss_ratio_now = {y: latest[y][1] / onlevel[y] for y in YEARS}

print("paid chain ladder: age (months), factor to ultimate, share paid")
show([(a, f"{c:.3f}", f"{1 / c:.1%}") for a, c in zip(AGES, CDF)], ("age", "cdf", "paid"))
print()
show([(y, money(onlevel[y]), money(latest[y][1]), f"{loss_ratio_now[y]:.1%}") for y in YEARS],
     ("year", "on-level prem", "incurred now", "incurred LR"))
```

    paid chain ladder: age (months), factor to ultimate, share paid
    age    cdf    paid
     12  2.560   39.1%
     24  1.381   72.4%
     36  1.130   88.5%
     48  1.044   95.7%
     60  1.016   98.4%
     72  1.007   99.3%
     84  1.002   99.8%
     96  1.001   99.9%
    108  1.000  100.0%
    120  1.000  100.0%

    year  on-level prem  incurred now  incurred LR
    2016         133.9m         41.5m        31.0%
    2017         138.0m         52.0m        37.7%
    2018         142.1m         57.9m        40.8%
    2019         146.4m         62.2m        42.5%
    2020         150.8m         70.8m        46.9%
    2021         155.3m         79.8m        51.4%
    2022         160.0m         80.5m        50.3%
    2023         164.7m         67.7m        41.1%
    2024         169.7m         83.7m        49.3%
    2025         174.8m         56.2m        32.2%

``` python
import matplotlib.pyplot as plt

fig, (left, right) = plt.subplots(1, 2, figsize=(10, 3.4))
left.plot([0, *[a / 12 for a in AGES]], [0, *[1 / c for c in CDF]], marker="o")
left.set_xlabel("years since the start of the accident year")
left.set_ylabel("share of ultimate paid")
left.set_title("Paid pattern (chain ladder)")
right.bar([str(y) for y in YEARS], [loss_ratio_now[y] for y in YEARS])
right.set_ylabel("incurred loss ratio at latest age")
right.set_title("Loss ratio by accident year")
right.tick_params(axis="x", rotation=60)
fig.tight_layout()
plt.show()
```


<figure class="figure">
<p><img src="ils_deal_analysis_files/ils_deal_analysis_6_0.png" class="img-fluid figure-img" /></p>
<figcaption>png</figcaption>
</figure>


**How well does the model forecast this cedant?** A **diagonal backtest** holds out the latest calendar diagonals. For each diagonal, it fits the model on the data known before that diagonal and scores the forecast of the cells that came next. Here the model is the Bayesian over-dispersed Poisson chain ladder on two diagonals, with a small sampler to keep the notebook fast. A real analysis would hold out more diagonals and add the other models that the fund considers (`diagonal_backtest` takes several). Coverage is the share of held-out cells inside the central 90% interval. Actual versus expected is the ratio of the actual cells to the expected cells.

``` python
backtest = diagonal_backtest(triangle, "paid", {"bayes_odp": BayesOdp(**SAMPLER)}, 2, n_sims=500, seed=SEED)
scores = backtest.mean()
print("held-out diagonals:", ", ".join(backtest.diagonals))
print(scores.to_string(index=False) if hasattr(scores, "to_string") else scores)
if backtest.warnings:
    print("sampler warnings:", backtest.warnings)
```

    held-out diagonals: 2024, 2025
        model          crps  coverage  actual_vs_expected    total_crps  mean_log_density  total_percentile
    bayes_odp 220491.978978     0.875            0.994299 545254.109224        -13.899986             0.471


# 3. The industry prior

A cedant with ten years of history still gets value from an outside view of the line. `IndustryPrior` estimates that view from other companies' triangles of the same line (#604): the mean ultimate loss ratio ([apriori](../reference/reserving.Benktander.md#prospicio.reserving.Benktander.apriori)), how far a company's level strays from it (`between_cv`), how far an origin strays from its company ([cv](../reference/distributions.Tweedie.md#prospicio.distributions.Tweedie.cv)), and a prior on the development pattern. [`reserving-industry-prior.md`](reserving-industry-prior.md) builds one from a Schedule P line fetched at run time, and tests it on held-out companies.

The peer triangles below are **synthetic**, so that the notebook runs without the fetch. A fixed low-discrepancy sequence draws them, so that the R twin has the same values. There are twelve companies with nine accident years at nine ages (the ages of the fit in section 4, since the pattern prior's ages must be the triangle's). Each has its own level, its own pattern and noise in each cell. With real data, replace `peers` with the companies' triangles and premiums. The method is the same.

``` python
N_PEERS, PEER_AGES = 12, [12 * (d + 1) for d in range(9)]
PEER_SHARES = [0.38, 0.33, 0.16, 0.07, 0.03, 0.015, 0.008, 0.004, 0.003]  # the line's incremental pattern


def peer(i):
    # One company: a level, a pattern, an origin effect and noise in each cell, from the fixed sequence.
    level = 0.48 + 0.06 * normal(i)
    shares = [s * math.exp(0.10 * normal(50 + 9 * i + d)) for d, s in enumerate(PEER_SHARES)]
    shares = [s / sum(shares) for s in shares]
    premium = [1e8 * (0.5 + 1.5 * uniform(500 + 9 * i + w)) for w in range(9)]
    origin, age, cumulative = [], [], []
    for w in range(9):
        ratio = level * (1 + 0.12 * normal(1000 + 9 * i + w))
        paid = 0.0
        for d in range(9 - w):
            paid += premium[w] * ratio * shares[d] * math.exp(0.05 * normal(2000 + 81 * i + 9 * w + d))
            origin.append(2016 + w)
            age.append(PEER_AGES[d])
            cumulative.append(paid)
    return Triangle.from_long(origin, age, {"paid": cumulative}), premium


peers = [peer(i) for i in range(N_PEERS)]
prior = IndustryPrior.from_triangles([t for t, _ in peers], "paid", [w for _, w in peers])
M_PRIOR, CV_PRIOR, COMMON_CV = prior.apriori, prior.cv, prior.common_cv
print(f"{prior.report['n_companies_used']} companies, {prior.report['n_origins_used']} origins; "
      f"warnings: {prior.report['warnings'] or 'none'}")
print(f"inputs used below: apriori {M_PRIOR:.3f} (se {prior.apriori_se:.3f}), cv {CV_PRIOR:.3f}, common cv {COMMON_CV:.3f}")
print("prior percent developed:", ", ".join(f"{p:.0%}" for p in prior.percent_developed))
```

    12 companies, 96 origins; warnings: none
    inputs used below: apriori 0.479 (se 0.016), cv 0.127, common cv 0.107
    prior percent developed: 38%, 71%, 87%, 94%, 97%, 98%, 99%, 100%, 100%


# 4. The cedant's ultimates against that prior

`BayesBfNormalised` is the Bayesian Bornhuetter-Ferguson with the prior on the **expected ultimate** of each accident year. [apriori](../reference/reserving.Benktander.md#prospicio.reserving.Benktander.apriori) is the expected ultimate loss ratio, [cv](../reference/distributions.Tweedie.md#prospicio.distributions.Tweedie.cv) sets how firmly the model holds each year to the cedant's level, and `common_cv` sets how far that level may stray from [apriori](../reference/reserving.Benktander.md#prospicio.reserving.Benktander.apriori), one error shared by all the years. The pattern prior takes the place of a vague prior on the shares. A flat prior (`cv=inf`) gives the Bayesian chain ladder, and a very tight prior gives the classical Bornhuetter-Ferguson. The industry prior is the usual compromise. The cedant's data carry the most weight where they are informative (old years), and the prior steadies the immature years.

The model fits the **paid** triangle on on-level premium, so that its pattern is the payment pattern that the cash flows need. The model has no tail beyond the last age.

``` python
def build(rows):
    return Triangle.from_long(
        [int(r["accident_year"]) for r in rows], [int(r["development_months"]) for r in rows],
        {"paid": [float(r["paid"]) for r in rows], "onlevel": [onlevel[int(r["accident_year"])] for r in rows]})


# The oldest age is dropped: only 2016 has it, the chain ladder shows no development there, and the model needs
# every column's increments to sum to more than zero (the one cell at 120 months is 3,000 below the one at 108).
fit_rows = [r for r in tri_rows if int(r["development_months"]) <= 108]
latest_fit = {int(r["accident_year"]): float(r["paid"]) for r in fit_rows}
base = BayesBfNormalised(n_sims=N_SIMS, seed=SEED, **SAMPLER)
fit = prior.fit(build(fit_rows), "paid", "onlevel", model=base)

origins = [int(o) for o in fit.origins]
exposure = dict(zip(origins, fit.exposure))
# Per origin: each simulation's ultimate (latest paid plus its reserve) over the on-level premium (#602).
ultimate_lr = {o: fit.loss_ratio_draws(o, exposure[o]) for o in origins}
post_mean = {o: mean(ultimate_lr[o]) for o in origins}
post_cv = {o: sd(ultimate_lr[o]) / post_mean[o] for o in origins}

print("ultimate loss ratio, paid basis: posterior mean, cv, and the prior mean")
show([(o, f"{post_mean[o]:.3f}", f"{post_cv[o]:.3f}", f"{M_PRIOR:.3f}") for o in origins],
     ("year", "posterior", "cv", "prior"))
print("pattern (share paid at each age):", ", ".join(f"{p:.3f}" for p in fit.pattern))
print("sampler diagnostics:", {k: v for k, v in fit.diagnostics.items() if k in ("max_rhat", "min_ess_bulk", "divergences")})
```

    ultimate loss ratio, paid basis: posterior mean, cv, and the prior mean
    year  posterior     cv  prior
    2016      0.310  0.000  0.479
    2017      0.377  0.000  0.479
    2018      0.409  0.002  0.479
    2019      0.427  0.002  0.479
    2020      0.474  0.003  0.479
    2021      0.522  0.004  0.479
    2022      0.517  0.006  0.479
    2023      0.436  0.010  0.479
    2024      0.554  0.014  0.479
    2025      0.477  0.030  0.479
    pattern (share paid at each age): 0.385, 0.331, 0.159, 0.072, 0.027, 0.012, 0.007, 0.004, 0.003
    sampler diagnostics: {'max_rhat': 1.0035091328995864, 'min_ess_bulk': 2888.4274083096298, 'divergences': 0}


# 5. The 2026 loss ratio

The model forecasts the cells of the years in the triangle. Section 4 reads a loss ratio for each simulation with `fit.loss_ratio_draws`: latest paid plus the reserve of that simulation, divided by premium (#602). For 2026, a year that is not in the triangle, `fit.new_year` draws the posterior predictive (#598). Each simulation takes a posterior draw of the cedant's level (the common multiplier), draws the year's expected ultimate about it with the prior's [cv](../reference/distributions.Tweedie.md#prospicio.distributions.Tweedie.cv), and adds process error. The draws are paired row by row with `year_2026.patterns`, the pattern of the same posterior draw, which section 7 uses.

Without `common_cv` the new year would be the prior itself, whatever the triangle says. With it, the level is the cedant's own, pooled over all the years. **The model has no trend.** The cell prints the mean of the last five years beside the forecast: loss ratios have increased over the ten years, so a level pooled over all of them can understate 2026. The returns in section 8 rest on this forecast, so they flatter the deal by that gap, and a reviewer should challenge it.

``` python
year_2026 = fit.new_year(P_2026, n_sims=N_SIMS, seed=SEED)
LR = year_2026.loss_ratio.marginal((year_2026.origin,)).draws  # the 2026 ultimate loss ratio, one per simulation
RECENT = origins[-5:]
MU_RECENT = mean(post_mean[o] for o in RECENT)
print(f"{year_2026.origin} loss ratio: mean {mean(LR):.3f}, cv {sd(LR) / mean(LR):.3f}; "
      f"the last five years' posterior mean {MU_RECENT:.3f}, the prior {M_PRIOR:.3f}")
print("percentiles 5, 50, 95:", ", ".join(f"{sorted(LR)[int(N_SIMS * p)]:.3f}" for p in (0.05, 0.5, 0.95)))
```

    2026 loss ratio: mean 0.454, cv 0.134; the last five years' posterior mean 0.501, the prior 0.479
    percentiles 5, 50, 95: 0.358, 0.451, 0.557


# 6. The structure

The fund takes 20% of the cedant's subject premium and of its losses: a **quota share**. The reinsurer pays a fixed share of each loss and receives that share of the premium, less a ceding commission to the cedant and brokerage. The notebook compares two commission terms:

- **A, flat**: a 32% ceding commission in all outcomes.
- **B, sliding scale**: the commission decreases as the loss ratio increases. It goes from 36% at a loss ratio of 45% to 24% at 70%, through 32% at 52%. The cedant gets more commission for good results, and the fund shares less of the bad results.

[Tower.apply_annual](../reference/reinsurance.Tower.md#prospicio.reinsurance.Tower.apply_annual) applies the contract to the 2026 annual losses (the loss ratio times the premium), one for each simulation. [deal_ratios](../reference/reinsurance.Tower.md#prospicio.reinsurance.Tower.deal_ratios) gives the loss ratio, the commission, the brokerage and the margin of each simulation. The ceded premium is `0.2 * P`.

``` python
CESSION, BROKERAGE = 0.20, 0.025
CEDED_PREMIUM = CESSION * P_2026
annual_loss = [lr * P_2026 for lr in LR]  # the cedant's whole-book loss, one per simulation

flat = (Layer.quota_share("A_flat", CESSION).with_premium_rate(1.0, P_2026)
        .with_ceding_commission(0.32).with_brokerage(BROKERAGE))
sliding = (Layer.quota_share("B_sliding", CESSION).with_premium_rate(1.0, P_2026)
           .with_sliding_scale([(0.36, 0.45), (0.32, 0.52), (0.24, 0.70)]).with_brokerage(BROKERAGE))

deals = {}
for layer in (flat, sliding):
    tower = Tower([layer])
    result = tower.apply_annual(annual_loss)
    ratios = tower.deal_ratios(result, layer.name)
    column = lambda name: ratios.marginal([name]).draws
    deals[layer.name] = dict(tower=tower, result=result,
                             loss=column("loss_ratio"),
                             commission=[c + b for c, b in zip(column("ceding_commission"), column("brokerage"))],
                             margin=column("margin"))
rows = [(name, f"{mean(d['loss']):.3f}", f"{mean(d['commission']):.3f}", f"{mean(d['margin']):+.3f}",
         f"{sd(d['margin']):.3f}") for name, d in deals.items()]
show(rows, ("structure", "mean LR", "mean comm+brkg", "mean margin", "sd margin"))
print(f"ceded premium {money(CEDED_PREMIUM)}")
```

    structure  mean LR  mean comm+brkg  mean margin  sd margin
       A_flat    0.454           0.345       +0.201      0.061
    B_sliding    0.454           0.371       +0.176      0.044
    ceded premium 36.0m


# 7. Collateral and cash flows

The money moves monthly. The parts:

- **Payment pattern.** Each simulation pays on its own pattern (#600, \#673). `year_2026.patterns` holds the pattern of each simulation's posterior draw, paired row by row with `LR`, and `.monthly(120, basis=UnderwritingBasis())` reads it month by month for a year of policies written evenly through 2026, each earning over twelve months (#722). The rows run for as many months as the converted patterns need to reach 1, though the deal commutes at month 60. `CashflowTerms.run(..., paid_patterns=)` pays each simulation on its row. The terms' own paid pattern, the mean of the rows, is what `deal_ave` compares with in section 10.
- **Premium.** The cedant writes premium evenly over 2026 and collects it as written. Each policy earns over twelve months, so a year of policies written evenly earns over 24 months and is fully earned after that. The written and earned shares are on the same basis as the paid rows.
- **Collateral.** The trust must hold 30% of the unearned premium plus 125% of the outstanding loss (the ultimate loss of the deal less paid to date). This rule is a `CollateralRequirement`. The fund posts the shortfall of the trust when it occurs and takes back the excess over the requirement. Thus most of the capital goes in at the start and comes back as the trust pays losses.
- **Yield, expenses and commutation.** The trust earns 3% a year, and expenses are 0.5% a year of the requirement. At month 60 the deal commutes: the trust pays the cedant the outstanding loss, and the fund takes the remainder.

The cash-flow engine takes the ultimate loss ratio of the **deal** (ceded loss over ceded premium) in each simulation and returns the investor's flows. The premium into the trust is `collected_rate` times the premium, a fixed value in the terms. The sliding scale makes the commission different in each simulation. Thus the cell groups the simulations by commission rate, to 0.1 percentage point. It runs the engine once for each group with the `collected_rate` of that group, and puts the flows back in simulation order.

``` python
T = 60  # commutation at the end of month 59
MONTHS = 120  # the rows run until the last converted pattern reaches 1
pattern = PaymentPattern.from_development([a / 12 for a in AGES], [*[max(1.0, c) for c in CDF[:-1]], 1.0])
# Premium written evenly over 2026, each policy earning over twelve months; each simulation paid on its own row.
basis = UnderwritingBasis()
paid_draws = year_2026.patterns.monthly(MONTHS, basis=basis)
written = [min(1.0, (m + 1) / 12) for m in range(MONTHS)]
earned = [min(1.0, sum(basis.exposure()[: m + 1])) for m in range(MONTHS)]
paid = [sum(column) / N_SIMS for column in zip(*paid_draws)]
print(f"chain ladder pattern: mean time to payment {pattern.duration:.2f} years; mean of the drawn patterns, "
      f"paid by month 12, 24, 60: {paid[11]:.1%}, {paid[23]:.1%}, {paid[59]:.1%}")

requirement = CollateralRequirement({"unearned-premium": 0.30, "outstanding": 1.25})


def make_terms(commission):
    return CashflowTerms(CEDED_PREMIUM, T, written, earned, paid, requirement,
                         commutation_requirement=CollateralRequirement({"outstanding": 1.0}),
                         collected_rate=1 - commission, annual_yield=0.03, expense_rate=0.005)


def run_structure(u, commission):
    # One engine run for each distinct commission rate, flows back in simulation order.
    groups = {}
    for i, c in enumerate(commission):
        groups.setdefault(round(c, 3), []).append(i)
    flows, funded, opening = [None] * len(u), [0.0] * len(u), [0.0] * len(u)
    for c, index in groups.items():
        out = make_terms(c).run([u[i] for i in index], paid_patterns=[paid_draws[i] for i in index])
        out_flows, out_funded, out_opening = out.flows, out.funded, out.opening  # each access copies the whole list
        for k, i in enumerate(index):
            flows[i], funded[i], opening[i] = out_flows[k], out_funded[k], out_opening[k]
    return flows, funded, opening


for name, d in deals.items():
    flows, funded, opening = run_structure(d["loss"], d["commission"])
    d["flows"], d["funded"], d["opening"] = flows, funded, opening
    d["run"] = (DealRun.from_tower(name, d["tower"], d["result"], name)
                .with_flows(flows, funded, opening).with_patterns(written, earned, paid))
    # A book of one deal: its IRR and MOIC in each simulation. The IRR search starts at -95% to +100% a year.
    # The best years of this deal are above 100%, so with extend=True a simulation with no root there is searched
    # above and below that range, and the root nearer 0 is taken (#675).
    book_cashflows = DealBook([d["run"]]).cashflows(extend=True)
    d["rate"], d["moic"] = list(book_cashflows.irr.rate), list(book_cashflows.moic)
print(f"{len(deals)} structures run, {N_SIMS} simulations each, {T} months")
print("capital called from the fund over the term, summed (mean; it is recycled as losses are paid):", ", ".join(f"{n} {money(mean(d['funded']))}" for n, d in deals.items()))
```

    chain ladder pattern: mean time to payment 2.07 years; mean of the drawn patterns, paid by month 12, 24, 60: 14.8%, 57.8%, 96.4%


    2 structures run, 10000 simulations each, 60 months
    capital called from the fund over the term, summed (mean; it is recycled as losses are paid): A_flat 19.3m, B_sliding 19.4m


# 8. What the investor gets

For each structure, the cell computes the return of each simulation:

- the **IRR**, the annual internal rate of return of the monthly flows. The search starts between -95% and 100% a year. The best years of this deal are above 100%, so the cell sets `extend=True` (#675): when the search finds no root in that range, it looks above and below it, so no simulation drops out of the percentiles (#670). The cell still excludes and counts any simulation with no root at all.
- the **MOIC** (multiple on invested capital): one plus the net flows divided by the capital called from the fund.
- the downside: the probability of a negative IRR or a MOIC below 1, a **TVaR** (the mean of the worst tail) of the return, and risk ratios on the deal margin.

Simulations with a total loss have strongly negative IRRs, so the mean IRR is a poor summary. Use the percentiles.

``` python
def finite(xs):
    return [x for x in xs if not math.isnan(x)]


rows = []
for name, d in deals.items():
    rate = finite(d["rate"])
    ordered = sorted(rate)
    pct = lambda p: ordered[min(len(ordered) - 1, int(p * len(ordered)))]
    worst = ordered[: max(1, len(ordered) // 20)]  # the worst 5% of IRRs
    rows.append((name, f"{mean(d['moic']):.3f}", f"{pct(0.05):+.1%}", f"{pct(0.5):+.1%}", f"{pct(0.95):+.1%}",
                 f"{mean(r < 0 for r in rate):.1%}", f"{mean(m < 1 for m in d['moic']):.1%}", f"{mean(worst):+.1%}",
                 f"{len(d['rate']) - len(rate)}"))
show(rows, ("structure", "mean MOIC", "IRR p5", "IRR p50", "IRR p95", "P(IRR<0)", "P(MOIC<1)", "IRR TVaR5", "no root"))
```

    structure  mean MOIC  IRR p5  IRR p50  IRR p95  P(IRR<0)  P(MOIC<1)  IRR TVaR5  no root
       A_flat      1.462  +22.8%   +55.6%  +113.6%      0.0%       0.0%     +16.9%        0
    B_sliding      1.407  +26.1%   +43.6%   +92.3%      0.0%       0.0%     +22.1%        0

``` python
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 3.4))
for name, d in deals.items():
    left.hist(finite(d["rate"]), bins=60, range=(-0.5, 1.0), alpha=0.55, label=name)
    right.hist(d["moic"], bins=60, range=(0.5, 1.6), alpha=0.55, label=name)
left.set_xlabel("IRR (annual)")
right.set_xlabel("MOIC")
left.set_title("Investor IRR")
right.set_title("Investor MOIC")
left.legend()
fig.tight_layout()
plt.show()
```


<figure class="figure">
<p><img src="ils_deal_analysis_files/ils_deal_analysis_21_0.png" class="img-fluid figure-img" /></p>
<figcaption>png</figcaption>
</figure>


`risk_ratios` takes the margin of each simulation, where large is good. It returns Sharpe, Sortino, Omega and the TVaR ratio about a threshold (here a target margin of 10%), under the conventions in its documentation. The quantity here is the deal's **margin** (one less the combined ratio), not the fund's return. The fund's return needs a capital base, which the deal-level ratios do not have. The IRR and MOIC above give the fund's view.

``` python
for name, d in deals.items():
    r = risk_ratios(d["margin"], threshold=0.10, tvar_levels=[95.0])
    print(name, {k: round(v, 3) for k, v in r.items()})
```

    A_flat {'Sharpe': 1.663, 'Sortino': 10.793, 'Omega': 62.652, 'TVaR ratio 95': -1.509}
    B_sliding {'Sharpe': 1.723, 'Sortino': 24.935, 'Omega': 228.763, 'TVaR ratio 95': -0.777}


# 9. Comparing the structures

`DealBook.summary()` shows the premium, loss and deductions of the structures side by side, per simulation. A `DealBook` adds its deals on the same simulated years, so its **total** row would be a portfolio that holds both structures. Read only the rows of each structure. The comparison is the purpose of the exercise. The sliding scale gives the fund a better result when losses are high, and less when losses are low.

``` python
book = DealBook([d["run"] for d in deals.values()])
summary = book.summary()
rows = [(summary["deal"][i], summary["item"][i], f"{summary['mean'][i] / 1e6:,.2f}m", f"{summary['ratio'][i]:.3f}")
        for i in range(len(summary["deal"])) if summary["deal"][i] != "total"]
show(rows, ("deal", "item", "mean", "ratio to premium"))
```

         deal               item    mean  ratio to premium
       A_flat            premium  35.98m             1.000
       A_flat               loss  16.32m             0.454
       A_flat  ceding_commission  11.51m             0.320
       A_flat          brokerage   0.90m             0.025
       A_flat   total_deductions  12.41m             0.345
       A_flat               nmbf   7.25m             0.201
       A_flat             margin   7.25m             0.201
    B_sliding            premium  35.98m             1.000
    B_sliding               loss  16.32m             0.454
    B_sliding  ceding_commission  12.44m             0.346
    B_sliding          brokerage   0.90m             0.025
    B_sliding   total_deductions  13.34m             0.371
    B_sliding               nmbf   6.32m             0.176
    B_sliding             margin   6.32m             0.176


# 10. Monitoring after binding

After binding, each quarter brings a new diagonal of actual paid losses. The fund asks: **was the latest year within the expected range?** The check below holds out the latest diagonal (the 2025 valuation) and fits the model on the data known one year earlier. It takes the **one-year view** (the distribution of the claims development result over the next year) and compares it with the actual diagonal.

The realised result is the opening reserve, less the amount paid in the year, less the closing reserve, for each accident year in the triangle. The model fitted to the full triangle estimates the closing reserve. A realised total in the middle of the forecast shows that the model tracks the data. A total in the tail is a signal to investigate.

This check is on the cedant's *history*. The second cell checks the **deal** itself (#603). `deal_ave` compares the deal's actual cumulative paid at the end of each month with the paid that the priced simulations expected (each simulation's loss ratio times the ceded premium times the paid pattern). The submission has no data after binding, so the actual paid below is an **illustration**: losses emerge on the pattern at a loss ratio 25% above the priced mean, for the first 24 months. With real data, replace `actual` with the cedant's reported paid, as a share of the deal. `CashflowTerms.valuation` then projects the remaining flows from the state of the trust at that month.

``` python
def valuation_year(row):
    return int(row["accident_year"]) + int(row["development_months"]) // 12 - 1


last = max(valuation_year(r) for r in fit_rows)
opening_rows = [r for r in fit_rows if valuation_year(r) < last]
tri_open = build(opening_rows)
paid_open = {}
for r in opening_rows:
    paid_open[int(r["accident_year"])] = float(r["paid"])

model_open = BayesBfNormalised(n_sims=N_ONE_YEAR, seed=SEED, **SAMPLER)
view = prior.one_year(tri_open, "paid", "onlevel", model=model_open, n_sims=N_ONE_YEAR)
cdr = view.cdr.total()

opening_reserve = dict(zip((int(o) for o in view.origins), view.opening_reserve))
closing_reserve = {o: mean(fit.reserves.marginal((str(o),)).draws) for o in origins}
paid_in_year = {o: latest_fit[o] - paid_open[o] for o in opening_reserve}
realised = sum(opening_reserve[o] - paid_in_year[o] - closing_reserve[o] for o in opening_reserve)
percentile = mean(x <= realised for x in cdr.draws)
print(f"valuation {last}: one-year claims development result, forecast mean {money(cdr.mean())}, "
      f"sd {money(sd(cdr.draws))}; realised {money(realised)}, at the {percentile:.0%} percentile of the forecast")
```

    valuation 2025: one-year claims development result, forecast mean 0.1m, sd 2.7m; realised 1.9m, at the 74% percentile of the forecast

``` python
deal_a = deals["A_flat"]
ACTUAL_LR = 1.25 * mean(deal_a["loss"])  # an illustration: the deal runs 25% above the priced mean
actual = [ACTUAL_LR * CEDED_PREMIUM * paid[m] for m in range(24)]  # the deal's cumulative paid, months 1 to 24
ave = deal_ave(actual, make_terms(0.32 + BROKERAGE), deal_a["loss"])


def thousands(x):
    return f"{x / 1e3:,.0f}k"


show([(m + 1, thousands(ave["actual"][m]), thousands(ave["expected"][m]), f"{ave['ratio'][m]:.2f}",
       f"{ave['percentile'][m]:.0%}", thousands(ave["quantiles"][m][0]), thousands(ave["quantiles"][m][2]))
      for m in (5, 11, 17, 23)],
     ("month", "actual paid", "expected", "ratio", "percentile", "p5", "p95"))
```

    month  actual paid  expected  ratio  percentile      p5      p95
        6         497k      398k   1.25         96%    314k     489k
       12       3,025k    2,420k   1.25         96%  1,910k   2,973k
       18       7,603k    6,082k   1.25         96%  4,799k   7,471k
       24      11,783k    9,426k   1.25         96%  7,437k  11,579k


# 11. A summary for the investor

One table of the results, as a plain printout of the quantities above. A report for an investment committee would add the contract terms, the data vintage and the diagnostics of the model. `docs/guides/submission-schema.md` writes such a report's tables, and the templates in `examples/templates/` render them (#605).

``` python
report = [
    ("2026 loss ratio, mean (cv)", f"{mean(LR):.1%} ({sd(LR) / mean(LR):.0%})"),
    ("industry prior apriori (cv, common cv)", f"{M_PRIOR:.1%} ({CV_PRIOR:.0%}, {COMMON_CV:.0%})"),
    ("ceded premium", money(CEDED_PREMIUM)),
    ("chain ladder pattern, mean time to payment", f"{pattern.duration:.2f} years"),
    ("backtest sampler warnings", str(len(backtest.warnings))),
    ("monitoring: realised CDR percentile", f"{percentile:.0%}"),
    ("monitoring: deal paid at month 24, percentile", f"{ave['percentile'][23]:.0%}"),
]
for name, d in deals.items():
    rate = finite(d["rate"])
    report += [(f"{name}: median IRR / mean MOIC", f"{sorted(rate)[len(rate) // 2]:+.1%} / {mean(d['moic']):.3f}"),
               (f"{name}: P(IRR < 0)", f"{mean(r < 0 for r in rate):.1%}")]
show([(k, v) for k, v in report], ("item", "value"))
```

                                             item             value
                       2026 loss ratio, mean (cv)       45.4% (13%)
           industry prior apriori (cv, common cv)  47.9% (13%, 11%)
                                    ceded premium             36.0m
       chain ladder pattern, mean time to payment        2.07 years
                        backtest sampler warnings                 0
              monitoring: realised CDR percentile               74%
    monitoring: deal paid at month 24, percentile               96%
                   A_flat: median IRR / mean MOIC    +55.6% / 1.462
                               A_flat: P(IRR < 0)              0.0%
                B_sliding: median IRR / mean MOIC    +43.6% / 1.407
                            B_sliding: P(IRR < 0)              0.0%


# Issues for the workarounds

The table lists each step that works around a gap in `prospicio`, with the issue for the gap. Where the issue is closed, the notebook uses the fix or says why it keeps the workaround.

| Ref | Step in this notebook | Status | Issue |
|----|----|----|----|
| G1 | the 2026 loss ratio in section 5 | closed; `fit.new_year` used, which has no trend (section 5 prints the gap) | \#598 |
| G2 | one program fitted under a fixed prior in sections 3 and 4, not several pooled | closed; `HierarchicalBf` pools programs, and this notebook still fits one program under a fixed prior | \#599 |
| G3 | one payment pattern for all simulations in section 7 | closed; each simulation pays on its own pattern, `year_2026.patterns` | \#600 |
| G4 | the monthly patterns in section 7 | closed; `patterns.monthly` on the underwriting basis used (section 7, \#722) | \#601 |
| G5 | the loss ratio draws in section 4 | closed; `fit.loss_ratio_draws` used | \#602 |
| G6 | the deal's paid against its simulations in section 10 | closed; `deal_ave` used | \#603 |
| G7 | the prior inputs in section 3 | closed; `IndustryPrior` used, on synthetic peers so that the notebook needs no fetch | \#604 |
| G8 | the printout in section 11 | closed; the report tables and templates of `submission-schema.md` | \#605 |
