Property catastrophe 3: writing Larkspur's contracts in code
cat-3-contract-terms.RmdRendered from docs/guides/cat-3-contract-terms.qmd.
The code runs each time the site is built, so the output below is
current.
A catastrophe treaty is a function: it takes a year of the cedent’s event losses and returns what the reinsurer pays. The contract terms set its shape: how the pieces of one storm add up, where each loss attaches, how much limit a year has and which losses the treaty sees.
This page turns the five contracts of Larkspur Re
(examples/data/cat_book_contracts.csv) into code, checks
the terms on small years you can follow by hand, then runs them on the
2,000 simulated years. The story and notation are on the overview. Page 1 introduces the loss tables.
This is the R twin of the Python guide cat-3-contract-terms.md,
with the same sections, files and numbers.
R/prospicio/tests/test-guides.R requires each chunk to
print exactly the text under it. Lists print in the Python page’s
form.
1. The book and its contracts
The year event loss table (YELT) has one row per cedent per event
piece, with a day and an hour. cedent_events() builds each
cedent’s event set by hand with events_from_years() (#594):
losses per year, loss times as fractions of the year, perils as
labels.
library(prospicio)
library(gt)
# The data files, found from the repository root (CI) or from docs/guides (Quarto).
find_data <- function(name, dir = getwd()) {
repeat {
path <- file.path(dir, "examples", "data", name)
if (file.exists(path)) return(path)
parent <- dirname(dir)
if (identical(parent, dir)) stop("examples/data/", name, " not found", call. = FALSE)
dir <- parent
}
}
read_book <- function(name) {
utils::read.csv(find_data(name), colClasses = "character", na.strings = character())
}
YELT <- utils::read.csv(find_data("cat_book_yelt.csv"), stringsAsFactors = FALSE)
CONTRACTS <- read_book("cat_book_contracts.csv")
rownames(CONTRACTS) <- CONTRACTS$contract
CEDENTS <- read_book("cat_book_cedents.csv")
rownames(CEDENTS) <- CEDENTS$cedent
N_YEARS <- 2000
# One cedent's years of losses, with times (fraction of the year) and peril labels.
cedent_events <- function(cedent, perils = "all") {
keep <- YELT$cedent == cedent
if (perils != "all") keep <- keep & YELT$peril %in% strsplit(perils, "+", fixed = TRUE)[[1]]
rows <- YELT[keep, ]
year <- factor(rows$year, levels = seq_len(N_YEARS))
time <- ((rows$day - 1) * 24 + rows$hour) / 8760
ev <- events_from_years(unname(split(rows$loss, year)), times = unname(split(time, year)))
with_labels(ev, list(peril = unlist(split(rows$peril, year), use.names = FALSE)))
}
terms <- data.frame(contract = CONTRACTS$contract, kind = CONTRACTS$kind, perils = CONTRACTS$perils,
share = as.numeric(CONTRACTS$share),
hours = ifelse(nzchar(CONTRACTS$hours), CONTRACTS$hours, "-"))
gt(terms, rowname_col = "contract") |>
tab_header("Larkspur's five contracts", "Terms from cat_book_contracts.csv; share is Larkspur's signed line") |>
fmt_number(columns = share, decimals = 2)| Larkspur's five contracts | ||||
| Terms from cat_book_contracts.csv; share is Larkspur's signed line | ||||
| kind | perils | share | hours | |
|---|---|---|---|---|
| alder_cat_1 | occurrence_xl | all | 0.30 | 72 |
| alder_cat_2 | occurrence_xl | all | 0.20 | 72 |
| bracken_cat | occurrence_xl | all | 0.25 | 72 |
| bracken_agg | aggregate_xl | CS+FL | 0.25 | - |
| corran_qs | quota_share | all | 0.10 | 72 |
Each row of the file becomes one xol_layer(). Amounts
are at 100%; share is Larkspur’s signed line and scales
every recovery. Premium is rate on line times limit times share. Only
this function reads the terms.
num <- function(x) if (nzchar(x)) as.numeric(x) else NA_real_
contract_layer <- function(k) {
share <- num(k$share)
if (k$kind == "occurrence_xl") {
limit <- num(k$limit)
return(xol_layer(k$contract, limit, num(k$attachment), share = share,
premium = num(k$rate_on_line) * limit * share,
reinstatement_rates = rep(num(k$reinstatement_rate), as.integer(k$reinstatements))))
}
if (k$kind == "aggregate_xl") {
agg_limit <- num(k$aggregate_limit)
return(xol_layer(k$contract, Inf, 0, share = share,
aggregate_deductible = num(k$aggregate_deductible), aggregate_limit = agg_limit,
premium = num(k$rate_on_line) * agg_limit * share))
}
premium <- share * as.numeric(CEDENTS[k$cedent, "cat_premium"])
with_ceding_commission(
xol_layer(k$contract, num(k$limit), 0, share = share, aggregate_limit = num(k$aggregate_limit),
premium = premium),
num(k$ceding_commission)
)
}
LAYERS <- lapply(setNames(rownames(CONTRACTS), rownames(CONTRACTS)), function(n) contract_layer(CONTRACTS[n, ]))
layers <- do.call(rbind, lapply(names(LAYERS), function(name) {
l <- LAYERS[[name]]
data.frame(contract = name, limit = l@limit, attachment = l@attachment,
annual_limit = l@aggregate_limit, premium = l@premium)
}))
gt(layers, rowname_col = "contract") |>
tab_header("The five contracts as layers", "Limits and attachments at 100%, in millions; premium on Larkspur's line") |>
cols_label(annual_limit = "annual limit") |>
fmt_number(columns = c(limit, attachment, annual_limit), decimals = 0) |>
fmt_number(columns = premium, decimals = 3)| The five contracts as layers | ||||
| Limits and attachments at 100%, in millions; premium on Larkspur's line | ||||
| limit | attachment | annual limit | premium | |
|---|---|---|---|---|
| alder_cat_1 | 40 | 30 | 80 | 1.800 |
| alder_cat_2 | 100 | 70 | 200 | 1.000 |
| bracken_cat | 50 | 25 | 150 | 1.750 |
| bracken_agg | Inf | 0 | 30 | 0.450 |
| corran_qs | 150 | 0 | 300 | 3.000 |
One paid reinstatement doubles a layer’s annual limit. The aggregate cover has no occurrence limit.
2. What counts as one loss: the hours clause
A storm can enter the loss table in pieces (a windstorm over two days, hail cells). The hours clause sets how many hours of losses make one occurrence. Under 40 xs 30, two pieces of 25 recover nothing separately and 20 together.
The rule on this track. hours_clause()
starts a window at a year’s first piece and joins every piece within
that many hours of it, then starts the next window at the next piece. It
groups all perils together, with the one hours value of the
contracts file. Both choices are simplifications.
A real clause usually lets the cedent choose where each window starts, so a fixed window can understate recoveries. Many clauses also set a window per peril, longer for flood (often 168 hours) than for windstorm. The chunks below test the per-peril rule on this book.
# Numbers and vectors printed as Python prints them, so both pages print the same.
py_num <- function(v) {
v <- as.character(round(v, 4))
if (grepl("[.e]", v)) v else paste0(v, ".0")
}
py_list <- function(x) {
if (!length(x)) return("[]")
if (is.character(x)) return(paste0("['", paste(x, collapse = "', '"), "']"))
paste0("[", paste(vapply(x, py_num, character(1)), collapse = ", "), "]")
}
alder <- cedent_events("alder")
alder_72 <- hours_clause(alder, 72)
cat("labels before", py_list(alder@label_dims), " after", py_list(alder_72@label_dims), "\n")## labels before ['peril'] after []
ceded_mean <- function(layer, events) {
res <- aggregate(apply_tower(reinsurance_tower(list(layer)), events), keep = c("kind", "layer"))
mean(marginal(res, list(kind = "ceded", layer = layer@name)))
}
cat_1 <- LAYERS[["alder_cat_1"]]Grouping removes the labels, because an occurrence of pieces of two
perils has no single peril. To group by peril, group each peril
separately, label it again and merge with
merge_event_sets(). The merged set keeps the labels and
orders each year’s occurrences in time. Page 4 reuses this helper.
grouped_by_peril <- function(cedent, hours) {
out <- NULL
for (p in c("WS", "EQ", "FL", "CS")) {
g <- hours_clause(cedent_events(cedent, p), hours)
g <- with_labels(g, list(peril = rep(p, sum(event_counts(g)))))
out <- if (is.null(out)) g else merge_event_sets(out, g)
}
out
}
alder_72p <- grouped_by_peril("alder", 72)
rules <- list(alder, alder_72, alder_72p)
grouping <- data.frame(rule = c("no clause", "72 hours, all perils", "72 hours, by peril"),
occurrences = vapply(rules, function(e) sum(event_counts(e)), numeric(1)),
expected_loss = vapply(rules, function(e) ceded_mean(cat_1, e), numeric(1)))
gt(grouping, rowname_col = "rule") |>
tab_header("alder_cat_1 under three grouping rules", "Expected loss in millions on Larkspur's line") |>
cols_label(expected_loss = "expected loss") |>
fmt_number(columns = occurrences, decimals = 0, use_seps = FALSE) |>
fmt_number(columns = expected_loss, decimals = 4)| alder_cat_1 under three grouping rules | ||
| Expected loss in millions on Larkspur's line | ||
| occurrences | expected loss | |
|---|---|---|
| no clause | 5391 | 0.7778 |
| 72 hours, all perils | 4238 | 0.8230 |
| 72 hours, by peril | 4275 | 0.8229 |
Grouping raises the expected loss by about 6%. Grouping by peril adds a few occurrences (pieces of different perils in the same 72 hours no longer join) and barely moves it, so the track prices with the single all-perils clause and groups by peril only where it needs the labels.
3. Alder’s layers: occurrence excess of loss with reinstatements
An occurrence x recovers
min(max(x - a, 0), l) from a layer l xs a.
Recoveries add up over the year until the annual limit, l
times one plus the reinstatements, is used. Paid reinstatements cost the
cedent more premium; page 5 prices them.
ceded_by_event() shows the order. Take
alder_cat_1 (40 xs 30, 30%, one reinstatement, so 80 of
annual limit) and four occurrences: one below the attachment, one
through the top, two in the middle.
year <- c(28, 110, 64, 95)
line <- as.numeric(CONTRACTS["alder_cat_1", "share"])
left <- cat_1@aggregate_limit
recs <- ceded_by_event(cat_1, year)
left_after <- numeric(length(year))
for (i in seq_along(year)) {
left <- left - recs[i] / line
left_after[i] <- max(left, 0)
}
cat(sprintf("year: %.2f\n", ceded(cat_1, year)))## year: 24.00
steps <- data.frame(loss = sprintf("%.0f", year), at_100 = recs / line, limit_left = left_after,
line = recs)
gt(steps, rowname_col = "loss") |>
tab_header("alder_cat_1 on a year of four occurrences", "Amounts in millions, in time order") |>
cols_label(at_100 = "at 100%", limit_left = "limit left", line = "Larkspur's line") |>
fmt_number(columns = c(at_100, limit_left), decimals = 1) |>
fmt_number(columns = line, decimals = 2)| alder_cat_1 on a year of four occurrences | |||
| Amounts in millions, in time order | |||
| at 100% | limit left | Larkspur's line | |
|---|---|---|---|
| 28 | 0.0 | 80.0 | 0.00 |
| 110 | 40.0 | 40.0 | 12.00 |
| 64 | 34.0 | 6.0 | 10.20 |
| 95 | 6.0 | 0.0 | 1.80 |
Alone, the 95 recovers 40, but only 6 of the annual limit remains:
late occurrences get what is left, so order matters. The book’s years
are in time order (the file lists pieces by slot). In the
figure, the first bar of each event is what the layer pays at 100%, and
the second is the annual limit left. The 28 pays nothing and the 95 gets
only the 6 that remain.
library(ggplot2, exclude = "layer") # keeps prospicio's layer()
paid <- ceded_by_event(cat_1, year) / line
remaining <- pmax(cat_1@aggregate_limit - cumsum(paid), 0)
occurrences <- factor(paste("loss", year), levels = paste("loss", year))
bars <- data.frame(occurrence = rep(occurrences, 2),
what = factor(rep(c("paid by the layer (100%)", "annual limit left"), each = length(year)),
levels = c("paid by the layer (100%)", "annual limit left")),
amount = c(paid, remaining))
ggplot(bars, aes(occurrence, amount, fill = what)) +
geom_col(position = "dodge") +
labs(x = "occurrence, in time order", y = "amount at 100% (millions)", fill = NULL,
title = "alder_cat_1, 40 xs 30: the annual limit runs out") +
theme(legend.position = "top")4. Corran’s quota share: an event limit and an annual limit
A plain quota share cedes a fixed share of every loss. A cat quota
share adds an event limit and an annual limit. corran_qs
cedes 10% with an event limit of 150 and an annual limit of 300 at 100%:
a layer 150 xs 0 at a 10% share with an annual limit of 300. In a year
of 200 and 120, the event limit caps the first event at 150, so the
cover pays 10% of 270. quota_share() has no limits and pays
10% of 320.
qs <- LAYERS[["corran_qs"]]
cat(py_num(ceded(qs, c(200, 120))), py_list(ceded_by_event(qs, c(200, 120))), "\n")## 27.0 [15.0, 12.0]
cat(py_num(ceded(quota_share("uncapped", 0.1), c(200, 120))), "\n")## 32.0
5. Bracken’s aggregate cover, and the losses it sees
The subject losses of a contract are the cedent’s
losses of its perils, grouped by its hours clause, before its terms.
bracken_agg covers only convective storm and flood, so
remove the other perils first:
cedent_events("bracken", "CS+FL") (#584).
A split by label cannot do this, because it comes after the cession. Take an earthquake of 25, then a windstorm of 30, under 20 xs 10 with an annual limit of 20. The earthquake recovers 15 and leaves 5 for the windstorm. A windstorm-only treaty pays 20 for it.
year <- with_labels(events_from_years(list(c(25, 30)), times = list(c(0.1, 0.2))),
list(peril = c("EQ", "WS")))
small <- xol_layer("20 xs 10", 20, 10, aggregate_limit = 20)
split_res <- apply_tower(reinsurance_tower(list(small)), year)
for (peril in c("EQ", "WS")) {
m <- mean(marginal(split_res, list(kind = "ceded", layer = "20 xs 10", peril = peril)))
cat(sprintf("%s share of the all-perils recovery %.1f\n", peril, m))
}## EQ share of the all-perils recovery 15.0
## WS share of the all-perils recovery 5.0
ws_only <- apply_tower(reinsurance_tower(list(small)), events_from_years(list(30), times = list(0.2)))
ws_only <- aggregate(ws_only, keep = c("kind", "layer"))
cat(sprintf("WS under a windstorm-only treaty %.1f\n",
mean(marginal(ws_only, list(kind = "ceded", layer = "20 xs 10")))))## WS under a windstorm-only treaty 20.0
A label split gives the windstorm’s part of this treaty’s recovery, not what a windstorm treaty pays.
An aggregate cover pays share * min(max(S - AD, 0), AL)
on the annual total S, with aggregate deductible
AD and limit AL. In prospicio it is a layer
with an infinite occurrence limit, no attachment and the annual terms.
bracken_agg is 30 xs 40 in the aggregate at 25%. A year of
10, 20 and 25 totals 55, so the cover pays a quarter of 15.
## 3.75
agg_pro_rata <- xol_layer("bracken_agg", Inf, 0, share = 0.25, aggregate_deductible = 40,
aggregate_limit = 30, allocation = "pro_rata")
split <- data.frame(loss = c("10", "20", "25"),
event_order = ceded_by_event(agg, c(10, 20, 25)),
pro_rata = ceded_by_event(agg_pro_rata, c(10, 20, 25)))
gt(split, rowname_col = "loss") |>
tab_header("bracken_agg on a year of 10, 20 and 25", "Recovery by event, in millions on Larkspur's line") |>
cols_label(event_order = "event order", pro_rata = "pro rata") |>
fmt_number(columns = c(event_order, pro_rata), decimals = 4)| bracken_agg on a year of 10, 20 and 25 | ||
| Recovery by event, in millions on Larkspur's line | ||
| event order | pro rata | |
|---|---|---|
| 10 | 0.0000 | 0.6818 |
| 20 | 0.0000 | 1.3636 |
| 25 | 3.7500 | 1.7045 |
The annual value is the same; the split by event differs. In event
order the deductible takes the first losses and the third event gets all
the recovery. allocation = "pro_rata" scales every event by
the same factor. The split matters only when a later step reads events,
such as an inuring stage (page 4).
On the book, the cover sees only Bracken’s convective storm and flood losses.
bracken_csfl <- cedent_events("bracken", "CS+FL")
annual <- total(total(bracken_csfl))@draws
largest <- total(annual_maxima(bracken_csfl))@draws
past <- which(annual > 40)
cat(sprintf("mean CS+FL annual loss %.4f\n", sum(annual) / N_YEARS))## mean CS+FL annual loss 7.1642
cat(sprintf("years past the deductible %.4f, years that use the whole limit %.4f\n",
length(past) / N_YEARS, sum(annual >= 70) / N_YEARS))## years past the deductible 0.0325, years that use the whole limit 0.0130
cat(sprintf("of the %d years past the deductible, %d have one loss above 40\n",
length(past), sum(largest[past] > 40)))## of the 65 years past the deductible, 52 have one loss above 40
cat(sprintf("bracken_agg expected loss %.4f, premium %.4f\n", ceded_mean(agg, bracken_csfl), agg@premium))## bracken_agg expected loss 0.1621, premium 0.4500
The cover attaches in about one year in thirty. It does not cap one event’s contribution, so a single large flood or storm outbreak is the usual trigger: in 52 of the 65 years past the deductible, one loss alone is above it. For frequency protection, add an each-and-every-loss cap on each event’s contribution.
6. All five contracts on the book
Each contract runs on its own perils and hours clause. The loss ratio is expected ceded loss over upfront premium, before reinstatement premium and commissions.
subject <- function(k) {
e <- cedent_events(k$cedent, k$perils)
if (nzchar(k$hours)) hours_clause(e, as.numeric(k$hours)) else e
}
contracts <- do.call(rbind, lapply(rownames(CONTRACTS), function(name) {
l <- LAYERS[[name]]
data.frame(contract = name,
expected_loss = ceded_mean(l, subject(CONTRACTS[name, ])), premium = l@premium)
}))
contracts$loss_ratio <- contracts$expected_loss / contracts$premium
gt(contracts, rowname_col = "contract") |>
tab_header("Larkspur's five contracts on the 2,000 simulated years",
"Amounts in millions, on Larkspur's line, before reinstatement premium and commissions") |>
cols_label(expected_loss = "expected loss", loss_ratio = "loss ratio") |>
fmt_number(columns = expected_loss, decimals = 4) |>
fmt_number(columns = c(premium, loss_ratio), decimals = 3)| Larkspur's five contracts on the 2,000 simulated years | |||
| Amounts in millions, on Larkspur's line, before reinstatement premium and commissions | |||
| expected loss | premium | loss ratio | |
|---|---|---|---|
| alder_cat_1 | 0.8230 | 1.800 | 0.457 |
| alder_cat_2 | 0.4163 | 1.000 | 0.416 |
| bracken_cat | 0.6847 | 1.750 | 0.391 |
| bracken_agg | 0.1621 | 0.450 | 0.360 |
| corran_qs | 1.2025 | 3.000 | 0.401 |
shown <- data.frame(contract = factor(rep(contracts$contract, 2), levels = rev(contracts$contract)),
what = factor(rep(c("premium", "expected loss"), each = nrow(contracts)),
levels = c("premium", "expected loss")),
amount = c(contracts$premium, contracts$expected_loss))
ggplot(shown, aes(amount, contract)) +
geom_col(aes(fill = what), position = position_dodge2(reverse = TRUE)) +
scale_fill_manual(values = c("premium" = "grey75", "expected loss" = scales::hue_pal()(2)[1])) +
labs(x = "millions, on Larkspur's line", y = NULL, fill = NULL,
title = "Expected loss against premium, by contract") +
theme(legend.position = "top")7. The contract year
A treaty covers losses that occur in a period (losses occurring) or
losses on policies written in a period (risks attaching). prospicio
models this with a timeline() of accident months, an
exposure matrix of how much of each month each underwriting year
carries, and a tower with a cover basis
(with_cover_basis()).
Under losses occurring, contract years start at month 0 of the timeline. Trap: an 18-month timeline with one underwriting year keeps an event in month 3 and silently drops an event in month 16.
ev <- events_from_years(list(c(100, 80)), times = list(c(3 / 18, 16.2 / 18)))
lo <- with_cover_basis(reinsurance_tower(list(xol_layer("XL", 50, 20))), "losses_occurring")
res <- apply_tower_timeline(lo, timeline(ev, 18), matrix(1, nrow = 1, ncol = 18))
keys <- res@keys
cat("[", paste(sprintf("('%s', '%s', %s)", keys$kind, keys$layer, keys$year), collapse = ", "), "]\n",
sep = "")## [('gross', 'ground_up', 1), ('ceded', 'XL', 1), ('net', 'retained', 1)]
cat(sprintf("gross seen %.1f\n", mean(marginal(res, list(kind = "gross", layer = "ground_up", year = 1)))))## gross seen 100.0
The 80 in month 16 is in no contract year, and prospicio gives no warning (#586). Here the simulated years are already contract years.
8. Surplus and per-risk covers
A surplus treaty cedes each risk in proportion to the amount by which
its sum insured exceeds a retention. A per-risk excess of loss attaches
on each risk, not each event. Both need losses by risk, which a
catastrophe event table does not have. reinsurance-price.md,
a Python guide, shows surplus_treaty() and risk
profiles.
In Python
The Python guide, cat-3-contract-terms.md,
builds the same contracts with Layer,
Layer.quota_share,
Layer.with_ceding_commission,
EventSet.grouped, EventSet.merge,
Layer.ceded_by_event, Tower.apply,
Timeline and Tower.apply_timeline.
Further reading
Page 4, programs, stacks these contracts into programs. reinsurance.dev by Oliver Baltzer is another introduction to property catastrophe reinsurance.