## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE, fig.width = 7, fig.height = 4)

## ----library------------------------------------------------------------------
library("NetSimR")

## ----policies-----------------------------------------------------------------
set.seed(2026)
n <- 20000
policies <- data.frame(
  age = sample(18:80, n, replace = TRUE),
  region = sample(c("North", "South", "East", "West"), n, replace = TRUE),
  vehicle = sample(c("car", "van", "motorcycle"), n, replace = TRUE, prob = c(0.7, 0.2, 0.1)),
  exposure = round(runif(n, 0.25, 1), 2)
)
frequency <- exp(-2.2 - 0.012 * (policies$age - 45) + 0.35 * (policies$region == "North") +
                 0.5 * (policies$vehicle == "motorcycle"))
policies$claims <- rpois(n, policies$exposure * frequency)
severity_mean <- 3000 * ifelse(policies$vehicle == "van", 1.4, 1)
policies$cost <- vapply(seq_len(n), function(i) {
  sum(rgamma(policies$claims[i], shape = 1.5, scale = severity_mean[i] / 1.5))
}, numeric(1))
head(policies)

## ----glm----------------------------------------------------------------------
test <- sample(n, n / 5)
training <- policies[-test, ]
frequency_model <- glm(claims ~ offset(log(exposure)) + age + region + vehicle, family = poisson(), data = training)
with_claims <- training[training$claims > 0, ]
severity_model <- glm(cost / claims ~ age + region + vehicle, family = Gamma(link = "log"),
                      weights = claims, data = with_claims)
round(exp(coef(frequency_model)), 3)
round(exp(coef(severity_model)), 3)

## ----tweedie------------------------------------------------------------------
tweedie_model <- glm(cost ~ offset(log(exposure)) + age + region + vehicle, family = tweedie_family(1.5),
                     data = training)
round(exp(coef(tweedie_model)), 3)

## ----lift---------------------------------------------------------------------
held_out <- policies[test, ]
predicted <- predict(tweedie_model, held_out, type = "response")
rate <- predicted / held_out$exposure
band <- cut(cumsum(held_out$exposure[order(rate)]) / sum(held_out$exposure), seq(0, 1, 0.2), labels = 1:5)
lift <- data.frame(
  band = levels(band),
  actual = tapply(held_out$cost[order(rate)], band, sum) / tapply(held_out$exposure[order(rate)], band, sum),
  predicted = tapply(predicted[order(rate)], band, sum) / tapply(held_out$exposure[order(rate)], band, sum)
)
lift

## ----expected claims----------------------------------------------------------
next_year <- policies
next_year$exposure <- 1
claim_count <- sum(predict(frequency_model, next_year, type = "response"))
claim_count

## ----severity-----------------------------------------------------------------
# the policies with one claim give the size of each claim
sizes <- training$cost[training$claims == 1]
meanlog <- mean(log(sizes))
sdlog <- sqrt(mean((log(sizes) - meanlog)^2))
c(meanlog = meanlog, sdlog = sdlog)

## ----simulate-----------------------------------------------------------------
years <- simulate_claims(5000, frequency = "Poisson", frequency_params = claim_count,
                         severity = "LogNormal", severity_params = c(meanlog, sdlog),
                         eel_layer = "limited", eel_deductible = 50000, eel_limit = 100000,
                         eel_reinstatements = 2, seed = 1)
years$retained <- years$gross_claims - years$total_claims
summary_of <- function(x) round(c(mean = mean(x), sd = sd(x), quantile(x, c(0.5, 0.9, 0.99, 0.995))))
rbind(gross = summary_of(years$gross_claims), ceded = summary_of(years$total_claims),
      retained = summary_of(years$retained))

## ----programmes---------------------------------------------------------------
gross_premium <- round(claim_count * exp(meanlog + sdlog^2 / 2) / 0.7, -4)
options <- list(`Layer 100k xs 50k` = list(xl = list(deductible = 50000, limit = 100000, reinstatements = 2)),
                `Quota share 25%` = list(quota_share = 0.25, commission = 0.30))
compare_reinsurance("Poisson", claim_count, "LogNormal", c(meanlog, sdlog), options,
                    premium = gross_premium, n = 5000, seed = 1)

## ----portfolio----------------------------------------------------------------
lines <- list(
  motor = years$retained,
  property = list(frequency = "Poisson", frequency_params = 8,
                  severity = "Pareto", severity_params = c(1.9, 50000))
)
gaussian <- simulate_portfolio(lines, correlation = 0.3, n = 5000, seed = 1)
gaussian
t_copula <- simulate_portfolio(lines, correlation = 0.3, copula = "t", df = 3, n = 5000, seed = 1)
rbind(gaussian = gaussian$diversification, t = t_copula$diversification)

## ----triangle-----------------------------------------------------------------
paid <- as_triangle(simulated_motor_claims, "accident_year", "development_year", "paid", cumulative = FALSE)
premium <- unique(simulated_motor_claims[c("accident_year", "earned_premium")])$earned_premium
cl <- chain_ladder(paid)
cl$total

## ----ave----------------------------------------------------------------------
ave <- actual_vs_expected(paid)
ave$by_origin[, c("origin", "expected", "actual", "actual_to_expected", "z")]

## ----clark--------------------------------------------------------------------
ldf <- clark_growth(paid, truncation = 20)
cape_cod <- clark_growth(paid, premium = premium, method = "cape cod", truncation = 20)
rbind(chain_ladder = cl$total[c("ibnr", "se")], clark_ldf = ldf$total[c("ibnr", "se")],
      clark_cape_cod = cape_cod$total[c("ibnr", "se")])

## ----inflation----------------------------------------------------------------
inflated <- inflation_adjusted_chain_ladder(paid, past = 0.03, future = 0.06)
inflated$total

## ----discount-----------------------------------------------------------------
be <- discount_reserves(cl, yield_curve = c(0.030, 0.032, 0.034, 0.036, 0.038))
be

## ----risk adjustment----------------------------------------------------------
boot <- bootstrap_chain_ladder(paid, n = 2000, seed = 1)
percentile <- risk_adjustment("percentile", boot = boot, level = 0.75, discounted = be)
coc <- risk_adjustment("cost of capital", boot = boot, discounted = be,
                       capital = 3 * 0.09 * be$total[["discounted"]], coc_rate = 0.06)
rbind(percentile = c(percentile$risk_adjustment, percentile$confidence_level),
      cost_of_capital = c(coc$risk_adjustment, coc$confidence_level))

## ----standard formula---------------------------------------------------------
volumes <- data.frame(segment = c(1, 4), premium = c(gross_premium, 1.2e6),
                      reserve = c(be$total[["discounted"]], 0.4e6))
sii <- sii_premium_reserve_risk(volumes)
sii$total

