Skip to contents

Rendered from docs/guides/reserving-compartmental.qmd. The code is not run when the site is built: the block after each chunk is what the chunk prints, and CI checks every one of them (R/prospicio/tests/test-guides.R).

Markus Gesmann and Jake Morris, Hierarchical Compartmental Reserving Models (CAS Research Paper, 2020), model a reserve as quantities that flow between compartments at rates. A pharmacologist models a drug in the body in the same way. Claims arise from premium. They stay in outstanding while they are known but unpaid, and they move to paid when they settle. One small set of parameters, each with a business meaning, describes the paid triangle and the outstanding triangle together.

This guide explains the idea and fits the paper’s two models to its example company with prospicio (compartmental()). It compares prospicio’s posterior summaries with the paper’s printed summaries.

This is the R twin of the Python guide reserving-compartmental.md. It has the same sections, models, checks and recorded numbers. It uses the R package functions gesmann_morris_priors(), gesmann_morris_2_priors(), compartmental_prior_predictive(), compartmental(), compartmental_model_2(), bayes_loo(), compartmental_one_year() and compartmental_model_2_one_year(). The R package calls the same Rust code as the Python package.

The paper’s text is the authors’. Read the paper for the derivations. The paper fits its models with the R package brms, which writes a Stan program. prospicio samples the same posterior with its own NUTS sampler. Money is in thousands of US dollars, as in the data. For a general choice of reserving method, read reserving-methods.md. For Meyers’ Bayesian models on one triangle, read reserving-meyers.md.

How the numbers here are checked. CI (R/prospicio/tests/test-guides.R) runs each R chunk that has a text block after it, and the chunk must print exactly that text. This text is the same as in the Python guide, except for one line in section 7. To render the page, install the R package and run quarto render docs/guides/reserving-compartmental.qmd.

Model 1 runs in CI with prospicio’s default sampler: 4 chains of 1,000 warm-up draws and 2,000 kept draws. It takes about 5 to 9 seconds in a release build (about 12 seconds in R on Windows). A model 2 fit takes about a minute and a one-year view takes several minutes, so CI does not run them. Three points apply to every comparison:

  • A Bayesian result is a Monte Carlo estimate. Another seed gives a slightly different number, and the paper’s own run has the same error. Each comparison states how far a number moves from seed to seed. These amounts come from the 200-seed studies in knowledge/findings/compartmental-gm1-parity.md and compartmental-gm2-parity.md (CI does not run these studies).
  • The exact digits of a NUTS run depend on the platform. The last bit of exp and ln differs between Windows and Linux, so the sampler’s paths diverge and the draws differ. Thus each checked chunk prints the paper’s value, a tolerance a few Monte Carlo errors wide, and whether prospicio’s value is in the tolerance. Where the paper prints no value, the chunk uses the paper’s code, run again in Stan. prospicio’s own values are in plain r blocks, with numbers from one run of the Python guide (Windows x86_64, release build, seed 0). CI does not run these blocks, which include every model 2 fit and both one-year views.
  • On Windows, the R package is built with the GNU toolchain. Its exp and ln differ again in the last bit from the MSVC build of the Python package, so its seed-0 draws also differ. For example, the b_ker mean of model 1 is -5.388 against -5.395 in Python, and its total reserve mean is 173,584 against 173,457. Every checked chunk prints the same text. The prior predictive check has no sampler paths, so it prints the same digits as Python.

1. The compartmental idea

Think of three tanks. The first tank, exposure (EX), starts each accident year full with the expected losses of that year. Claims leave it when they are reported, at a rate k_er a year, and go into the second tank, outstanding (OS). Claims leave outstanding when they are settled, at a rate k_p a year, and go into the third tank, paid (PD).

Linear differential equations describe the flow. With constant rates, they have a closed form. Let t be the development time in years (12 months is t = 1) and let

g(t) = (exp(-k_p t) - exp(-k_er t)) / (k_er - k_p)

Then the expected outstanding and cumulative paid of origin i with premium P_i are

OS_i(t) = P_i RLR_i k_er g(t)
PD_i(t) = P_i RLR_i RRF_i [(1 - exp(-k_p t)) - k_p g(t)]

Outstanding rises from zero to a peak and then decreases. Paid rises toward its ultimate. Each of the four parameters describes the business:

  • RLR_i, the reported loss ratio: the share of premium that goes through outstanding, valued at the level of the case reserves.
  • RRF_i, the reserve robustness factor: the part of the reported amount that is paid in the end. Below 1, the case reserves are redundant. Above 1, they are not sufficient.
  • RLR_i RRF_i, the ultimate loss ratio. It has the role of the expected loss ratio (ELR) in a Bornhuetter-Ferguson or Cape Cod reserve. But the model estimates it from paid and outstanding together, and it is not a separate selection.
  • k_er and k_p, the speeds of reporting and payment. In model 1, all accident years share them. In model 2, they vary by accident year and development year.

The hierarchy. RLR and RRF vary by accident year, but not freely. The value of each year is the population value times a random effect. The two effects are correlated, and the model estimates their spread from the data. A young year with little data uses information from the other years, as a credibility-weighted ELR does. A mature year depends mostly on its own data. An accident year with premium and no data (1997 below) takes a new effect from the population in each simulation.

Identification. The two rates can change places, with RLR and RRF rescaled, and every mean stays exactly the same (knowledge/findings/compartmental-rate-swap.md). Only the priors separate the two mirror solutions. prospicio gives a warning if a posterior draw has k_er <= k_p. No draw does here.

2. Company 337

The paper uses NAIC company 337, workers’ compensation, accident years 1988 to 1997, from the CAS loss reserve database. Its outstanding is incurred (with bulk and IBNR reserves) less paid. Its premium is direct earned premium. The training data are the calendar years up to 1996. They contain 45 paid cells and 45 outstanding cells for 1988 to 1996, and the premium of 1997 only. The data hold the full 10 by 10 square, so the 1997 calendar diagonal and the 120-month outcome are known and test the forecast.

library(prospicio)

# The data file, found from the repository root (CI) or from docs/guides (Quarto).
find_data <- function(name, dir = getwd()) {
  repeat {
    path <- file.path(dir, "validation", "data", name)
    if (file.exists(path)) return(path)
    parent <- dirname(dir)
    if (identical(parent, dir)) stop("validation/data/", name, " not found", call. = FALSE)
    dir <- parent
  }
}

# Python's format specs: ",.0f" (thousands), ".1f", ".2f", ".3f", ".4f".
fmt <- function(x, spec = ",.0f", width = 0) {
  out <- switch(spec,
    ",.0f" = formatC(x, format = "f", digits = 0, big.mark = ","),
    ".1f" = sprintf("%.1f", x),
    ".2f" = sprintf("%.2f", x),
    ".3f" = sprintf("%.3f", x),
    ".4f" = sprintf("%.4f", x))
  formatC(out, width = width)
}
# numpy's std: the population standard deviation.
psd <- function(x) sqrt(mean((x - mean(x))^2))

square <- utils::read.csv(find_data("clrd_wkcomp_337.csv"), comment.char = "#")
square$os <- square$incurred - square$paid
cell <- function(origin, age, key) square[[key]][square$origin == origin & square$development == age]
premium <- stats::setNames(square$premium[square$development == 12],
                           square$origin[square$development == 12])

# Training cells: calendar years up to 1996. 1997 enters with its premium only.
cols <- c("origin", "development", "paid", "incurred", "premium")
train <- square[square$origin + square$development %/% 12 - 1 <= 1996, cols]
y1997 <- square[square$origin == 1997 & square$development == 12, cols]
y1997$paid <- NA
y1997$incurred <- NA
tri <- triangle(rbind(train, y1997), "origin", "development", c("paid", "incurred", "premium"))
latest_paid <- sum(train$paid[train$origin + train$development %/% 12 - 1 == 1996])
ultimate_paid <- sum(square$paid[square$development == 120])
cat(sprintf("training cells %d of each type, premium %s\n", nrow(train), fmt(sum(premium))))
cat(sprintf("1988 at 12 months: premium %s, paid %s, outstanding %s\n", fmt(premium[["1988"]]),
            fmt(cell(1988, 12, "paid")), fmt(cell(1988, 12, "os"))))
cat(sprintf("latest paid %s; paid at 120 months %s; outcome reserve %s\n", fmt(latest_paid),
            fmt(ultimate_paid), fmt(ultimate_paid - latest_paid)))
training cells 45 of each type, premium 903,152
1988 at 12 months: premium 104,437, paid 9,558, outstanding 53,121
latest paid 402,015; paid at 120 months 589,435; outcome reserve 187,420

Morris (2016), the predecessor of the paper, printed the same 1988 cell in millions: premium 104, outstanding 53, paid 10. The outcome reserve is the amount that every accident year, 1997 included, paid after the end of 1996 up to 120 months. The models below try to predict this number.

3. Priors, and the prior predictive check

The priors are a required argument of compartmental(), because the rates and loss ratios are specific to a line and a book. gesmann_morris_priors() is the paper’s set for model 1. Each positive parameter is a median times exp(sd o), with o standard normal. The medians are k_er 3 (sd 0.1 on the log scale), k_p 1 (0.1), RLR 0.7 (0.2) and RRF 0.8 (0.1). The sds of the accident-year effects have half Student-t priors (scales 0.2 and 0.1 on that o scale). Their correlation has a uniform LKJ(1) prior, and each log sigma has a Student-t prior so wide that it is effectively flat.

The paper recommends a prior predictive check before the fit. Draw the parameters from the priors alone, calculate the curves, and examine whether the development looks like a plausible book. compartmental_prior_predictive() returns those paths (the means, without the noise of the likelihood). The block below prints the paid and outstanding loss ratios of 1988 under the priors, and the actual values of 1988:

gm1 <- gesmann_morris_priors()


# `...` passes model 2's paid response, incremental: each year's paid uses that
# year's development effects.
prior_check <- function(priors, label, ...) {
  paths <- compartmental_prior_predictive(tri, "premium", priors, n_sims = 2000, ...)
  cat(sprintf("%s: 1988 loss ratios under the priors alone (5%%, 50%%, 95%%) and actual\n", label))
  for (kind in c("paid", "outstanding")) {
    key <- if (kind == "paid") "paid" else "os"
    for (age in c(12, 36, 120)) {
      m <- marginal(paths[[kind]], list(origin = "1988", age = age))
      q <- quantile(m, c(0.05, 0.5, 0.95)) / premium[["1988"]]
      actual <- cell(1988, age, key) / premium[["1988"]]
      cat(sprintf("  %-11s %3d months  %.2f %.2f %.2f   actual %.2f\n", kind, age, q[1], q[2], q[3],
                  actual))
    }
  }
}


prior_check(gm1, "model 1")
model 1: 1988 loss ratios under the priors alone (5%, 50%, 95%) and actual
  paid         12 months  0.18 0.26 0.39   actual 0.09
  paid         36 months  0.36 0.52 0.76   actual 0.32
  paid        120 months  0.39 0.56 0.82   actual 0.50
  outstanding  12 months  0.24 0.33 0.47   actual 0.51
  outstanding  36 months  0.03 0.05 0.09   actual 0.31
  outstanding 120 months  0.00 0.00 0.00   actual 0.01

The check finds a conflict before the fit. Under the preset, payment is fast (k_p near 1 a year). Thus the priors put about a quarter of premium in paid after 12 months, and outstanding is empty within a few years. Company 337 pays much more slowly: 9% paid at 12 months, and 31% of premium outstanding at 36 months, where the priors expect about 5%. The data move the rates many prior sds away (section 4: k_er about 1.76 and k_p about 0.43, against medians 3 and 1).

The paper keeps the preset. For your own book, make the rate priors wider or move their centre after a check like this one. For example, build a set with compartmental_priors().

4. Model 1: one likelihood for paid and outstanding amounts

Model 1 puts a normal likelihood on each observed cumulative paid amount and outstanding amount, centred on its curve, with one sigma for each type. RLR and RRF vary by accident year, and the rates do not. The paper prints its posterior summary (m1fit, section 7.2.2) on the brms scale. The summary gives the intercepts b_* on the standardised o scale of each parameter, and the sds tau of the accident-year effects on that scale. It also gives their correlation rho and the log sigma of each type. prospicio reports the same names.

prospicio’s means move by at most 0.032 posterior sds from seed to seed, and its sds by at most 2.3% (200 seeds). The paper’s run had about 1,300 to 2,200 effective draws, so its means also have about 0.03 sds of error. The paper rounds to two decimals. A tolerance of 0.15 printed sds plus 0.005 (for the rounding) on a mean, and 10% on an sd, is about three combined errors wide.

check <- function(label, target, ours, tol, spec = ".3f", source = "paper") {
  agrees <- abs(ours - target) <= tol
  cat(sprintf("%-24s %-5s %9s  tolerance %7s  agrees: %s\n", label, source, fmt(target, spec),
              fmt(tol, spec), if (agrees) "True" else "False"))
  invisible(agrees)
}


# The fit and how many warnings it raised.
fit_quietly <- function(expr) {
  n <- 0
  fit <- withCallingHandlers(expr, warning = function(w) {
    n <<- n + 1
    invokeRestart("muffleWarning")
  })
  list(fit = fit, n_warnings = n)
}


param <- function(fit, name, column = "mean") {
  s <- fit@summary
  s[[column]][s$parameter == name]
}


check_posterior <- function(fit, printed) {
  ok <- 0
  for (name in names(printed)) {
    mean <- printed[[name]][1]
    sd <- printed[[name]][2]
    ok <- ok + check(paste(name, "mean"), mean, param(fit, name), 0.15 * sd + 0.005, ".4f")
    ok <- ok + check(paste(name, "sd"), sd, param(fit, name, "sd"), 0.10 * sd + 0.005, ".4f")
  }
  ok
}


# The paper's printed m1fit, mean and sd.
M1FIT <- list(
  b_ker = c(-5.40, 0.81), b_kp = c(-8.49, 0.36), b_RLR = c(1.44, 0.26), b_RRF = c(-1.36, 0.42),
  tau_RLR = c(0.64, 0.15), tau_RRF = c(0.74, 0.22), rho = c(0.54, 0.26),
  log_sigma_os = c(8.25, 0.16), log_sigma_pd = c(6.66, 0.20)
)
run1 <- fit_quietly(compartmental(tri, "paid", "premium", gm1, incurred = "incurred",
                                  n_sims = 2000))
fit1 <- run1$fit
cat(sprintf("warnings %d | rate swaps %d\n", run1$n_warnings, fit1@rate_swaps))
cat(sprintf("rows agreeing %d of %d\n", check_posterior(fit1, M1FIT), 2 * length(M1FIT)))
warnings 0 | rate swaps 0
b_ker mean               paper   -5.4000  tolerance  0.1265  agrees: True
b_ker sd                 paper    0.8100  tolerance  0.0860  agrees: True
b_kp mean                paper   -8.4900  tolerance  0.0590  agrees: True
b_kp sd                  paper    0.3600  tolerance  0.0410  agrees: True
b_RLR mean               paper    1.4400  tolerance  0.0440  agrees: True
b_RLR sd                 paper    0.2600  tolerance  0.0310  agrees: True
b_RRF mean               paper   -1.3600  tolerance  0.0680  agrees: True
b_RRF sd                 paper    0.4200  tolerance  0.0470  agrees: True
tau_RLR mean             paper    0.6400  tolerance  0.0275  agrees: True
tau_RLR sd               paper    0.1500  tolerance  0.0200  agrees: True
tau_RRF mean             paper    0.7400  tolerance  0.0380  agrees: True
tau_RRF sd               paper    0.2200  tolerance  0.0270  agrees: True
rho mean                 paper    0.5400  tolerance  0.0440  agrees: True
rho sd                   paper    0.2600  tolerance  0.0310  agrees: True
log_sigma_os mean        paper    8.2500  tolerance  0.0290  agrees: True
log_sigma_os sd          paper    0.1600  tolerance  0.0210  agrees: True
log_sigma_pd mean        paper    6.6600  tolerance  0.0350  agrees: True
log_sigma_pd sd          paper    0.2000  tolerance  0.0250  agrees: True
rows agreeing 18 of 18

Every row agrees. On Windows at seed 0, prospicio gives these posterior means (sds in parentheses):

Parameter Mean (sd) Parameter Mean (sd)
b_ker -5.395 (0.833) tau_RRF 0.739 (0.220)
b_kp -8.485 (0.356) rho 0.533 (0.259)
b_RLR 1.446 (0.260) log_sigma_os 8.249 (0.160)
b_RRF -1.357 (0.414) log_sigma_pd 6.671 (0.204)
tau_RLR 0.643 (0.150)

The largest difference from the paper is 0.011 on log_sigma_pd, which is 0.055 printed sds. A reconstruction of the brms Stan program, run under CmdStan for 100,000 draws, gives values within 0.04 sds of the paper (knowledge/references/gesmann-morris-2020.md).

On the natural scale, k_er is about 1.76 and k_p about 0.43 a year. On average, claims are reported about seven months after the start (1 / k_er years) and paid about 2.3 years after that (1 / k_p). The population RLR is about 0.94 and RRF about 0.70. Thus the case reserves (with bulk) are redundant by about 30%, and the population ultimate loss ratio is about 0.65:

for (name in c("k_er", "k_p", "RLR", "RRF")) {
  cat(sprintf("%-4s posterior mean %.2f, 90%% interval %.2f to %.2f\n", name, param(fit1, name),
              param(fit1, name, "q05"), param(fit1, name, "q95")))
}
k_er posterior mean 1.76, 90% interval 1.54 to 2.02
k_p  posterior mean 0.43, 90% interval 0.40 to 0.45
RLR  posterior mean 0.94, 90% interval 0.86 to 1.02
RRF  posterior mean 0.70, 90% interval 0.65 to 0.75

5. The fitted paid and outstanding development

Each posterior draw gives a curve from its rates and from the RLR and RRF of its accident year. The fit is the posterior mean of these curves. The block below shows a mature accident year and a young one, with the actual and fitted values at each observed age:

par <- fit1@draws


fitted <- function(origin, age) {
  ker <- par[, "k_er"]
  kp <- par[, "k_p"]
  rlr <- par[, sprintf("RLR[%d]", origin)]
  rrf <- par[, sprintf("RRF[%d]", origin)]
  t <- age / 12
  g <- (exp(-kp * t) - exp(-ker * t)) / (ker - kp)
  p <- premium[[as.character(origin)]]
  c(os = mean(p * rlr * ker * g), pd = mean(p * rlr * rrf * ((1 - exp(-kp * t)) - kp * g)))
}


for (origin in c(1988, 1994)) {
  cat(sprintf("%d  age   paid actual  fitted   outstanding actual  fitted\n", origin))
  for (age in seq(12, 12 * (1997 - origin), by = 12)) {
    f <- fitted(origin, age)
    cat(sprintf("      %3d  %11s %7s  %18s %7s\n", age, fmt(cell(origin, age, "paid")), fmt(f[["pd"]]),
                fmt(cell(origin, age, "os")), fmt(f[["os"]])))
  }
}
1988  age   paid actual  fitted   outstanding actual  fitted
       12        9,558  10,266              53,121  53,150
       24       22,778  23,740              41,222  43,904
       36       33,298  33,712              32,309  30,258
       48       40,348  40,423              24,944  20,017
       60       45,146  44,835              17,104  13,101
       72       48,048  47,718              13,137   8,551
       84       49,782  49,599               9,605   5,578
       96       50,623  50,826               6,515   3,638
      108       51,812  51,626               1,661   2,373
1994  age   paid actual  fitted   outstanding actual  fitted
       12       11,194  11,693              62,434  58,627
       24       26,893  27,040              46,661  48,432
       36       38,488  38,401              32,248  33,380

Paid fits closely at every age. Outstanding does not. The actual outstanding of 1988 decreases more slowly than the two-rate curve permits. It is 24,944 at 48 months against 20,017 fitted, and 13,137 at 72 months against 8,551. The curve compensates at the latest age. With one k_p for every age, only slower payment can keep outstanding high for longer, and the paid cells do not agree with slower payment.

A normal likelihood with one sigma for each type also measures the error of a cell in absolute terms. Thus the large early cells dominate, and the small late cells fit loosely. Model 2 (section 7) addresses both points.

The test diagonal, calendar year 1997, is not in the training data. The paid and outstanding of the fit are the posterior predictive distributions of every future cell, with the noise of the likelihood:

cat("origin age   paid actual  predicted (5% to 95%)      outstanding actual  predicted (5% to 95%)\n")
inside <- 0
for (origin in 1988:1997) {
  age <- 12 * (1997 - origin + 1)
  row <- sprintf("%d  %3d", origin, age)
  for (kind in c("paid", "outstanding")) {
    dist <- if (kind == "paid") fit1@paid else fit1@outstanding
    m <- marginal(dist, list(origin = as.character(origin), age = age))
    q <- quantile(m, c(0.05, 0.95))
    actual <- cell(origin, age, if (kind == "paid") "paid" else "os")
    inside <- inside + (q[[1]] <= actual && actual <= q[[2]])
    row <- paste0(row, sprintf("  %11s %9s (%7s to %7s)", fmt(actual), fmt(mean(m)), fmt(q[[1]]),
                               fmt(q[[2]])))
  }
  cat(row, "\n", sep = "")
}
cat(sprintf("actual inside the 90%% interval: %d of 20 cells\n", inside))
origin age   paid actual  predicted (5% to 95%)      outstanding actual  predicted (5% to 95%)
1988  120       51,939    52,134 ( 50,555 to  53,704)        1,322     1,442 ( -4,767 to   7,654)
1989  108       46,229    46,471 ( 44,974 to  47,984)        2,071     2,225 ( -4,221 to   8,463)
1990   96       53,956    53,918 ( 52,229 to  55,396)        3,015     3,400 ( -2,962 to   9,698)
1991   84       66,566    68,301 ( 66,629 to  69,847)        3,966     6,093 (   -214 to  12,605)
1992   72       59,437    59,640 ( 57,874 to  61,288)        8,408     9,719 (  3,262 to  16,244)
1993   60       50,742    51,569 ( 49,766 to  53,265)       16,955    15,255 (  8,524 to  21,299)
1994   48       45,580    46,036 ( 44,052 to  47,800)       24,140    21,936 ( 15,299 to  28,437)
1995   36       44,045    44,009 ( 41,575 to  46,110)       35,336    32,662 ( 26,005 to  39,666)
1996   24       31,474    29,551 ( 26,296 to  32,548)       41,707    43,566 ( 35,806 to  51,858)
1997   12        9,372     6,225 (  4,061 to   8,740)       40,799    29,044 ( 19,668 to  38,538)
actual inside the 90% interval: 17 of 20 cells

Seventeen of the twenty cells are inside their 90% intervals. Two of the three misses are in the youngest accident year. The first paid (9,372) and outstanding (40,799) of 1997 are much higher than the model expects from its premium. This is a first sign of the result that section 7 finds in the reserve.

The outstanding intervals of the old years go below zero. The normal likelihood with a constant sigma (about 3,900) does not use the size of a cell. This is another reason for the log-normal likelihood of model 2.

6. The reserve distribution

The reserve of an accident year is its paid at 120 months less its latest paid. For 1997, the reserve is all of its paid. fit1@reserves is the joint posterior predictive distribution by accident year, with parameter error and process error.

The paper prints no reserve. Thus the comparison is with the Stan reconstruction of the paper’s code (100,000 draws). At 10,000 simulations, prospicio’s mean moves by about 0.016 sds from seed to seed and its sd by about 1.4%. These blocks use 2,000 simulations, so the tolerances are 0.1 sds and 7%:

r1 <- draw_matrix(fit1@reserves)
total1 <- rowSums(r1)
check("total reserve mean", 173341, mean(total1), 1000, ",.0f", "Stan")
check("total reserve sd", 10076, psd(total1), 700, ",.0f", "Stan")
i97 <- which(fit1@origins == "1997")
check("1997 reserve mean", 31321, mean(r1[, i97]), 600, ",.0f", "Stan")
check("1997 reserve sd", 6125, psd(r1[, i97]), 430, ",.0f", "Stan")
outcome <- ultimate_paid - latest_paid
q <- quantile(total1, c(0.05, 0.95), names = FALSE)
cat(sprintf("outcome %s inside the 90%% interval: %s\n", fmt(outcome),
            if (q[1] <= outcome && outcome <= q[2]) "True" else "False"))
total reserve mean       Stan    173,341  tolerance   1,000  agrees: True
total reserve sd         Stan     10,076  tolerance     700  agrees: True
1997 reserve mean        Stan     31,321  tolerance     600  agrees: True
1997 reserve sd          Stan      6,125  tolerance     430  agrees: True
outcome 187,420 inside the 90% interval: True
cat("origin  premium  latest paid  reserve mean      sd  ultimate loss ratio\n")
frame <- as.data.frame(fit1)
for (i in seq_len(nrow(frame))) {
  with(frame[i, ], cat(sprintf("%-6s %8s %12s %13s %7s %20.3f\n", origin, fmt(premium),
                               fmt(latest_paid), fmt(mean), fmt(std_dev), ultimate_loss_ratio)))
}
q <- quantile(total1, c(0.05, 0.95), names = FALSE)
cat(sprintf("total: mean %s, sd %s, 5%% %s, 95%% %s; outcome %s at percentile %.1f\n",
            fmt(mean(total1)), fmt(psd(total1)), fmt(q[1]), fmt(q[2]), fmt(outcome),
            100 * mean(total1 <= outcome)))
origin  premium  latest paid  reserve mean      sd  ultimate loss ratio
1988    104,437       51,812           322     948                0.509
1989     88,883       45,871         1,056     953                0.538
1990     85,956       52,879         2,471     984                0.656
1991     99,339       65,039         6,776   1,113                0.736
1992    104,897       56,406         8,756   1,172                0.633
1993    119,427       46,722        13,272   1,208                0.512
1994    110,784       38,488        20,927   1,420                0.546
1995     77,731       31,604        36,486   2,228                0.893
1996     63,646       13,194        51,755   4,388                1.041
1997     48,052            0        31,636   6,109                0.665
total: mean 173,457, sd 10,260, 5% 156,936, 95% 189,868; outcome 187,420 at percentile 91.9

The total reserve is about 173,500 with an sd of about 10,300 (Stan’s reconstruction: 173,341 and 10,076). The two youngest years have half of it. 1997 has no data and the widest uncertainty, because its loss ratio is the population value, drawn again in every simulation. The ultimate loss ratios are the RLR RRF of each year: the model’s ELR by accident year, shrunk toward the population value. The outcome, 187,420, is at about the 92nd percentile. It is inside the 90% interval, but high.

7. Model 2: log-normal loss ratios and effects on the rates

Model 2 changes three things:

  • The response. Model 2 models loss ratios to premium, not amounts. For paid, it uses the incremental paid loss ratio of each year, not the cumulative one. An incremental cell is the difference of the paid curve between t - 1 and t. Cumulative paid cells are strongly correlated, and an independent likelihood on them overstates their information. Incremental cells are closer to independent.
  • The likelihood. Each response is log-normal about its curve, so the noise is proportional to the size of the cell. Thus a large early cell does not swamp a small late cell, as it does under the constant sigma of model
    1. The log sigma priors are now informative: normal, with median 0.2 for sigma. This is the value in the paper’s code. The paper’s text gives 0.1 (see the reference note).
  • The hierarchy. All four parameters have accident-year effects (RLR and RRF correlated, the rates independent). All four also have development-year effects, so each cell has its own k_er, k_p, RLR and RRF. A development effect lets the curve bend where the two-rate shape is too stiff. An age with no observed cell (120 months here) draws a new effect from the population.

compartmental_model_2() with gesmann_morris_2_priors() fits model 2. It has a longer sampler than model 1: 4 chains of 2,000 warm-up draws and 8,000 kept draws, at target acceptance 0.999. The model has 87 parameters, several effect sds near zero and a slowly mixing k_p. With the sampler of model 1, it gave divergent transitions on most seeds. Its prior predictive check is fast, so it runs. The Python chunk also prints the settings of the model in its first line:

gm2 <- gesmann_morris_2_priors()
prior_check(gm2, "model 2", paid_response = "incremental")
model 2: 1988 loss ratios under the priors alone (5%, 50%, 95%) and actual
  paid         12 months  0.15 0.26 0.45   actual 0.09
  paid         36 months  0.32 0.51 0.85   actual 0.32
  paid        120 months  0.35 0.56 0.92   actual 0.50
  outstanding  12 months  0.20 0.33 0.57   actual 0.51
  outstanding  36 months  0.03 0.05 0.10   actual 0.31
  outstanding 120 months  0.00 0.00 0.00   actual 0.01

The medians are the same as for model 1, because the rate priors and ratio priors are the same. The intervals are wider, because each development year and accident year can also shift the rates and ratios. The conflict with the slow payment of company 337 is the same. The posterior again moves far from the preset, but less than for model 1, because the development effects can now bend the curve. At the population, k_er is about 2.6 and k_p about 0.60, against 1.76 and 0.43 for model 1.

The fit takes about a minute. The block below compares it with the paper’s printed m2fit (section 7.2.3). It shows prospicio’s value and the difference in printed sds:

M2FIT <- list(
  b_ker = c(-1.31, 1.08), b_kp = c(-5.07, 1.75), b_RLR = c(1.54, 0.44), b_RRF = c(-1.45, 0.69),
  tau_RLR = c(0.69, 0.31), tau_RRF = c(0.73, 0.47), tau_ker = c(0.26, 0.22),
  tau_kp = c(2.23, 1.35), rho = c(0.37, 0.47), tau_dev_RLR = c(0.35, 0.26),
  tau_dev_RRF = c(1.11, 0.49), tau_dev_ker = c(0.27, 0.23), tau_dev_kp = c(0.45, 0.43),
  log_sigma_os = c(-1.78, 0.16), log_sigma_pd = c(-1.89, 0.16)
)
run2 <- fit_quietly(compartmental_model_2(tri, "paid", "premium", gm2, incurred = "incurred",
                                          n_sims = 2000))
fit2 <- run2$fit
cat(sprintf("warnings %d | draws with k_er <= k_p in an observed cell %.1f\n", run2$n_warnings,
            fit2@cell_rate_swaps))
cat(sprintf("%-14s %10s %7s %7s   %8s %6s\n", "", "paper mean", "ours", "gap/sd", "paper sd", "ours"))
for (name in names(M2FIT)) {
  mean <- M2FIT[[name]][1]
  sd <- M2FIT[[name]][2]
  m <- param(fit2, name)
  cat(sprintf("%-14s %10.2f %7.3f %7.3f   %8.2f %6.3f\n", name, mean, m, (m - mean) / sd, sd,
              param(fit2, name, "sd")))
}
warnings 0 | draws with k_er <= k_p in an observed cell 0.0
               paper mean    ours  gap/sd   paper sd   ours
b_ker               -1.31  -1.294   0.015       1.08  1.064
b_kp                -5.07  -5.112  -0.024       1.75  1.692
b_RLR                1.54   1.539  -0.002       0.44  0.447
b_RRF               -1.45  -1.456  -0.009       0.69  0.697
tau_RLR              0.69   0.699   0.030       0.31  0.306
tau_RRF              0.73   0.731   0.003       0.47  0.470
tau_ker              0.26   0.263   0.015       0.22  0.214
tau_kp               2.23   2.175  -0.041       1.35  1.315
rho                  0.37   0.358  -0.025       0.47  0.474
tau_dev_RLR          0.35   0.352   0.009       0.26  0.264
tau_dev_RRF          1.11   1.124   0.029       0.49  0.498
tau_dev_ker          0.27   0.274   0.016       0.23  0.228
tau_dev_kp           0.45   0.483   0.076       0.43  0.511
log_sigma_os        -1.78  -1.787  -0.045       0.16  0.165
log_sigma_pd        -1.89  -1.887   0.017       0.16  0.162

Every mean is within 0.08 printed sds of the paper’s mean. Every sd is within 4% of the paper’s sd, except tau_dev_kp, the sd of the development effects on k_p: 0.511 against the printed 0.43. This sd has a heavy tail and mixes slowly. The paper’s own run had only about 500 effective draws on the parameters of k_p. The Stan reconstruction of the paper’s code with 100,000 draws gives 0.518. Thus the difference is the paper’s Monte Carlo error, not a difference of model.

prospicio’s means move by at most 0.036 posterior sds from seed to seed (200 seeds). Every draw keeps k_er above k_p in every observed cell.

The block below gives the reserves and ultimate loss ratios of the two models, and the paid of each accident year at 120 months:

r2 <- draw_matrix(fit2@reserves)
total2 <- rowSums(r2)
for (label in c("model 1", "model 2")) {
  t <- if (label == "model 1") total1 else total2
  q <- quantile(t, c(0.05, 0.95), names = FALSE)
  cat(sprintf("%s: total reserve mean %s, sd %s, 5%% %s, 95%% %s; outcome at percentile %.1f\n",
              label, fmt(mean(t)), fmt(psd(t)), fmt(q[1]), fmt(q[2]), 100 * mean(t <= outcome)))
}
cat("ultimate loss ratio by accident year, model 1 and model 2\n")
for (i in seq_along(fit1@origins)) {
  o <- fit1@origins[i]
  actual <- cell(as.integer(o), 120, "paid") / premium[[o]]
  cat(sprintf("  %s  %.3f  %.3f   paid at 120 months %.3f\n", o, fit1@ultimate_loss_ratio[i],
              fit2@ultimate_loss_ratio[i], actual))
}
model 1: total reserve mean 173,457, sd 10,260, 5% 156,936, 95% 189,868; outcome at percentile 91.9
model 2: total reserve mean 151,861, sd 13,729, 5% 130,835, 95% 175,476; outcome at percentile 99.2
ultimate loss ratio by accident year, model 1 and model 2
  1988  0.509  0.543   paid at 120 months 0.497
  1989  0.538  0.582   paid at 120 months 0.523
  1990  0.656  0.686   paid at 120 months 0.638
  1991  0.736  0.727   paid at 120 months 0.694
  1992  0.633  0.657   paid at 120 months 0.604
  1993  0.512  0.565   paid at 120 months 0.485
  1994  0.546  0.586   paid at 120 months 0.499
  1995  0.893  0.849   paid at 120 months 0.862
  1996  1.041  0.885   paid at 120 months 1.072
  1997  0.665  0.674   paid at 120 months 1.152

The total of model 2 is about 151,900 (Stan’s reconstruction: 152,242, sd 13,938). This is about 21,600 below model 1, with a wider spread. The outcome, 187,420, is at the 92nd percentile of model 1 and the 99th percentile of model 2.

The miss is in the youngest years. 1996 and 1997 paid 1.07 and 1.15 of their premium by 120 months. Their ultimate loss ratios are 0.89 and 0.67 under model 2, and 1.04 and 0.67 under model 1. Premium decreased from 119,427 in 1993 to 48,052 in 1997, but losses did not, which is the pattern of a softening market. Both models shrink a young year toward the population loss ratio. Model 2 has more effects that share information, so it shrinks more.

One triangle gives one outcome. Thus this result does not show the calibration of the models in general. It shows only that the shrinkage of young years needs a judgement when the market changes.

8. Do not compare the two models by elpd_loo

Both fits report PSIS-LOO (bayes_loo()): the expected log predictive density of each observed cell, with that cell left out. Do not compare the elpd_loo of model 1 with that of model 2. The responses of model 1 are amounts in thousands, with cumulative paid. The responses of model 2 are loss ratios, with incremental paid. A log density depends on the unit of its response. Thus the two numbers are on different scales and do not show which model predicts better.

Compare elpd_loo only between fits of the same responses, for example two prior sets for model 1. CI runs the elpd_loo of model 1 and checks it against the Stan reconstruction, which moves by about 0.35 from seed to seed:

loo1 <- bayes_loo(fit1)
check("model 1 elpd_loo", -811.0, loo1$estimates[["elpd"]], 2.0, ".1f", "Stan")
cat(sprintf("model 1 cells with Pareto k above 0.7: at least one %s\n",
            if (any(loo1$pareto_k > 0.7)) "True" else "False"))
model 1 elpd_loo         Stan     -811.0  tolerance     2.0  agrees: True
model 1 cells with Pareto k above 0.7: at least one True
for (label in c("model 1", "model 2")) {
  loo <- bayes_loo(if (label == "model 1") fit1 else fit2)
  k <- loo$pareto_k
  cat(sprintf(paste0("%s: elpd_loo %.1f (se %.1f), outstanding %.1f, paid %.1f; ",
                     "Pareto k above 0.7 in %d of %d cells, largest %.2f\n"),
              label, loo$estimates[["elpd"]], loo$estimates[["se"]], loo$elpd_outstanding,
              loo$elpd_paid, sum(k > 0.7), length(k), max(k)))
}
model 1: elpd_loo -810.7 (se 10.2), outstanding -440.8, paid -370.0; Pareto k above 0.7 in 3 of 90 cells, largest 0.96
model 2: elpd_loo 203.8 (se 11.5), outstanding 71.5, paid 132.2; Pareto k above 0.7 in 9 of 90 cells, largest 1.30

A few cells have Pareto k above 0.7. In these cells, the importance sampling approximation behind PSIS-LOO is not reliable. The left-out cell moves the posterior too much, so the draws of the full posterior do not represent the fit without that cell. The elpd_loo is then an estimate with an unknown error, not a measure of predictive accuracy. Exact LOO, a refit without those cells, removes this uncertainty.

For model 2, the elpd_loo agreed with the arviz calculation on the same draws (finding compartmental-gm2-parity.md). Thus that row checks the arithmetic, not the fit. To select between the two models, compare their forecasts of the test diagonal and of the outcome (sections 5 to 7). These forecasts are on the same scale.

9. The one-year view

A solvency view asks how far the best estimate can move in the next year. It does not ask how far the reserve can move over its full life. This movement is the claims development result (CDR): the opening reserve, less the paid of the year, less the reserve estimated again one year later.

compartmental_one_year() simulates the next calendar diagonal (paid and outstanding of every accident year) from the posterior. For each simulated year, it estimates the posterior again without a refit. It reweights the existing draws by the likelihood of the new cells (Pareto smoothed importance sampling).

The new cells move this posterior a lot, so the weights of most simulations fail the Pareto k test (k above 0.7). For model 1, prospicio then moment matches the draws: it applies small affine shifts to the draws so that the weights are reliable again. It refits with NUTS only the few simulations that matching cannot rescue. On company 337, matching rescues about 95% of them, within about 0.05 sds of a refit (knowledge/findings/compartmental-one-year.md). By default, the view runs at most 2,000 simulations and takes several minutes:

run <- fit_quietly(compartmental_one_year(tri, "paid", "premium", gm1, incurred = "incurred",
                                          n_sims = 2000))
view1 <- run$fit
cdr1 <- rowSums(draw_matrix(view1@cdr))
cat(sprintf("model 1: flagged %.0f%%, moment-matched %s, refitted %s, refits with a diagnostic warning %d\n",
            100 * view1@flagged_share, fmt(length(view1@moment_matched)),
            fmt(length(view1@refitted)), view1@refit_warnings))
cat("warnings", run$n_warnings, "\n")
cat(sprintf("total CDR mean %s, sd %s; lifetime reserve sd %s; ratio %.2f\n", fmt(mean(cdr1)),
            fmt(psd(cdr1)), fmt(psd(total1)), psd(cdr1) / psd(total1)))
model 1: flagged 81%, moment-matched 1,549, refitted 78, refits with a diagnostic warning 8
warnings 1
total CDR mean 55, sd 7,982; lifetime reserve sd 10,260; ratio 0.78

About four in five simulations are flagged. Matching rescues about 95% of them, and NUTS refits the others, which takes most of the run time. The warning is about the refits: 8 of them missed an MCMC diagnostic threshold. Thus read view1@refit_warnings before you use the far tail of the CDR. About 78% of the sd of the lifetime reserve emerges in the first year, which agrees with the 200-seed study (0.80, sd 0.03). The mean of the CDR is about zero, as expected.

The R package’s own run on Windows (seed 0, GNU toolchain) gives 82% flagged, 1,548 matched, 102 refitted and a ratio of 0.81.

For model 2, matching rescues none of the flagged simulations. Its posterior has 95 sampled values and several effect sds near zero, which is far from the near-normal shape that the shifts can follow. A refit takes as long as a fit, so a view with a full refit for each flagged simulation would take days. Thus the default view refits the flagged simulations with a light refit: a shorter, warm-started NUTS run, scaled by the opening posterior (compartmental_model_2_one_year()). On company 337, this view is within about 0.03 sds of the total CDR of full refits. It takes about half an hour at the default 2,000 simulations.

light_refit = FALSE reweights only, and gives a warning that the view is approximate. Such a view is about 0.4 sds of the total CDR from a refit for each simulation. one_year_sims, refit and max_refits change the balance between accuracy and time. To save time, the run below reweights only.

run <- fit_quietly(compartmental_model_2_one_year(tri, "paid", "premium", gm2,
                                                  incurred = "incurred", n_sims = 2000,
                                                  light_refit = FALSE))
view2 <- run$fit
cdr2 <- rowSums(draw_matrix(view2@cdr))
cat(sprintf("model 2: flagged %.0f%%, moment-matched %s, refitted %s\n", 100 * view2@flagged_share,
            fmt(length(view2@moment_matched)), fmt(length(view2@refitted))))
cat("warnings", run$n_warnings, "\n")
cat(strwrap(paste("approximate:", view2@approximate), width = 89), sep = "\n")
cat(sprintf("total CDR mean %s, sd %s; lifetime reserve sd %s; ratio %.2f\n", fmt(mean(cdr2)),
            fmt(psd(cdr2)), fmt(psd(total2)), psd(cdr2) / psd(total2)))
model 2: flagged 100%, moment-matched 0, refitted 0
warnings 1
approximate: the one-year view reweights its flagged simulations only, as the light refit
of development effects (model 2) was turned off: moment matching rescues none of them. The
view is approximate, about 0.4 sd of the total claims development result off a refit per
simulation on company 337; leave light_refit at its default to refit them with a shorter
sampler (within about 0.03 sd there, at about 20 times the run time of reweighting only),
or refit (with max_refits as a budget) for the fit's own sampler
total CDR mean 103, sd 11,379; lifetime reserve sd 13,729; ratio 0.83

Every simulation is flagged and reweighted only. The view reports this in view2@approximate and in a warning. Its CDR sd is 0.83 of the lifetime sd (0.82 in the study, 0.78 to 0.84 over three seeds). Use it as an approximation good to about 0.4 sds, not as a value of refit quality.

The R package’s own run on Windows gives a ratio of 0.80 (CDR sd 11,401, lifetime sd 14,261).

10. Several triangles and the backtest

compartmental_segments() fits segments on their own seeds, independent or rank-correlated. compartmental_one_year_segments() does the same for the one-year view. compartmental_candidate() puts the model in diagonal_backtest() next to the other Bayesian models. compartmental_outstanding_backtest() scores the held-out outstanding diagonals as well as the paid diagonals.

11. Quarterly and monthly cells

The model allows development cells finer than a year, with origins a whole multiple of them (annual origins with quarterly development, say), and the rates stay per year on every grain. A study on simulated books (design note decision 14; no real sub-annual triangle was available) found these things, and the library keeps to them.

  • Rate priors: the paper’s presets are kept as they are. A line whose first year runs much faster or slower than the preset’s k_er of about 3 needs priors of its own.
  • Model 2’s development levels: development_levels = "per_age" or "by_year" (model 2 only). One level for each age is the default. Choose by LOO. Where effects move by year, by-year levels gave the same reserve (0.10 sd apart on average) and won elpd in 30 of 30 quarterly books, and on 10 monthly books under a short sampler took 89 s against 126 s (rough times) with a worst R-hat of 1.07 against 1.62, though a median bulk ESS of 101 against 114. Where effects move within a year, they lost 361 of elpd in 30 of 30 books and widened the reserve’s sd by 59%. A year is counted from each origin’s own start (ages 1 to 12 months, 13 to 24 and so on). At annual grain the two settings are the same model, and model 1 has no development effects to group.
  • Seasonality: there is no seasonal term. Model 1 reads a season as noise (the sd up to 54% wider for a 30% season, the mean up to 0.94 sd off), and model 2’s per-age levels do not absorb a season unless every origin starts in the same calendar quarter. A calendar-quarter factor is not built.
  • Cumulative paid: its interval narrows as the cells get finer. That is right where the noise of the cells is independent, and too narrow where it persists from cell to cell. In the study, at one persistence chosen by hand and fitted to no book (PERSIST_PHI 25, PERSIST_RHO 0.95; a smaller fall is expected with less, untested), the 90% interval covered 88%, 70% and 56% at annual, quarterly and monthly cells and the RMSE rose from 1,623 to 2,033. A fit with cumulative paid on cells finer than a year therefore warns, asking you to check the residuals, and it warns on a calibrated fit too, since the data do not say which world they are in. Incremental paid keeps the interval but, in the study’s persistent-noise world, ran 1.3 to 2 times too wide, with a worse RMSE at quarterly and monthly grain and a failing Meyers’ D at annual grain. The library picks neither form for you.
  • Earned exposure: all of an origin’s exposure starts at age 0, so quarterly development of annual origins fits an exposure the model does not have. Use quarterly origins where the data allow. On simulated books with earned premium, annual origins failed Meyers’ D at annual, quarterly and monthly development, and quarterly origins of the same books passed narrowly (17.8 against a critical 19.2, on a short sampler, with 3 books at the default sampler). That comparison also changes the number of origins. A setting that spreads the exposure over the origin’s period is not built.