## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE, fig.width = 7, fig.height = 4)

## ----triangle-----------------------------------------------------------------
library("NetSimR")
raa_triangle

## ----as triangle--------------------------------------------------------------
head(simulated_motor_claims)
motor <- as_triangle(simulated_motor_claims, "accident_year", "development_year", "paid", cumulative = FALSE)
motor[1:4, 1:6]

## ----chain ladder-------------------------------------------------------------
cl <- chain_ladder(raa_triangle)
cl
round(cl$factors, 3)

## ----factors------------------------------------------------------------------
round(cl$link_ratios[1:3, 1:3], 2)
exclude <- matrix(FALSE, 10, 9)
exclude[2, 1] <- TRUE
selected <- chain_ladder(raa_triangle, average = "simple", periods = 5, exclude = exclude)
round(selected$factors, 3)
selected$total[c("ultimate", "ibnr", "se")]

## ----tail---------------------------------------------------------------------
tailed <- chain_ladder(raa_triangle, tail = "exponential")
tailed$tail
tailed$total[c("ultimate", "ibnr", "se")]

## ----premiums-----------------------------------------------------------------
premium <- unique(simulated_motor_claims[c("accident_year", "earned_premium")])$earned_premium
cl_motor <- chain_ladder(motor)
bf <- bornhuetter_ferguson(cl_motor, premium, loss_ratio = 0.68)
bk <- bornhuetter_ferguson(cl_motor, premium, loss_ratio = 0.68, iterations = 2)
cc <- cape_cod(cl_motor, premium)
cc$total[["loss_ratio"]]

ultimates <- data.frame(
  origin = cl_motor$by_origin$origin,
  developed = round(cl_motor$by_origin$developed, 3),
  chain_ladder = round(cl_motor$by_origin$ultimate),
  bornhuetter_ferguson = round(bf$by_origin$ultimate),
  benktander = round(bk$by_origin$ultimate),
  cape_cod = round(cc$by_origin$ultimate)
)
tail(ultimates, 4)

## ----loss ratios--------------------------------------------------------------
round(tail(cc$by_origin$ultimate_loss_ratio, 4), 3)

## ----bootstrap----------------------------------------------------------------
boot <- bootstrap_chain_ladder(raa_triangle, n = 5000, seed = 1)
round(boot$total[c("ibnr", "se", "p75", "p99.5")])
hist(boot$total_reserves, breaks = 50, main = "Simulated total IBNR", xlab = NULL)
abline(v = boot$total[c("ibnr", "p99.5")], lty = c(1, 2))

## ----one year-----------------------------------------------------------------
merz_wuthrich(raa_triangle)

## ----munich-------------------------------------------------------------------
mcl <- munich_chain_ladder(quarg_mack_paid, quarg_mack_incurred)
shown <- mcl$by_origin[, c("origin", "latest_ratio", "chain_ladder_paid", "chain_ladder_incurred",
                           "ultimate_paid", "ultimate_incurred")]
shown[-1] <- round(shown[-1], 2)
shown

