import csv
from statistics import mean, variance
from prospicio.aggregate import audit_grid, fft
from prospicio.credibility import LimitedFluctuation
from prospicio.distributions import Grid, NegativeBinomial, Truncated, fit_severity, goodness_of_fit
from prospicio.pricing import DevelopmentPattern, LargeLossExperience, Period, Quote, RateHistory, credibility_weighted, price
from prospicio.reinsurance import Layer, Tower
from prospicio.reserving import ChainLadder, Triangle
from prospicio.risk import Distortion
VALUATION, FUTURE, LOSS_TREND = 2026.0, 2027.5, 0.05 # yours: valuation date, mid-point of the period priced, trend
FUTURE_PREMIUM = 120.0 # yours: subject premium of the period priced
THRESHOLD, POLICY_LIMIT = 1.0, 25.0 # yours: reporting threshold of large claims, policy limit
ATTACHMENT, LIMIT = 5.0, 10.0 # the layer priced
COUNT_IBNR = {} # yours: large-claim count development factor by year (default 1)
premium = {int(r["year"]): float(r["earned_premium"]) for r in csv.DictReader(open("my_premium.csv"))}
rows = list(csv.DictReader(open("my_losses.csv")))
years = sorted(premium)
# 1. Premium at today's rate level (the losses are trended in step 2)
history = RateHistory([2023.0, 2025.0], [0.05, 0.03]) # yours: effective dates and rate changes
on_level = [premium[y] * history.rate_level(Period.calendar(y, y + 1), 1.0).on_level_factor for y in years]
# 2. Develop to ultimate: the ground-up triangle, and each large claim's IBNER from the claims' own histories
tri = Triangle.from_long([int(r["accident_year"]) for r in rows], [int(r["development"]) for r in rows],
{"incurred": [float(r["incurred"]) for r in rows]})
cl = ChainLadder().fit(tri, "incurred")
print("ultimate loss ratios:", [round(u / p, 3) for u, p in zip(cl.ultimate, on_level)])
age = [int(r["development"]) / 12 - 0.5 for r in rows] # years since a mid-year accident
ibner = DevelopmentPattern.from_history([r["claim_id"] for r in rows], age,
[float(r["incurred"]) for r in rows], ages=sorted(set(age)))
latest = {r["claim_id"]: r for r in sorted(rows, key=lambda r: int(r["development"]))}
ids = list(latest)
record = LargeLossExperience(ids, [int(latest[i]["accident_year"]) + 0.5 for i in ids],
[float(latest[i]["incurred"]) for i in ids], threshold=THRESHOLD, valuation=VALUATION)
prepared = record.prepare(rate=LOSS_TREND, to=FUTURE, development=ibner) # developed (IBNER) and trended
floor = prepared.complete_above # every year is complete above this trended size
# 3. Severity of the large claims above the floor, and their yearly count at next year's premium
large = [(int(latest[i]["accident_year"]), x, float(latest[i]["incurred"]) >= POLICY_LIMIT)
for i, x in zip(ids, prepared.trended) if x > floor]
sizes = [x for _, x, _ in large]
capped = [c for _, _, c in large] # censored: a policy limit capped the loss
fit = fit_severity("lognormal", sizes, reporting_thresholds=[floor] * len(sizes), censored=capped)
gof = goodness_of_fit(fit.distribution, sizes, reporting_thresholds=[floor] * len(sizes), censored=capped)
print(fit.parameters, "largest gap to the data:", round(gof["max_distance"], 3))
counts = [FUTURE_PREMIUM * COUNT_IBNR.get(y, 1.0) * sum(v == y for v, _, _ in large) / p for y, p in zip(years, on_level)]
frequency = NegativeBinomial.from_mean_variance(mean(counts), max(variance(counts), 1.01 * mean(counts)))
severity = Truncated(fit.distribution, lower=floor) # the fit is ground up; the count is of claims above the floor
# 4. Aggregate distribution, with the grid chosen and checked
audit = audit_grid(frequency, severity)
claims, _ = Grid.rounding(severity, audit.step, round(POLICY_LIMIT / audit.step) + 1) # capped at the policy limit
_, report = fft(frequency, claims, 2**audit.log2)
assert report.aliasing_error < 1e-6 and report.tail_mass < 1e-6, "use more points or a larger step"
# 5. Contract terms
tower = Tower([Layer("layer", LIMIT, ATTACHMENT)])
layer_loss = tower.on_grid(frequency, claims, 2**audit.log2).ceded[0]
# 6. Expected loss two ways, blended by credibility
burn = prepared.burning_cost(tower, years, premium=on_level, development=[COUNT_IBNR.get(y, 1.0) for y in years])
experience = burn.loss_cost[0] * FUTURE_PREMIUM # the layer's loss cost on on-level premium, at next year's premium
exposure = layer_loss.mean() # yours: a stand-in; use a RiskProfile or an exposure curve
lf = LimitedFluctuation(0.90, 0.05)
z = lf.credibility(sum(x > ATTACHMENT for x in sizes), lf.frequency_standard())
blended = credibility_weighted(experience, z, exposure)
print(f"experience {experience:.3f}, exposure {exposure:.3f}, credibility {z:.2f}, blended {blended:.3f}")
# 7 to 9. Capital standard and price of risk (for a book: Portfolio.calibrate and Portfolio.price, section 8)
TAIL = Distortion.tvar(0.99)
risk = price(layer_loss, TAIL, cost_of_capital=0.10)
scale = blended / layer_loss.mean() # moves the modelled layer loss to the blended estimate
# 10. Quote and sensitivity. Scaling loss, premium and assets together leaves every return unchanged.
quote = Quote.technical(risk, expenses=0.05, brokerage=0.10, limit=LIMIT)
print(f"technical premium {quote.premium * scale:.3f}, rate on line {quote.premium * scale / LIMIT:.1%}")
for market in (0.8, 1.0, 1.2):
print(f"at {market:.0%} of technical: return on capital {quote.at(market * quote.premium).return_on_capital:.1%}")