## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(comment = "#>", collapse = TRUE, fig.align = "center", fig.width = 6, fig.height = 4)
old_options <- options(width = 80, digits = 4, scipen = 8)

## ----panel--------------------------------------------------------------------
library("baggingReserve")
data("synthetic_claims", "synthetic_payments", package = "baggingReserve")
cl <- synthetic_claims[synthetic_claims$Type %in% c("2", "3"), ]
pay <- synthetic_payments[synthetic_payments$Id %in% cl$Id, ]
panel <- claims_panel(cl, pay, t = 12, L = 11, features = c("Type", "Age", "AccWeekday"))
panel
round(as_triangle(panel) / 1e6, 1)

## ----tree---------------------------------------------------------------------
tree <- reserve_tree(panel, seed = 1)
tree
pred_tree <- predict(tree)
pred_tree

## ----tree-draw----------------------------------------------------------------
pred_draw <- predict(tree, completion = "draw", R = 50, seed = 1)
cbind(plug_in = calendar_year_payments(pred_tree)[, 1],
      simulated = rowMeans(calendar_year_payments(pred_draw)))[c(1, 11, 12), ]

## ----bagging------------------------------------------------------------------
bag <- bag_reserve(panel, B = 20, seed = 2026)
oob_score(bag)[, c("period", "n_train", "coverage", "oob_score")]
res <- ibnr_reserve(predict(bag), claim_counts(panel))
res
summary(res, probs = c(0.025, 0.5, 0.975))$tables$total

## ----bagging-draw-------------------------------------------------------------
bag_draw <- bag_reserve(panel, B = 20, seed = 2026, completion = "draw")
res_draw <- ibnr_reserve(predict(bag_draw), claim_counts(panel))

## ----backtest-----------------------------------------------------------------
data("synthetic_claims_full", "synthetic_payments_full", package = "baggingReserve")
cl_full <- synthetic_claims_full[synthetic_claims_full$Type %in% c("2", "3"), ]
pay_full <- synthetic_payments_full[synthetic_payments_full$Id %in% cl_full$Id, ]
cl_ref <- chain_ladder(as_triangle(panel))
bt <- backtest(res, cl_full, pay_full, reference = cl_ref)
bt$tables$total[, c("calendar", "truth", "predicted", "rel_error", "reference_rel_error")]
bt_draw <- backtest(res_draw, cl_full, pay_full)
bt_draw$tables$total[c(1, 12), c("calendar", "truth", "predicted", "rel_error")]

## ----plot, fig.cap="Predicted payments by calendar year with the realised payments."----
plot(res, "calendar", truth = setNames(bt$tables$total$truth, bt$tables$total$calendar))

## ----restore-options, include=FALSE-------------------------------------------
options(old_options)

