diff --git a/.Rbuildignore b/.Rbuildignore index 6bba28a..5a3bf74 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -7,3 +7,6 @@ ^pkgdown$ ^doc$ ^Meta$ +^\.positai$ +^\.claude$ +^data-raw$ diff --git a/.github/workflows/r-checkrelease.yml b/.github/workflows/r-checkrelease.yml index 1b5e463..3b42e77 100644 --- a/.github/workflows/r-checkrelease.yml +++ b/.github/workflows/r-checkrelease.yml @@ -1,26 +1,156 @@ -# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples -# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +# CRAN-oriented package checks. +# Based on the current r-lib/actions v2 standard workflow, with additional +# package-specific audits and a strict full-manual release check. + on: push: branches: [main, master] pull_request: branches: [main, master] + workflow_dispatch: + +name: CRAN-ready checks -name: R-CMD-check +permissions: read-all + +concurrency: + group: cran-ready-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: - R-CMD-check: + package-audit: + name: Package-specific audit runs-on: ubuntu-latest + timeout-minutes: 45 env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} R_KEEP_PKG_SOURCE: yes + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: r-lib/actions/setup-r@v2 with: + r-version: release use-public-rspm: true + - name: Verify apc is not declared as a dependency + run: | + description <- read.dcf("DESCRIPTION") + dependency_fields <- intersect( + c("Depends", "Imports", "Suggests", "Enhances", "LinkingTo"), + colnames(description) + ) + entries <- unlist( + strsplit( + paste(description[1L, dependency_fields], collapse = ","), + ",", + fixed = TRUE + ) + ) + packages <- sub("[[:space:]]*\\(.*$", "", trimws(entries)) + if ("apc" %in% packages) { + stop("The retired package 'apc' is still declared in DESCRIPTION.") + } + shell: Rscript {0} + + - name: Verify no active apc usage remains + shell: bash + run: | + if grep -RInE \ + --exclude-dir=.git \ + --exclude-dir=docs \ + --exclude=test-no-apc-dependency.R \ + --exclude=r-checkrelease.yml \ + --exclude=r-checkrelease-cran-ready.yml \ + 'library[[:space:]]*\([[:space:]]*apc[[:space:]]*\)|require[[:space:]]*\([[:space:]]*apc[[:space:]]*\)|requireNamespace[[:space:]]*\([[:space:]]*["'\'' ]*apc["'\'' ]*|import[[:space:]]*\([[:space:]]*apc[[:space:]]*\)|importFrom[[:space:]]*\([[:space:]]*apc[[:space:]]*,|apc::|apc\.(data|fit|forecast)|github::cran/apc' \ + DESCRIPTION NAMESPACE R tests vignettes README.md .github; then + echo "Active use of the retired 'apc' package was found." + exit 1 + fi + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: | + any::devtools + any::rcmdcheck + any::testthat + any::urlchecker + local::. + needs: check + + - name: Regenerate and verify documentation + run: | + devtools::document() + changes <- system2( + "git", + c("status", "--short", "--", "NAMESPACE", "man"), + stdout = TRUE + ) + if (length(changes)) { + stop( + "Generated documentation is stale:\n", + paste(changes, collapse = "\n") + ) + } + shell: Rscript {0} + + - name: Run testthat suite + run: testthat::test_local(stop_on_failure = TRUE) + shell: Rscript {0} + + - name: Replication regression smoke test + run: | + data("AutoBI", package = "ChainLadder") + triangle <- ChainLadder::incr2cum(AutoBI$AutoBIPaid) + fit <- clmplus::clmplus(clmplus::AggregateDataPP(triangle), "a") + prediction <- predict(fit) + reference <- ChainLadder::MackChainLadder(triangle)$FullTriangle + + stopifnot( + isTRUE( + all.equal( + unname(prediction$full_triangle), + unname(reference), + tolerance = 1e-10 + ) + ) + ) + shell: Rscript {0} + + - name: Check package URLs + run: urlchecker::url_check(".", parallel = FALSE) + shell: Rscript {0} + + platform-checks: + name: ${{ matrix.config.os }} (R ${{ matrix.config.r }}) + runs-on: ${{ matrix.config.os }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + config: + - {os: macos-latest, r: release} + - {os: windows-latest, r: release} + - {os: ubuntu-latest, r: devel, http-user-agent: release} + - {os: ubuntu-latest, r: oldrel-1} + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v6 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + http-user-agent: ${{ matrix.config.http-user-agent }} + - uses: r-lib/actions/setup-r-dependencies@v2 with: extra-packages: any::rcmdcheck @@ -28,5 +158,48 @@ jobs: - uses: r-lib/actions/check-r-package@v2 with: + args: 'c("--no-manual", "--as-cran")' + build_args: 'c("--no-manual", "--compact-vignettes=gs+qpdf")' + error-on: '"warning"' + upload-results: true + upload-snapshots: true + + cran-release-check: + name: Ubuntu release, manual and vignettes + runs-on: ubuntu-latest + timeout-minutes: 90 + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v6 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: release + use-public-rspm: true + + - uses: r-lib/actions/setup-tinytex@v2 + + - name: Install HTML Tidy + run: | + sudo apt-get update + sudo apt-get install --yes tidy + tidy --version + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + needs: check + + - name: Full CRAN-style check + uses: r-lib/actions/check-r-package@v2 + with: + args: 'c("--as-cran")' + build_args: 'c("--compact-vignettes=gs+qpdf")' + error-on: '"note"' + upload-results: true upload-snapshots: true - build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' diff --git a/.github/workflows/rhub.yaml b/.github/workflows/rhub.yaml deleted file mode 100644 index 74ec7b0..0000000 --- a/.github/workflows/rhub.yaml +++ /dev/null @@ -1,95 +0,0 @@ -# R-hub's generic GitHub Actions workflow file. It's canonical location is at -# https://github.com/r-hub/actions/blob/v1/workflows/rhub.yaml -# You can update this file to a newer version using the rhub2 package: -# -# rhub::rhub_setup() -# -# It is unlikely that you need to modify this file manually. - -name: R-hub -run-name: "${{ github.event.inputs.id }}: ${{ github.event.inputs.name || format('Manually run by {0}', github.triggering_actor) }}" - -on: - workflow_dispatch: - inputs: - config: - description: 'A comma separated list of R-hub platforms to use.' - type: string - default: 'linux,windows,macos' - name: - description: 'Run name. You can leave this empty now.' - type: string - id: - description: 'Unique ID. You can leave this empty now.' - type: string - -jobs: - - setup: - runs-on: ubuntu-latest - outputs: - containers: ${{ steps.rhub-setup.outputs.containers }} - platforms: ${{ steps.rhub-setup.outputs.platforms }} - - steps: - # NO NEED TO CHECKOUT HERE - - uses: r-hub/actions/setup@v1 - with: - config: ${{ github.event.inputs.config }} - id: rhub-setup - - linux-containers: - needs: setup - if: ${{ needs.setup.outputs.containers != '[]' }} - runs-on: ubuntu-latest - name: ${{ matrix.config.label }} - strategy: - fail-fast: false - matrix: - config: ${{ fromJson(needs.setup.outputs.containers) }} - container: - image: ${{ matrix.config.container }} - - steps: - - uses: r-hub/actions/checkout@v1 - - uses: r-hub/actions/platform-info@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/setup-deps@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/run-check@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - other-platforms: - needs: setup - if: ${{ needs.setup.outputs.platforms != '[]' }} - runs-on: ${{ matrix.config.os }} - name: ${{ matrix.config.label }} - strategy: - fail-fast: false - matrix: - config: ${{ fromJson(needs.setup.outputs.platforms) }} - - steps: - - uses: r-hub/actions/checkout@v1 - - uses: r-hub/actions/setup-r@v1 - with: - job-config: ${{ matrix.config.job-config }} - token: ${{ secrets.RHUB_TOKEN }} - - uses: r-hub/actions/platform-info@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/setup-deps@v1 - with: - job-config: ${{ matrix.config.job-config }} - token: ${{ secrets.RHUB_TOKEN }} - - uses: r-hub/actions/run-check@v1 - with: - job-config: ${{ matrix.config.job-config }} - token: ${{ secrets.RHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index ac41711..1c78fef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .Rproj.user .Rhistory -.RData +/.RData .Ruserdata /doc/ /Meta/ +.positai diff --git a/DESCRIPTION b/DESCRIPTION index 44fe477..934ab9e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,12 +1,14 @@ Package: clmplus Type: Package +Depends: + R (>= 3.5.0) Title: Tool-Box of Chain Ladder Plus Models -Version: 1.0.1 +Version: 1.1.0 Authors@R: c(person(given = "Gabriele", family = "Pittarello", role = c("aut", "cre", "cph"), - email = "gabriele.pittarello@uniroma1.it", + email = "gabriele.pittarello@sund.ku.dk", comment = c(ORCID = "0000-0003-3360-5826")), person(given = "Munir", family = "Hiabu", @@ -17,7 +19,7 @@ Authors@R: family = "Villegas", role = c("aut", "cph"), email="a.villegas@unsw.edu.au")) -Description: Implementation of the age-period-cohort models for the claim development presented in the manuscript 'Replicating and extending chain-ladder via an age-period-cohort structure on the claim development in a run-off triangle' . +Description: Implementation of the age-period-cohort models for the claim development presented in the manuscript 'Replicating and extending chain-ladder via an age-period-cohort structure on the claim development in a run-off triangle' . URL: https://github.com/gpitt71/clmplus, https://gpitt71.github.io/clmplus/ BugReports: https://github.com/gpitt71/clmplus/issues @@ -33,11 +35,9 @@ Imports: Encoding: UTF-8 LazyData: true Suggests: + testthat (>= 3.0.0), knitr, - rmarkdown, - apc, - dplyr, - viridis, - tidyr + rmarkdown VignetteBuilder: knitr, rmarkdown +Config/testthat/edition: 3 RoxygenNote: 7.3.3 diff --git a/R/AggregateDataPP.R b/R/AggregateDataPP.R index 973a1e1..e8f3ae1 100644 --- a/R/AggregateDataPP.R +++ b/R/AggregateDataPP.R @@ -1,30 +1,48 @@ #' Pre-process Run-Off Triangles #' #' Pre-process Run-Off Triangles. -#' @param cumulative.payments.triangle \code{triangle matrix} or \code{matrix array} object, input triangle of cumulative payments. -#' @param entries.weights \code{triangle matrix} or \code{matrix array} model entries weights. -#' @param eta \code{numeric}, individual claims exposure in the cell, also known as lost exposure. It must be in the interval (0,1]. +#' @param cumulative.payments.triangle A square numeric matrix with at least +#' two rows. Rows are accident periods, columns are development periods, and +#' observed upper-triangle cells satisfy `row + column <= J + 1`. Values are +#' non-negative cumulative paid amounts in the source data's monetary units, +#' non-decreasing across each row; unavailable cells may be `NA`. Recoveries +#' (negative incremental payments) are not supported. +#' @param entries.weights Optional non-negative numeric `J` by `J` matrix of +#' fitting weights in the same accident/development layout. `NULL` gives +#' observed cells weight one. The first development period and missing cells +#' are always zero-weighted after conversion to calendar coordinates. +#' @param eta One finite numeric value in `(0, 1]`, default `0.5`, describing +#' expected within-cell payment timing (lost exposure). It is used to derive +#' exposure and to convert fitted hazards to development factors. #' #' @examples #' data(sifa.mtpl) #' sifa.mtpl.rtt <- AggregateDataPP(cumulative.payments.triangle=sifa.mtpl) #' -#' @return An object of class \code{AggregateDataPP}. Lists the following elements: -#' \item{cumulative.payments.triangle}{\code{triangle matrix} object, input triangle of cumulative payments.} +#' @return An `AggregateDataPP` list with: +#' \item{cumulative.payments.triangle}{The input `J` by `J` cumulative paid +#' triangle, unchanged.} #' -#' \item{occurrance}{\code{matrix array} object, the occurrence derived from the input triangle.} +#' \item{occurrance}{A `J` by `J` matrix of incremental paid amounts in +#' development-period by calendar-period coordinates. The misspelling is +#' retained as a stable public field name.} #' -#' \item{exposure}{\code{matrix array} object, the exposure derived from the input triangle, under the \code{eta} claims arrival assumption.} +#' \item{exposure}{A `J` by `J` numeric matrix in the same calendar +#' coordinates, calculated as cumulative payments minus +#' `(1 - eta) * occurrence`.} #' -#' \item{incremental.payments.triangle}{\code{triangle matrix} object, incremental payments derived from the input.} +#' \item{incremental.payments.triangle}{A `J` by `J` +#' accident/development matrix of incremental paid amounts.} #' -#' \item{fit.w}{\code{matrix array} object, the weights used during estimation.} +#' \item{fit.w}{The `J` by `J` fitting-weight matrix in +#' development/calendar coordinates.} #' -#' \item{J}{\code{integer}, Run-off triangle dimension.} +#' \item{J}{The integer triangle dimension.} #' -#' \item{diagonal}{ \code{numeric}, cumulative payments last diagonal.} +#' \item{diagonal}{A length-`J` numeric vector containing the latest observed +#' cumulative diagonal in calendar representation.} #' -#' \item{eta}{ \code{numeric}, Expected time-to-event in the cell. I.e., lost exposure.} +#' \item{eta}{The supplied within-cell timing scalar.} #' #' #' @references @@ -33,16 +51,13 @@ #' @export AggregateDataPP <- function(cumulative.payments.triangle, entries.weights=NULL, eta=1/2) { - - rtt.input.env$properties.cpt(cumulative.payments.triangle) - - incrementals = ChainLadder::cum2incr(cumulative.payments.triangle) - J=dim(cumulative.payments.triangle)[2] + incrementals <- validate_triangle(cumulative.payments.triangle, entries.weights, eta) + J <- ncol(cumulative.payments.triangle) # find out occurrance and exposure - occurrance=pkg.env$t2c(incrementals) - drop=1-eta - exposure=pkg.env$t2c(cumulative.payments.triangle-drop*incrementals) + occurrance <- triangle_to_calendar(incrementals) + calendar_cumulative <- triangle_to_calendar(cumulative.payments.triangle) + exposure <- calendar_cumulative - (1 - eta) * occurrance # find out the weights @@ -59,7 +74,7 @@ AggregateDataPP <- function(cumulative.payments.triangle, entries.weights=NULL, } fit.w[,1]=0 - fit.w=pkg.env$t2c(fit.w) + fit.w=triangle_to_calendar(fit.w) fit.w[is.na(fit.w)]=0 @@ -70,7 +85,7 @@ AggregateDataPP <- function(cumulative.payments.triangle, entries.weights=NULL, fit.w=fit.w, incremental.payments.triangle = incrementals, J=J, - diagonal=pkg.env$t2c(cumulative.payments.triangle)[,J], + diagonal=calendar_cumulative[,J], eta=eta ) diff --git a/R/clmplusAggregateDataPP.R b/R/clmplusAggregateDataPP.R index a234c83..2f5d6bb 100644 --- a/R/clmplusAggregateDataPP.R +++ b/R/clmplusAggregateDataPP.R @@ -1,309 +1,164 @@ -#' Fit Chain Ladder plus on Run-off Triangles. +#' Fit a Chain Ladder Plus hazard model #' -#' Method to Estimate Chain Ladder plus models. -#' -#' @param AggregateDataPP \code{AggregateDataPP} object, reverse time triangle to be fitted. -#' @param hazard.model \code{character}, hazard model supported from our package. The model can be chosen from: -#' \itemize{ -#' \item{'a': Age model, this is equivalent to the Mack chain-ladder.} -#' \item{'ac': Age and cohort effects.} -#' \item{'ap': Age and cohort effects.} -#' \item{'apc': Age cohort and period effects.} +#' Fits one of the package's age, age-cohort, age-period, or +#' age-period-cohort claim-development models to data prepared by +#' [AggregateDataPP()]. Estimation is performed by [StMoMo::fit.StMoMo()]. +#' +#' @param AggregateDataPP An object created by [AggregateDataPP()]. It contains +#' a square cumulative paid-claims triangle and the corresponding +#' development-calendar occurrence, exposure, and weight matrices. +#' @param hazard.model A required character scalar selecting `"a"` (age only, +#' equivalent to chain ladder), `"ac"` (age-cohort), `"ap"` (age-period), or +#' `"apc"` (age-period-cohort). +#' @param link,staticAgeFun,periodAgeFun,cohortAgeFun,constFun Compatibility +#' arguments retained from the original interface. The package's four +#' built-in model definitions determine these settings, so these arguments +#' are currently ignored. +#' @param effect_log_scale A logical scalar. If `TRUE` (the default), fitted +#' effects are returned on the linear-predictor/log scale; if `FALSE`, they +#' are exponentiated. +#' @param verbose A logical scalar passed to [StMoMo::fit.StMoMo()]. The default +#' `FALSE` hides StMoMo fitting progress. `TRUE` displays progress, including +#' zero-weighted ages, years, and cohorts and the start/finish of the gnm fit. +#' @param ... Reserved for future extensions; no arguments are currently +#' forwarded. +#' +#' @return A `clmplusmodel` list with: +#' \describe{ +#' \item{model.fit}{The underlying `fitStMoMo` object. Its fitted `ax`, `kt`, +#' and `gc` fields contain the selected age, period, and cohort effects; +#' inapplicable effects are `NULL`. Other fields are supplied by StMoMo and +#' should be treated as implementation details.} +#' \item{apc_input}{A list containing `J` (triangle dimension), `eta` +#' (within-cell exposure timing), `hazard.model`, `diagonal` (latest observed +#' cumulative payments by calendar representation), and the original +#' `cumulative.payments.triangle`.} +#' \item{hazard_scaled_deviance_residuals}{A `J` by `J` numeric matrix in +#' accident-year by development-year triangle orientation. Unobserved cells +#' are `NA`.} +#' \item{fitted_development_factors}{A `J` by `J` numeric matrix of fitted +#' multiplicative cumulative development factors; unavailable cells are +#' `NA`.} +#' \item{fitted_effects}{A list with `fitted_development_effect`, +#' `fitted_calendar_effect`, and `fitted_accident_effect`. Components not +#' included in the selected model are `NULL`.} #' } -#' -#' -#' @param link \code{character}, defines the link function and random component associated with -#' the mortality model. \code{"log"} would assume that deaths follow a -#' Poisson distribution and use a log link while \code{"logit"} would assume -#' that deaths follow a Binomial distribution and a logit link. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param staticAgeFun \code{logical}, indicates if a static age function -#' \eqn{\alpha_x} is to be included. To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param periodAgeFun \code{list}, a list of length \eqn{N} with the definitions of the -#' period age modulating parameters \eqn{\beta_x^{(i)}}. Each entry can take -#' values: \code{"NP"} for non-parametric age terms, \code{"1"} for -#' \eqn{\beta_x^{(i)}=1} or a predefined parametric function of -#' age (see details). Set this to \code{NULL} if there are no period terms -#' in the model. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param cohortAgeFun \code{character} or \code{function}, defines the cohort age modulating parameter -#' \eqn{\beta_x^{(0)}}. It can take values: \code{"NP"} for non-parametric -#' age terms, \code{"1"} for \eqn{\beta_x^{(0)}=1}, a predefined parametric -#' function of age (see details) or \code{NULL} if there is no cohort effect. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param effect_log_scale \code{logical}, whether effects should be on the logarithmic scale. By default, \code{TRUE}. -#' @param constFun \code{function}, it defines the identifiability constraints of the -#' model. It must be a function of the form -#' \code{constFun <- function(ax, bx, kt, b0x, gc, wxt, ages)} taking a set -#' of fitted model parameters and returning a list -#' \code{list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc)} -#' of the model parameters with the identifiability constraints applied. If -#' omitted no identifiability constraints are applied to the model. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param ... parameters to be passed to clmplus. -#' -#' @return No return value, called to pass method \code{clmplus.AggregateDataPP}. See \code{clmplus.AggregateDataPP} documentation. -#' +#' +#' @details Incremental payment amounts can be non-integer even though the +#' StMoMo fit uses a Poisson quasi-likelihood. Warnings whose messages begin +#' exactly with `non-integer x =` are therefore expected and are selectively +#' muffled. All other warnings, including convergence and numerical warnings, +#' remain visible. +#' #' @examples #' data(sifa.mtpl) -#' sifa.mtpl.rtt <- AggregateDataPP(cumulative.payments.triangle=sifa.mtpl) -#' hz.chl=clmplus(sifa.mtpl.rtt, 'a') -#' -#' @references -#' Pittarello, Gabriele, Munir Hiabu, and Andrés M. Villegas. "Replicating and extending chain ladder -#' via an age-period-cohort structure on the claim development in a run-off triangle." arXiv preprint arXiv:2301.03858 (2023). -#' -#' @export -clmplus <- function(AggregateDataPP, - hazard.model=NULL, - link = c("log", "logit"), - staticAgeFun = TRUE, - periodAgeFun = "NP", - cohortAgeFun = NULL, - effect_log_scale=TRUE, - constFun = function(ax, bx, kt, b0x, gc, wxt, ages) list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc), - ...){ - - UseMethod("clmplus")} - -#' Fit Chain Ladder Plus to reverse time triangles. -#' -#' Default method to fit Chain Ladder plus models. -#' -#' @param AggregateDataPP \code{AggregateDataPP} object, reverse time triangle to be fitted. -#' @param hazard.model \code{character}, hazard model supported from our package. The model can be chosen from: -#' \itemize{ -#' \item{'a': Age model, this is equivalent to the Mack chain-ladder.} -#' \item{'ac': Age and cohort effects.} -#' \item{'ap': Age and cohort effects.} -#' \item{'apc': Age cohort and period effects.} +#' prepared <- AggregateDataPP(sifa.mtpl) +#' age_fit <- clmplus(prepared, hazard.model = "a", verbose = FALSE) +#' age_fit$fitted_effects +#' \donttest{ +#' apc_fit <- clmplus(prepared, hazard.model = "apc", verbose = FALSE) +#' plot(apc_fit) #' } -#' -#' @param link \code{character}, defines the link function and random component associated with -#' the mortality model. \code{"log"} would assume that deaths follow a -#' Poisson distribution and use a log link while \code{"logit"} would assume -#' that deaths follow a Binomial distribution and a logit link. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param staticAgeFun \code{logical}, indicates if a static age function -#' \eqn{\alpha_x} is to be included. To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param periodAgeFun \code{list}, a list of length \eqn{N} with the definitions of the -#' period age modulating parameters \eqn{\beta_x^{(i)}}. Each entry can take -#' values: \code{"NP"} for non-parametric age terms, \code{"1"} for -#' \eqn{\beta_x^{(i)}=1} or a predefined parametric function of -#' age (see details). Set this to \code{NULL} if there are no period terms -#' in the model. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param cohortAgeFun \code{character} or \code{function}, defines the cohort age modulating parameter -#' \eqn{\beta_x^{(0)}}. It can take values: \code{"NP"} for non-parametric -#' age terms, \code{"1"} for \eqn{\beta_x^{(0)}=1}, a predefined parametric -#' function of age (see details) or \code{NULL} if there is no cohort effect. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param effect_log_scale \code{logical}, whether effects should be on the logarithmic scale. By default, \code{TRUE}. -#' @param constFun \code{function}, it defines the identifiability constraints of the -#' model. It must be a function of the form -#' \code{constFun <- function(ax, bx, kt, b0x, gc, wxt, ages)} taking a set -#' of fitted model parameters and returning a list -#' \code{list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc)} -#' of the model parameters with the identifiability constraints applied. If -#' omitted no identifiability constraints are applied to the model. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param ... parameters to be passed to clmplus. -#' -#' @return No return value, called to pass method \code{clmplus.AggregateDataPP}. See \code{clmplus.AggregateDataPP} documentation. -#' -#' @references -#' Pittarello, Gabriele, Munir Hiabu, and Andrés M. Villegas. "Replicating and extending chain ladder -#' via an age-period-cohort structure on the claim development in a run-off triangle." arXiv preprint arXiv:2301.03858 (2023). -#' -#' Hiabu, Munir. “On the relationship between classical chain ladder and granular reserving.” -#' Scandinavian Actuarial Journal 2017 (2017): 708 - 729. -#' +#' +#' @seealso [AggregateDataPP()], [predict.clmplusmodel()], +#' [predictReserve.clmplusmodel()], [plot.clmplusmodel()] #' @export -clmplus.default <- function(AggregateDataPP, - hazard.model=NULL, - link = c("log", "logit"), - staticAgeFun = TRUE, - periodAgeFun = "NP", - cohortAgeFun = NULL, - effect_log_scale=TRUE, - constFun = function(ax, bx, kt, b0x, gc, wxt, ages) list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc), - ...){message('The object provided must be of class AggregateDataPP')} +clmplus <- function(AggregateDataPP, hazard.model = NULL, + link = c("log", "logit"), staticAgeFun = TRUE, + periodAgeFun = "NP", cohortAgeFun = NULL, + effect_log_scale = TRUE, verbose = FALSE, + constFun = function(ax, bx, kt, b0x, gc, wxt, ages) { + list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc) + }, ...) { + UseMethod("clmplus") +} -#' Fit Chain Ladder Plus to reverse time triangles. -#' -#' Method to fit Chain Ladder plus models to \code{AggregateDataPP} objects. -#' -#' @param AggregateDataPP \code{AggregateDataPP} object, reverse time triangle to be fitted. -#' @param hazard.model \code{character}, hazard model supported from our package. The model can be chosen from: -#' \itemize{ -#' \item{'a': Age model, this is equivalent to the Mack chain-ladder.} -#' \item{'ac': Age and cohort effects.} -#' \item{'ap': Age and cohort effects.} -#' \item{'apc': Age cohort and period effects.} -#' } -#' -#' @param link \code{character}, defines the link function and random component associated with -#' the mortality model. \code{"log"} would assume that deaths follow a -#' Poisson distribution and use a log link while \code{"logit"} would assume -#' that deaths follow a Binomial distribution and a logit link. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param staticAgeFun \code{logical}, indicates if a static age function -#' \eqn{\alpha_x} is to be included. To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param periodAgeFun \code{list}, a list of length \eqn{N} with the definitions of the -#' period age modulating parameters \eqn{\beta_x^{(i)}}. Each entry can take -#' values: \code{"NP"} for non-parametric age terms, \code{"1"} for -#' \eqn{\beta_x^{(i)}=1} or a predefined parametric function of -#' age (see details). Set this to \code{NULL} if there are no period terms -#' in the model. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param cohortAgeFun \code{character} or \code{function}, defines the cohort age modulating parameter -#' \eqn{\beta_x^{(0)}}. It can take values: \code{"NP"} for non-parametric -#' age terms, \code{"1"} for \eqn{\beta_x^{(0)}=1}, a predefined parametric -#' function of age (see details) or \code{NULL} if there is no cohort effect. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param effect_log_scale \code{logical}, whether effects should be on the logarithmic scale. By default, \code{TRUE}. -#' @param constFun \code{function}, it defines the identifiability constraints of the -#' model. It must be a function of the form -#' \code{constFun <- function(ax, bx, kt, b0x, gc, wxt, ages)} taking a set -#' of fitted model parameters and returning a list -#' \code{list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc)} -#' of the model parameters with the identifiability constraints applied. If -#' omitted no identifiability constraints are applied to the model. -#' To be disregarded unless the practitioner specifies his own hazard model in StMoMo. -#' @param ... parameters to be passed to clmplus. -#' -#' @return An object of class \code{clmplusmodel}. A list with the following elements: -#' \item{model.fit}{\code{fitStMoMo} object, specified hazard model fit from StMoMo.} -#' -#' \item{apc_input}{\code{list} object. A list containing the following model inputs in age-period-cohort notation: \code{J} (\code{integer}) Run-off triangle dimension. \code{eta} (\code{numeric}) Expected time-to-event in the cell. I.e., lost exposure. -#' \code{diagonal} (\code{numeric}) Cumulative payments last diagonal. \code{hazard.model} (\code{character}), hazard model specified from the user. Set to \code{user.specific} when a custom model is passed. -#' } -#' -#' \item{hazard_scaled_deviance_residuals}{ \code{matrix array} Triangle of the scaled deviance residuals. } -#' -#' \item{fitted_development_factors}{ \code{matrix array} Triangle of the fitted development factors. } -#' -#' \item{fitted_effects}{ \code{list} List of the development-accident-calendar effects fitted. } -#' -#' -#' @examples -#' data(sifa.mtpl) -#' sifa.mtpl.rtt <- AggregateDataPP(cumulative.payments.triangle=sifa.mtpl) -#' hz.chl=clmplus(sifa.mtpl.rtt, 'a') -#' -#' @references -#' Pittarello, Gabriele, Munir Hiabu, and Andrés M. Villegas. "Replicating and extending chain ladder -#' via an age-period-cohort structure on the claim development in a run-off triangle." arXiv preprint arXiv:2301.03858 (2023). -#' +#' @rdname clmplus +#' @return The default method always raises an informative error because +#' `AggregateDataPP` does not inherit from `"AggregateDataPP"`. #' @export -clmplus.AggregateDataPP <- function(AggregateDataPP, - hazard.model=NULL, - link = c("log", "logit"), - staticAgeFun = TRUE, - periodAgeFun = "NP", - cohortAgeFun = NULL, - effect_log_scale=TRUE, - constFun = function(ax, bx, kt, b0x, gc, wxt, ages) list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc), - ...){ - - - stopifnot(is.null(hazard.model) | typeof(hazard.model)=="character") - # - # if(is.null(hazard.model)){ - # - # - # stmomo.model = StMoMo::StMoMo(link = link, - # staticAgeFun = staticAgeFun, - # periodAgeFun = periodAgeFun, - # cohortAgeFun = cohortAgeFun, - # constFun = constFun) - # - # model <- StMoMo::fit(stmomo.model, - # Dxt = AggregateDataPP$occurrance, - # Ext = AggregateDataPP$exposure, - # wxt = AggregateDataPP$fit.w, - # iterMax=as.integer(1e+05)) - # - # #forecasting horizon - # J=dim(AggregateDataPP$cumulative.payments.triangle)[2] - # #compute the development factors - # alphaij <- forecast::forecast(model, h = J) - # # fij=(2+alphaij$rates)/(2-alphaij$rates) - # fij=(1+(1-AggregateDataPP$eta)*alphaij$rates)/(1-(AggregateDataPP$eta*alphaij$rates)) - # # pick the last diagonal - # d=AggregateDataPP$diagonal[1:(J-1)] - # # extrapolate the results - # lt=array(0.,c(J,J)) - # lt[,1]=c(0.,d)*fij[,1] - # for(j in 2:J){lt[,j]=c(0.,lt[1:(J-1),(j-1)])*fij[,j]} - # - # ot_=pkg.env$t2c(AggregateDataPP$cumulative.payments.triangle) - # ultimate_cost=c(rev(lt[J,1:(J-1)]),ot_[J,J]) - # reserve=rev(ultimate_cost-ot_[,J]) - # ultimate_cost=rev(ultimate_cost) - # converged=TRUE - # citer=NULL - # - # - # out <- list(model.fit=model, - # hazard.model='user.defined', - # ultimate.cost=ultimate_cost, - # reserve=reserve, - # model.fcst = alphaij, - # converged=converged, - # citer=citer) - # - # class(out) <- c('clmplusmodel') - # - # out} - # - - if(hazard.model %in% names(pkg.env$models)){ - - model <- StMoMo::fit(pkg.env$models[[hazard.model]], - Dxt = AggregateDataPP$occurrance, - Ext = AggregateDataPP$exposure, - wxt=AggregateDataPP$fit.w, - iterMax=as.integer(1e+05)) - +clmplus.default <- function(AggregateDataPP, hazard.model = NULL, + link = c("log", "logit"), staticAgeFun = TRUE, + periodAgeFun = "NP", cohortAgeFun = NULL, + effect_log_scale = TRUE, verbose = FALSE, + constFun = function(ax, bx, kt, b0x, gc, wxt, ages) { + list(ax = ax, bx = bx, kt = kt, b0x = b0x, gc = gc) + }, ...) { + stop("`AggregateDataPP` must inherit from class \"AggregateDataPP\".", + call. = FALSE) +} - - #forecasting horizon - J=dim(AggregateDataPP$cumulative.payments.triangle)[2] - - # Find fitted development factors - fij.fit <- pkg.env$find.development.factors(J, - age.eff= model$ax, - cohort.eff= model$gc, - period.eff=model$kt, - eta=AggregateDataPP$eta) - - res.m = stats::residuals(model) - res.tr=pkg.env$c2t(res.m$residuals) - - fitted_effects <- pkg.env$find.fitted.effects(J, - age.eff= model$ax, - cohort.eff= model$gc, - period.eff=model$kt, - effect_log_scale=effect_log_scale) - +#' @rdname clmplus +#' @export +clmplus.AggregateDataPP <- function(AggregateDataPP, hazard.model = NULL, + link = c("log", "logit"), + staticAgeFun = TRUE, + periodAgeFun = "NP", + cohortAgeFun = NULL, + effect_log_scale = TRUE, + verbose = FALSE, + constFun = function(ax, bx, kt, b0x, gc, + wxt, ages) { + list(ax = ax, bx = bx, kt = kt, + b0x = b0x, gc = gc) + }, ...) { + if (length(hazard.model) != 1L || !is.character(hazard.model) || + !hazard.model %in% names(supported_models)) { + stop("`hazard.model` must be one of: ", + paste(names(supported_models), collapse = ", "), ".", call. = FALSE) } - - - - out <- list(model.fit=model, - apc_input=list(J=J, - eta=AggregateDataPP$eta, - hazard.model=hazard.model, - diagonal=AggregateDataPP$diagonal, - cumulative.payments.triangle=AggregateDataPP$cumulative.payments.triangle - ), - hazard_scaled_deviance_residuals=res.tr, - fitted_development_factors = fij.fit, - fitted_effects=fitted_effects) - - class(out) <- c('clmplusmodel') - + if (length(verbose) != 1L || !is.logical(verbose) || is.na(verbose)) { + stop("`verbose` must be a single non-missing logical value.", call. = FALSE) + } + + model <- withCallingHandlers( + StMoMo::fit( + supported_models[[hazard.model]], + Dxt = AggregateDataPP$occurrance, + Ext = AggregateDataPP$exposure, + wxt = AggregateDataPP$fit.w, + iterMax = as.integer(1e+05), + verbose = verbose + ), + warning = function(w) { + if ( + !isTRUE(verbose) || + grepl("^non-integer x\\s*=", conditionMessage(w)) + ) { + invokeRestart("muffleWarning") + } + }, + message = function(m) { + if (!isTRUE(verbose)) { + invokeRestart("muffleMessage") + } + } + ) + + J <- ncol(AggregateDataPP$cumulative.payments.triangle) + fij.fit <- fitted_development_factors( + J, age = model$ax, cohort = model$gc, period = model$kt, + eta = AggregateDataPP$eta + ) + residuals <- stats::residuals(model) + residual_triangle <- calendar_to_triangle(residuals$residuals) + effects <- extract_fitted_effects( + age = model$ax, cohort = model$gc, period = model$kt, + log_scale = effect_log_scale + ) + + out <- list( + model.fit = model, + apc_input = list( + J = J, eta = AggregateDataPP$eta, hazard.model = hazard.model, + diagonal = AggregateDataPP$diagonal, + cumulative.payments.triangle = + AggregateDataPP$cumulative.payments.triangle + ), + hazard_scaled_deviance_residuals = residual_triangle, + fitted_development_factors = fij.fit, + fitted_effects = effects + ) + class(out) <- "clmplusmodel" out - } diff --git a/R/data.R b/R/data.R index ead3336..b773df9 100644 --- a/R/data.R +++ b/R/data.R @@ -1,6 +1,9 @@ #' @title Sifa MTPL #' @description Dataset of cumulative paid claims for a medium italian company in the line of business: motor third party liability. -#' @format Run-off triangle with 12 development periods. +#' @format A 12 by 12 numeric matrix of cumulative paid claims. Rows index +#' accident years and columns index development years; cells below the +#' observed run-off triangle are `NA`. Amounts are in the source's recorded +#' monetary units. No additional preprocessing has been applied. #' @references #' Savelli, Nino, and Clemente, Gian Paolo. "Lezioni di matematica attuariale delle assicurazioni danni." EDUCatt-Ente per il diritto allo studio universitario dell'Università Cattolica, 2014 #' @@ -8,7 +11,10 @@ #' @title Amases MTPL #' @description Dataset of cumulative paid claims for a small italian company in the line of business: motor third party liability. -#' @format Run-off triangle with 12 development periods. +#' @format A 12 by 12 numeric matrix of cumulative paid claims. Rows index +#' accident years and columns index development years; cells below the +#' observed run-off triangle are `NA`. Amounts are in the source's recorded +#' monetary units. No additional preprocessing has been applied. #' @references #' Savelli, Nino, and Clemente, Gian Paolo. "Lezioni di matematica attuariale delle assicurazioni danni." EDUCatt-Ente per il diritto allo studio universitario dell'Università Cattolica, 2014 #' @@ -16,7 +22,10 @@ #' @title Sifa GTPL #' @description Dataset of cumulative paid claims for a medium italian company in the line of business: general third party liability. -#' @format Run-off triangle with 12 development periods. +#' @format A 12 by 12 numeric matrix of cumulative paid claims. Rows index +#' accident years and columns index development years; cells below the +#' observed run-off triangle are `NA`. Amounts are in the source's recorded +#' monetary units. No additional preprocessing has been applied. #' @references #' Savelli, Nino, and Clemente, Gian Paolo. "Lezioni di matematica attuariale delle assicurazioni danni." EDUCatt-Ente per il diritto allo studio universitario dell'Università Cattolica, 2014 #' @@ -24,7 +33,10 @@ #' @title Amases GTPL #' @description Dataset of cumulative paid claims for a small italian company in the line of business: general third party liability. -#' @format Run-off triangle with 12 development periods. +#' @format A 12 by 12 numeric matrix of cumulative paid claims. Rows index +#' accident years and columns index development years; cells below the +#' observed run-off triangle are `NA`. Amounts are in the source's recorded +#' monetary units. No additional preprocessing has been applied. #' @references #' Savelli, Nino, and Clemente, Gian Paolo. "Lezioni di matematica attuariale delle assicurazioni danni." EDUCatt-Ente per il diritto allo studio universitario dell'Università Cattolica, 2014 #' @@ -33,7 +45,10 @@ #' @title Sifa MOD #' @description Dataset of cumulative paid claims for a medium italian company in the line of business: motor or damage. -#' @format Run-off triangle with 12 development periods. +#' @format A 12 by 12 numeric matrix of cumulative paid claims. Rows index +#' accident years and columns index development years; cells below the +#' observed run-off triangle are `NA`. Amounts are in the source's recorded +#' monetary units. No additional preprocessing has been applied. #' @references #' Savelli, Nino, and Clemente, Gian Paolo. "Lezioni di matematica attuariale delle assicurazioni danni." EDUCatt-Ente per il diritto allo studio universitario dell'Università Cattolica, 2014 #' @@ -41,7 +56,10 @@ #' @title Amases MOD #' @description Dataset of cumulative paid claims for a small italian company in the line of business: motor or damage. -#' @format Run-off triangle with 12 development periods. +#' @format A 12 by 12 numeric matrix of cumulative paid claims. Rows index +#' accident years and columns index development years; cells below the +#' observed run-off triangle are `NA`. Amounts are in the source's recorded +#' monetary units. No additional preprocessing has been applied. #' @references #' Savelli, Nino, and Clemente, Gian Paolo. "Lezioni di matematica attuariale delle assicurazioni danni." EDUCatt-Ente per il diritto allo studio universitario dell'Università Cattolica, 2014 #' diff --git a/R/fitted-effects.R b/R/fitted-effects.R new file mode 100644 index 0000000..577f4d9 --- /dev/null +++ b/R/fitted-effects.R @@ -0,0 +1,30 @@ +fitted_development_factors <- function(size, age, period, cohort, eta) { + age <- c(NA_real_, age[!is.na(age)]) + cohort <- if (is.null(cohort)) rep(0, size) else c(cohort[!is.na(cohort)], NA_real_) + period <- if (is.null(period)) rep(0, size) else c(NA_real_, period[!is.na(period)]) + out <- matrix(NA_real_, size, size) + index <- which(row(out) + col(out) <= size + 1L, arr.ind = TRUE) + linear <- age[index[, 2L]] + cohort[index[, 1L]] + period[rowSums(index) - 1L] + out[index] <- (1 + (1 - eta) * exp(linear)) / (1 - eta * exp(linear)) + out +} + +extract_fitted_effects <- function(age, period, cohort, log_scale) { + age <- c(NA_real_, age[!is.na(age)]) + names(age) <- seq_along(age) - 1L + if (!is.null(period)) { + period <- c(NA_real_, period[!is.na(period)]) + names(period) <- seq_along(period) - 1L + } + if (!is.null(cohort)) { + cohort <- c(cohort[!is.na(cohort)], NA_real_) + names(cohort) <- seq_along(cohort) - 1L + } + out <- list( + fitted_development_effect = age, + fitted_calendar_effect = period, + fitted_accident_effect = cohort + ) + if (!log_scale) out <- lapply(out, exp) + out +} diff --git a/R/forecasting.R b/R/forecasting.R new file mode 100644 index 0000000..e65dd44 --- /dev/null +++ b/R/forecasting.R @@ -0,0 +1,57 @@ +forecast_hazard_rates <- function(object, model_name, gk.fc.model = "a", + ckj.fc.model = "a", gk.order = c(1, 1, 0), + ckj.order = c(0, 1, 0)) { + size <- ncol(object$Dxt) + rates <- matrix(0, size, size) + components <- model_components[[model_name]] + kt.f <- gc.f <- NULL + + if (isTRUE(components[["cohort"]])) { + last <- max(which(!is.na(object$gc))) + if (gk.fc.model == "a") { + fitted <- forecast::Arima(object$gc[seq_len(last)], order = gk.order, + include.constant = TRUE) + gc.f <- forecast::forecast(fitted, h = length(object$cohorts) - last) + } else if (gk.fc.model == "l") { + fitted <- stats::lm(y ~ x, data = data.frame( + y = object$gc[seq_len(last)], x = object$cohorts[seq_len(last)] + )) + gc.f <- forecast::forecast(fitted, newdata = data.frame( + x = object$cohorts[(last + 1L):length(object$cohorts)] + )) + } else { + stop("`gk.fc.model` must be either \"a\" or \"l\".", call. = FALSE) + } + cohort <- c(object$gc[!is.na(object$gc)], unname(gc.f$mean)) + cohort_matrix <- matrix(cohort, nrow = size, ncol = size) + cohort_matrix <- triangle_to_full_calendar(cohort_matrix) + cohort_matrix[is.na(cohort_matrix)] <- 0 + rates <- rates + cohort_matrix[, (size + 1L):(2L * size), drop = FALSE] + } + + if (isTRUE(components[["period"]])) { + period <- as.vector(object$kt[1L, ]) + last <- max(which(!is.na(period))) + if (ckj.fc.model == "a") { + fitted <- forecast::Arima(period[seq_len(last)], order = ckj.order, + include.constant = TRUE) + kt.f <- forecast::forecast(fitted, h = size) + } else if (ckj.fc.model == "l") { + fitted <- stats::lm(y ~ x, data = data.frame( + y = period[seq_len(last)], x = object$years[seq_len(last)] + )) + kt.f <- forecast::forecast(fitted, newdata = data.frame(x = seq.int(size + 1L, 2L * size))) + } else { + stop("`ckj.fc.model` must be either \"a\" or \"l\".", call. = FALSE) + } + rates <- sweep(rates, 2L, unname(kt.f$mean), `+`) + } + + if (isTRUE(components[["age"]])) { + age <- unname(object$ax) + age[is.na(age)] <- 0 + rates <- sweep(rates, 1L, age, `+`) + } + + list(rates = exp(rates), kt.f = kt.f, gc.f = gc.f) +} diff --git a/R/globalVariables.R b/R/globalVariables.R deleted file mode 100644 index 09d5204..0000000 --- a/R/globalVariables.R +++ /dev/null @@ -1,713 +0,0 @@ -#' @importFrom forecast Arima -#' @importFrom forecast forecast - - -# Create environment ---- -pkg.env <- new.env() - - -#Supported models ---- - -pkg.env$models=list( - - ## a model - a = StMoMo::StMoMo(link="log", - staticAgeFun = TRUE, - periodAgeFun = NULL, - cohortAgeFun = NULL), - ## p model - - p = StMoMo::StMoMo(link="log", - staticAgeFun = FALSE, - periodAgeFun = c("1"), - cohortAgeFun = NULL), - ## c model - c = StMoMo::StMoMo(link="log", - staticAgeFun = FALSE, - periodAgeFun = NULL, - cohortAgeFun = c("1")), - ## ac model - - ac = StMoMo::StMoMo(link="log", - staticAgeFun = TRUE, - periodAgeFun = NULL, - cohortAgeFun = c("1")), - - ## ap model - - ap = StMoMo::StMoMo(link="log", - staticAgeFun = TRUE, - periodAgeFun = c("1"), - cohortAgeFun = NULL), - - - ## pc model - - pc = StMoMo::StMoMo(link="log", - staticAgeFun = FALSE, - periodAgeFun = c("1"), - cohortAgeFun = c("1")), - - ## apc model - - apc = StMoMo::apc(), - - ## cbd model - - cbd = StMoMo::cbd(link = c("log")), - - ## m6 model - - m6 = StMoMo::m6(link = c("log")), - - ## m7 model - - m7 = StMoMo::m7(link = c("log")) - - - ) - - - -# Utils ---- -## Transform the upper run-off triangle to the life-table representation. -pkg.env$t2c <- function(x){ - " - Transform the upper run-off triangle to the life-table representation. - " - I= dim(x)[1] - J= dim(x)[2] - - mx=matrix(NA,nrow=I,ncol=J) - for(i in 1:(I)){ - for(j in 1:(J)){ - if(i+j<=J+1){ - mx[j,(i+j-1)]=x[i,j] - } - } - } - return(mx) -} - -## Rotate a matrix -pkg.env$rotate <- function(x){ - " - It rotates a matrix by 90 degrees. - " - - - t(apply(x, 2, rev))} - -pkg.env$c2t <- function(x){ - I= dim(x)[1] - J= dim(x)[2] - - mx=matrix(NA,nrow=I,ncol=J) - for(i in 1:(I)){ - for(j in 1:(J)){ - if(i+j<=J+1){ - mx[i,j]=x[j,(i+j-1)] - } - } - } - return(mx) -} - - -pkg.env$t2c.full.square <- function(x){ - " - Function to transform a full run-off triangle into a square. - - This function takes a run-off triangle as input. - - It returns a square. - " - - I= dim(x)[1] - J= dim(x)[2] - - mx = matrix(NA, nrow = I, ncol = 2 * J) - for (i in 1:(I)) { - for (j in 1:(J)) { - mx[j,(i+j-1)]=x[i,j] - - } - } - return(mx) - } - - -# lee-carter models -pkg.env$fit.lc.nr <- function(data.T, - iter.max=1e+04, - tolerance.max=1e-06){ - " - Fits the LC model via a Netwon-Rhapson from scratch implementation to the data. - - " - - data.O <- data.T$occurrance - data.E <- data.T$exposure - - wxc <- data.T$fit.w - - # wxc <- matrix(1, - # nrow = dim(data.O)[1], - # ncol=dim(data.O)[2]) - # wxc[is.na(data.E)]<-0 - - - ## parameters initial values - ax = runif(dim(data.O)[1]) - bx = rep(1/dim(data.O)[1],dim(data.O)[1]) - kt = rep(0,dim(data.O)[2]) - - #create matrices to compute the linear predictor - ax.mx = matrix(rep(ax,dim(data.O)[2]), - byrow = F, - ncol=dim(data.O)[2]) - - bx.mx = matrix(rep(bx, - dim(data.O)[2]), - byrow = F, - ncol=dim(data.O)[2]) - - kt.mx = matrix(rep(kt, - dim(data.O)[1]), - byrow = T, - nrow=dim(data.O)[1]) - - - mu.mx = exp(ax.mx+bx.mx*kt.mx) - - dhat = data.E*mu.mx - - dxt0=1000 - niter=1000 - - deltaax=100 - deltabx=100 - deltakt=100 - - deltadxt=100 - - kt0=(abs(kt)) - ax0=(abs(ax)) - bx0=(abs(bx)) - - citer=0 - - dxt.v=NULL - - deltakt.v=NULL - deltaax.v=NULL - deltabx.v=NULL - - deltadxt.v=NULL - - kt1.v=NULL - - converged=TRUE - - while((abs(deltaax)>tolerance.max|abs(deltabx)>tolerance.max|abs(deltakt)>tolerance.max)&citertolerance.max|abs(deltabx)>tolerance.max|abs(deltakt)>tolerance.max)){ - warning('The Newton-Rhapson algorithm for the lee-carter may have not converged') - converged=FALSE - } - - return(list(ax=ax, - bx=bx, - kt=kt, - citer=citer, - data.T=data.T, - converged=converged, - deltaax=deltaax, - deltabx=deltabx, - deltakt=deltakt, - dxt0=dxt0, - deltadxt=deltadxt, - converged=converged - )) - -} - - -pkg.env$fit.aac.nr <- function(data.T, - iter.max=1e+04, - tolerance.max=1e-06, - ax.start=NULL, - gc.start=NULL){ - " - Fits the AAC model via a Netwon-Rhapson from scratch implementation to the data. - - " - data.O <- pkg.env$rotate(pkg.env$c2t(data.T$occurrance)) - data.E <- pkg.env$rotate(pkg.env$c2t(data.T$exposure)) - - wxc <- matrix(1, - nrow = dim(data.O)[1], - ncol=dim(data.O)[2]) - wxc[is.na(data.E)]<-0 - - - ## parameters initial values - ax = ax.start - bx = rep(1/dim(data.O)[1],dim(data.O)[1]) - gc = gc.start - - #create matrices to compute the linear predictor - ax.mx = matrix(rep(ax,dim(data.O)[2]), - byrow = F, - ncol=dim(data.O)[2]) - - bx.mx = matrix(rep(bx, - dim(data.O)[2]), - byrow = F, - ncol=dim(data.O)[2]) - - gc.mx = matrix(rep(gc, - dim(data.O)[1]), - byrow = T, - nrow=dim(data.O)[1]) - - - mu.mx = exp(ax.mx+bx.mx*gc.mx) - - dhat = data.E*mu.mx - - dxt0=1000 - niter=1000 - - deltaax=100 - deltabx=100 - deltagc=100 - - deltadxt=100 - - gc0=(abs(gc)) - ax0=(abs(ax)) - bx0=(abs(bx)) - - citer=0 - - dxt.v=NULL - - deltagc.v=NULL - deltaax.v=NULL - deltabx.v=NULL - - deltadxt.v=NULL - - gc1.v=NULL - - converged=TRUE - - while((abs(deltaax)>tolerance.max|abs(deltabx)>tolerance.max|abs(deltagc)>tolerance.max)&citertolerance.max|abs(deltabx)>tolerance.max|abs(deltagc)>tolerance.max)){ - warning('The Newton-Rhapson algorithm for the lee-carter may have not converged') - converged=FALSE - } - - return(list(ax=ax, - bx=bx, - gc=rev(gc), #reverse it as you read the data in the opposite direction - citer=citer, - converged=converged, - deltaax=deltaax, - deltabx=deltabx, - deltagc=deltagc, - dxt0=dxt0, - deltadxt=deltadxt, - converged=converged - )) - -} - -# forecasting with linear trend - - -pkg.env$fcst <- function(object, - hazard.model, - gk.fc.model='a', - ckj.fc.model='a', - gk.order=c(1,1,0), - ckj.order=c(0,1,0)){ - - - J=dim(object$Dxt)[2] - - rates=array(.0,dim=c(J,J)) - - if(!is.null(hazard.model)){ - - a.tf <- grepl('a',hazard.model) - c.tf <- grepl('c',hazard.model) - p.tf <- grepl('p',hazard.model) - kt.f=NULL - gc.f=NULL - - } - - ## cohorts model - if(c.tf){ - # c.model <- substr(fc.model,1,1) - gc.nNA <- max(which(!is.na(object$gc))) - - if(gk.fc.model=='a'){ - - gc.model <- Arima(object$gc[1:gc.nNA], - order = gk.order, - include.constant = T) - gc.f <- forecast(gc.model,h=(length(object$cohorts)-gc.nNA)) - - - }else{ - - gc.data=data.frame(y=object$gc[1:gc.nNA], - x=object$cohorts[1:gc.nNA]) - new.gc.data <- data.frame(x=object$cohorts[(gc.nNA+1):length(object$cohorts)]) - - gc.model <- lm('y~x', - data=gc.data) - - gc.f <- forecast::forecast(gc.model, - newdata=new.gc.data) - - - } - - #forecasting rates - cond = !is.na(object$gc) - gc.2.add = c(object$gc[cond],gc.f$mean) - gc.mx= matrix(rep(unname(gc.2.add), - J), - byrow = F, - nrow=J) - rates <- gc.mx+rates - rates <- pkg.env$t2c.full.square(rates) - rates[is.na(rates)]=.0 - rates <- rates[,(J+1):(2*J)] - - - - } - - ## period model - if(p.tf){ - # p.model <- substr(fc.model,2,2) - kt.nNA <- max(which(!is.na(object$kt[1, ]))) - - if(ckj.fc.model=='a'){ - - kt.model=forecast::Arima(as.vector(object$kt[1:kt.nNA]),ckj.order,include.constant = T) - kt.f <- forecast::forecast(kt.model,h=J) - - }else{ - - kt.data=data.frame(y=object$kt[1:kt.nNA], - x=object$years[1:kt.nNA]) - new.kt.data <- data.frame(x=seq(J+1,2*J)) - - kt.model <- lm('y~x', - data=kt.data) - - kt.f <- forecast::forecast(kt.model,newdata=new.kt.data) - - } - #forecasting rates - kt.mx = matrix(rep(unname(kt.f$mean), - J), - byrow = T, - nrow=J) - - rates=kt.mx+rates - - } - - # projecting age - if(a.tf){ - - ax.mx = matrix(rep(unname(object$ax), - J), - byrow = F, - nrow=J) - ax.mx[is.na(ax.mx)]=.0 - rates=ax.mx+rates - } - - output<- list(rates=exp(rates), - kt.f=kt.f, - gc.f=gc.f) - - return(output) - -} - - -pkg.env$create_lower_triangle <- function(lt){ - - J <- dim(lt)[1] - J.stop <- dim(lt)[2] - out <- array(NA,c(J,J)) - - for(age in 1:J){ - - for(calendar in 1:J.stop){ - - tmp.ix <- J+calendar - if(tmp.ix-age+1<=J & age<=J){ - out[tmp.ix-age+1,age] <- lt[age,calendar]} - - - } - - } - - return(out) - - -} - -pkg.env$create_full_triangle <- function(cumulative.payments.triangle, lt){ - - J <- dim(lt)[1] - J.stop <- dim(lt)[2] - out <- cumulative.payments.triangle - - for(age in 1:J){ - - for(calendar in 1:J.stop){ - - tmp.ix <- J+calendar - if(tmp.ix-age+1<=J & age<=J){ - out[tmp.ix-age+1,age] <- lt[age,calendar]} - - - } - - } - - return(out) - - -} - - -pkg.env$find.development.factors <- function(J, - age.eff, - period.eff, - cohort.eff, - eta){ - - # Function that finds the development factors on the upper triangle. - - out <- array(NA,dim=c(J,J)) - - ax <- c(NA,age.eff[!is.na(age.eff)]) - - if(!is.null(cohort.eff)){ - gc <- c(cohort.eff[!is.na(cohort.eff)],NA) #last cohort effect will be extrapolated - - - }else{gc<-rep(0,J)} - - if(!is.null(period.eff)){ - - kt <- c(NA,period.eff[!is.na(period.eff)]) #the first period is disregarded - - - }else{kt<-rep(0,J)} - - - for(i in 1:J){ - for(j in 1:J){ - - if((i+j-1)<=J){out[i,j] <- ax[j]+gc[i]+kt[i+j-1]} - - } - - } - - out <- (1+(1-eta)*exp(out))/(1-(eta*exp(out))) - - return(out) - - } - - -pkg.env$find.fitted.effects <- function(J, - age.eff, - period.eff, - cohort.eff, - effect_log_scale){ - - # Function that finds the fitted effects. - - ax <- c(NA,age.eff[!is.na(age.eff)]) - names(ax) <- c(0:(length(ax)-1)) - - if(!is.null(cohort.eff)){ - gc <- c(cohort.eff[!is.na(cohort.eff)],NA) #last cohort effect will be extrapolated - names(gc) <- c(0:(length(gc)-1)) - - }else{gc<-NULL} - - if(!is.null(period.eff)){ - - kt <- c(NA,period.eff[!is.na(period.eff)]) #the first period is disregarded - names(kt) <- c(0:(length(kt)-1)) - - }else{kt<-NULL} - - out <- list( - fitted_development_effect= ax, - fitted_calendar_effect=kt, - fitted_accident_effect= gc - ) - - if(effect_log_scale==FALSE){out<-lapply(out,exp)} - - return(out) - - - } - diff --git a/R/model-definitions.R b/R/model-definitions.R new file mode 100644 index 0000000..26e6ba2 --- /dev/null +++ b/R/model-definitions.R @@ -0,0 +1,28 @@ +#' @importFrom forecast Arima forecast +NULL + +supported_models <- list( + a = StMoMo::StMoMo("log", TRUE, NULL, NULL), + p = StMoMo::StMoMo("log", FALSE, "1", NULL), + c = StMoMo::StMoMo("log", FALSE, NULL, "1"), + ac = StMoMo::StMoMo("log", TRUE, NULL, "1"), + ap = StMoMo::StMoMo("log", TRUE, "1", NULL), + pc = StMoMo::StMoMo("log", FALSE, "1", "1"), + apc = StMoMo::apc(), + cbd = StMoMo::cbd(link = "log"), + m6 = StMoMo::m6(link = "log"), + m7 = StMoMo::m7(link = "log") +) + +model_components <- list( + a = c(age = TRUE, period = FALSE, cohort = FALSE), + p = c(age = FALSE, period = TRUE, cohort = FALSE), + c = c(age = FALSE, period = FALSE, cohort = TRUE), + ac = c(age = TRUE, period = FALSE, cohort = TRUE), + ap = c(age = TRUE, period = TRUE, cohort = FALSE), + pc = c(age = FALSE, period = TRUE, cohort = TRUE), + apc = c(age = TRUE, period = TRUE, cohort = TRUE), + cbd = c(age = TRUE, period = TRUE, cohort = FALSE), + m6 = c(age = TRUE, period = TRUE, cohort = TRUE), + m7 = c(age = TRUE, period = TRUE, cohort = TRUE) +) diff --git a/R/plotAggregateDataPP.R b/R/plotAggregateDataPP.R index 46571c0..0c3c3e4 100644 --- a/R/plotAggregateDataPP.R +++ b/R/plotAggregateDataPP.R @@ -2,14 +2,15 @@ #' #' This function allows to define the behavior of the triangle payments. #' -#' @param x AggregateDataPP to be plotted. -#' @param ... Arguments to be passed to plot. +#' @param x An `AggregateDataPP` object. +#' @param ... Reserved; currently ignored. #' @examples #' data(sifa.mtpl) #' sifa.mtpl.pp <- AggregateDataPP(cumulative.payments.triangle=sifa.mtpl) #' plot(sifa.mtpl.pp) #' -#' @return No return value, plots the run-off triangle cumulative payments and incremental payments. +#' @return A `gtable` containing two ggplot panels (incremental and cumulative +#' paid amounts), returned visibly after being drawn. #' #' @references #' Pittarello, Gabriele, Munir Hiabu, and Andrés M. Villegas. "Replicating and extending chain ladder @@ -34,7 +35,7 @@ plot.AggregateDataPP <- function(x, ...){ y=incrementals, by=ay, colour=ay))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::ggtitle("Incremental payments")+ ggplot2::theme_classic() @@ -43,7 +44,7 @@ plot.AggregateDataPP <- function(x, ...){ y=cumulatives, by=ay, colour=ay))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::ggtitle("Cumulative payments")+ ggplot2::theme_classic() diff --git a/R/plotclmplusmodel.R b/R/plotclmplusmodel.R index 4d6264d..74a4dcc 100644 --- a/R/plotclmplusmodel.R +++ b/R/plotclmplusmodel.R @@ -2,9 +2,10 @@ #' #' This function allows to plot the hazard model residuals on the triangle payments. #' -#' @param x \code{clmplusmodel} object, model fit to plot. -#' @param heat.lim limits in the residuals plot. -#' @param ... Extra arguments to be passed to the plot function. +#' @param x A fitted `clmplusmodel` object. +#' @param heat.lim A length-two numeric vector giving the lower and upper fill +#' scale limits for scaled deviance residuals. +#' @param ... Reserved; currently ignored. #' #' @examples #' data(sifa.mtpl) @@ -12,7 +13,8 @@ #' clm.fit<-clmplus(sifa.mtpl.rtt, 'a') #' plot(clm.fit) #' -#' @return No return value, plots the hazard model residuals in triangular form. +#' @return A `ggplot` object showing scaled deviance residuals in +#' accident-year by development-year triangle form. #' #' @references #' @@ -24,57 +26,13 @@ plot.clmplusmodel <- function(x, heat.lim=c(-2.5,2.5), ...){ - if((x$apc_input$hazard.model %in% names(pkg.env$models))|(x$apc_input$hazard.model=="user.defined")){ - - res.m = stats::residuals(x$model.fit) - res.tr=pkg.env$c2t(res.m$residuals) + if (x$apc_input$hazard.model %in% names(supported_models)) { + res.tr <- x$hazard_scaled_deviance_residuals colnames(res.tr) <- rownames(res.tr) <- c(0:(dim(res.tr)[2]-1)) longdf.no.0 = ChainLadder::as.LongTriangle(res.tr) } - # if(x$apc_input$hazard.model == 'lc'){ - # - # data.O= x$model.fit$data.T$occurrance - # data.E= x$model.fit$data.T$exposure - # ind <- is.na(data.E) - # W = matrix(1,nrow=dim(data.O)[1],ncol=dim(data.E)[2]) - # W[ind]=0 - # - # ax.mx = matrix(rep(x$model.fit$ax,dim(data.O)[2]), - # byrow = F, - # ncol=dim(data.O)[2]) - # - # bx.mx = matrix(rep(x$model.fit$bx, - # dim(data.O)[2]), - # byrow = F, - # ncol=dim(data.O)[2]) - # - # kt.mx = matrix(rep(x$model.fit$kt, - # dim(data.O)[1]), - # byrow = T, - # nrow=dim(data.O)[1]) - # - # - # mu.mx = exp(ax.mx+bx.mx*kt.mx) - # - # data.O.h = data.E*mu.mx - # - # res <- array(NA, dim(W)) - # - # res[!ind] <- 2 * W[!ind] * (data.O[!ind] * log(data.O[!ind] / data.O.h[!ind]) - (data.O[!ind] - data.O.h[!ind])) - # signRes <- sign(data.O - data.O.h) - # - # phi <- sum(res[!ind]) / ((dim(data.O)[1]*(dim(data.O)[1]+1))/2 - 3*dim(data.O)[1]) - # res.m <- signRes * sqrt(abs(res) / phi) - # - # res.tr=pkg.env$c2t(res.m) - # colnames(res.tr) <- rownames(res.tr) <- c(0:(dim(res.tr)[2]-1)) - # longdf.no.0 = ChainLadder::as.LongTriangle(res.tr) - # - # } - # - # p_hm <- ggplot2::ggplot(data=longdf.no.0, ggplot2::aes(x=as.integer(dev)-1, y=as.integer(origin)-1)) + ggplot2::geom_tile(ggplot2::aes(fill = value))+ggplot2::scale_y_reverse()+ ggplot2::scale_fill_gradient2(name="model residuals", @@ -90,7 +48,7 @@ plot.clmplusmodel <- function(x, ggplot2::ggtitle(x$modelfamily)+ ggplot2::theme(axis.title.x = ggplot2::element_text(size=8), axis.text.x = ggplot2::element_text(size=7))+ ggplot2::theme(axis.title.y = ggplot2::element_text(size=8), axis.text.y = ggplot2::element_text(size=7))+ - ggplot2::theme(panel.background = ggplot2::element_rect(fill = "grey", colour = "grey", size = 2, linetype = "solid"), + ggplot2::theme(panel.background = ggplot2::element_rect(fill = "grey", colour = "grey", linewidth = 2, linetype = "solid"), panel.grid = ggplot2::element_line(colour="grey")) + NULL diff --git a/R/plotclmpluspredictions.R b/R/plotclmpluspredictions.R index e981791..6ab962f 100644 --- a/R/plotclmpluspredictions.R +++ b/R/plotclmpluspredictions.R @@ -2,9 +2,11 @@ #' #' This function allows to define the behavior of the triangle payments. #' -#' @param x \code{clmpluspredictions}, Model effects (fitted and extrapolated) to be plotted. -#' @param cy.type \code{character}, whether to show fitted period effect with or without extrapolatio Default is "fe", standing for fitted and extrapolated. Alternative is to specify "f" for fitted effect. -#' @param ... Arguments to be passed to plot. +#' @param x A `clmpluspredictions` object returned by +#' [predict.clmplusmodel()]. +#' @param cy.type Either `"fe"` (the default) to include extrapolated calendar +#' effects or `"f"` to show only fitted calendar effects. +#' @param ... Reserved; currently ignored. #' @examples #' data(sifa.mtpl) #' sifa.mtpl.rtt <- AggregateDataPP(cumulative.payments.triangle=sifa.mtpl) @@ -12,7 +14,8 @@ #' clm <- predict(clm.fit) #' plot(clm) #' -#' @return No return value, plots coefficients of the hazard models. +#' @return A `gtable` containing one ggplot panel for each effect included in +#' the fitted model. The table is returned visibly after being drawn. #' #' @references #' Pittarello, G., Hiabu, M., & Villegas, A. M. (2023). Replicating and extending chain-ladder via an age-period-cohort structure on the claim development in a run-off triangle. arXiv preprint arXiv:2301.03858. @@ -26,10 +29,11 @@ plot.clmpluspredictions <- function(x, if(!is.null(x$apc_output$hazard.model)){ - a.tp <- grepl('a',x$apc_output$hazard.model) - c.tp <- grepl('c',x$apc_output$hazard.model) - p.tp <- grepl('p',x$apc_output$hazard.model) - lc.tp <- grepl('lc',x$apc_output$hazard.model) + components <- model_components[[x$apc_output$hazard.model]] + a.tp <- isTRUE(components[["age"]]) + c.tp <- isTRUE(components[["cohort"]]) + p.tp <- isTRUE(components[["period"]]) + lc.tp <- FALSE if(lc.tp){ @@ -40,7 +44,7 @@ plot.clmpluspredictions <- function(x, #age effect p1 <- ggplot2::ggplot(a.df, ggplot2::aes(x=x,y=y))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Development period')+ ggplot2::ylab(expression(a[j])) + @@ -49,7 +53,7 @@ plot.clmpluspredictions <- function(x, #age deviation from calendar p2 <- ggplot2::ggplot(a.df, ggplot2::aes(x=x,y=y2))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Development period')+ ggplot2::ylab(expression(b[j])) + @@ -75,16 +79,16 @@ plot.clmpluspredictions <- function(x, p3 <- ggplot2::ggplot(data=ckj.df[1:length(kt),], ggplot2::aes(x=x, y=y))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Calendar period')+ ggplot2::ylab(expression(c[k+j]))+ ggplot2::ggtitle('Fitted effect') p3.f <- ggplot2::ggplot(data=ckj.df[-1,],ggplot2::aes(x=x,y=y))+ - ggplot2::geom_line()+ - ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l80, ymax = kt.u80), alpha = 0.2)+ - ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l95, ymax = kt.u95), alpha = 0.1)+ + ggplot2::geom_line(na.rm = TRUE)+ + ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l80, ymax = kt.u80), alpha = 0.2, na.rm = TRUE)+ + ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l95, ymax = kt.u95), alpha = 0.1, na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Calendar period')+ ggplot2::ylab(expression(c[k+j]))+ @@ -112,7 +116,7 @@ plot.clmpluspredictions <- function(x, y=x$apc_output$model.fit$ax) p1 <- ggplot2::ggplot(a.df, ggplot2::aes(x=x,y=y))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Development period')+ ggplot2::ylab(expression(a[j])) + @@ -151,8 +155,9 @@ plot.clmpluspredictions <- function(x, p2 <- ggplot2::ggplot(data=c.df[1:(dim(c.df)[1]-1),], ggplot2::aes(x=x, y=y))+ - ggplot2::geom_point(ggplot2::aes(x=c.df[dim(c.df)[1],'x'],y=c.df[dim(c.df)[1],'y']),colour="red")+ - ggplot2::geom_line()+ + ggplot2::annotate("point", x = c.df[nrow(c.df), "x"], + y = c.df[nrow(c.df), "y"], colour = "red")+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Accident period')+ ggplot2::ylab(expression(g[k]))+ @@ -187,16 +192,16 @@ plot.clmpluspredictions <- function(x, p3 <- ggplot2::ggplot(data=ckj.df[1:length(kt),], ggplot2::aes(x=x, y=y))+ - ggplot2::geom_line()+ + ggplot2::geom_line(na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Calendar period')+ ggplot2::ylab(expression(c[k+j]))+ ggplot2::ggtitle('Fitted effect') p3.f <- ggplot2::ggplot(data=ckj.df[-1,],ggplot2::aes(x=x,y=y))+ - ggplot2::geom_line()+ - ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l80, ymax = kt.u80), alpha = 0.2)+ - ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l95, ymax = kt.u95), alpha = 0.1)+ + ggplot2::geom_line(na.rm = TRUE)+ + ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l80, ymax = kt.u80), alpha = 0.2, na.rm = TRUE)+ + ggplot2::geom_ribbon(ggplot2::aes(ymin = kt.l95, ymax = kt.u95), alpha = 0.1, na.rm = TRUE)+ ggplot2::theme_classic()+ ggplot2::xlab('Calendar period')+ ggplot2::ylab(expression(c[k+j]))+ diff --git a/R/predictclmplusmodel.R b/R/predictclmplusmodel.R index 6cbcfdd..33304bd 100644 --- a/R/predictclmplusmodel.R +++ b/R/predictclmplusmodel.R @@ -8,7 +8,7 @@ #' @param gk.order \code{integer}, order of the arima model with drift for the accident year effect extrapolation. Default to (1,1,0). #' @param ckj.order \code{integer}, order of the arima model with drift for the calendar year effect extrapolation. Default to (0,1,0). #' @param forecasting_horizon \code{integer}, between 1 and the triangle width. Calendar periods ahead for the predictions. Default predictions are to run-off. -#' @param constrained_development_factor \code{logical}, if \code{TRUE} the predict function will set negative development factors to 1. +#' @param constrained_development_factors \code{logical}, if \code{TRUE} the predict function will set negative development factors to 1. #' @param ... Extra arguments to be passed to the predict function. #' #' @return Returns the following output: @@ -42,115 +42,59 @@ predict.clmplusmodel <- function(object, forecasting_horizon=NULL, constrained_development_factors=FALSE, ...){ - - # forecasting horizon - J <- object$apc_input$J - # fitted model + if (!inherits(object, "clmplusmodel")) { + stop("`object` must be a `clmplusmodel` object.", call. = FALSE) + } + size <- object$apc_input$J + horizon <- validate_horizon(forecasting_horizon, size) model <- object$model.fit - # occurrences distribution eta <- object$apc_input$eta - # hazard model - hazard.model <- object$apc_input$hazard.model - # diagonal - d <- object$apc_input$diagonal[1:J-1] - # cumulative payments - cumulative.payments.triangle <- object$apc_input$cumulative.payments.triangle - - if(hazard.model %in% names(pkg.env$models)){ - - alphaij <- pkg.env$fcst(model, - hazard.model = hazard.model, - gk.fc.model=gk.fc.model, - ckj.fc.model=ckj.fc.model, - gk.order=gk.order, - ckj.order=ckj.order + model_name <- object$apc_input$hazard.model + if (!model_name %in% names(supported_models)) { + stop("The fitted object's hazard model is not supported.", call. = FALSE) + } + + alphaij <- forecast_hazard_rates( + model, model_name, gk.fc.model, ckj.fc.model, gk.order, ckj.order ) - - fij=(1+(1-eta)*alphaij$rates)/(1-(eta*alphaij$rates)) - - if(constrained_development_factors){fij=apply(fij,MARGIN = 2,function(x) pmax(1,x))} - - # browser() - - # d=AggregateDataPP$diagonal[1:(J-1)] - if(is.null(forecasting_horizon)){ - J.stop=J - }else{ - J.stop=forecasting_horizon + factors <- (1 + (1 - eta) * alphaij$rates) / (1 - eta * alphaij$rates) + if (isTRUE(constrained_development_factors)) factors <- pmax(1, factors) + + forecast <- matrix(0, size, horizon) + forecast[, 1L] <- c(0, object$apc_input$diagonal[seq_len(size - 1L)]) * factors[, 1L] + if (horizon >= 2L) { + for (calendar in 2L:horizon) { + forecast[, calendar] <- c(0, forecast[seq_len(size - 1L), calendar - 1L]) * + factors[, calendar] } - - - lt=array(0.,c(J,J.stop)) - - if(!is.null(forecasting_horizon)){ - # plus one is added artificially to make indexing consistent - J.stop=J.stop+1 } - - lt[,1]=c(0.,d)*fij[,1] - - if(J.stop>2){ - for(j in 2:J.stop){lt[,j]=c(0.,lt[1:(J-1),(j-1)])*fij[,j]} - } - - # ot_=pkg.env$t2c(AggregateDataPP$cumulative.payments.triangle) + factors <- factors[, seq_len(horizon), drop = FALSE] + observed_calendar <- triangle_to_calendar(object$apc_input$cumulative.payments.triangle) - ot_=pkg.env$t2c(cumulative.payments.triangle) - - if(is.null(forecasting_horizon)){ - - - ultimate_cost=c(rev(lt[J,1:(J-1)]),ot_[J,J]) - reserve=rev(ultimate_cost-ot_[,J]) - ultimate_cost=rev(ultimate_cost) - #remove last column (not necessary) - lt <- lt[,1:(dim(lt)[2]-1)] - fij <- fij[,1:(dim(fij)[2]-1)] - - }else{ - - ultimate_cost=rev(lt[,J.stop-1]) - ultimate_cost<-c(ultimate_cost[ultimate_cost==0],ultimate_cost[ultimate_cost!=0]) - ultimate_cost[1]=c(ot_[J,J]) - - fij <- fij[1:dim(lt)[1],1:dim(lt)[2],drop=FALSE] - - if(J.stop>2){ - - for(cohort in 2:(J.stop-1)){ - - ultimate_cost[cohort] <- lt[J,cohort-1] - - } - - } - - reserve=ultimate_cost-rev(ot_[,J]) - - } - - - names(reserve) <- 0:(length(reserve)-1) - names(ultimate_cost) <- 0:(length(ultimate_cost)-1) - - out <- list(reserve=reserve, - ultimate_cost=ultimate_cost, - full_triangle= pkg.env$create_full_triangle(cumulative.payments.triangle=cumulative.payments.triangle, - lt), - lower_triangle = pkg.env$create_lower_triangle(lt), - development_factors_predicted = pkg.env$create_lower_triangle(fij), - apc_output=list(model.fit=model, - hazard.model=hazard.model, - alphaij=alphaij, - lower_triangle_apc=lt, - development_factors_apc=fij)) - - class(out) <- 'clmpluspredictions' - - return(out) - - - + if (is.null(forecasting_horizon)) { + ultimate_cost <- rev(c(rev(forecast[size, ]), observed_calendar[size, size])) + } else { + ultimate_cost <- rev(forecast[, horizon]) + ultimate_cost <- c(ultimate_cost[ultimate_cost == 0], ultimate_cost[ultimate_cost != 0]) + ultimate_cost[1L] <- observed_calendar[size, size] + if (horizon >= 2L) ultimate_cost[2L:horizon] <- forecast[size, seq_len(horizon - 1L)] } + reserve <- ultimate_cost - rev(observed_calendar[, size]) + names(reserve) <- names(ultimate_cost) <- seq_along(reserve) - 1L + + lower <- place_forecast_triangle(forecast) + out <- list( + reserve = reserve, + ultimate_cost = ultimate_cost, + full_triangle = place_forecast_triangle(forecast, object$apc_input$cumulative.payments.triangle), + lower_triangle = lower, + development_factors_predicted = place_forecast_triangle(factors), + apc_output = list( + model.fit = model, hazard.model = model_name, alphaij = alphaij, + lower_triangle_apc = forecast, development_factors_apc = factors + ) + ) + class(out) <- "clmpluspredictions" + out } diff --git a/R/properties.R b/R/properties.R deleted file mode 100644 index f42c1e6..0000000 --- a/R/properties.R +++ /dev/null @@ -1,18 +0,0 @@ -rtt.input.env <- new.env() - -# Input checks ---- - -rtt.input.env$properties.cpt <- function(cumulative.payments.triangle){ - - if(sum(cumulative.payments.triangle<0, na.rm = T) !=0 ){ - stop('Please provide an input triangle without negative values') - } - - temp = ChainLadder::cum2incr(cumulative.payments.triangle) - - if(sum(temp<0, na.rm = T) !=0 ){ - stop('Please provide an input triangle of cumulative payments.\n Payments recoveries are not allowed in our model framework.') - } - -} - diff --git a/R/triangle-transformations.R b/R/triangle-transformations.R new file mode 100644 index 0000000..80aee10 --- /dev/null +++ b/R/triangle-transformations.R @@ -0,0 +1,38 @@ +triangle_to_calendar <- function(x) { + nr <- nrow(x) + nc <- ncol(x) + out <- matrix(NA_real_, nr, nc) + index <- which(row(x) + col(x) <= nc + 1L, arr.ind = TRUE) + out[cbind(index[, 2L], rowSums(index) - 1L)] <- x[index] + out +} + +calendar_to_triangle <- function(x) { + nr <- nrow(x) + nc <- ncol(x) + out <- matrix(NA_real_, nr, nc) + index <- which(row(out) + col(out) <= nc + 1L, arr.ind = TRUE) + out[index] <- x[cbind(index[, 2L], rowSums(index) - 1L)] + out +} + +triangle_to_full_calendar <- function(x) { + nr <- nrow(x) + nc <- ncol(x) + out <- matrix(NA_real_, nr, 2L * nc) + index <- which(matrix(TRUE, nr, nc), arr.ind = TRUE) + out[cbind(index[, 2L], rowSums(index) - 1L)] <- x[index] + out +} + +place_forecast_triangle <- function(forecast, observed = NULL) { + size <- nrow(forecast) + out <- if (is.null(observed)) matrix(NA_real_, size, size) else observed + index <- which(row(out) + col(out) > size + 1L, arr.ind = TRUE) + calendar <- rowSums(index) - size - 1L + valid <- calendar >= 1L & calendar <= ncol(forecast) + index <- index[valid, , drop = FALSE] + calendar <- calendar[valid] + out[index] <- forecast[cbind(index[, 2L], calendar)] + out +} diff --git a/R/validation.R b/R/validation.R new file mode 100644 index 0000000..6bfb209 --- /dev/null +++ b/R/validation.R @@ -0,0 +1,31 @@ +validate_triangle <- function(x, weights = NULL, eta = 0.5) { + if (!is.matrix(x) || !is.numeric(x) || nrow(x) != ncol(x) || nrow(x) < 2L) { + stop("`cumulative.payments.triangle` must be a square numeric matrix with at least two rows.", call. = FALSE) + } + if (length(eta) != 1L || !is.finite(eta) || eta <= 0 || eta > 1) { + stop("`eta` must be one finite number in (0, 1].", call. = FALSE) + } + if (any(x < 0, na.rm = TRUE)) { + stop("Please provide an input triangle without negative values.", call. = FALSE) + } + incremental <- x + incremental[, -1L] <- x[, -1L, drop = FALSE] - x[, -ncol(x), drop = FALSE] + if (any(incremental < 0, na.rm = TRUE)) { + stop("Please provide an input triangle of cumulative payments. Payments recoveries are not allowed in our model framework.", call. = FALSE) + } + if (!is.null(weights) && (!is.matrix(weights) || !identical(dim(weights), dim(x)) || + !is.numeric(weights) || any(!is.finite(weights[!is.na(weights)])) || + any(weights < 0, na.rm = TRUE))) { + stop("`entries.weights` must be a non-negative numeric matrix with the same dimensions as the triangle.", call. = FALSE) + } + incremental +} + +validate_horizon <- function(horizon, size) { + if (is.null(horizon)) return(size - 1L) + if (length(horizon) != 1L || is.na(horizon) || horizon != as.integer(horizon) || + horizon < 1L || horizon > size - 1L) { + stop("`forecasting_horizon` must be an integer between 1 and J - 1.", call. = FALSE) + } + as.integer(horizon) +} diff --git a/data-raw/amases.gtpl.R b/data-raw/amases.gtpl.R new file mode 100644 index 0000000..592ef8d --- /dev/null +++ b/data-raw/amases.gtpl.R @@ -0,0 +1 @@ +load(file.path("data", "amases.gtpl.rda")) diff --git a/data-raw/amases.mod.R b/data-raw/amases.mod.R new file mode 100644 index 0000000..43087ed --- /dev/null +++ b/data-raw/amases.mod.R @@ -0,0 +1 @@ +load(file.path("data", "amases.mod.rda")) diff --git a/data-raw/amases.mtpl.R b/data-raw/amases.mtpl.R new file mode 100644 index 0000000..d13d87e --- /dev/null +++ b/data-raw/amases.mtpl.R @@ -0,0 +1 @@ +load(file.path("data", "amases.mtpl.rda")) diff --git a/data-raw/sifa.gtpl.R b/data-raw/sifa.gtpl.R new file mode 100644 index 0000000..df7fbc3 --- /dev/null +++ b/data-raw/sifa.gtpl.R @@ -0,0 +1 @@ +load(file.path("data", "sifa.gtpl.rda")) diff --git a/data-raw/sifa.mod.R b/data-raw/sifa.mod.R new file mode 100644 index 0000000..7c7af80 --- /dev/null +++ b/data-raw/sifa.mod.R @@ -0,0 +1 @@ +load(file.path("data", "sifa.mod.rda")) diff --git a/data-raw/sifa.mtpl.R b/data-raw/sifa.mtpl.R new file mode 100644 index 0000000..dbbac8e --- /dev/null +++ b/data-raw/sifa.mtpl.R @@ -0,0 +1 @@ +load(file.path("data", "sifa.mtpl.rda")) diff --git a/data/amases.gtpl.R b/data/amases.gtpl.R deleted file mode 100644 index 56f538e..0000000 --- a/data/amases.gtpl.R +++ /dev/null @@ -1 +0,0 @@ -load("amases.gtpl.RDa") diff --git a/data/amases.gtpl.RDa b/data/amases.gtpl.rda similarity index 100% rename from data/amases.gtpl.RDa rename to data/amases.gtpl.rda diff --git a/data/amases.mod.R b/data/amases.mod.R deleted file mode 100644 index 4577b89..0000000 --- a/data/amases.mod.R +++ /dev/null @@ -1 +0,0 @@ -load("amases.mod.RDa") \ No newline at end of file diff --git a/data/amases.mod.RDa b/data/amases.mod.rda similarity index 100% rename from data/amases.mod.RDa rename to data/amases.mod.rda diff --git a/data/amases.mtpl.R b/data/amases.mtpl.R deleted file mode 100644 index 8bdaf4e..0000000 --- a/data/amases.mtpl.R +++ /dev/null @@ -1 +0,0 @@ -load("amases.mtpl.RDa") \ No newline at end of file diff --git a/data/amases.mtpl.RDa b/data/amases.mtpl.rda similarity index 100% rename from data/amases.mtpl.RDa rename to data/amases.mtpl.rda diff --git a/data/amasesgtpl.RDa b/data/amasesgtpl.RDa deleted file mode 100644 index 2d9eea2..0000000 Binary files a/data/amasesgtpl.RDa and /dev/null differ diff --git a/data/amasesmod.RDa b/data/amasesmod.RDa deleted file mode 100644 index c1b3311..0000000 Binary files a/data/amasesmod.RDa and /dev/null differ diff --git a/data/amasesmtpl.RDa b/data/amasesmtpl.RDa deleted file mode 100644 index deb2bef..0000000 Binary files a/data/amasesmtpl.RDa and /dev/null differ diff --git a/data/sifa.gtpl.R b/data/sifa.gtpl.R deleted file mode 100644 index dee41ee..0000000 --- a/data/sifa.gtpl.R +++ /dev/null @@ -1 +0,0 @@ -load("sifa.gtpl.RDa") \ No newline at end of file diff --git a/data/sifa.gtpl.RDa b/data/sifa.gtpl.rda similarity index 100% rename from data/sifa.gtpl.RDa rename to data/sifa.gtpl.rda diff --git a/data/sifa.mod.R b/data/sifa.mod.R deleted file mode 100644 index 86126ee..0000000 --- a/data/sifa.mod.R +++ /dev/null @@ -1 +0,0 @@ -load("sifa.mod.RDa") \ No newline at end of file diff --git a/data/sifa.mod.RDa b/data/sifa.mod.rda similarity index 100% rename from data/sifa.mod.RDa rename to data/sifa.mod.rda diff --git a/data/sifa.mtpl.R b/data/sifa.mtpl.R deleted file mode 100644 index 6b94bdf..0000000 --- a/data/sifa.mtpl.R +++ /dev/null @@ -1 +0,0 @@ -load("sifa.mtpl.RDa") \ No newline at end of file diff --git a/data/sifa.mtpl.RDa b/data/sifa.mtpl.rda similarity index 100% rename from data/sifa.mtpl.RDa rename to data/sifa.mtpl.rda diff --git a/data/sifagtpl.RDa b/data/sifagtpl.RDa deleted file mode 100644 index 5b0183a..0000000 Binary files a/data/sifagtpl.RDa and /dev/null differ diff --git a/data/sifamod.RDa b/data/sifamod.RDa deleted file mode 100644 index af04971..0000000 Binary files a/data/sifamod.RDa and /dev/null differ diff --git a/data/sifamtpl.RDa b/data/sifamtpl.RDa deleted file mode 100644 index a224dc4..0000000 Binary files a/data/sifamtpl.RDa and /dev/null differ diff --git a/docs/404.html b/docs/404.html index 84a377f..5a03325 100644 --- a/docs/404.html +++ b/docs/404.html @@ -20,7 +20,7 @@ clmplus - 1.0.0 + 1.0.2 @@ -67,7 +67,7 @@

Page not found (404)

diff --git a/docs/404.md b/docs/404.md new file mode 100644 index 0000000..5107f89 --- /dev/null +++ b/docs/404.md @@ -0,0 +1,3 @@ +Content not found. Please use links in the navbar. + +# Page not found (404) diff --git a/docs/articles/casestudy1.html b/docs/articles/casestudy1.html index 1408099..af5231b 100644 --- a/docs/articles/casestudy1.html +++ b/docs/articles/casestudy1.html @@ -20,7 +20,7 @@ clmplus - 1.0.0 + 1.0.2 @@ -60,7 +60,7 @@

Vignette 1

Gabriele Pittarello

-

2025-06-12

+

2026-07-23

Source: vignettes/casestudy1.Rmd
casestudy1.Rmd
@@ -73,8 +73,7 @@

IntroductionPittarello, Hiabu, and Villegas -(2025).

+paper, Pittarello et al. (2025).

In this vignette:

  • We replicate the chain-ladder model using an age-model for the @@ -140,12 +139,7 @@

    Replicate the chain

    The desired model is fit using the clmplus method.

     a.model.fit=clmplus(AggregateDataPP =  pp_data, 
    -             hazard.model = "a")
    -#> StMoMo: The following ages have been zero weighted: 1 
    -#> StMoMo: The following years have been zero weighted: 1 
    -#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7 
    -#> StMoMo: Start fitting with gnm
    -#> StMoMo: Finish fitting with gnm
    + hazard.model = "a")

    Out of the fitted model, it is possible to extract the fitted development factors:

    @@ -258,52 +252,36 @@ 

    Replicate the chain #> #> Total reserve: 431058.9

    -

    Claims reserving with GLMs compared to hazard models +

    Reproducible chain-ladder comparison

    -

    We fit the stochastic model replicating the chain-ladder with an -age-cohort GLM for the claim amounts described in England and Verrall (1999) using the -apcpackage Fannon and Nielsen -(2020).

    +

    The original replication workflow used the apc package, +which has been removed from CRAN. The revised workflow no longer depends +on apc and uses the current clmplus +implementation instead. This keeps the analysis reproducible with +currently available software and is intended to preserve the original +numerical results.

    -library(apc)
    -#> Warning: package 'apc' was built under R version 4.4.3
    -
    -ds.apc = apc.data.list(cum2incr(dataset),
    -                       data.format = "CL")
    -
    -ac.model.apc = apc.fit.model(ds.apc,
    -                         model.family = "od.poisson.response",
    -                         model.design = "AC")
    -

    Inspect the model coefficients derived from the output:

    -
    -
    -ac.model.apc$coefficients.canonical[,'Estimate']
    -#>        level    age slope cohort slope     DD_age_3     DD_age_4     DD_age_5 
    -#>   7.41596168   0.74105900   0.16519698  -1.16411707  -0.02909890  -0.17467013 
    -#>     DD_age_6     DD_age_7     DD_age_8  DD_cohort_3  DD_cohort_4  DD_cohort_5 
    -#>  -0.17533888   0.17408744  -0.55360421   0.02140672  -0.07364998  -0.03603392 
    -#>  DD_cohort_6  DD_cohort_7  DD_cohort_8 
    -#>  -0.15911660   0.20095088  -0.17521544
    -
    -ac.fcst.apc = apc.forecast.ac(ac.model.apc)
    -
    -data.frame(reserve.mack=ultimate.chl-diagonal,
    -           reserve.apc=c(0,ac.fcst.apc$response.forecast.coh[,'forecast']),
    -           reserve.clmplus=a.model$reserve
    -           
    -           )
    -#>   reserve.mack reserve.apc reserve.clmplus
    -#> 1         0.00     0.00000            0.00
    -#> 2     11995.02    67.23865        11995.02
    -#> 3     28848.23   345.18727        28848.23
    -#> 4     47752.62   940.68770        47752.62
    -#> 5     67734.68  2350.85562        67734.68
    -#> 6     74742.25  4466.77443        74742.25
    -#> 7     97541.29  9103.24335        97541.29
    -#> 8    102444.81 14480.43832       102444.81
    +data.frame( + reserve.mack = ultimate.chl - diagonal, + reserve.clmplus = a.model$reserve +) +#> reserve.mack reserve.clmplus +#> 1 0.00 0.00 +#> 2 11995.02 11995.02 +#> 3 28848.23 28848.23 +#> 4 47752.62 47752.62 +#> 5 67734.68 67734.68 +#> 6 74742.25 74742.25 +#> 7 97541.29 97541.29 +#> 8 102444.81 102444.81 +stopifnot(isTRUE(all.equal( + unname(mck.chl$FullTriangle), + unname(a.model$full_triangle), + tolerance = 1e-10 +)))

    Our method is able to replicate the chain-ladder results without adding the cohort component.

    -
    +
     a.model.fit$fitted_effects
     #> $fitted_development_effect
     #>          0          1          2          3          4          5          6 
    @@ -320,9 +298,9 @@ 

    Claims reserving w package, which provides the graphical tools to inspect the fitted effects. The fitted effects can be plotted using the plot function on the output of the predict method.

    -
    +
     plot(a.model)
    -

    Fitted effect by development period, age-model.

    +

    Fitted effect by development period, age-model.

    @@ -332,56 +310,41 @@

    Adding a cohort e improve the scaled-deviance residuals. The scaled-deviance residuals can be plotted using the plot function on the output of the clmplus method.

    -
    +
     #make it triangular
     plot(a.model.fit)
    -

    Scaled deviance residuals, age-model.

    +

    Scaled deviance residuals, age-model.

    The red and blue areas suggest that there are some trends that the age-model wasn’t able to catch.

    -
    +
     ac.model.fit <- clmplus(pp_data, 
                         hazard.model="ac")
    -#> StMoMo: The following ages have been zero weighted: 1 
    -#> StMoMo: The following years have been zero weighted: 1 
    -#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7 
    -#> StMoMo: Start fitting with gnm
    -#> StMoMo: Finish fitting with gnm
     
     ac.model <- predict(ac.model.fit,
                         gk.fc.model='a')
     plot(ac.model.fit)
    -

    Scaled deviance residuals, age-cohort model. +

    Scaled deviance residuals, age-cohort model. The fitted effect are displayed below. The cohort component is extrapolated for the last available accident period as discussed in our paper.

    -
    +
     
     plot(ac.model)
    -

    Fitted effects, age-cohort model.

    +

    Fitted effects, age-cohort model.

    Modelling a period effect on the claim development

    It is also possible to add a period component and choose an age-period model or an age-period-cohort model.

    -
    +
     ap.model.fit = clmplus(pp_data,
                        hazard.model = "ap")
    -#> StMoMo: The following ages have been zero weighted: 1 
    -#> StMoMo: The following years have been zero weighted: 1 
    -#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7 
    -#> StMoMo: Start fitting with gnm
    -#> StMoMo: Finish fitting with gnm
     
     ap.model<-predict(ap.model.fit, 
                        ckj.fc.model='a',
                        ckj.order = c(0,1,0))
     
     apc.model.fit = clmplus(pp_data,hazard.model = "apc")
    -#> StMoMo: The following ages have been zero weighted: 1 
    -#> StMoMo: The following years have been zero weighted: 1 
    -#> StMoMo: The following cohorts have been zero weighted: -7 -6 -5 -4 -3 -2 -1 7 
    -#> StMoMo: Start fitting with gnm
    -#> StMoMo: Finish fitting with gnm
     
     apc.model<-predict(apc.model.fit, 
                        gk.fc.model='a', 
    @@ -392,34 +355,29 @@ 

    Modelling a period e using an age-period model compared to the residuals plot obtained using the age-cohort model. Conversely, the plot seems to improve using an age-period-cohort model.

    -
    +
     plot(ap.model.fit)
    -

    Scaled deviance residuals, age-period model.

    -
    +

    Scaled deviance residuals, age-period model.

    +
     plot(apc.model.fit)
    -

    Scaled deviance residuals, age-period-cohort model.

    +

    Scaled deviance residuals, age-period-cohort model.

    Below, the effects of the age-period-cohort model.

    -
    +
     plot(apc.model)
    -

    Fitted effects, age-period-cohort model.

    +

    Fitted effects, age-period-cohort model.

    References

    -
    +
    England, Peter, and Richard Verrall. 1999. “Analytic and Bootstrap Estimates of Prediction Errors in Claims Reserving.” Insurance: Mathematics and Economics 25 (3): 281–93.
    -
    -Fannon, Zoe, and Bent Nielsen. 2020. Apc: Age-Period-Cohort -Analysis. https://CRAN.R-project.org/package=apc. -
    -Gesmann, Markus, Daniel Murphy, Yanwei (Wayne) Zhang, Alessandro -Carrato, Mario Wuthrich, Fabio Concina, and Eric Dal Moro. 2025. +Gesmann, Markus, Daniel Murphy, Yanwei (Wayne) Zhang, et al. 2025. ChainLadder: Statistical Methods and Models for Claims Reserving in General Insurance. https://CRAN.R-project.org/package=ChainLadder.
    @@ -447,7 +405,7 @@

    References -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.0.

    diff --git a/docs/articles/casestudy1.md b/docs/articles/casestudy1.md new file mode 100644 index 0000000..b978baf --- /dev/null +++ b/docs/articles/casestudy1.md @@ -0,0 +1,369 @@ +# Vignette 1 + +## Introduction + +The `clmplus` package aims to offer a fast and user-friendly +implementation of the modeling framework introduced in our paper, +Pittarello et al. (2025). + +In this vignette: + +- We replicate the chain-ladder model using an age-model for the claim + development. We can replicate the chain ladder model using an + age-model for the claim development. As discussed in the paper, + modeling claim development allows us to replicate chain-ladder + estimate for claims reserve using fewer parameters than modeling claim + amounts (England and Verrall (1999)). + +- We provide an example illustrating how incorporating a cohort effect + can enhance model fit. + +Before proceeding, we summarise in a table the notation of the claim +development models implemented in `clmplus` package. The implementation +of the models for the claim development available in the `clmplus` is +based on the implementation of the models for human mortality +implemented in the `StMoMo` package. Users can either rely on our +default models or set their own configuration for the claim development. + +| Model | Lexis dimension | Claims reserving | +|:-----:|:-----------------:|---------------------------------:| +| a | age | development (chain-ladder model) | +| ac | age-cohort | development-accident | +| ap | age-period | development-calendar | +| apc | age-period-cohort | development-calendar-accident | + +## Replicate the chain-ladder with the `clmplus` package + +For this tutorial, we use the `AutoBIPaid` run-off triangle available in +the `ChainLadder` package (Gesmann et al. (2025)). Please make sure that +the `ChainLadder` package is installed on your computer before executing +the following code. + +The data is pre-processed using the `AggregateDataPP` method. + +The desired model is fit using the `clmplus` method. + +``` r + +a.model.fit=clmplus(AggregateDataPP = pp_data, + hazard.model = "a") +``` + +Out of the fitted model, it is possible to extract the fitted +development factors: + +``` r + + +a.model.fit$fitted_development_factors +#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] +#> [1,] NA 4.098156 2.087506 1.619294 1.414518 1.302461 1.236005 1.191122 +#> [2,] NA 4.098156 2.087506 1.619294 1.414518 1.302461 1.236005 NA +#> [3,] NA 4.098156 2.087506 1.619294 1.414518 1.302461 NA NA +#> [4,] NA 4.098156 2.087506 1.619294 1.414518 NA NA NA +#> [5,] NA 4.098156 2.087506 1.619294 NA NA NA NA +#> [6,] NA 4.098156 2.087506 NA NA NA NA NA +#> [7,] NA 4.098156 NA NA NA NA NA NA +#> [8,] NA NA NA NA NA NA NA NA +``` + +It is also possible to extract the fitted effects on the claims +development. + +``` r + + +a.model.fit$fitted_effects +#> $fitted_development_effect +#> 0 1 2 3 4 5 6 +#> NA 0.1950754 -0.3503294 -0.7489324 -1.0689916 -1.3366344 -1.5554467 +#> 7 +#> -1.7461089 +#> +#> $fitted_calendar_effect +#> NULL +#> +#> $fitted_accident_effect +#> NULL +``` + +Predictions can be computed with the `predict` method. + +``` r + + +a.model <- predict(a.model.fit) +``` + +Out of the model predictions, we can extract the predicted development +factors, the full and lower triangle of predicted cumulative claims. + +``` r + + +a.model$development_factors_predicted +#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] +#> [1,] NA NA NA NA NA NA NA NA +#> [2,] NA NA NA NA NA NA NA 1.191122 +#> [3,] NA NA NA NA NA NA 1.236005 1.191122 +#> [4,] NA NA NA NA NA 1.302461 1.236005 1.191122 +#> [5,] NA NA NA NA 1.414518 1.302461 1.236005 1.191122 +#> [6,] NA NA NA 1.619294 1.414518 1.302461 1.236005 1.191122 +#> [7,] NA NA 2.087506 1.619294 1.414518 1.302461 1.236005 1.191122 +#> [8,] NA 4.098156 2.087506 1.619294 1.414518 1.302461 1.236005 1.191122 +``` + +``` r + + +a.model$lower_triangle +#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] +#> [1,] NA NA NA NA NA NA NA NA +#> [2,] NA NA NA NA NA NA NA 74756.02 +#> [3,] NA NA NA NA NA NA 75506.30 89937.23 +#> [4,] NA NA NA NA NA 67786.58 83784.54 99797.62 +#> [5,] NA NA NA NA 55952.67 72876.17 90075.29 107290.68 +#> [6,] NA NA NA 35679.53 50469.34 65734.34 81247.96 96776.25 +#> [7,] NA NA 24926.91 40364.00 57095.61 74364.80 91915.25 109482.29 +#> [8,] NA 11478.94 23962.35 38802.09 54886.26 71487.21 88358.53 105245.81 +``` + +``` r + + +a.model$full_triangle +#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] +#> [1,] 1904 7302.00 14798.00 23680.00 33392.00 43463.00 53662.00 63918.00 +#> [2,] 2235 8496.00 17187.00 27630.00 38976.00 50730.00 62761.00 74756.02 +#> [3,] 2441 9789.00 20451.00 33106.00 46854.00 61089.00 75506.30 89937.23 +#> [4,] 2503 10676.00 22486.00 36662.00 52045.00 67786.58 83784.54 99797.62 +#> [5,] 2838 11550.00 24278.00 39556.00 55952.67 72876.17 90075.29 107290.68 +#> [6,] 2405 10263.00 22034.00 35679.53 50469.34 65734.34 81247.96 96776.25 +#> [7,] 2759 11941.00 24926.91 40364.00 57095.61 74364.80 91915.25 109482.29 +#> [8,] 2801 11478.94 23962.35 38802.09 54886.26 71487.21 88358.53 105245.81 +``` + +We can also predict for different forecasting horizons. Below +predictions for one calendar period ahead. The forecasting horizon can +be specified with the `forecasting_horizon` argument in the `predict` +method. + +``` r + + +a.model.2 <- predict(a.model.fit, + forecasting_horizon=1) +``` + +We compare our estimates with those obtained with the Mack chain-ladder +method (Mack (1993)) as implemented in the `ChainLadder` package. We +predict the same reserve as the literature benchmark. + +``` r + +mck.chl <- MackChainLadder(input_data) +ultimate.chl=mck.chl$FullTriangle[,dim(mck.chl$FullTriangle)[2]] +diagonal=rev(t2c(mck.chl$FullTriangle)[,dim(mck.chl$FullTriangle)[2]]) +``` + +Estimates are gathered in a `data.frame` for comparison. + +``` r + +data.frame(ultimate.cost.mack=ultimate.chl, + ultimate.cost.clmplus=a.model$ultimate_cost, + reserve.mack=ultimate.chl-diagonal, + reserve.clmplus=a.model$reserve + ) +#> ultimate.cost.mack ultimate.cost.clmplus reserve.mack reserve.clmplus +#> 1 63918.00 63918.00 0.00 0.00 +#> 2 74756.02 74756.02 11995.02 11995.02 +#> 3 89937.23 89937.23 28848.23 28848.23 +#> 4 99797.62 99797.62 47752.62 47752.62 +#> 5 107290.68 107290.68 67734.68 67734.68 +#> 6 96776.25 96776.25 74742.25 74742.25 +#> 7 109482.29 109482.29 97541.29 97541.29 +#> 8 105245.81 105245.81 102444.81 102444.81 + +cat('\n Total reserve:', + sum(a.model$reserve)) +#> +#> Total reserve: 431058.9 +``` + +### Reproducible chain-ladder comparison + +The original replication workflow used the `apc` package, which has been +removed from CRAN. The revised workflow no longer depends on `apc` and +uses the current `clmplus` implementation instead. This keeps the +analysis reproducible with currently available software and is intended +to preserve the original numerical results. + +``` r + +data.frame( + reserve.mack = ultimate.chl - diagonal, + reserve.clmplus = a.model$reserve +) +#> reserve.mack reserve.clmplus +#> 1 0.00 0.00 +#> 2 11995.02 11995.02 +#> 3 28848.23 28848.23 +#> 4 47752.62 47752.62 +#> 5 67734.68 67734.68 +#> 6 74742.25 74742.25 +#> 7 97541.29 97541.29 +#> 8 102444.81 102444.81 +stopifnot(isTRUE(all.equal( + unname(mck.chl$FullTriangle), + unname(a.model$full_triangle), + tolerance = 1e-10 +))) +``` + +Our method is able to replicate the chain-ladder results without adding +the cohort component. + +``` r + +a.model.fit$fitted_effects +#> $fitted_development_effect +#> 0 1 2 3 4 5 6 +#> NA 0.1950754 -0.3503294 -0.7489324 -1.0689916 -1.3366344 -1.5554467 +#> 7 +#> -1.7461089 +#> +#> $fitted_calendar_effect +#> NULL +#> +#> $fitted_accident_effect +#> NULL +``` + +Further inspection can be performed with the `clmplus` package, which +provides the graphical tools to inspect the fitted effects. The fitted +effects can be plotted using the `plot` function on the output of the +`predict` method. + +``` r + +plot(a.model) +``` + +![Fitted effect by development period, +age-model.](casestudy1_files/figure-html/plot%20effects%20ax-1.png) + +## Adding a cohort effect on the claim development model + +By adding a cohort component to the claim development model, we improve +the scaled-deviance residuals. The scaled-deviance residuals can be +plotted using the `plot` function on the output of the `clmplus` method. + +``` r + +#make it triangular +plot(a.model.fit) +``` + +![Scaled deviance residuals, +age-model.](casestudy1_files/figure-html/amodel%20residuals-1.png) + +The red and blue areas suggest that there are some trends that the +age-model wasn’t able to catch. + +``` r + +ac.model.fit <- clmplus(pp_data, + hazard.model="ac") + +ac.model <- predict(ac.model.fit, + gk.fc.model='a') +plot(ac.model.fit) +``` + +![Scaled deviance residuals, age-cohort +model.](casestudy1_files/figure-html/ac%20residuals-1.png) The fitted +effect are displayed below. The cohort component is extrapolated for the +last available accident period as discussed in our paper. + +``` r + + +plot(ac.model) +``` + +![Fitted effects, age-cohort +model.](casestudy1_files/figure-html/ac%20effects-1.png) + +### Modelling a period effect on the claim development + +It is also possible to add a period component and choose an age-period +model or an age-period-cohort model. + +``` r + +ap.model.fit = clmplus(pp_data, + hazard.model = "ap") + +ap.model<-predict(ap.model.fit, + ckj.fc.model='a', + ckj.order = c(0,1,0)) + +apc.model.fit = clmplus(pp_data,hazard.model = "apc") + +apc.model<-predict(apc.model.fit, + gk.fc.model='a', + ckj.fc.model='a', + gk.order = c(1,1,0), + ckj.order = c(0,1,0)) +``` + +There is no clear difference between the residuals plot obtained using +an age-period model compared to the residuals plot obtained using the +age-cohort model. Conversely, the plot seems to improve using an +age-period-cohort model. + +``` r + +plot(ap.model.fit) +``` + +![Scaled deviance residuals, age-period +model.](casestudy1_files/figure-html/residuals%20apmodel-1.png) + +``` r + +plot(apc.model.fit) +``` + +![Scaled deviance residuals, age-period-cohort +model.](casestudy1_files/figure-html/residuals%20apcmodel-1.png) + +Below, the effects of the age-period-cohort model. + +``` r + +plot(apc.model) +``` + +![Fitted effects, age-period-cohort +model.](casestudy1_files/figure-html/apc%20effects-1.png) + +## References + +England, Peter, and Richard Verrall. 1999. “Analytic and Bootstrap +Estimates of Prediction Errors in Claims Reserving.” *Insurance: +Mathematics and Economics* 25 (3): 281–93. + +Gesmann, Markus, Daniel Murphy, Yanwei (Wayne) Zhang, et al. 2025. +*ChainLadder: Statistical Methods and Models for Claims Reserving in +General Insurance*. . + +Mack, Thomas. 1993. “Distribution-Free Calculation of the Standard Error +of Chain Ladder Reserve Estimates.” *ASTIN Bulletin: The Journal of the +IAA* **23** (2): 213–25. + +Pittarello, Gabriele, Munir Hiabu, and Andrés M Villegas. 2025. +“Replicating and Extending Chain-Ladder via an Age–Period–Cohort +Structure on the Claim Development in a Run-Off Triangle.” *North +American Actuarial Journal*, 1–31. diff --git a/docs/articles/casestudy1_files/figure-html/ac effects-1.png b/docs/articles/casestudy1_files/figure-html/ac effects-1.png index 1485d4b..0b53deb 100644 Binary files a/docs/articles/casestudy1_files/figure-html/ac effects-1.png and b/docs/articles/casestudy1_files/figure-html/ac effects-1.png differ diff --git a/docs/articles/casestudy1_files/figure-html/apc effects-1.png b/docs/articles/casestudy1_files/figure-html/apc effects-1.png index 229e13e..6b76047 100644 Binary files a/docs/articles/casestudy1_files/figure-html/apc effects-1.png and b/docs/articles/casestudy1_files/figure-html/apc effects-1.png differ diff --git a/docs/articles/casestudy1_files/figure-html/plot effects ax-1.png b/docs/articles/casestudy1_files/figure-html/plot effects ax-1.png index d87e3d0..d531b8d 100644 Binary files a/docs/articles/casestudy1_files/figure-html/plot effects ax-1.png and b/docs/articles/casestudy1_files/figure-html/plot effects ax-1.png differ diff --git a/docs/articles/index.html b/docs/articles/index.html index f2d29c7..5d51975 100644 --- a/docs/articles/index.html +++ b/docs/articles/index.html @@ -7,7 +7,7 @@ clmplus - 1.0.0 + 1.0.2

@@ -56,11 +56,8 @@
-
-modelsranking <- function(list.of.datasets){
-  
-  "
-  This functions returns the datasets to plot in the ranking section of the paper.
-  
-  The input is a list of datasets that constitue the sample. 
-  
-  The output is the rankings across different data sources.
-  "
-  
-  
-  full.ranks=NULL
-  
-  for(df.ix in names(list.of.datasets)){
-    
-    out.df=modelsranking.1d(AggregateDataPP(list.of.datasets[[df.ix]]))
-    out.df$models.ranks[,'data.source']=rep(df.ix,dim(out.df$models.ranks)[1])
-    full.ranks=rbind(full.ranks,out.df$models.ranks)  
-  }
-  
-  return(list(full.ranks=full.ranks))
-}
+plot(fits[["apc"]])
+

-p_min_expd0 <- ggplot(full.ranks$full.ranks, aes(model.name, data.source)) +
-   geom_tile(aes(fill = cut(ei.rank, breaks=0:6, labels=1:6)), colour = "grey") +
-   ggtitle(" ") +
-  theme_classic()+
-  geom_text(aes(label = ei.rank))+
-   scale_y_discrete(limits=names(list.of.datasets)) +
-   scale_fill_manual(drop=FALSE, values=colorRampPalette(c("white","#6699CC"))(6), na.value="#EEEEEE", name="Rank") + 
-   xlab("Model") + ylab("Data source")
-p_min_expd0
-

Models ranking plot.

-
-tbl=full.ranks$full.ranks %>%
-  dplyr::group_by(model.name) %>%
-  dplyr::summarise(mean.rank = mean(ei.rank))
-tbl
-#> # A tibble: 6 × 2
-#>   model.name  mean.rank
-#>   <chr>           <dbl>
-#> 1 apc.ac           3.09
-#> 2 apc.apc          4.14
-#> 3 clmplus.a        3.09
-#> 4 clmplus.ac       2.32
-#> 5 clmplus.ap       3   
-#> 6 clmplus.apc      2.45
-
-library(dplyr)
-temp.df=full.ranks$full.ranks[,c('model.name','ei.rank')] %>%
-  group_by(model.name, ei.rank) %>% summarise(count = n())
-#> `summarise()` has grouped output by 'model.name'. You can override using the
-#> `.groups` argument.
-

The following picture was not included in the paper but it shows the -models ranks counts for each model.

-
-ggplot(temp.df, aes(y=count, x=factor(ei.rank))) + 
-    geom_bar(position="stack", stat="identity",fill='#6699CC') +
-  scale_y_continuous(limits=c(0,15))+
-  facet_wrap(~model.name, scales='free')+
-  theme_classic()+
-  ylab("")+
-  xlab("Rank")
-

Model rank count.

- -
-

Code for Section 4.3.2. Model Families Comparison -

-

We evaluate the out-of-sample performance of our models by using a -training, validation and testing split.

-
-J=12
-df<-data.frame(expand.grid(c(0:(J-1)),c(0:(J-1))),c(1:(J^2)))
-colnames(df) <- c("origin","dev","value")
-df$value[df$origin+df$dev==(J-1)]=c(3)
-df$value[df$origin+df$dev<(J-2)]=c(1)
-df$value[df$origin+df$dev==(J-2)]=c(2)
-df$value[df$origin+df$dev>=J]=c(NA)
-#nas in the lower
-df[J,3]=c(NA)
-df[J-1,3]=c(NA)
-df[J+J-1,3]=c(NA)
-df[J*J-J+1,3]=c(NA)
-df[J*J-J+1,3]=c(NA)
-#nas in the upper tail
-df[J*J-J+1-12,3]=c(NA)
-df[J*J-J+2-12,3]=c(NA)
-
-ggplot(data=df, aes(x=as.integer(dev), y=as.integer(origin))) + 
-  geom_tile(aes(fill = as.factor(value),color="#000000"))+scale_y_reverse()+
-  scale_fill_manual(values=c("royalblue", "darkred", "darkgreen","white"),
-                    na.value = "white",
-                    labels=c("Train","Validation","Test",""))+
-  theme_classic()+
-  labs(x="Development year", y="Accident year",fill="")+
-  theme(axis.title.x = element_text(size=8), axis.text.x  = element_text(size=7))+
-  theme(axis.title.y = element_text(size=8), axis.text.y  = element_text(size=7))+
-  scale_color_brewer(guide = 'none')
-

Data split, Train, Validation, and Test.

-
-best.of.the.bests <- function(df1,df2){
-  "
-  Util to turn character columns values into numeric.
-  "
-  
-  df1=apply(df1,MARGIN=2,FUN=as.numeric)
-  df2=apply(df2,MARGIN=2,FUN=as.numeric)
-  df3 <- rbind(df1,df2)
-  df3=apply(df3,FUN=abs.min,MARGIN = 2)
-  
-  return(df3)
-  
-}
-
-modelcomparison.1d <- function(cumulative.payments.triangle){
-  "
-  Function to compare the clmplus package age-period-cohort models with apc package age-period-cohort models  performances across different triangles.
-  
-  This function takes a triangle of cumulative payments as input.
-  
-  It returns the accuracy measures for the two families on the triangle.
-  "
-  # function internal variables
-  
-  leave.out=2
-  
-  rmse = NULL
-  mae = NULL
-  error.pc = NULL
-  model.name = NULL
-  error.incidence = NULL
-  model.family = NULL
-  mre = NULL
-  
-  # data pre-precessing ----
-  
-  J <- dim(cumulative.payments.triangle)[2]
-  reduced.triangle <- c2t(t2c(cumulative.payments.triangle)[1:(J-leave.out),1:(J-leave.out)])
-  newt.rtt <- AggregateDataPP(reduced.triangle)
-  
-  newt.apc <- apc.data.list(response=newt.rtt$incremental.payments.triangle,
-                            data.format="CL")
-  
-  ## stmomo -----
-  to.project <- t2c(cumulative.payments.triangle)[1:(J-leave.out-1),J-leave.out]
-  true.values <- t2c(cumulative.payments.triangle)[2:(J-leave.out),(J-leave.out+1):J]
-  
-  
-  for(ix in c('a','ac','ap','apc')){ ##names(models)
-    
-    hz.fit <- StMoMo::fit(models[[ix]], 
-                          Dxt = newt.rtt$occurrance, 
-                          Ext = newt.rtt$exposure,
-                          wxt=newt.rtt$fit.w,
-                          iterMax=as.integer(1e+05))
-    hz.rate = fcst.fn(hz.fit,
-                   hazard.model = ix,
-                   gk.fc.model = 'a',
-                   ckj.fc.model= 'a')$rates[,1:leave.out]
-    
-    J.new=dim(reduced.triangle)[2]
-    fij = (2+hz.rate)/(2-hz.rate)
-    pred.mx = fij
-    pred.mx[,1]=fij[,1]*c(NA,to.project)
-    temp=unname(pred.mx[1:(J.new-1),1][!is.na(pred.mx[1:(J.new-1),1])])
-    pred.mx[,2]=fij[,2]*c(rep(NA,J.new-length(temp)),temp)
-    true.mx= rbind(rep(NA,2),true.values)
-    # this is meant to be NA
-    true.mx[2,2]=NA
-  
-    sq.errors = (pred.mx-true.mx)^2
-    abs.errors = abs(pred.mx-true.mx)
-    r.errors = (pred.mx-true.mx)/true.mx
-    error.inc.num = apply(pred.mx-true.mx,sum,MARGIN=2,na.rm=T)
-    error.inc.den = apply(true.mx,sum,MARGIN=2,na.rm=T)
-    model.name.ix = c(paste0(ix,".val"),paste0(ix,".test"))
-    
-    model.name = c(model.name,model.name.ix)
-    model.family = c(model.family,rep(ix,2))
-    rmse = c(rmse,sqrt(apply(sq.errors,MARGIN = 2,mean,na.rm=T)))
-    mae = c(mae,apply(abs.errors,MARGIN = 2,mean,na.rm=T))
-    mre = c(mre,apply(r.errors,MARGIN = 2,mean,na.rm=T))
-    error.incidence = c(error.incidence,error.inc.num/error.inc.den)
-    
-  }
-
-  
-  ## stmomo results ---- 
-  
-   out1 <- data.frame(
-    model.name,
-    model.family,
-    mre,
-    error.incidence,
-    rmse,
-    mae)
-  
-  temp.ix <- grepl(".val", model.name)
-  temp.df <- out1[temp.ix,]
-  
-  out2 <- data.frame(
-    rmse=temp.df$model.name[which(abs(temp.df$rmse)==min(abs(temp.df$rmse)))],
-    mre=temp.df$model.name[which(abs(temp.df$mre)==min(abs(temp.df$mre)))],
-    mae=temp.df$model.name[which(abs(temp.df$mae)==min(abs(temp.df$mae)))],
-    error.incidence=temp.df$model.name[which(abs(temp.df$error.incidence)==min(abs(temp.df$error.incidence)))])
-
-  
-  temp.ix <- grepl(".test", model.name)
-  out3 <- out1[temp.ix,]
-  
-  best.df = out2
-  best.df[1,]=NA
-  
-  out.test.min <- data.frame(
-    rmse=out3$model.name[which(abs(out3$rmse)==min(abs(out3$rmse)))],
-    mre=out3$model.name[which(abs(out3$mre)==min(abs(out3$mre)))],
-    mae=out3$model.name[which(abs(out3$mae)==min(abs(out3$mae)))],
-    error.incidence=out3$model.name[which(abs(out3$error.incidence)==min(abs(out3$error.incidence)))])
-  
-  temp.mx=matrix((sub("\\..*", "", out2) == sub("\\..*", "", out.test.min)),nrow=1)
-  choices.mx.clmplus=matrix(sub("\\..*", "", out2),nrow=1)
-  
-  agreement.frame.clmplus=data.frame(temp.mx)
-  choices.frame.clmplus=data.frame(choices.mx.clmplus)
-  
-  colnames(agreement.frame.clmplus)=colnames(out2)
-  colnames(choices.frame.clmplus)=colnames(out2)
-  
-  for(col.ix in colnames(out2)){
-  
-  res=out1$model.family[out1$model.name == out2[1,col.ix]]
-  res.test = out3$model.family == res
-  best.df[1,col.ix] = out3[res.test,col.ix]}
-  
-  families.set=c('a','apc') #'ap',
-  temp.ix = out3$model.family %in% families.set
-  comparison.df = out3[temp.ix,]
-  comparison.df = cbind(comparison.df,
-                        approach=rep('clmplus',length(families.set)))
-
-  
-  ## apc ----
-  
-  rmse = NULL
-  mae = NULL
-  error.pc = NULL
-  model.name = NULL
-  error.incidence = NULL
-  model.family = NULL
-  mre = NULL
-  
-  true.inc.values <- t2c(cum2incr(cumulative.payments.triangle))[2:(J-leave.out),(J-leave.out+1):J]
-  
-  
-  for(apc.mods in c("AC","APC")){ #,"AP"
-    
-    fit <- apc.fit.model(newt.apc,
-                         model.family = "od.poisson.response",
-                         model.design = apc.mods)
-    
-    if(apc.mods == "AC"){fcst <- apc.forecast.ac(fit)$trap.response.forecast}
-    # if(apc.mods == "AP"){fcst <- apc.forecast.ap(fit)$trap.response.forecast}
-    if(apc.mods == "APC"){fcst <- apc.forecast.apc(fit)$trap.response.forecast}
-    
-    plogram.hat = t2c.full.square(incr2cum(t(fcst)))
-    pred.mx = plogram.hat[,(J-leave.out+1):J]
-    
-    # true.mx= rbind(rep(NA,2),true.inc.values)
-    # # this is meant to be NA
-    # true.mx[2,2]=NA
-  
-    sq.errors = (pred.mx-true.mx)^2
-    abs.errors = abs(pred.mx-true.mx)
-    r.errors = (pred.mx-true.mx)/true.mx #use same benchmark
-    error.inc.num = apply(pred.mx-true.mx,sum,MARGIN=2,na.rm=T)
-    error.inc.den = apply(true.mx,sum,MARGIN=2,na.rm=T) #use same benchmark
-    model.name.ix = c(paste0(apc.mods,".val"),paste0(apc.mods,".test"))
-    
-    model.name = c(model.name,tolower(model.name.ix))
-    model.family = c(model.family,tolower(rep(apc.mods,2)))
-    rmse = c(rmse,sqrt(apply(sq.errors,MARGIN = 2,mean,na.rm=T)))
-    mae = c(mae,apply(abs.errors,MARGIN = 2,mean,na.rm=T))
-    mre = c(mre,apply(r.errors,MARGIN = 2,mean,na.rm=T))
-    error.incidence = c(error.incidence,error.inc.num/error.inc.den)}
-    
-      
-   out4 <- data.frame(
-    model.name,
-    model.family,
-    mre,
-    error.incidence,
-    rmse,
-    mae)
-  
-  temp.ix <- grepl(".val", model.name)
-  temp.df <- out4[temp.ix,]
-  
-  out5 <- data.frame(
-    rmse=temp.df$model.name[which(abs(temp.df$rmse)==min(abs(temp.df$rmse)))],
-    mre=temp.df$model.name[which(abs(temp.df$mre)==min(abs(temp.df$mre)))],
-    mae=temp.df$model.name[which(abs(temp.df$mae)==min(abs(temp.df$mae)))],
-    error.incidence=temp.df$model.name[which(abs(temp.df$error.incidence)==min(abs(temp.df$error.incidence)))])
-  
-  temp.ix <- grepl(".test", model.name)
-  out6 <- out4[temp.ix,]
-  
-  out.test.min2 <- data.frame(
-  rmse=out6$model.name[which(abs(out6$rmse)==min(abs(out6$rmse)))],
-  mre=out6$model.name[which(abs(out6$mre)==min(abs(out6$mre)))],
-  mae=out6$model.name[which(abs(out6$mae)==min(abs(out6$mae)))],
-  error.incidence=out6$model.name[which(abs(out6$error.incidence)==min(abs(out6$error.incidence)))])
-
-  temp.mx=matrix((sub("\\..*", "", out5) == sub("\\..*", "", out.test.min2)),nrow=1)
-  choices.mx.apc=matrix(sub("\\..*", "", out5),nrow=1)
-  
-  choices.frame.apc=data.frame(choices.mx.apc)
-  agreement.frame.apc=data.frame(temp.mx)
-  
-  colnames(agreement.frame.apc)=colnames(out5)
-  colnames(choices.frame.apc)=colnames(out5)
-  
-  best.df.apc = out5
-  best.df.apc[1,]=NA
-  
-  for(col.ix in colnames(out5)){
-  
-  res=out4$model.family[out4$model.name == out5[1,col.ix]]
-  res.test = out6$model.family == res
-  best.df.apc[1,col.ix] = out6[res.test,col.ix]}
-      
-  families.set=c('ac','apc') #'ap',
-  temp.ix = out6$model.family %in% families.set
-  comparison.df.apc = out6[temp.ix,]
-  comparison.df.apc = cbind(comparison.df.apc,
-                            approach=rep('apc',length(families.set)))
-  
-  
-  out = list(
-    best.model.clmplus = best.df,
-    best.model.apc = best.df.apc,
-    agreement.frame.clmplus=agreement.frame.clmplus,
-    agreement.frame.apc=agreement.frame.apc,
-    choices.frame.clmplus=choices.frame.clmplus,
-    choices.frame.apc=choices.frame.apc,
-    comparison.df = rbind(comparison.df,
-                          comparison.df.apc))
-  
-  return(out)}
-  
-
-
-modelcomparison<-function(list.of.datasets){
-  "This functions returns the datasets to plot the bake-off section of the paper.
-  
-  The input is a list of datasets that constitue the sample. 
-  
-  The output is datasets that contain accuracy measures.
-  
-  "
-  best.fit=NULL
-  families.fit=NULL
-  agreement.clmplus=NULL
-  agreement.apc=NULL
-  choices.clmplus=NULL
-  choices.apc=NULL
-  
-  for(df.ix in names(list.of.datasets)){
-    cat(paste0(".. Comparison on dataset: ",df.ix))
-    out.ix = modelcomparison.1d(list.of.datasets[[df.ix]])
-    
-    best.of.the.bests.df=best.of.the.bests(out.ix$best.model.clmplus,
-                                        out.ix$best.model.apc)
-    
-    out.ix$best.model.clmplus['package']= 'clmplus'
-    out.ix$best.model.apc['package']= 'apc'
-    best.of.the.bests.df['package']='overall.best'
-    
-    best.fit=rbind(best.fit,
-                   out.ix$best.model.clmplus,
-                   out.ix$best.model.apc,
-                   best.of.the.bests.df)
-    
-    families.fit=rbind(families.fit,
-                   out.ix$comparison.df)
-    
-    agreement.clmplus=rbind(agreement.clmplus,
-                         out.ix$agreement.frame.clmplus)
-    
-    agreement.apc=rbind(agreement.apc,
-                         out.ix$agreement.frame.apc)
-    
-    choices.clmplus=rbind(choices.clmplus,
-                         out.ix$choices.frame.clmplus)
-    
-    choices.apc=rbind(choices.apc,
-                         out.ix$choices.frame.apc)
-  }
-  
-  best.fit[,1:4]=apply(best.fit[,1:4],MARGIN = 2,FUN = as.numeric)
-  
-  families.fit[,c('mre',
-                  'error.incidence',
-                  'rmse',
-                  'mae')]=apply(
-                    families.fit[,c('mre',
-                                    'error.incidence',
-                                    'rmse',
-                                    'mae')],
-                    MARGIN = 2,
-                    FUN = as.numeric)
-  
-  
-  out = list(best.fit=best.fit,
-             families.fit=families.fit,
-             agreement.clmplus=agreement.clmplus,
-             agreement.apc=agreement.apc,
-             choices.clmplus=choices.clmplus,
-             choices.apc=choices.apc)
-  
-  return(out)
-  
-}
-
-
-bake.off <- function(models.comparison){
-  "
-  This function plots out the results from the previous computations. 
-  
-  It takes as input the resulting dataframes of model.comparison.
-  
-  The output is the boxplots of the paper's bake-off section. 
-  
-  "
-  
-  # browser()
-  
-  p1<- models.comparison$best.fit[,c("rmse","mae","package")] %>%
-    tidyr::pivot_longer(-c(package)) %>%
-    ggplot(aes(x=package,y=value))+
-    geom_boxplot()+
-    facet_wrap(.~name,nrow = 1,strip.position = 'bottom')+
-    theme_bw()+
-    theme(strip.placement = 'outside',strip.background = element_blank())
-  
-  p2<- models.comparison$best.fit[,c("mre","error.incidence","package")] %>%
-    tidyr::pivot_longer(-c(package)) %>%
-    ggplot(aes(x=package,y=value))+
-    geom_boxplot()+
-    facet_wrap(.~name,nrow = 1,strip.position = 'bottom')+
-    theme_bw()+
-    theme(strip.placement = 'outside',strip.background = element_blank())
-  
-   abs.best=models.comparison$best.fit[,c("mre","error.incidence","package")]
-  abs.best[,c("mre","error.incidence")]=apply(abs.best[,c("mre","error.incidence")],
-                                              MARGIN=2,
-                                              FUN=abs)
-  p3<- abs.best %>%
-    tidyr::pivot_longer(-c(package)) %>%
-    ggplot(aes(x=package,y=value))+
-    geom_boxplot()+
-    facet_wrap(.~name,nrow = 1,strip.position = 'bottom')+
-    theme_bw()+
-    theme(strip.placement = 'outside',strip.background = element_blank())
-  
-  only.ei=models.comparison$best.fit[,c("error.incidence","package")]
-  only.ei[,c("error.incidence")]=abs(only.ei[,c("error.incidence")])
-  
-  p4<- abs.best %>%
-  tidyr::pivot_longer(-c(package)) %>%
-  ggplot(aes(x=package,y=value))+
-  geom_boxplot()+
-  # facet_wrap(.~name,nrow = 1,strip.position = 'bottom')+
-  theme_bw()+
-  theme(strip.placement = 'outside',strip.background = element_blank())
-  
-  
-  out = list(p1=p1,
-             p2=p2,
-             p3=p3,
-             p4=p4)
-  
-  return(out)
-}
-

The models in the clmplus package are compared to those -in the apc package. Below it can be found the code we used -to create the box-plot in figure 8 of our paper.

-

For each case we are able to pick the best model based on the error -incidence.

-

Error Incidence.

-
-
-

References -

-
-
-Fannon, Zoe, and Bent Nielsen. 2020. Apc: Age-Period-Cohort -Analysis. https://CRAN.R-project.org/package=apc. -
-
-Pittarello, Gabriele, Munir Hiabu, and Andrés M Villegas. 2025. -“Replicating and Extending Chain-Ladder via an Age–Period–Cohort -Structure on the Claim Development in a Run-Off Triangle.” -North American Actuarial Journal, 1–31. -
-
+plot(predictions[["apc"]])
+

@@ -815,7 +146,7 @@

References -

Site built with pkgdown 2.1.1.

+

Site built with pkgdown 2.2.0.

diff --git a/docs/articles/modelscomparison.md b/docs/articles/modelscomparison.md new file mode 100644 index 0000000..c55bbcf --- /dev/null +++ b/docs/articles/modelscomparison.md @@ -0,0 +1,85 @@ +# Model comparison and reproducible regression checks + +## Updated replication workflow + +The replication code has been updated because the `apc` package used by +the original implementation has been removed from CRAN. The revised code +no longer depends on `apc` and uses the current `clmplus` implementation +instead. These changes are intended to preserve the numerical results of +the original analysis while ensuring that the replication workflow can +be run using packages that are currently available. + +The strings `"a"`, `"ac"`, `"ap"`, and `"apc"` below are model +identifiers, not package dependencies. + +## Deterministic comparison + +``` r + +data("AutoBI", package = "ChainLadder") +triangle <- ChainLadder::incr2cum(AutoBI$AutoBIPaid) +prepared <- AggregateDataPP(triangle) +model_ids <- c("a", "ac", "ap", "apc") +fits <- setNames(lapply(model_ids, function(id) { + clmplus(prepared, hazard.model = id, verbose = FALSE) +}), model_ids) +#> Warning in fit.StMoMo(supported_models[[hazard.model]], Dxt = AggregateDataPP$occurrance, : StMoMo: 28 missing values which have been zero weighted +#> Warning in fit.StMoMo(supported_models[[hazard.model]], Dxt = AggregateDataPP$occurrance, : StMoMo: 28 missing values which have been zero weighted +#> Warning in fit.StMoMo(supported_models[[hazard.model]], Dxt = AggregateDataPP$occurrance, : StMoMo: 28 missing values which have been zero weighted +#> Warning in fit.StMoMo(supported_models[[hazard.model]], Dxt = AggregateDataPP$occurrance, : StMoMo: 28 missing values which have been zero weighted +predictions <- lapply(fits, predict) +``` + +The age-only fit reproduces chain ladder. + +``` r + +mack <- ChainLadder::MackChainLadder(triangle) +age_prediction <- predictions[["a"]] +stopifnot(isTRUE(all.equal( + unname(age_prediction$full_triangle), + unname(mack$FullTriangle), + tolerance = 1e-10 +))) +data.frame( + accident_period = seq_along(age_prediction$reserve) - 1L, + reserve = unname(age_prediction$reserve), + ultimate = unname(age_prediction$ultimate_cost) +) +#> accident_period reserve ultimate +#> 1 0 0.00 63918.00 +#> 2 1 11995.02 74756.02 +#> 3 2 28848.23 89937.23 +#> 4 3 47752.62 99797.62 +#> 5 4 67734.68 107290.68 +#> 6 5 74742.25 96776.25 +#> 7 6 97541.29 109482.29 +#> 8 7 102444.81 105245.81 +sum(age_prediction$reserve) +#> [1] 431058.9 +``` + +Partial forecasting fills only the requested future calendar diagonals. + +``` r + +one_year <- predict(fits[["apc"]], forecasting_horizon = 1) +dim(one_year$full_triangle) +#> [1] 8 8 +dim(one_year$apc_output$lower_triangle_apc) +#> [1] 8 1 +``` + +``` r + +plot(fits[["apc"]]) +``` + +![](modelscomparison_files/figure-html/plots-1.png) + +``` r + +plot(predictions[["apc"]]) +``` + +![](modelscomparison_files/figure-html/plots-2.png) diff --git a/docs/articles/modelscomparison_files/figure-html/plots-1.png b/docs/articles/modelscomparison_files/figure-html/plots-1.png new file mode 100644 index 0000000..0398869 Binary files /dev/null and b/docs/articles/modelscomparison_files/figure-html/plots-1.png differ diff --git a/docs/articles/modelscomparison_files/figure-html/plots-2.png b/docs/articles/modelscomparison_files/figure-html/plots-2.png new file mode 100644 index 0000000..9873484 Binary files /dev/null and b/docs/articles/modelscomparison_files/figure-html/plots-2.png differ diff --git a/docs/authors.html b/docs/authors.html index 37ecbe6..3675107 100644 --- a/docs/authors.html +++ b/docs/authors.html @@ -7,7 +7,7 @@ clmplus - 1.0.0 + 1.0.2 @@ -214,9 +214,9 @@

Citation

Developers

    -
  • Gabriele Pittarello
    Author, maintainer, copyright holder
  • -
  • Munir Hiabu
    Author, copyright holder
  • -
  • Andres Villegas
    Author, copyright holder
  • +
  • Gabriele Pittarello
    Author, maintainer, copyright holder
  • +
  • Munir Hiabu
    Author, copyright holder
  • +
  • Andres Villegas
    Author, copyright holder
@@ -239,7 +239,7 @@

Dev status

diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..2cfa8a8 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,136 @@ +# clmplus + +`clmplus` is an `R` package for implementing the age-period-cohort +models for the claim development presented in the manuscript +‘Replicating and extending chain-ladder via an age-period-cohort +structure on the claim development in a run-off triangle’ +. + +## Our models + +The models for the claim development available in the `clmplus` are +based on the models for human mortality implemented in the `StMoMo` +package. Users can either rely on our default models or set their own +configuration for the claim development. + +| Model | Lexis dimension | Claims reserving | +|:-----:|:-----------------:|---------------------------------:| +| a | age | development (chain-ladder model) | +| ac | age-cohort | development-accident | +| ap | age-period | development-calendar | +| apc | age-period-cohort | development-calendar-accident | + +## Installation + +The developer version of `clmplus` can be installed from GitHub. + + library(devtools) + devtools::install_github("gpitt71/clmplus") + +The current version of `clmplus` can be installed from CRAN. + + install.packages('clmplus') + +## Get Started + +In this brief example, we work with the `sifa.mtpl` data from the +`clmplus` package. Further examples can be found in the [package +vignettes](https://github.com/gpitt71/clmplus/tree/main/vignettes). The +data set of cumulative claim payments is transformed into an +`AggregateDataPP` object that pre-processes the data for claim +development modelling. + + library(clmplus) + + data ("sifa.mtpl") + dataset = sifa.mtpl + datapp = AggregateDataPP(cumulative.payments.triangle = dataset, eta= 1/2) + +Our models can be fit with the `clmplus` function. + + a.model.fit=clmplus(datapp, + hazard.model = "a") # age-model replicates the chain ladder + + ac.model.fit=clmplus(datapp, + hazard.model = "ac") + + ap.model.fit=clmplus(datapp, + hazard.model = "ap") + + apc.model.fit=clmplus(datapp, + hazard.model = "apc") + +The `plot` function can be be used to explore the scaled deviance +residuals of fitted models. Below, an example for the age-period-cohort +(`apc`) model for the claim development. + + plot(apc.model.fit) + +Predictions are performed with the `predict` function. + + a.model=predict(a.model.fit) + + # clmplus reserve (age model) + sum(a.model$reserve) + #226875.5 + + + ac.model=predict(ac.model.fit, + gk.fc.model = 'a', + gk.order = c(1,1,0)) + + # clmplus reserve (age-cohort model) + sum(ac.model$reserve) + #205305.7 + + ap.model= predict(ap.model.fit, + ckj.fc.model = 'a', + ckj.order = c(0,1,0)) + + # clmplus reserve (age-period model) + sum(ap.model$reserve) + #215602.8 + + + apc.model= predict(apc.model.fit, + gk.fc.model = 'a', + ckj.fc.model = 'a', + gk.order = c(1,1,0), + ckj.order = c(0,1,0)) + # clmplus reserve (age-period-cohort model) + sum(apc.model$reserve) + #213821.6 + +The fitted effect (and extrapolated) effects can be inspected with the +`plot` function. We continue below the example with the `apc` model. + + plot(apc.model) + +## Citation + +**APA Style** + +Pittarello, G., Hiabu, M., & Villegas, A. M. (2025). Replicating and +Extending Chain-Ladder via an Age–Period–Cohort Structure on the Claim +Development in a Run-Off Triangle. North American Actuarial Journal, +1-31. + +**BibTeX** + +``` bibtex +@article{ , + title={Replicating and Extending Chain-Ladder via an Age--Period--Cohort Structure on the Claim Development in a Run-Off Triangle}, + author={Pittarello, Gabriele and Hiabu, Munir and Villegas, Andr{\'e}s M}, + journal={North American Actuarial Journal}, + pages={1--31}, + year={2025}, + publisher={Taylor \& Francis} + doi = {10.1080/10920277.2025.2496725}, +} +``` + +## Further Resources + +The most recent tutorials and replication files associated with the +manuscript can be accessed via [our project +website](https://gpitt71.github.io/clmplus/). diff --git a/docs/katex-auto.js b/docs/katex-auto.js index 20651d9..2adab3a 100644 --- a/docs/katex-auto.js +++ b/docs/katex-auto.js @@ -11,4 +11,6 @@ document.addEventListener("DOMContentLoaded", function () { macros: macros, fleqn: false }); - }}}); + } + } +}); diff --git a/docs/lightswitch.js b/docs/lightswitch.js index 9467125..3808ca1 100644 --- a/docs/lightswitch.js +++ b/docs/lightswitch.js @@ -26,7 +26,7 @@ const setTheme = theme => { } } -function bsSetupThemeToggle () { +function bsSetupThemeToggle() { 'use strict' const showActiveTheme = (theme, focus = false) => { @@ -35,7 +35,7 @@ function bsSetupThemeToggle () { document.querySelectorAll('[data-bs-theme-value]').forEach(element => { const buttonTheme = element.getAttribute('data-bs-theme-value') const isActive = buttonTheme == theme - + element.classList.toggle('active', isActive) element.setAttribute('aria-pressed', isActive) diff --git a/docs/llms.txt b/docs/llms.txt new file mode 100644 index 0000000..216aa1b --- /dev/null +++ b/docs/llms.txt @@ -0,0 +1,179 @@ +# clmplus + +`clmplus` is an `R` package for implementing the age-period-cohort +models for the claim development presented in the manuscript +‘Replicating and extending chain-ladder via an age-period-cohort +structure on the claim development in a run-off triangle’ +. + +## Our models + +The models for the claim development available in the `clmplus` are +based on the models for human mortality implemented in the `StMoMo` +package. Users can either rely on our default models or set their own +configuration for the claim development. + +| Model | Lexis dimension | Claims reserving | +|:-----:|:-----------------:|---------------------------------:| +| a | age | development (chain-ladder model) | +| ac | age-cohort | development-accident | +| ap | age-period | development-calendar | +| apc | age-period-cohort | development-calendar-accident | + +## Installation + +The developer version of `clmplus` can be installed from GitHub. + + library(devtools) + devtools::install_github("gpitt71/clmplus") + +The current version of `clmplus` can be installed from CRAN. + + install.packages('clmplus') + +## Get Started + +In this brief example, we work with the `sifa.mtpl` data from the +`clmplus` package. Further examples can be found in the [package +vignettes](https://github.com/gpitt71/clmplus/tree/main/vignettes). The +data set of cumulative claim payments is transformed into an +`AggregateDataPP` object that pre-processes the data for claim +development modelling. + + library(clmplus) + + data ("sifa.mtpl") + dataset = sifa.mtpl + datapp = AggregateDataPP(cumulative.payments.triangle = dataset, eta= 1/2) + +Our models can be fit with the `clmplus` function. + + a.model.fit=clmplus(datapp, + hazard.model = "a") # age-model replicates the chain ladder + + ac.model.fit=clmplus(datapp, + hazard.model = "ac") + + ap.model.fit=clmplus(datapp, + hazard.model = "ap") + + apc.model.fit=clmplus(datapp, + hazard.model = "apc") + +The `plot` function can be be used to explore the scaled deviance +residuals of fitted models. Below, an example for the age-period-cohort +(`apc`) model for the claim development. + + plot(apc.model.fit) + +Predictions are performed with the `predict` function. + + a.model=predict(a.model.fit) + + # clmplus reserve (age model) + sum(a.model$reserve) + #226875.5 + + + ac.model=predict(ac.model.fit, + gk.fc.model = 'a', + gk.order = c(1,1,0)) + + # clmplus reserve (age-cohort model) + sum(ac.model$reserve) + #205305.7 + + ap.model= predict(ap.model.fit, + ckj.fc.model = 'a', + ckj.order = c(0,1,0)) + + # clmplus reserve (age-period model) + sum(ap.model$reserve) + #215602.8 + + + apc.model= predict(apc.model.fit, + gk.fc.model = 'a', + ckj.fc.model = 'a', + gk.order = c(1,1,0), + ckj.order = c(0,1,0)) + # clmplus reserve (age-period-cohort model) + sum(apc.model$reserve) + #213821.6 + +The fitted effect (and extrapolated) effects can be inspected with the +`plot` function. We continue below the example with the `apc` model. + + plot(apc.model) + +## Citation + +**APA Style** + +Pittarello, G., Hiabu, M., & Villegas, A. M. (2025). Replicating and +Extending Chain-Ladder via an Age–Period–Cohort Structure on the Claim +Development in a Run-Off Triangle. North American Actuarial Journal, +1-31. + +**BibTeX** + +``` bibtex +@article{ , + title={Replicating and Extending Chain-Ladder via an Age--Period--Cohort Structure on the Claim Development in a Run-Off Triangle}, + author={Pittarello, Gabriele and Hiabu, Munir and Villegas, Andr{\'e}s M}, + journal={North American Actuarial Journal}, + pages={1--31}, + year={2025}, + publisher={Taylor \& Francis} + doi = {10.1080/10920277.2025.2496725}, +} +``` + +## Further Resources + +The most recent tutorials and replication files associated with the +manuscript can be accessed via [our project +website](https://gpitt71.github.io/clmplus/). + +# Package index + +## All functions + +- [`AggregateDataPP()`](https://gpitt71.github.io/clmplus/reference/AggregateDataPP.md) + : Pre-process Run-Off Triangles +- [`amases.gtpl`](https://gpitt71.github.io/clmplus/reference/amases.gtpl.md) + : Amases GTPL +- [`amases.mod`](https://gpitt71.github.io/clmplus/reference/amases.mod.md) + : Amases MOD +- [`amases.mtpl`](https://gpitt71.github.io/clmplus/reference/amases.mtpl.md) + : Amases MTPL +- [`clmplus()`](https://gpitt71.github.io/clmplus/reference/clmplus.md) + : Fit a Chain Ladder Plus hazard model +- [`plot(`*``*`)`](https://gpitt71.github.io/clmplus/reference/plot.AggregateDataPP.md) + : Plot the payments behavior +- [`plot(`*``*`)`](https://gpitt71.github.io/clmplus/reference/plot.clmplusmodel.md) + : Plot the hazard model residuals +- [`plot(`*``*`)`](https://gpitt71.github.io/clmplus/reference/plot.clmpluspredictions.md) + : Plot the hazard model fitted and forecasted parameters +- [`predict(`*``*`)`](https://gpitt71.github.io/clmplus/reference/predict.clmplusmodel.md) + : Predict the Reserve using Chain Ladder Plus Models +- [`predictReserve(`*``*`)`](https://gpitt71.github.io/clmplus/reference/predictReserve.clmplusmodel.md) + [`predictReserve(`*``*`)`](https://gpitt71.github.io/clmplus/reference/predictReserve.clmplusmodel.md) + : Convert clmplus predictions to the ReSurv reserving interface +- [`predictReserve()`](https://gpitt71.github.io/clmplus/reference/predictReserve.md) + : Predict reserves +- [`sifa.gtpl`](https://gpitt71.github.io/clmplus/reference/sifa.gtpl.md) + : Sifa GTPL +- [`sifa.mod`](https://gpitt71.github.io/clmplus/reference/sifa.mod.md) + : Sifa MOD +- [`sifa.mtpl`](https://gpitt71.github.io/clmplus/reference/sifa.mtpl.md) + : Sifa MTPL + +# Articles + +### All vignettes + +- [Vignette + 1](https://gpitt71.github.io/clmplus/articles/casestudy1.md): +- [Model comparison and reproducible regression + checks](https://gpitt71.github.io/clmplus/articles/modelscomparison.md): diff --git a/docs/pkgdown.js b/docs/pkgdown.js index 1a99c65..0a5573a 100644 --- a/docs/pkgdown.js +++ b/docs/pkgdown.js @@ -1,6 +1,6 @@ /* http://gregfranko.com/blog/jquery-best-practices/ */ -(function($) { - $(function() { +(function ($) { + $(function () { $('nav.navbar').headroom(); @@ -27,45 +27,45 @@ $('[data-bs-toggle="tooltip"]').tooltip(); - /* Clipboard --------------------------*/ + /* Clipboard --------------------------*/ - function changeTooltipMessage(element, msg) { - var tooltipOriginalTitle=element.getAttribute('data-bs-original-title'); - element.setAttribute('data-bs-original-title', msg); - $(element).tooltip('show'); - element.setAttribute('data-bs-original-title', tooltipOriginalTitle); - } + function changeTooltipMessage(element, msg) { + var tooltipOriginalTitle = element.getAttribute('data-bs-original-title'); + element.setAttribute('data-bs-original-title', msg); + $(element).tooltip('show'); + element.setAttribute('data-bs-original-title', tooltipOriginalTitle); + } - if(ClipboardJS.isSupported()) { - $(document).ready(function() { - var copyButton = ""; + if (ClipboardJS.isSupported()) { + $(document).ready(function () { + var copyButton = ""; - $("div.sourceCode").addClass("hasCopyButton"); + $("div.sourceCode").addClass("hasCopyButton"); - // Insert copy buttons: - $(copyButton).prependTo(".hasCopyButton"); + // Insert copy buttons: + $(copyButton).prependTo(".hasCopyButton"); - // Initialize tooltips: - $('.btn-copy-ex').tooltip({container: 'body'}); + // Initialize tooltips: + $('.btn-copy-ex').tooltip({ container: 'body' }); - // Initialize clipboard: - var clipboard = new ClipboardJS('[data-clipboard-copy]', { - text: function(trigger) { - return trigger.parentNode.textContent.replace(/\n#>[^\n]*/g, ""); - } - }); + // Initialize clipboard: + var clipboard = new ClipboardJS('[data-clipboard-copy]', { + text: function (trigger) { + return trigger.parentNode.textContent.replace(/\n#>[^\n]*/g, ""); + } + }); - clipboard.on('success', function(e) { - changeTooltipMessage(e.trigger, 'Copied!'); - e.clearSelection(); - }); + clipboard.on('success', function (e) { + changeTooltipMessage(e.trigger, 'Copied!'); + e.clearSelection(); + }); - clipboard.on('error', function(e) { - changeTooltipMessage(e.trigger,'Press Ctrl+C or Command+C to copy'); - }); + clipboard.on('error', function (e) { + changeTooltipMessage(e.trigger, 'Press Ctrl+C or Command+C to copy'); + }); - }); - } + }); + } /* Search marking --------------------------*/ var url = new URL(window.location.href); @@ -80,80 +80,80 @@ }); } - /* Search --------------------------*/ - /* Adapted from https://github.com/rstudio/bookdown/blob/2d692ba4b61f1e466c92e78fd712b0ab08c11d31/inst/resources/bs4_book/bs4_book.js#L25 */ + /* Search --------------------------*/ + /* Adapted from https://github.com/rstudio/bookdown/blob/2d692ba4b61f1e466c92e78fd712b0ab08c11d31/inst/resources/bs4_book/bs4_book.js#L25 */ // Initialise search index on focus - var fuse; - $("#search-input").focus(async function(e) { - if (fuse) { - return; - } - - $(e.target).addClass("loading"); - var response = await fetch($("#search-input").data("search-index")); - var data = await response.json(); + var fuse; + $("#search-input").focus(async function (e) { + if (fuse) { + return; + } + + $(e.target).addClass("loading"); + var response = await fetch($("#search-input").data("search-index")); + var data = await response.json(); + + var options = { + keys: ["what", "text", "code"], + ignoreLocation: true, + threshold: 0.1, + includeMatches: true, + includeScore: true, + }; + fuse = new Fuse(data, options); + + $(e.target).removeClass("loading"); + }); + // Use algolia autocomplete var options = { - keys: ["what", "text", "code"], - ignoreLocation: true, - threshold: 0.1, - includeMatches: true, - includeScore: true, + autoselect: true, + debug: true, + hint: false, + minLength: 2, }; - fuse = new Fuse(data, options); - - $(e.target).removeClass("loading"); - }); - - // Use algolia autocomplete - var options = { - autoselect: true, - debug: true, - hint: false, - minLength: 2, - }; - var q; -async function searchFuse(query, callback) { - await fuse; - - var items; - if (!fuse) { - items = []; - } else { - q = query; - var results = fuse.search(query, { limit: 20 }); - items = results - .filter((x) => x.score <= 0.75) - .map((x) => x.item); - if (items.length === 0) { - items = [{dir:"Sorry 😿",previous_headings:"",title:"No results found.",what:"No results found.",path:window.location.href}]; + var q; + async function searchFuse(query, callback) { + await fuse; + + var items; + if (!fuse) { + items = []; + } else { + q = query; + var results = fuse.search(query, { limit: 20 }); + items = results + .filter((x) => x.score <= 0.75) + .map((x) => x.item); + if (items.length === 0) { + items = [{ dir: "Sorry 😿", previous_headings: "", title: "No results found.", what: "No results found.", path: window.location.href }]; + } + } + callback(items); } - } - callback(items); -} - $("#search-input").autocomplete(options, [ - { - name: "content", - source: searchFuse, - templates: { - suggestion: (s) => { - if (s.title == s.what) { - return `${s.dir} >
${s.title}
`; - } else if (s.previous_headings == "") { - return `${s.dir} >
${s.title}
> ${s.what}`; - } else { - return `${s.dir} >
${s.title}
> ${s.previous_headings} > ${s.what}`; - } + $("#search-input").autocomplete(options, [ + { + name: "content", + source: searchFuse, + templates: { + suggestion: (s) => { + if (s.title == s.what) { + return `${s.dir} >
${s.title}
`; + } else if (s.previous_headings == "") { + return `${s.dir} >
${s.title}
> ${s.what}`; + } else { + return `${s.dir} >
${s.title}
> ${s.previous_headings} > ${s.what}`; + } + }, }, }, - }, - ]).on('autocomplete:selected', function(event, s) { - window.location.href = s.path + "?q=" + q + "#" + s.id; - }); + ]).on('autocomplete:selected', function (event, s) { + window.location.href = s.path + "?q=" + q + "#" + s.id; + }); }); })(window.jQuery || window.$) -document.addEventListener('keydown', function(event) { +document.addEventListener('keydown', function (event) { // Check if the pressed key is '/' if (event.key === '/') { event.preventDefault(); // Prevent any default action associated with the '/' key diff --git a/docs/pkgdown.yml b/docs/pkgdown.yml index 26a3256..c07eef7 100644 --- a/docs/pkgdown.yml +++ b/docs/pkgdown.yml @@ -1,10 +1,10 @@ -pandoc: '3.4' -pkgdown: 2.1.1 +pandoc: 3.8.3 +pkgdown: 2.2.0 pkgdown_sha: ~ articles: casestudy1: casestudy1.html modelscomparison: modelscomparison.html -last_built: 2025-06-12T10:08Z +last_built: 2026-07-23T16:16Z urls: reference: https://gpitt71.github.io/clmplus/reference article: https://gpitt71.github.io/clmplus/articles diff --git a/docs/reference/AggregateDataPP.html b/docs/reference/AggregateDataPP.html index e50e1ab..b8296a2 100644 --- a/docs/reference/AggregateDataPP.html +++ b/docs/reference/AggregateDataPP.html @@ -7,7 +7,7 @@ clmplus - 1.0.0 + 1.0.2