| Title: | Modelling Traditional Life Insurance Contracts |
|---|---|
| Description: | R6 classes to model traditional life insurance contracts like annuities, whole life insurances or endowments. Such life insurance contracts provide a guaranteed interest and are not directly linked to the performance of a particular investment vehicle, but they typically provide (discretionary) profit participation. This package provides a framework to model such contracts in a very generic (cash-flow-based) way and includes modelling profit participation schemes, dynamic increases or more general contract layers, as well as contract changes (like sum increases or premium waivers). All relevant quantities like premium decomposition, reserves and benefits over the whole contract period are calculated and potentially exported to 'Excel'. Mortality rates are given using the 'MortalityTables' package. |
| Authors: | Reinhold Kainhofer [aut, cre, cph] |
| Maintainer: | Reinhold Kainhofer <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.2 |
| Built: | 2026-05-11 05:53:03 UTC |
| Source: | https://github.com/kainhofer/lifeinsurer |
Calculate the age of the insured based on exact age at contract closing, rounded to the nearest birthday.
age.exactRounded(params, values)age.exactRounded(params, values)
params |
The parameters of the contract. |
values |
Unused by default (already calculated values of the contract) |
the resulting age
Calculate the age of the insured based on the difference of the bith year and contract closing year.
age.yearDifference(params, values)age.yearDifference(params, values)
params |
The parameters of the contract. |
values |
Unused by default (already calculated values of the contract) |
the resulting age
hook is a function, apply it to val, otherwise return val unchangedIf hook is a function, apply it to val, otherwise return val unchanged
applyHook(hook, val, ...)applyHook(hook, val, ...)
hook |
(optional) function to apply to |
val |
The value to which the hook is applied (ifgiven) |
... |
optional parameters passed to the hook function (if it is a function) |
the value with the hook function applied (if a function) or unchanged otherwiese
applyHook(NULL, 3) # returns 3 unchanged applyHook(function(x) 2*x, 3) # applies the function, returns 6 applyHook(`+`, 3, 1) # returns 4applyHook(NULL, 3) # returns 3 unchanged applyHook(function(x) 2*x, 3) # applies the function, returns 6 applyHook(`+`, 3, 1) # returns 4
Enum to define how much of a contract needs to be calculated automatically.
When an InsuranceContract object is created, all time series are immediately calculated. However, sometimes, one only needs part of the values, so it would be a waste of resources to calculate e.g. all future reserves and profit participation, if only premiums are of interest.
Possible values are:
"all"
"probabilities"
"cashflows"
"presentvalues"
"premiums"
"absvalues"
"reserves"
"premiumcomposition"
"profitparticipation"
"history"
The function contractGrid creates a (two- or multi-dimensional) grid
of InsuranceContract objects, where each axis represents one of the insurance
parameters varying as given in the axes argument (as a named list).
The function contractGridPremium returns a grid of premiums as requested in
the premium parameter rather than the full InsuranceContract objects.
It is a convenience wrapper around contractGrid and is recommended if
one is only interested in a grid of one particular value (typically some
kind of premium).
The function contractGridPremium can also be used on an existing
contractGrid-generated grid of contracts to extract grid of numerical
values of the specified premiums. If no contract grid is passed to
contractGridPremium, contractGrid will be called to create it.
contractGrid( axes = list(age = seq(20, 60, 10), policyPeriod = seq(5, 35, 5)), YOB = NULL, observationYear = NULL, ... ) contractGridPremium( contractGrid = NULL, premium = "written", .fun = function(cntr) { cntr$Values$premiums[[premium]] }, ... )contractGrid( axes = list(age = seq(20, 60, 10), policyPeriod = seq(5, 35, 5)), YOB = NULL, observationYear = NULL, ... ) contractGridPremium( contractGrid = NULL, premium = "written", .fun = function(cntr) { cntr$Values$premiums[[premium]] }, ... )
axes |
List of paramters spanning the dimensions of the grid. |
YOB |
optional year of bith. If missing, the |
observationYear |
The observation year, for which the grid shall be calculated. If given, the YOB is calculated from it, otherwise the contract's YOB is used |
... |
In |
contractGrid |
(optional) existing contract grid from which to derive
premiums. If not given, contractGrid is called with all parameters, so
|
premium |
The type of premium to derive (key of the |
.fun |
The function to extract the desired premium from a contract
object. By default it accesses the premium vector and extracts the
type of premium given in the |
The function contractGrid will return the full InsuranceContract
objects, so apply can later be used to extract premiums, reserves and other
values to display in a grid. For this feature, one can also use the convenience
function contractGridPremium.
The axes list describing the parameters changing along the axes of the
resulting grid is internally expanded with expand.grid(). The resulting flat
list of parameter (together with the fixed parameters passed as ...)
is then passed to the InsuranceContract$new() call to create the corresponding
contract object.
To create the human-readable row-/columnnames of the resulting array,
the function makeContractGridDimname() for each value of the axes, allowing
human-readable representations e.g. of a tariff or a mortality table as
the dimension label.
multi-dimensional array of insurance contracts (dimensions defined by the axes argument)
a array of premiums (or other contract-specific value) for the grid defined by the axes argument to contractGrid
library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs, premiums during whole # deferral period, 30 years annuity payments: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01, deferralPeriod = function(params, ...) { params$ContractData$premiumPeriod }, policyPeriod = function(params, ...) { params$ContractData$premiumPeriod + 30 } ) contractGrid( axes = list( age = seq(20, 60, 10), premiumPeriod = seq(5,30, 5) ), tarif = tariff, sumInsured = 1000, contractClosing = as.Date("2023-11-01") ) library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs, premiums during whole # deferral period, 30 years annuity payments: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01, deferralPeriod = function(params, ...) { params$ContractData$premiumPeriod }, policyPeriod = function(params, ...) { params$ContractData$premiumPeriod + 30 } ) contractGridPremium( axes = list( age = seq(20, 60, 10), premiumPeriod = seq(5,30, 5) ), tarif = tariff, sumInsured = 1000, contractClosing = as.Date("2023-11-01") )library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs, premiums during whole # deferral period, 30 years annuity payments: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01, deferralPeriod = function(params, ...) { params$ContractData$premiumPeriod }, policyPeriod = function(params, ...) { params$ContractData$premiumPeriod + 30 } ) contractGrid( axes = list( age = seq(20, 60, 10), premiumPeriod = seq(5,30, 5) ), tarif = tariff, sumInsured = 1000, contractClosing = as.Date("2023-11-01") ) library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs, premiums during whole # deferral period, 30 years annuity payments: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01, deferralPeriod = function(params, ...) { params$ContractData$premiumPeriod }, policyPeriod = function(params, ...) { params$ContractData$premiumPeriod + 30 } ) contractGridPremium( axes = list( age = seq(20, 60, 10), premiumPeriod = seq(5,30, 5) ), tarif = tariff, sumInsured = 1000, contractClosing = as.Date("2023-11-01") )
Returns a function that sets base alpha (and Zillmer) costs to the given value, but otherwise uses the full costs defined by the Costs parameter.
costs.baseAlpha(alpha)costs.baseAlpha(alpha)
alpha |
The minimum alpha / Zillmer cost that cannot be waived |
This function can be set as minCosts parameter for a tariff and makes sure that only alpha costs are modified / waived, but no other costs.
Returns a function that modifies alpha (and Zillmer) costs by the given scale, but otherwise uses the full costs defined by the Costs parameter.
costs.scaleAlpha(scale)costs.scaleAlpha(scale)
scale |
The scale for alpha / Zillmer cost |
This function can be set as adjustCosts or adjustMinCosts hook parameters for a tariff or contract and can be used to apply cost adjustments on a per-contract basis.
Returns a data.frame with columns
costsDisplayTable(costs)costsDisplayTable(costs)
costs |
The cost structure to be displayed in a concise table style. |
Convert the cost values array to a tx15 matrix
costValuesAsDF(costValues)costValuesAsDF(costValues)
costValues |
Cost definition data structure |
Not to be called directly, but implicitly by the InsuranceContract object. Convert the array containing cost values like cashflows, present values, etc. (objects of dimension tx5x3) to a matrix with dimensions (tx15)
The death benefit will be the full sumInsured for the first year after the
deferral period and then decrease like an annuity to 0 at the end of the policyPeriod.
This can be used with the deathBenefit parameter for insurance
contracts, but should not be called directly.
deathBenefit.annuityDecreasing(interest)deathBenefit.annuityDecreasing(interest)
interest |
The interest rate of the loan, which is underlying the insurance. |
This function is a mere generator function, which takes the interest rate and generates a function that describes a decreasing annuity.
The generated function has the following parameters:
The desired length of the Cash flow vector (can be shorter than the policyPeriod, if q_x=1 before the end of the contract, e.g. for life-long insurances)
The full parameter set of the insurance contract (including all inherited values from the tariff and the profit participation)
The values calculated from the insurance contract so far
vector of decreasing death benefits
The death benefit will be the full sumInsured for the first year after the
deferral period and then decrease linearly to 0 at the end of the policyPeriod.
This can be used with the deathBenefit parameter for insurance
contracts, but should not be called directly.
deathBenefit.linearDecreasing(len, params, values)deathBenefit.linearDecreasing(len, params, values)
len |
The desired length of the Cash flow vector (can be shorter than the policyPeriod, if q_x=1 before the end of the contract, e.g. for life-long insurances) |
params |
The full parameter set of the insurance contract (including all inherited values from the tariff and the profit participation) |
values |
The values calculated from the insurance contract so far |
vector of linearly decreasing benefits over the whole insurance coverage period
Checks that object and expected are approximately equal using an
element-wise absolute tolerance. This is similar to
testthat::expect_equal(), but uses abs(x - y) <= tolerance as the
element-wise criterion and treats missing reference values as a no-op.
expect_equal_abs( object, expected, ..., tolerance = 0.01, info = NULL, label = NULL, expected.label = NULL )expect_equal_abs( object, expected, ..., tolerance = 0.01, info = NULL, label = NULL, expected.label = NULL )
object |
Expression or value producing the actual result. |
expected |
Expression or value producing the reference result.
If |
... |
Additional arguments forwarded to |
tolerance |
A non-negative numeric scalar. The maximum allowed
absolute difference per element. Default: |
info |
A character string appended to the failure message. |
label, expected.label
|
Optional labels used in messages to describe
|
The comparison is vectorised and applies the rule abs(x - y) <= tolerance
element-wise. All elements must satisfy the rule for the expectation to pass.
The function mirrors testthat conventions:
On success, it succeeds silently and returns object invisibly.
On failure, it throws an expectation error with a waldo diff.
Special handling:
If expected is NULL or all values in expected are NA, the check
is skipped and the expectation succeeds silently. Similarly, individual
NA entries in expected are skipped and allow any value in object.
Invisibly returns object on success; otherwise signals a testthat
expectation failure.
testthat::expect_equal(), waldo::compare()
# Passes: absolute differences ≤ 0.01 expect_equal_abs(c(1, 2, 3), c(1.001, 1.999, 3.0001), tolerance = 0.01) # Fails with a waldo diff when any element exceeds tolerance ## Not run: expect_equal_abs(c(1, 2, 3), c(1.1, 2, 3), tolerance = 0.05) ## End(Not run) # Skips check when expected is NULL or all NA expect_equal_abs(1:3, NULL) expect_equal_abs(1:3, c(NA, NA, NA)) # Forward options to waldo::compare for clearer diffs ## Not run: expect_equal_abs(1:3, 1:3 + 1e-4, tolerance = 0, ignore_attr = TRUE, max_diffs = 10) ## End(Not run)# Passes: absolute differences ≤ 0.01 expect_equal_abs(c(1, 2, 3), c(1.001, 1.999, 3.0001), tolerance = 0.01) # Fails with a waldo diff when any element exceeds tolerance ## Not run: expect_equal_abs(c(1, 2, 3), c(1.1, 2, 3), tolerance = 0.05) ## End(Not run) # Skips check when expected is NULL or all NA expect_equal_abs(1:3, NULL) expect_equal_abs(1:3, c(NA, NA, NA)) # Forward options to waldo::compare for clearer diffs ## Not run: expect_equal_abs(1:3, 1:3 + 1e-4, tolerance = 0, ignore_attr = TRUE, max_diffs = 10) ## End(Not run)
Export an insurance contract (object of class InsuranceContract) to an 'Excel' file
exportInsuranceContract.xlsx(contract, filename)exportInsuranceContract.xlsx(contract, filename)
contract |
The insurance contract to export |
filename |
Target 'Excel' file name for export |
The function exportInsuranceContract.xlsx exports an object
of class InsuranceContract to an 'Excel' file. All basic data, as well as
the time series of (absolute and unit) cash flows, reserves, premiums, premium
composition and all profit participation scenarios are exported to the file
in nicely looking tables.
No new calculations are done in this function. It only prints out the values
stored in contract$Values.
None
library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name = "Test Annuity", type = "annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); exportInsuranceContract.xlsx(contract, tempfile("Example_annuity_contract", fileext = ".xlsx"))library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name = "Test Annuity", type = "annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); exportInsuranceContract.xlsx(contract, tempfile("Example_annuity_contract", fileext = ".xlsx"))
Export the given contract to 'Excel' (full history/timeseries of all cash flows, reserves, premiums, etc.) and to a text file (sample calculation required by the Austrian regulation).
exportInsuranceContractExample( contract, prf = 10, outdir = ".", basename = NULL, extraname = NULL, ... )exportInsuranceContractExample( contract, prf = 10, outdir = ".", basename = NULL, extraname = NULL, ... )
contract |
The |
prf |
The time of the premium waiver |
outdir |
The output directory (the file names are not configurable) |
basename |
The base output filename (sans .xlsx). If missing, a name of the form 2020-08-01_TARIFNAME_EXTRANAME_RZ0.01_x35_YoB1977_LZ45_PrZ20_VS100000 is used. If given, the main contract without modification will be exported to basename.xlsx, while the example with premium waiver will be exported to basename_PremiumWaiver_t10.xlsx and the text file containing the examples required by the LV-VMGV is exported to basename_VmGlg.txt. |
extraname |
If basename is not given, this allows a suffix to distinguish multiple exports. |
... |
Further parameters (passed on to |
Three output files are generated:
{DATE}_{TARIFF}_Example.xlsx: Full history/timeseries
{DATE}_{TARIFF}_Example_PremiumWaiver_t10.xlsx: Full history/timeseries
after a premium waiver at the given time prf
{DATE}_{TARIFF}_Examples_VmGlg.txt: Example calculation required for the Austrian regulation (LV-VMGLV)
None
library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); exportInsuranceContractExample(contract, prf = 10, outdir = tempdir())library("MortalityTables") mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A", mortalityTable = AVOe2005R.unisex, i=0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); exportInsuranceContractExample(contract, prf = 10, outdir = tempdir())
Replace all missing values in fields (either missing or NA) with their corresponding values from fallback. Members in fallback that are missing in fields are inserted
fallbackFields(fields, valuelist)fallbackFields(fields, valuelist)
fields |
existing list |
valuelist |
list of fields to replace in |
fields with missing values filled from the fallback data
Overwrite all existing fields in the first argument with values given in valuelist. Members of valuelist that are not yet in fields are ignored. This allows a huge valuelist to be used to fill fields in multiple lists with given structure.
fillFields(fields, valuelist)fillFields(fields, valuelist)
fields |
existing list |
valuelist |
list of fields to replace in |
updated fields list
NA entries of a vector with the previous non-NA valueSometimes one has a vector with some gaps (NA) values, which cause
problems for several numeric functions. This function fillNAgaps fills
these missing values by inserting the last preceeding non-NA-value. Leading
NA values (at the start of the vector will not be modified). If the
argument firstBack = TRUE, leading NA-values are replaced by
the first non-NA value.
Trailing NAs are always replaced by the last previous NA-value.
fillNAgaps(x, firstBack = FALSE)fillNAgaps(x, firstBack = FALSE)
x |
The vector where NA-values should be filled by repeating the last preceeding non-NA value |
firstBack |
if |
This code was taken from the R Cookbook: http://www.cookbook-r.com/Manipulating_data/Filling_in_NAs_with_last_non-NA_value/ LICENSE (from that page): The R code is freely available for use without any restrictions. In other words: you may reuse the R code for any purpose (and under any license).
vector with NAs properly replaced
This is a rather trivial helper function, which just calls dplyr::filter().
filterProfitRates(rates, classes)filterProfitRates(rates, classes)
rates |
data.frame containing all profit rates for multiple profit classes |
classes |
the profit classes, for which rates should be extracted |
Tariffs are typically calculated with yearly premium installments. When premiums are paid more often then one a year (in advance), the insurance receives part of the premium later (or not at all in case of death), so a surcharge for premium payment frequencies higher than yearly is applied to the premium, typically in the form of a percentage of the premium.
This function generates the internal data structure to define surcharges for monthly, quarterly and semiannual premium payments. The given surcharges can be either given as percentage points (e.g. 1.5 means 1.5% = 0.015) or as fractions of 1 (i.e. 0.015 also means 1.5% surcharge). The heuristics applied to distinguish percentage points and fractions is that all values larger than 0.1 are understood as percentage points and values 0.1 and lower are understood as fractions of 1. As a consequence, a frequency charge of 10% or more MUST be given as percentage points.
Currently, the frequency charges are internally represented as a named list,
list("1" = 0, "2" = 0.01, "4" = 0.02, "12" = 0.03), but that might
change in the future, so it is advised to use this function rather than
explicitly using the named list in your code.
freqCharge(monthly = 0, quarterly = 0, semiannually = 0, yearly = 0)freqCharge(monthly = 0, quarterly = 0, semiannually = 0, yearly = 0)
monthly |
Surcharge for monthly premium payments |
quarterly |
Surcharge for quarterly premium payments |
semiannually |
Surcharge for semi-annual premium payments |
yearly |
Surcharge for yearly premium payments (optiona, default is no surcharge) |
a named list of surcharges for names 1 (yearly), 2 (semiannually), 4 (quarterly) and 12 (monthly) payments
While the package allows individual tariff object to be created and used, one can also register the tariffs for each company with the package.
get.tariff(Company, Produkt, GV = NULL, AV = NULL)get.tariff(Company, Produkt, GV = NULL, AV = NULL)
Company |
The (short) identifier for the company. Must contain only letters, digits and periods (i.e. a valid R identifier, given as string). |
Produkt |
The short product/tariff ID to identify the tariff. |
GV |
The (optional) profit group ("Gewinnverband") for the product. |
AV |
The (optional) profit sub-group ("Abrechnungsveband") for the product |
After registering the tariff/product with the function register.tariff(),
this function can be used to retrieve the InsuranceTarif object using
the given ID.
The InsuranceTarif object defining the tariff/product.
library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV") Tariff.ImmAnnuity = get.tariff("ExVAG", "ImmAnn1")library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV") Tariff.ImmAnnuity = get.tariff("ExVAG", "ImmAnn1")
While the package allows individual tariff object to be created and used, one can also register the tariffs for each company with the package.
get.tariffs(Company = NULL)get.tariffs(Company = NULL)
Company |
The (short) identifier for the company. Must contain only letters, digits and periods (i.e. a valid R identifier, given as string). If NULL, the list of all tariffs for all companies is returned. |
After registering the tariff/product with the function register.tariff(),
this function can be used to retrieve the InsuranceTarif object using
the given ID.
The list of InsuranceTarif objects registered for the company
library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV") get.tariffs("ExVAG")library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV") get.tariffs("ExVAG")
Set all entries of the given vector to 0 up until index 'start'
head0(v, start = 0, value.start = 0)head0(v, start = 0, value.start = 0)
v |
the vector to modify |
start |
how many leading elements to zero out |
value.start |
the value to insert before the start index. |
the vector v with the first start elements replaced by 0.
head0(1:10, 3)head0(1:10, 3)
Initialize a cost matrix with dimensions: {CostType, Basis, Period}, where:
alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts
SumInsured, SumPremiums, GrossPremium, NetPremium, Benefits, Constant
once, PremiumPeriod, PremiumFree, PolicyPeriod, CommissionPeriod
This cost structure can then be modified for non-standard costs using the setCost() function.
The main purpose of this structure is to be passed to InsuranceContract or
InsuranceTarif definitions.
initializeCosts( costs, alpha, Zillmer, alpha.ongoing, alpha.commission, beta, gamma, gamma.paidUp, gamma.premiumfree, gamma.contract, gamma.afterdeath, gamma.fullcontract, unitcosts, unitcosts.PolicyPeriod )initializeCosts( costs, alpha, Zillmer, alpha.ongoing, alpha.commission, beta, gamma, gamma.paidUp, gamma.premiumfree, gamma.contract, gamma.afterdeath, gamma.fullcontract, unitcosts, unitcosts.PolicyPeriod )
costs |
(optional) existing cost structure to duplicate / use as a starting point |
alpha |
Alpha costs (charged once, relative to sum of premiums) |
Zillmer |
Zillmer costs (charged once, relative to sum of premiums) |
alpha.ongoing |
Alpha costs charged with every premium (relative to gross premium) |
alpha.commission |
Alpha costs (charged during the commission period,
relative to sum of premiums; Use the |
beta |
Collection costs (charged on each gross premium, relative to gross premium) |
gamma |
Administration costs while premiums are paid (relative to sum insured) |
gamma.paidUp |
Administration costs for paid-up contracts (relative to sum insured) |
gamma.premiumfree |
Administration costs for planned premium-free period (reltaive to sum insured) |
gamma.contract |
Administration costs for the whole contract period (relative to sum insured) |
gamma.afterdeath |
Administration costs after the insured person has dies (for term-fix insurances) |
gamma.fullcontract |
Administration costs for the full contract period, even if the insured has already dies (for term-fix insurances) |
unitcosts |
Unit costs (absolute monetary amount, during premium period) |
unitcosts.PolicyPeriod |
Unit costs (absolute monetary amount, during full contract period) |
an insurance cost structure (multi-dimensional matrix)
# empty cost structure (only 0 costs) initializeCosts() # the most common cost types can be given in initializeCosts() initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001) # The same cost structure manually costs.Bsp = initializeCosts(); costs.Bsp[["alpha", "SumPremiums", "once"]] = 0.04; costs.Bsp[["Zillmer", "SumPremiums", "once"]] = 0.025; costs.Bsp[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05; costs.Bsp[["gamma", "SumInsured", "PolicyPeriod"]] = 0.001; # The same structure using the setCost() function: library(magrittr) costs.Bsp = initializeCosts() %>% setCost("alpha", "SumPremiums", "once", 0.04) %>% setCost("Zillmer", "SumPremiums", "once", 0.025) %>% setCost("beta", "GrossPremium", "PremiumPeriod", 0.05) %>% setCost("gamma", "SumInsured", "PolicyPeriod", 0.001)# empty cost structure (only 0 costs) initializeCosts() # the most common cost types can be given in initializeCosts() initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001) # The same cost structure manually costs.Bsp = initializeCosts(); costs.Bsp[["alpha", "SumPremiums", "once"]] = 0.04; costs.Bsp[["Zillmer", "SumPremiums", "once"]] = 0.025; costs.Bsp[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05; costs.Bsp[["gamma", "SumInsured", "PolicyPeriod"]] = 0.001; # The same structure using the setCost() function: library(magrittr) costs.Bsp = initializeCosts() %>% setCost("alpha", "SumPremiums", "once", 0.04) %>% setCost("Zillmer", "SumPremiums", "once", 0.025) %>% setCost("beta", "GrossPremium", "PremiumPeriod", 0.05) %>% setCost("gamma", "SumInsured", "PolicyPeriod", 0.001)
R6 class that models a complete, general insurance contract. The corresponding tariff and the profit participation scheme, as well as all other relevant contract parameters (if not defined by the tariff or explicitly overridden by the contract) can be given in the constructor.
The typical usage of this class is to simply call
InsuranceContract$new().
All parameters from the InsuranceContract.ParameterDefaults can be passed
to the constructor of the class (i.e. the InsuranceContract$new()-call).
Parameters not explicitly given, will be taken from the tariff or as a fall-back
mechanism from the InsuranceContract.ParameterDefaults defaults.
Immediately upon construction, all premiums, reserves and cash flows for the
whole contract period are calculated and can be accessed via the Values
field of the object.
The calculation of all contract values is controlled by the function
InsuranceContract$calculateContract() (using methods of the InsuranceTarif
object) and follows the following logic:
First the contingent (unit) cash flows and the transition probbilities are determined.
The actuarial equivalence principle states that at time of inception, the (net and gross) premium must be determined in a way that the present value of the future benefits and costs minus the present value of the future premiums must be equal, i.e. in expectation the future premiums ove the whole lifetime of the contract will exactly cover the benefits and costs. Similarly, at all later time steps, the difference between these two present values needs to be reserved (i.e. has already been paid by the customer by previous premiums).
This allows the premiums to be calculated by first calculating the present values for all of the benefit and costs cash flow vectors.
The formulas to calculate the gross, Zillmer and net premiums involve simple linear combinations of these present values, so the coefficients of these formulas are determined next.
With the coefficients of the premium formulas calculated, all premiums can be calculated (first the gross premium, because due to potential gross premium refunds in case of death, the formula for the net premium requires the gross premium, which the formula for the gross premium involves no other type of premuim).
With premiums determined, all unit cash flows and unit present values can now be expressed in monetary terms / as absolute cash flows (i.e. the actual Euro-amount that flows rather than a percentage).
As described above, the difference between the present values of premiums and present values of benefits and costs is defined as the required amount of reserves, so the reserves (net, gross, administration cost, balance sheet) and all values derived from them (i.e. surrender value, sum insured in case of premium waiver, etc.) are calculated.
The decomposition of the premium into parts dedicated to specific purposes (tax, rebates, net premium, gross premium, Zillmer premium, cost components, risk premium, savings premium, etc.) can be done once the reserves are ready (since e.g. the savings premium is defined as the difference of discounted reserves at times $t$ and $t+1$).
If the contract has (discretionary or obligatory) profit sharingB mechanisms
included, the corresponding ProfitParticipation object can calculate that
profit sharing amounts, once all guaranteed values are calculated. This can
also be triggered manually (with custom profit sharing rates) by calling
the methods InsuranceContract$profitScenario()]
or InsuranceContract$addProfitScenario().
An insurance contract is basically defined by the (unit) cash flows it produces:
Premium payments (in advance or in arrears) at each timestep
Survival payments at each timestep
Guaranteed payments at each timestep
Death benefits at each timestep
Disease benefits at each timestep
Together with the transition probabilities (mortalityTable parameter) the present values can be calculated, from which the premiums follow and finally the reserves and a potential profit sharing.
For example, a term life insurance with regular premiums would have the following cash flows:
premium cash flows: 1, 1, 1, 1, 1, ...
survival cash flows: 0, 0, 0, 0, 0, ...
guaranteed cash flows: 0, 0, 0, 0, 0, ...
death benefit cash flows: 1, 1, 1, 1, 1, ...
A single-premium term life insurance would look similar, except for the premiums:
premium cash flows: 1, 0, 0, 0, 0, ...
A pure endowment has no death benefits, but a survival benefit of 1 at the maturity of the contract:
premium cash flows: 1, 1, 1, 1, 1, ...
survival cash flows: 0, 0, ..., 0, 1
guaranteed cash flows: 0, 0, 0, 0, 0, ...
death benefit cash flows: 0, 0, 0, 0, 0, ...
An endowment has also death benefits during the contract duration:
premium cash flows: 1, 1, 1, 1, 1, ...
survival cash flows: 0, 0, ..., 0, 1
guaranteed cash flows: 0, 0, 0, 0, 0, ...
death benefit cash flows: 1, 1, 1, 1, 1, ...
A (deferred) annuityB has premium cash flows only during the deferral peroid and only survival cash flows during the annuity payment phase. Often, in case of death during the deferral period, all premiums paid are refunded as a death benefit.:
premium cash flows: 1, 1, ..., 1, 0, 0, 0, ...
survival cash flows: 0, 0, ..., 0, 1, 1, 1,...
guaranteed cash flows: 0, 0, 0, 0, 0, ...
death benefit cash flows: 1, 2, 3, 4, 5, ..., 0, 0, ...
A terme-fix (termfix) insurance has a guaranteed payment at maturity, even if the insured has already died. The premiums, however, are only paid until death (which is not reflected in the contingent cash flows, but rather in the transition probabilities):
premium cash flows: 1, 1, 1, 1, ..., 1
survival cash flows: 0, 0, 0, 0, ..., 0
guaranteed cash flows: 0, 0, 0, ..., 0, 1
death benefit cash flows: 0, 0, 0, 0, ..., 0
tarifThe InsuranceTarif underlying this contract. The tarif is the abstract product description (i.e. defining the type of insurance, fixing tpyes of benefits, specifying costs, guaranteed interest rate, mortality tables, potential profit sharing mechanisms, etc.), while the contract holds the individual parts like age, sum insured, contract duration, premium payment frequency, etc.
parentA pointer to the parent contract. Some contracts consist of multiple parts (e.g. a main savings contract with a dread-disease rider, or a contract with multiple dynamic increases). These are internally represented by one InsuranceContract object per contract part, plus one contract object combining them and deriving combined premiums, reserves and profit participation. The child contracts (i.e. the objects representing the individual parts) have a pointer to their parent, while the overall contract holds a list of all its child contract parts.
ContractParametersInsurance contract parameters explicitly specified in the contract (i.e. parameters that are NOT taken from the tariff of the defaults). The possible structure follows the InsuranceContract.ParameterStructure, but only values explicitly set for this contract are filled, without any fallback values taken from the tariff, profit scheme or the global defaults.
ParametersFull set of insurance contract parameters applying to this contract. The structure of this field follows InsuranceContract.ParameterStructure. The set of parameters is a combination of explicitly given (contract-specific) values, parameters determined by the tariff and default values.
ValuesList of all contract values (cash flows, present values, premiums, reserves, premium decomposition, profit participation, etc.). These values will be calculated and filled when the contract is created and updated whenever the contract is changed.
The fields of the array are:
contract ... A pointer to the InsuranceContract object
tarif ... A pointer to the underlying InsuranceTarif object
basicData ... A data.frame with colums PremiumPayment, SumInsured, Premiums, InterestRate, PolicyDuration, PremiumPeriod. Each row describes one year of the contract.
int ... A list of internal contract values:
l ... Length of the underlying data.frames
policyTerm ... The real-life policy term of the whole contract, evaluated numerically and cut at the maximum age of the mortality table.
premiumTerm ... The real-life premium term of the contract, evaluated numerically and cut at the maximum age and the policy term.
premiumCalculateionTime ... The time at which the currently stored premiums are calculated from the contract cash flows.
maxAge ... The maximum age available in the mortality table.
transitionProbabilities ... The transition probabilities (and the corresponding ages) relevant for the contract, derived from the mortality table. Columns are age, qx, ix, px.
cashFlowsBasic* ... The underlying basic cash flows, from which the actual unit cash flows will be built.
cashFlows* ... A data.frame containing the unit cash flows (for sum insured 1) of the contract: premiums, guaranteed, survival, death and disease cash flows (both in arrears and in advance where applicable), as well as additional capital insertions and premium refunds.
cashFlowsCosts* ... A array containing all cost cash flows for the whole contract term, split by type of costs, calculation base and charging period. The corresponding dimension of the array are:
Time: "0", "1", ....,
Type of costs: "alpha", "Zillmer", "beta", "gamma", "gamma_nopremiums", "unitcosts"
Calculation base: "SumInsured", "SumPremiums", "GrossPremium", "NetPremium", "Benefits", "Constant", "Reserve"
Contingency of the cost charged: "survival", "guaranteed", "after.death" (note: different cost rates depending on premium term, payout phase, etc. are already considered in the values of the cash flow vectors! This dimension only specifies whether the cost is charged at all if the insured is alive or dead)
unitPremiumSum* ... The premium sum (for unit premiums), i.e. this is also the number of premiums to be paid.
presentValues* ... A data.frame containing the present value vectors of premiums, additional capital, guaranteed, survival, death and disease payments, as well as premium refunds and costs (aggregated!).
presentValuesCosts* ... A array containing the present values of the cost cash flows given in the cashFlowsCosts array.
premiumCoefficients* ... A nested array containing all coefficients for the premium calculation. The hierarchy of the nesting is:
Type of premium to be calculated: "gross", "Zillmer" and "net". Each of them has two children:
Coefficient for: "SumInsured" and "Premium". Each of them has two children:
Type of cash flows: "benefits" and "costs".
For "benefits", the coefficients are a vector with names as given in the cashFlows data.frame
For "costs", the coefficients are an array with the same structure as cashFlowsCosts (except for the time dimension)
premiums* ... A vector of resulting premiums: unit premiums ("unit.net", "unit.Zillmer", "unit.gross") and absolute (yearly) premiums ("net", "Zillmer", "gross", "unitcost", "written_yearly", "additional_capital") and written premiums per frequency ("written_beforetax", "tax", "written").
absCashFlows ... A data.frame containing the absolute cash flows of the contract. The structure is identical to cashFlows. For wrapper contracts, the values are aggregated from all children.
absPresentValues ... A data.frame containing the absolute present values of the cash flows of the contract. The structure is identical to presentValues. For wrapper contracts, the values are aggregated from all children.
reserves ... A data.fram holding all reserves (columns "SumInsured", "net", "Zillmer", "adequate", "gamma", "contractual", "conversion", "alphaRefund", "reduction", "PremiumsPaid", "Surrender" and "PremiumFreeSumInsured") over the whole policy term (for wrapper contracts, aggregated values from all children)
reservesBalanceSheet ... A data.frame holding all reserves for the respective balance sheet date. Columns are "date", "time" (numeric contract age in years), "net", "Zillmer", "gamma", "gross", "Balance Sheet Reserve", and "unearned Premiums"
profitParticipation ... If the tariff is profit-participating, and a profit scenario was given: a list of profit scenarios, each holding a data.frame with all profit values (profit bases, rates, assigned profits, reserves, and surrender/paid-up values, including terminal bonus funds)
premiumComposition ... A data.frame showing all components of the premium composition over the whole time horizon of the contract.
premiumCompositionSums ... A data.frame showing the premium composition as given in premiumComposition as aggregated sums.
premiumCompositionPV ... A data.frame showing the premium composition as given in premiumComposition as present values, using interest rates and mortality.
For wrapper contracts (e.g. InsuranceContract objects that do not describe a contract (slice) itself, but group together several individual contracts, e.g. a main contract with dynamic increases, riders, or a conversion to a completely different tariff), the fields marked with an asterisk * above will not be calculated, as they only make sense at the individual contract/tariff level, but not on the aggation level where multiple contract blocks are added up.
blocksFor contracts with multiple contract parts: List of all tariff blocks (independently calculated InsuranceContract objects, that are combined to one contract, e.g. dynamic/sum increases). If this field is empty, this object describes a contract block (calculated as a stand-alone tariff), otherwise it will simply be the sum of its blocks (adjusted to span the same time periods)
historyA list keeping track of all contract changes (including the whole contract state and its values before the change).
dummy.publicdummy field to allow a trailing comma after the previous field/method
new()
Create a new insurance contract (for the given tariff/product) and calculate all time series
InsuranceContract$new( tarif, parent = NULL, calculate = "all", profitid = "default", ... )
tarifThe InsuranceTarif object describing the Tariff/Product and providing defaults for the parameters.
parentFor contracts with multiple contract blocks (dynamic increases, sum increases, riders), each child is created with a pointer to its parent. NULL for single-block contracts or for the overall-contract of a multi-block contract. This parameter is used internally, but should not be used in user-written code.
calculatehow much of the contract's time series need to be calculated. See CalculationEnum for all possible values. This is usefull to prevent calculation of e.g. reserves and profit participation, when one only wants to create a grid of premiums.
profitidThe ID of the default profit participation scenario.
The default profit participation scenario uses the default
values passed, while further scenarios can be added by
InsuranceContract$addProfitScenario().
...Further parameters (age, sum insured, contract closing / begin, premium payment details, etc.) of the contract, which can also override parameters defined at the tariff-level. Possible values are all sub-fields of the InsuranceContract.ParameterDefaults data structure.
Deep-copy the contract
Returns a fully independent copy of the contract, including deep copies
of all sub-contracts/blocks stored in blocks.
The InsuranceContract$new() function creates a new
insurance contract for the given tariff, using the parameters passed
to the function (and the defaults specified in the tariff).
As soon as this function is called, the contract object calculates all time series (cash flows, premiums, reserves, profit participation) for the whole contract duration.
The most important parameters that are typically passed to the constructor are:
age ... Age of the insured person (used to derive mortalities / transition probabilities)
policyPeriod ... Maturity of the policy (in years)
premiumPeriod ... How long premiums are paid (premiumPeriod = 1
for single-premium contracts, premiumPeriod equals
policyPeriod for regular premium payments for the whole
contract period, while other premium payment durations indicate
premium payments only for shorter periods than the whole contract
duration. Contract extensions without any premium payments are
indicated by premiumPeriod=0). Default is equal to
policyPeriod
sumInsured ... The sum insured (i.e. survival benefit for
endowments, death benefit for whole/term life insurances,
annuity payments for annuities)
contractClosing ... Date of the contract beginning (typically
created using something like as.Date("2020-08-01"))
YOB ... Year of birth of the insured (for cohort mortality
tables). If not given, YOB is derived from age and
contractClosing.
deferralPeriod ... Deferral period for deferred annuities
(i.e. when annuity payments start at a future point in time).
Default is 0.
premiumFrequency ... How many premium payments per year are
made (e.g. 1 for yearly premiums, 4 for quarterly premiumd,
12 for monthly premium payments). Default is 1 (yearly premiums).
While these are the most common and most important parameters, all parameters can be overwritten on a per-contract basis, even those that are defined by the tariff. For a full list and explanation of all parameters, see InsuranceContract.ParameterDefaults.
copy()
InsuranceContract$copy()
A new object of InsuranceContract class with independently cloned blocks.
addHistorySnapshot()
Add the current state of the contract to the history list
InsuranceContract$addHistorySnapshot( time = 0, comment = "Initial contract values", type = "Contract", params = self$Parameters, values = self$Values, tarif = self$tarif, blocks = self$blocks )
timethe time described by the snapshot
commenta comment to store together with the contract state
typeThe type of action that caused a history snapshot to be stored. Typical values are "Contract" to describe the initial contract, "Premium Waiver" or "Dynamic Increase".
paramsThe set of params to be stored in the history snapshot
(default is self$Parameters, if not explicitly given)
valuesThe calculated time series of all contract values
calculated so far. Default is self$Values, if not
explicitly given
tarifThe underlying InsuranceTarif object describing the
Product/Tariff. Default is self$tarif, if not explicitly given.
blocksThe list of all contract children for contracts with multiple insurance blocks (e.g. dynamic increases, riders, etc.)
The InsuranceContract$addHistorySnapshot() function
adds the current (or the explicitly given) state of the contract
(parameters, calculated values, tarif, list of all contract blocks)
to the history list (available in the history field of the
contract, i.e. InsuranceContract$history).
# TODO
addBlock()
Add a child contract block (e.g. a dynamic increase or a rider) to an insurance contract
InsuranceContract$addBlock(
id = NULL,
block = NULL,
t = block$Values$int$blockStart,
comment = paste0("Additional block at time t=", t),
blockType = "Dynamics",
parent = self,
...
)idThe identifier of the child block to be inserted
blockThe InsuranceContract object describing the child block. If NULL (or not given at all), a copy of the parent will be created.
tThen the child block starts, relative to the parent block. The child block is calculated independently (with time 0 describing its own start), so when aggregating all values from the individual blocks to overall values for the whole contract, the child's values need to be translated to the parent contracts's time frame using this parameter
commentThe comment to use in the history snapshot.
blockTypeThe type of block to be added (e.g. Dynamics, Extension, etc.). Can be any (short) string.
parentThe parent InsuranceContract object, if any.
...parameters to be passed to InsuranceContract$new() when
block is not given and a copy of the parent should be
created with overrides.
Contracts with multiple contract blocks (typically either contracts with dynamic increases, sum increases or protection riders) are constructed by instantiating the child block (e.g. a single dynamic increase or the rider) independently with its own (shorter) duration and then inserting it into the parent contract with this function at the given time.
If no InsuranceContract object is passed as block, a copy
of the parent is created with overriding parameters given in ....
# TODO
addDynamics()
Add a dynamic increase with the same parameters as the main contract part
InsuranceContract$addDynamics(t, NewSumInsured, SumInsuredDelta, id, ...)
tThe time within the main contract when the sum increase happens. The InsuranceContract object describing the dynamic increase will still internally start at its own time 0, but the aggregation by the main contract will correctly offset to the time $t$ within the main contract.
NewSumInsuredThe over-all new sum insured (sum of original
contract and all dynamica increaeses). The sumInsured
of the new dynamic increase block will be determined as the
difference of the old and new overall sum insured. Alternatively,
it can directly be given as the SumInsuredDelta
argument instead.
SumInsuredDeltaThe sum insured of only the dynamic increase,
i.e. the sumInsured of the dynamic contract block only. The
overall sum insured will increase by this amount. Only one of
NewSumInsured and SumInsuredDelta is needed,
the other one will be calculated accordingly. If both are
given, the SumInsuredDelta will take precedence.
idThe identifier of the contract block describing the dynamic increase. This is a free-form string that should be unique within the list of child blocks. It will be displayed in the 'Excel' export feature and in the history snapshot list.
...Parameters to override in the dynamic block. By default, all parameters of the main contract block will be used, but they can be overridden per dynamic increase block.
This method adds a new contract block describing a dynamic
or sum increase (increasing the sum insured at a later time
$t$ than contract inception). This increase is modelled by a
separate InsuranceContract object with the sum difference
as its own sumInsured.
By default, all parameters are taken from the main contract,
with the maturity adjusted to match the original contract's
maturity.
The main contract holds all child blocks, controls their
valueation and aggregates all children's values to the
total values of the overall contract.
# TODO
addExtension()
Add a contract extension after the contract has ended (existing reserve is used as initial capital of the follow-up contract).
InsuranceContract$addExtension(
id = NULL,
t = NULL,
comment = paste0("Contract extension at time t=", t),
...
)idThe identifier of the child block to be inserted
tThe time of the extension (relative to the parent block), by default contract expiration of the parent block. The extension is calculated independently (with time 0 describing its own start), but using the existing reserve as initialCapital and the parent's parameters as fall-back values.
commentThe comment to use in the history snapshot.
...Additional parameters to be passed to
InsuranceContract$new to create the contract
extension object.
When a contract expires, this function adds a follow-up contract
(with either the same or a different tariff), using the existing
reserve as additionalCapital at inception.
Technically, a child block using the new contract data of the extension
is added to the original contract. The over-all contract values are then
the sum of the original contract (providing values until expiration)
and the extension (providing values after the extension).
# TODO
calculateContract()
Calculate all time series of the contract from the parameters
InsuranceContract$calculateContract( calculate = "all", valuesFrom = 0, premiumCalculationTime = 0, preservePastPV = TRUE, additionalCapital = 0, recalculatePremiums = TRUE, recalculatePremiumSum = TRUE, history_comment = NULL, history_type = "Contract" )
calculateWhich values to calculate. See CalculationEnum
valuesFromCalculate only values starting from this time step on (all values before that time will be preserved). This is required when a contract is changed significantly (potentially even switching to a new tariff), so that the calculation bases for previous periods are no longer available.
premiumCalculationTimeThe time point when the premium should be re-calculated (including existing reserves) based on the actuarial equivalence principle. All reserves will be based on these new premiums.
preservePastPVWhether present value before the recalculation
time valuesFrom should be preserved or recalculated.
When they are recalculated, the present values are consistent
to the new cash flows over the whole contract period, but
they no longer represent the actual contract state at these
times. If values are not recalculated, the reserves at each
time step represent the proper state at that point in time.
additionalCapitalThe capital that is added to the contract (e.g. capital carried over from a previous contract) at the premium calculation time.
recalculatePremiumsWhether the premiums should be recalculated
at time premiumCalculationTime at all.
recalculatePremiumSumWhether to recalculate the overall premium sum when the premium is recalculated.
history_commentThe comment for the history snapshot entry
history_typeThe type (free-form string) to record in the history snapshot
This method calculates all contract values (potentially
starting from and preserving all values before a later time
valuesFrom). This function is not meant to be called
directly, but internally, whenever a contract is created or
modified.
There is, however, a legitimate case to call this function
when a contract was initially created with a value of
\code{calculate} other than "all", so not all values of the
contract were calculated. When one later needs more values
than were initially calculated, this function can be called.
However, any contract changes might need to be rolled back
and reapplied again afterwards. So even in this case it is
probably easier to create the contract object from scratch
again.
consolidateBlocks()
Aggregate values from all child contract blocks (if any)
InsuranceContract$consolidateBlocks(valuesFrom = 0)
valuesFromThe time from when to aggragate values. Values before that time will be left unchanged.
This function is an internal function for contracts with multiple child blocks (dynamic increases, sum increases, riders). It takes the values from all child blocks and calculates the overall values from all child blocks aggregated.
This function should not be called manually.
premiumWaiver()
Stop premium payments and re-calculate sumInsured of the paid-up contract
InsuranceContract$premiumWaiver(t, ...)
tTime of the premium waiver.
...Further parameters (currently unused)
This function modifies the contract at time $t$ so that
no further premiums are paid (i.e. a paid-up contract) and the
sumInsured is adjusted according to the existing reserves.
# TODO
profitScenario()
Calculate one profit scenario and return all values
InsuranceContract$profitScenario(...)
...Scenario-specific profit sharing parameters, overriding the default values. Typically, adjusted profit rates are required in a profitScenario.
This function calculates one profit scenario with the provided profit participation parameters (all parameters not given in the call are taken from their values of the contract, profit participation scheme or tariff).
a data.frame holding all profit participation values (rates, bases for the different profit types, profit allocations, terminal bonus funds, profit in case of death/surrender/premium waiver)
# TODO
addProfitScenario()
Calculate one profit scenario and store it in the contract
InsuranceContract$addProfitScenario(id, ...)
idThe unique ID of the profit scenario. Will be used as key in the list of profit scenarios and printed out in the 'Excel' export.
...Scenario-specific profit sharing parameters, overriding the default values. Typically, adjusted profit rates are required in a profitScenario.
This function calculates one profit scenario with the provided profit participation parameters (all parameters not given in the call are taken from their values of the contract, profit participation scheme or tariff). The results are stored in a list of profit scenarios inside the contract.
This function can be chained to calculate and add multiple
profit scenarios.
# TODO
getCFlength()
Retrieve the actual length of all cashflows, derived from the contract's parameters
Getter method to get the actual cash flow length for benefits, premiums, costs, etc. The returned value takes into account the policyPeriod parameter, but also the maximum age of the underlying mortality tables and potentially other parameters.
The return value also includes time steps that are zero by definition, i.e. for the premiums cash flows, the return value will also include the remaining policy period after the premium payment phase. It merely returns the maximum length that algorithms must / should consider.
InsuranceContract$getCFlength()
The length of the corresponding cash flow vectors/matrices. In many cases, it will be equal to policyPeriod, but might be shorter (e.g. if the mortality table ends before the contractual policy period) or longer in exceptional cases.
getPolicyTerm()
Retrieve the actual length of the contract's maturity, factoring in the length of the mortality table
Getter method to get the actual policy duration, taking into account the policyPeriod parameter, but also the maximum age of the underlying mortality tables and potentially other parameters.
InsuranceContract$getPolicyTerm()
The length of the whole contract period. In many cases, it will be equal to policyPeriod, but might be shorter (e.g. if the mortality table ends before the contractual policy period) or longer in exceptional cases.
getPremiumTerm()
Retrieve the actual length of the contract's premium payment term, factoring in the length of the mortality table
Getter method to get the actual premium payment term, taking into account the premiumPeriod and policyPeriod parameters, but also the maximum age of the underlying mortality tables and potentially other parameters.
InsuranceContract$getPremiumTerm()
The length of the premium payment period. In many cases, it will be equal to premiumPeriod or policyPeriod, but might be shorter (e.g. if the mortality table ends before the contractual policy period) or longer in exceptional cases.
clone()
The objects of this class are cloneable with this method.
InsuranceContract$clone(deep = FALSE)
deepWhether to make a deep clone.
# TODO ## ------------------------------------------------ ## Method `InsuranceContract$addHistorySnapshot` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addBlock` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addDynamics` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addExtension` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$premiumWaiver` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$profitScenario` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addProfitScenario` ## ------------------------------------------------ # TODO# TODO ## ------------------------------------------------ ## Method `InsuranceContract$addHistorySnapshot` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addBlock` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addDynamics` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addExtension` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$premiumWaiver` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$profitScenario` ## ------------------------------------------------ # TODO ## ------------------------------------------------ ## Method `InsuranceContract$addProfitScenario` ## ------------------------------------------------ # TODO
A new contract will be pre-filled with these values, and values passed in the constructor (or with other setter functions) will override these values.
InsuranceContract.ParameterDefaultsInsuranceContract.ParameterDefaults
The parameter list is a list of lists with the following structure:
Sublists:
$ContractData ... Contract-specific data (policy period,
closing, age, sum insured, premium payments, etc.)
$ContractState ... Current contract state (paid-up, surrender
penalty already applied, alpha costs already (partially) refunded)
$ActuarialBases ... Actuarial bases for the contract
calculation (mortality/invalidity table, guaranteed interest,
surrender penalty, etc.)
$Costs, $minCosts ... Expenses charged to the contract (see initializeCosts())
$Loadings ... Loadings, rebates and other charges of the
tariff / contract (tax, unit costs, surcharge for no medial exam, premium/benefit frequency loading)
$Features ... Peculiarities of the tariff (to enable
non-standard formulas for certain company-specific historical
"glitches" in the tariff definitions.)
$ProfitParticipation ... Profit scheme and profit participation
rates (default values, can be overwritten per profit scenario)
$Hooks ... Hook functions to allow modification of various
calculation aspects (e.g. modify the default cash flows after
their setup)
InsuranceContract.ParameterDefault$ContractData
These values are typically set per contract and not by the tariff. Notable exceptions are the contract duration in some instances and the premiumPeriod=1 for single-premium contracts.
$idID of the contract (to distinguish individual parts in contracts with multiple parts, e.g. dynamic increases), default = "Hauptvertrag"
$sumInsuredSum insured, default = 100,000
$premiumPremium, given to determine the sumInsured (default: NULL)
$initialCapitalReserve/Capital that is already available at contract inception, e.g. from a previous contract. No tax or acquisition costs are applied to this capital.
$YOB (deprecated)Year of birth of the insured, used to determine the age for the application of the mortality table
$birthDateDate of birth of the insured, used to determine the
age for the application of the mortality table. Alternatively,
the year alone can be passed as YOB.
$ageAge of the insured
$technicalAgeTechnical age of the insured (when the age for the application of the mortality table does not coincide with the real age)
$ageDifferencesVector of age differences to the first insured for contracts with multiple insured (i.e. joint-lives)
$sexSex of the insured, to allow gender-specific prixing (e.g. different mortalities or age modification), default="unisex", Type is SexEnum
$policyPeriodPolicy Duration (in years)
$premiumPeriodPremium payment period (in year), for
single-premium contracts, premiumPeriod = 1. Default is
policyPeriod, i.e. regular premiums during the whole
contract period
$deferralPerioddeferral period for annuities, i.e. the period survival payments start only after this period, typically the retirement age. This applies mostly to tariffs of type annuity, although deferral periods are possible (but not common) for all other types of insurance, too.
$guaranteedPeriodguaranteed annuity payment period. The annuity pays out for this period, even if the insured dies. This applies only to tariffs of type annuity.
$contractClosingThe date (variable of type lubridate::Date) when
the coverage of the contract starts (not neccessarily equal to
the date when the contract was signed). Typically generated by
a call to as.Date(). The year is relevant to derive the age
of the insured, while month and day are relevant for the
interpolation of the balance sheet reserves
$blockStartFor contracts with multiple blocks (e.g. multiple dynamic increases, where each increase is modelled like a separate contract), this variable holds the offset of the current contract block relative to the main contract block. The main block starts a 0, dynamic increases start later! This value is only used by the parent block (i.e. $t=0$ of the child is aligned with $t=blockStart$ of the parent block.
$premiumPaymentsWhether premiums are paid in advance (default) or arrears. Value is of type PaymentTimeEnum with possible values "in advance" and "in arrears"
$benefitPaymentsWhether recurring benefits (e.g. annuities) are paid in advance (default) or arrears. Value is of type PaymentTimeEnum with possible values "in advance" and "in arrears"
$premiumFrequencyNumber of premium payments per year, default is 1.
$benefitFrequencyNumber of benefit payments per year, default is 1.
$premiumRefundProportion of (gross) premiums refunded on death (including additional risk, e.g. 1.10 = 110% of paid premiums)
$premiumRefundPeriodThe period, during which the premium
refund on death applies. By default, deferred contracts will
refund premiums only during the deferral period, all other
contracts during the whole contract. Default is
premiumRefundPeriod.default
$premiumIncreaseThe yearly growth factor of the premium, i.e. 1.05 means +5% increase each year; a vector describes the premiums for all years
$annuityIncreaseThe yearly growth factor of the annuity payments, i.e. 1.05 means +5% increase each year; a vector describes the annuity unit payments for all years
$deathBenefitThe yearly relative death benefit (relative
to the initial sum insured); Can be set to a function(len,
params, values), e.g. deathBenefit = deathBenefit.linearDecreasing
$survivalBenefitThe survival benefit (relative to the initial
sum insured). By default, for (pure) endowments a survival benefit
of 1 is assumed at the end of the contract period. Other values
(e.g. double survival benefit in endowments) or multiple survival
payments during the contract period can be set with this parameter.
A single numeric value indicates a single survival benefit at
the end of the contract, a vector of numeric values indicates
yearly survival benefits (not neccessarily with a survival
payment at the end of the contract). Can be set to a function(len,
params, values) returning the benefit as a numeric value or vector.
$benefitParameter(optional) Tariff-specific parameter to
indicate special benefit conditions (e.g. for non-constant benefits
the initial starting value, or a minimum benefit, etc.). This
parameter is not used automatically, but needs to be processed
by a custom $deathBenefit function.
$costWaiverThe fraction of the costs that are waived (only
those cost components that are defined to be waivable, i.e. by
defining a corresponding $minCosts). Linearly interpolates
between $Costs and $minCosts, if the latter is set.
Otherwise is has no effect.
$attributesAdditional custom attributes (as a named list), which can be used for particular behaviour of different contracts or contract slices.
InsuranceContract.ParameterDefault$ContractState
Contract-specific status variables holding the status of the contract.
$premiumWaiverWhether the contract is paid-up.
$surrenderPenaltyWhether a surrender penalty still applies (e.g. because it has already been applied during a contract change, or because due to legal reasons it can no longer be applied)
$alphaRefundedWhether alpha costs have (at least partially) been refunded (e.g. when a contract is changed or paid-up). Default is not yet refunded.
InsuranceContract.ParameterDefault$ActuarialBases
Tarif-specific actuarial calculation parameters of the contract. Typically, these values are set by the tariff, but can be overridden by contract (e.g. while prototyping a new product or a product change).
$mortalityTableThe mortalityTable object describing the mortality of the insured
$invalidityTableFor contracts with invalidity benefits, the mortalityTable object describing the probabilities of invalidity
$invalidityEndsContractFor contracts with invalidity benefits, whether a payment of an invalidity benefit ends the contract.
$iGuaranteed yearly interest rate, default is 0.00, i.e. 0%
$balanceSheetDateThe day/month when balance sheet reserves
are calculated. Value of type lubridate::Date, typically generated with
as.Date(). The year is actually irrelevant, only the day and
month are relevant.
$balanceSheetMethodHow to interpolate the balance sheet
reserves (at the balandeSheetDate) from the yearly contractual
reserves. Either a string "30/360", "act/act", "act/360", "act/365"
or a function with signature balanceSheetMethod(params, contractDates, balanceDates)
that returns a vector of coefficients for each year to
interpolate the reserves available at the given contractDates
for the desired balanceDates
$unearnedPremiumsMethodHow to calculate the unearned
premiums (considering the balance sheet date and the premium
frequency). A function with signature unearnedPremiumsMethod(params, dates)
$surrenderValueCalculationA function describing the surrender
value calculation. If NULL, the full reserve will be used as
surrender value. If given, it must be a function with signature
function(SurrenderReserve, params, values).
$paidUpSumCalculationA function describing the calculation
of the paid-up sum insured If given, it must be a function
with signature function(res, absPV, params, values), where
res is a data.frame of the calculated reserves.
$premiumFrequencyOrderOrder of the approximation for payments within the year (unless an extra frequency loading is used => then leave this at 0)
$benefitFrequencyOrderOrder of the approximation for payments within the year (unless an extra frequency loading is used => then leave this at 0)
InsuranceContract.ParameterDefault$Costs
Definition of contractual costs charged to the contract. See initializeCosts().
$CostsThe full cost defined for the contract / tariff,
usually set with initializeCosts() and setCost()
$minCostsThe minimum costs defined for the contract / tariff
that cannot be waived. Either an explicit cost definition structure
generated by initializeCosts() and setCost(), or a
function(params, values, costs), where the full costs are passed
as third parameter, so the function can modify only those cost parts
that can be waived at all.
InsuranceContract.ParameterDefault$Loadings
$ongoingAlphaGrossPremiumAcquisition cost that increase the gross premium
$taxinsurance tax, factor on each premium paid, default is 4%, i.e. i=0.04
$unitcostsAnnual unit cost for each policy, absolute value (can be a function)
$securityAdditional security loading on all benefit payments, factor on all benefits
$noMedicalExamLoading when no medicial exam is done, % of SumInsured
$noMedicalExamRelativeLoading when no medicial exam is done, % of gross premium
$sumRebategross premium reduction for large premiums, % of SumInsured
$extraRebategross premium reduction for any reason, % of SumInsured
$premiumRebategross premium reduction for large premiums, % of gross premium
$partnerRebateRebate on premium with all surcharges and rebates when more than one contract is written with identical parameters. Sums with advanceBonusInclUnitCost and premiumRebate.
$extraChargeGrossPremiumextra charges on gross premium (smoker, leisure activities, BMI too high, etc.)
$benefitFrequencyLoadingLoading on the benefit for premium
payment frequencies of more than once a year. Format is
list("1" = 0.0, "2" = 0.0, "4" = 0.0, "12" = 0.0)
$premiumFrequencyLoadingLoading on the premium for premium
payment frequencies of more than once a year. Format is
list("1" = 0.0, "2" = 0.0, "4" = 0.0, "12" = 0.0)
$alphaRefundPeriodHow long the acquisition costs should be (partially) refunded in case of surrender or premium waiver.
$commissionPeriodPeriod, over which the acquisition costs are charged to the contract (if not fully up-front or over the whole contract period). This has only an effect for cost definitions with duration "CommissionPeriod". Default is 5 years.
InsuranceContract.ParameterDefault$Features
$zillmeringWhether the contract uses Zillmering (and bases reserves on the Zillmer reserve as opposed to the adequate reserve) (default: TRUE)
$betaGammaInZillmerWhether beta and gamma-costs should be included in the Zillmer premium calculation
$gammaInZillmerWhether gamma- (but not beta-) costs should be included in the Zillmer premium calculation
$alphaRefundLinearWhether the refund of alpha-costs on surrender is linear in t or follows the NPV of an annuity
$useUnearnedPremiumsWhether unearned premiums should be reported in the balance sheet reserves. Otherwise, a premium paid at the beginning of the period is added to the reserve at that time for balance-sheet purposes. For regular premiums, the default is TRUE, i.e. the balance-sheet reserve at time $t$ does not include the premium paid at time $t$, but unearned premiums are included in the balance sheet reserves. For single-premium contracts, there are no "unearned" premiums, but the initial single premium is added to the reserve immediately for balance-sheet purposes. In particular, the balance sheet reserve at time $t=0$ is not 0, but the premium paid. In turn, no unearned premiums are applied.
$surrenderIncludesCostsReservesWhether (administration) cost reserves are paid out on surrender (i.e. included in the surrender value before surrender penalties are applied)
$unitcostsInGrossWhether unit costs are included in the gross premium calculation or added after gross premiums. (default: FALSE)
$absPremiumRefundConstant death benefit (typically premium refund of a previous contract), relative to the sum insured.
$alphaCostsCommissionWhether alpha costs over the commision period are given as their actual yearly value ("actual"), or whether the given value is the sum ("sum") or the present value ("presentvalue") over the whole commission period.
$surrenderPenaltyOnPremiumWaiverWhether the surrender penalty is also applied to premium waivers (but no longer on surrenders after a premium waiver), or only on surrenders (with or without a preceding premium waiver). (default: TRUE)
InsuranceContract.ParameterDefault$ProfitParticipation
Parameters describing the profit participation (instance of ProfitParticipation) Most element descrive some kind of profit rate (which can vary in time), while the bases, on which they are applied is defined in the profit scheme.
$advanceProfitParticipationAdvance profit participation rate (percentage rebate of the gross premium)
$advanceProfitParticipationInclUnitCostAdvance profit participation rate (percentage rebate on the gross premium after all surcharges and unit costs.
$waitingPeriodWaiting period of the profit sharing (e.g. no profit in the first two years of a contract, or similar)
$guaranteedInterestIndividual contract-specific overrides of the guaranteed interest rate (i.e. not keyed by year)
$interestProfitRateInterest profit rate (guaranteed interest rate + interest profit rate = total credited rate)
$totalInterestTotal credited rate (guarantee + interest profit)
$mortalityProfitRateMortality Profit rate
$expenseProfitRateExpense profit rate
$sumProfitRateSum profit rate (for high sumInsured)
$terminalBonusRateTerminal bonus rate (non-terminal-bonus fund, but "old" Austrian terminal bonus)
$terminalBonusFundRateTerminal bonus fund rate
$profitParticipationSchemeProfit participation scheme (object of class ProfitParticipation)
$profitComponentsProfit components of the profit scheme. List containing one or more of c("interest", "risk", "expense", "sum", "terminal")
$profitClassString describing the profit class the tariff is assigned to. Profit classes are used to bundle similar contracts (e.g. following similar risks) together. Profit participation rates are defined at the level of profit classes.
$profitRatesGeneral, company-wide profit rates, key columns are year and profitClass
$profitAttributionAtExpirationWhether the profit attribution at expiration is relevant or should be zeroed out. The latter is needed when profits are calculated at the balance sheet date and assigned on the next policy anniversarz
$scenariosprofit participation scenarios (list of overridden parameters for each scenario)
InsuranceContract.ParameterDefault$Hooks
$adjustCashFlowsFunction with signature function(x, params, values, ...) to adjust the benefit/premium cash flows after their setup.
$adjustCashFlowsCostsFunction with signature function(x, params, values, ...) to adjust the costs cash flows after their setup.
$adjustCostsFunction with signature function(costs, params, values, ...) to adjust the tariff costs after their setup (e.g. contract-specific conditions/waivers, etc.).
$adjustMinCostsFunction with signature function(minCosts, costs, params, values, ...) to adjust the tariff minimum (unwaivable) costs after their setup (e.g. contract-specific conditions/waivers, etc.).
$adjustPresentValuesAdjust the present value vectors that are later used to derive premiums and reserves. function(presentValues, params, values)
$adjustPresentValuesCostsAdjust the present value cost vectors used to derive premiums and reserves. function(presentValuesCosts, params, values)
$adjustPremiumCoefficientsFunction with signature function(coeff, type, premiums, params, values, premiumCalculationTime) to adjust the coefficients for premium calculation after their default setup. Use cases are e.g. term-fix tariffs where the Zillmer premium term contains the administration cost over the whole contract, but not other gamma- or beta-costs.
$adjustPremiumsAdjust the resulting premiums. function(premiums = list(premiums, coefficients, sumInsured), params, values)
$adjustPVForReservesAdjust the absolute present value vectors used to derive reserves (e.g. when a sum rebate is subtracted from the gamma-cost reserves without influencing the premium calculation). function(absPV, params, values)
$premiumRebateCalculationCalculate the actual premium rebate from the rebate rate (e.g. when the premium rate is given as a yearly cost reduction applied to a single-premium contract). function(premiumRebateRate, params = params, values = values)
$RoundingA RoundingHelper object to specify rounding of intermediate values. Alternatively, a named list of rounding specifications can be given, which is used to construct a new RoundingHelper object.
InsuranceContract.ParameterDefaultsInsuranceContract.ParameterDefaults
Provide default values for the insurance contract parameters if any of the parameters is not explicitly set.
InsuranceContract.ParametersFallback(params, fallback, ppParameters = TRUE)InsuranceContract.ParametersFallback(params, fallback, ppParameters = TRUE)
params |
Current, explicitly set contract parameters. All NULL values
will be filled with the corresponding entry from |
fallback |
Fallback values that will be used when the corresponding
entry in |
ppParameters |
Whether profit participation parameters should also be filled (default is TRUE) |
Initialize the insurance contract parameters from the passed arguments. Arguments not given are left unchanged. If no existing parameter structure is given, an empty (i.e. all NULL entries) structure is used.
InsuranceContract.ParametersFill( params = InsuranceContract.ParameterStructure, costs = NULL, minCosts = NULL, ... )InsuranceContract.ParametersFill( params = InsuranceContract.ParameterStructure, costs = NULL, minCosts = NULL, ... )
params |
Initial values of the insurance contract parameters. (default: empty parameter structure) |
costs, minCosts, ...
|
Values for any of the entries in the insurance contract
parameter structure. These values take precedence over the
initial parameters provided in |
All values are filled with NULL,
so the functions InsuranceContract.ParametersFill and
InsuranceContract.ParametersFallback can be used to override
existing parameters or to provide default values for unset (NULL) entries.
InsuranceContract.ParameterStructureInsuranceContract.ParameterStructure
An object of class list of length 9.
Data structure (filled only with NULL) for insurance contract class member values.
InsuranceContract.ValuesInsuranceContract.Values
An object of class list of length 19.
The class InsuranceTarif provides the code and general
framework to implement contract-independent functionality of a life insurance
product.
This is a base class for holding contract-independent values and
providing methods to calculate cash flows, premiums, etc. Objects of this
class do NOT contain contract-specific values like age, death probabilities,
premiums, reserves, etc. Rather, they are the calculation kernels that will
be called by the InsuranceContract objects to make the actual,
tariff-specific calculations.
Most methods of this class are not meant to be called manually, but are supposed
to be called by the InsuranceContract object with contract-specific information.
The only methods that are typically used for defining an insurance tariff are
the constructor InsuranceTarif$new() and the cloning method
InsuranceTarif$createModification().
All other methods should never be called manually.
However, as overriding private methods is not possible in an R6 class, all the methods need to be public to allow overriding them in derived classes.
nameThe tariff's unique name. Will also be used as the key for exported data.
tarifThe tariff's public name (typically a product name), not necessarily unique.
descA short human-readable description of the tariff and its main features.
tariffTypeAn enum specifying the main characteristics of the tarif. Possible values are:
Whole life or term annuity (periodic survival benefits) with flexible payouts (constand, increasing, decreasing, arbitrary, etc.)
A whole or term life insurance with only death benefits. The benefit can be constant, increasing, decreasing, described by a function, etc.
An endowment with death and survival benefits, potentially with different benefits.
A pure endowment with only a survival benefit at the end of the contract. Optionally, in case of death, all or part of the premiums paid may be refunded.
A terme-fix insurance with a fixed payout at the end of the contract, even if the insured dies before that time. Premiums are paid until death of the insured.
A dread-disease insurance, which pays in case of a severe illness (typically heart attacks, cancer, strokes, etc.), but not in case of death.
A combination of an endowment and a temporary dread-disease insurance. Benefits occur either on death, severe illness or survival, whichever comes first.
ParametersA data structure (nested list) containing all relevant parameters describing a contract, its underlying tariff, the profit participation scheme etc. See InsuranceContract.ParameterStructure for all fields.
dummyDummy field to allow commas after the previous method
new()
Initialize a new tariff object
InsuranceTarif$new( name = NULL, type = "wholelife", tarif = "Generic Tarif", desc = "Description of tarif", ... )
nameThe unique name / ID of the tariff
typeAn enum specifying the main characteristics of the tarif. See TariffTypeEnum
tarifThe tariff's public name to be stored in the tarif field.
descA short human-readable description to be stored in the desc field.
...Parameters for the InsuranceContract.ParameterStructure, defining the characteristics of the tariff.
The constructor function defines a tariff and generates the corresponding data structure, which can then be used with the InsuranceContract class to define an actual contract using the tariff.
The arguments passed to this function will be stored inside the
Parameters field of the class, inside one of the lists sublists.
The parameters are stacked from different layers (higher levels override
default values from lower layers):
InsuranceContract object (parameters passed directly to the individual contract)
ProfitParticipation object (parameters for profit participation, passed to the definition of the profit plan, which is used for the tarif definition or the contract)
InsuranceTarif object (parameters passed to the definition of the tariff that was used for the contract)
Defaults taken from InsuranceContract.ParameterStructure
The general implementation of this parameter layering means that (a) a tariff can already provide default values for contracts (e.g. a default maturity, default sum insured, etc) and (b) individual contracts can override all parameters defined with the underlying tariff. In particular the latter feature has many use-cases in prototyping: E.g. when you have a tariff with a guaranteed interest rate of 1\ one can immediately instantiate a contract with an updated interest rate or mortality table for comparison. There is no need to re-implement a tariff for such comparisons, as long as only parameters are changed.
MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
i = 0.01, mortalityTable = AVOe2005R.male)
createModification()
create a copy of a tariff with certain parameters changed
InsuranceTarif$createModification( name = NULL, tarif = NULL, desc = NULL, tariffType = NULL, ... )
nameThe unique name / ID of the tariff
tarifThe tariff's public name to be stored in the tarif field.
descA short human-readable description to be stored in the desc field.
tariffTypeAn enum specifying the main characteristics of the tarif. See TariffTypeEnum
...Parameters for the InsuranceContract.ParameterStructure, defining the characteristics of the tariff.
This method createModification returns a copy of the tariff
with all given arguments changed in the tariff's InsuranceTarif$Parameters
parameter list.
As InsuranceTarif is a R6 class with reference logic, simply assigning the object to a new variable does not create a copy, but references the original tariff object. To create an actual copy, one needs to call this method, which first clones the whole object and then adjusts all parameters to the values passed to this method.
MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
i = 0.01, mortalityTable = AVOe2005R.male)
tarif.unisex = tarif.male$createModification(name = "Annuity unisex",
mortalityTable = AVOe2005R.unisex)
getParameters()
Retrieve the parameters for this tariff (can be overridden for each contract)
InsuranceTarif$getParameters()
tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
i = 0.01, mortalityTable = AVOe2005R.male)
tarif.male$getParameters()
updateInternalValues()
Update some internal parameters cached (length of data.frames, policy periods cut at max.age, etc.)
InsuranceTarif$updateInternalValues(int, params, ...)
intcurrent cached internal values
paramsparameters of the contract
...currently unused
This method is not meant to be called explicitly, but rather used by the InsuranceContract class. It returns a list of maturities and ages relevant for the contract-specific calculations
getCFlength()
Retrieve the actual length of all cashflows, derived from the contract's parameters
Getter method to get the actual cash flow length for benefits, premiums, costs, etc. The returned value takes into account the policyPeriod parameter, but also the maximum age of the underlying mortality tables and potentially other parameters.
The return value also includes time steps that are zero by definition, i.e. for the premiums cash flows, the return value will also include the remaining policy period after the premium payment phase. It merely returns the maximum length that algorithms must / should consider.
InsuranceTarif$getCFlength(values)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
The length of the corresponding cash flow vectors/matrices. In many cases, it will be equal to policyPeriod, but might be shorter (e.g. if the mortality table ends before the contractual policy period) or longer in exceptional cases.
getPolicyTerm()
Retrieve the actual length of the contract's maturity, factoring in the length of the mortality table
Getter method to get the actual policy duration, taking into account the policyPeriod parameter, but also the maximum age of the underlying mortality tables and potentially other parameters.
InsuranceTarif$getPolicyTerm(values)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
The length of the whole contract period. In many cases, it will be equal to policyPeriod, but might be shorter (e.g. if the mortality table ends before the contractual policy period) or longer in exceptional cases.
getPremiumTerm()
Retrieve the actual length of the contract's premium payment term, factoring in the length of the mortality table
Getter method to get the actual premium payment term, taking into account the premiumPeriod and policyPeriod parameters, but also the maximum age of the underlying mortality tables and potentially other parameters.
InsuranceTarif$getPremiumTerm(values)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
The length of the premium payment period. In many cases, it will be equal to premiumPeriod or policyPeriod, but might be shorter (e.g. if the mortality table ends before the contractual policy period) or longer in exceptional cases.
getAges()
Calculate the contract-relevant age(s) given a certain parameter data structure (contract-specific values)
InsuranceTarif$getAges(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
This method is not meant to be called explicitly, but rather used by the InsuranceContract class. It returns the relevant ages during the whole contract period
getTransitionProbabilities()
Calculate the transition probabilities from the contract-specific
parameters passed as params and the already-calculated contract
values values
InsuranceTarif$getTransitionProbabilities(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getCostValues()
Obtain the cost structure from the cost parameter and the given paremeter set
InsuranceTarif$getCostValues(params)
paramsThe parameters of the contract / tariff
Not to be called directly, but implicitly by the InsuranceContract object.
The cost parameter can be either an array of costs (generated by initializeCosts())
or a function with parameters param and values(=NULL) returning
an array of the required dimensions. This function makes sures that the
latter function is actually evaluated.
getPremiumCF()
Returns the unit premium cash flow for the whole contract period.
For constant premiums it will be rep(1, premiumPeriod),
for single premiums it will be c(1, 0, 0, ...),
for increasing premiums it will be (1+increase)^(0:(premiumPeriod-1)) and 0 after the premium period
InsuranceTarif$getPremiumCF(len, params, values)
lenThe desired length of the returned data frame (the number of contract periods desire)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getAnnuityCF()
Returns the unit annuity cash flow (guaranteed and contingent) for the whole annuity payment period (after potential deferral period)
For constant annuity it will be rep(1, annuityPeriod),
for increasing annuities it will be (1+increase)^(0:(premiumPeriod-1)) and 0 after the premium period
InsuranceTarif$getAnnuityCF(len, params, values)
lenThe desired length of the returned data frame (the number of contract periods desire)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getDeathCF()
Returns the unit death cash flow for the whole protection period (after potential deferral period!)
For constant death benefit it will be rep(1, policyPeriod),
for linearly decreasing sum insured it will be (policyPeriod:0)/policyPeriod
InsuranceTarif$getDeathCF(len, params, values)
lenThe desired length of the returned data frame (the number of contract periods desired)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getSurvivalCF()
Returns the unit survival cash flow profile for the whole contract period (after potential deferral period!)
a single numeric value indicates a single survival payment at the end of the contract
a vector of numeric values indicates potentially multiple survival payments for the whole contract period (paddded with 0 to the full contract length if shorter)
InsuranceTarif$getSurvivalCF(len, params, values)
lenThe desired length of the returned data frame (the number of contract periods desired)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getBasicCashFlows()
Returns the basic (unit) cash flows associated with the type
of insurance given in the InsuranceTarif's tariffType field
InsuranceTarif$getBasicCashFlows(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getCashFlows()
Returns the cash flows for the contract given the parameters
InsuranceTarif$getCashFlows(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getCashFlowsCosts()
Returns the cost cash flows of the contract given the contract and tariff parameters
InsuranceTarif$getCashFlowsCosts(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
presentValueCashFlows()
Returns the present values of the cash flows of the contract
(cash flows already calculated and stored in the cashFlows data.frame)
InsuranceTarif$presentValueCashFlows(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
cashFlowsdata.frame of cash flows calculated by a call to InsuranceTarif$getCashFlows()
Not to be called directly, but implicitly by the InsuranceContract object.
presentValueCashFlowsCosts()
Calculates the present values of the cost cash flows of the
contract (cost cash flows alreay calculated by InsuranceTarif$getCashFlowsCosts()
and stored in the values list
InsuranceTarif$presentValueCashFlowsCosts(params, values, presentValues)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
presentValuesThe present values of the insurance claims (without costs)
Not to be called directly, but implicitly by the InsuranceContract object.
getAbsCashFlows()
Calculate the cash flows in monetary terms of the insurance contract
InsuranceTarif$getAbsCashFlows(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Once the premiums of the insurance contracts are calculated, all cash flows can also be expressed in absolute terms. This function calculates these time series in monetary terms, once the premiums are calculated by the previous functions of this class.
This method is NOT to be called directly, but implicitly by the InsuranceContract object.
getAbsPresentValues()
Calculate the absolute present value time series of the insurance contract
InsuranceTarif$getAbsPresentValues(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Once the premiums of the insurance contracts are calculated, all present values can also be expressed in absolute terms. This function calculates these time series in monetary terms, once the premiums and the unit-benefit present values are calculated by the previous functions of this classe.
This method is NOT to be called directly, but implicitly by the InsuranceContract object.
presentValueBenefits()
Calculate the absolute present value time series of the benefits of the insurance contract
InsuranceTarif$presentValueBenefits(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Once the premiums of the insurance contracts are calculated, all present values can also be expressed in absolute terms. This function calculates these time series of the benefits present values in monetary terms, once the premiums and the unit-benefit present values are calculated by the previous functions of this classe.
This method is NOT to be called directly, but implicitly by the InsuranceContract object.
getPremiumCoefficients()
Calculate the linear coefficients of the premium calculation formula for the insurance contract
InsuranceTarif$getPremiumCoefficients( type = "gross", coeffBenefits, coeffCosts, premiums, params, values, premiumCalculationTime = values$int$premiumCalculationTime )
typeThe premium that is supposed to be calculated ("gross", "Zillmer", "net")
coeffBenefits(empty) data structure of the benefit coefficients. The actual values have no meaning, this parameter is only used to derive the required dimensions
coeffCosts(empty) data structure of the cost coefficients. The actual values have no meaning, this parameter is only used to derive the required dimensions
premiumsThe premium components that have already been calculated (e.g. for net and Zillmer, the gross premium has already been calculated to allow modelling the premium refund)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
premiumCalculationTimeThe time when the premiums should be (re-)calculated according to the equivalence principle. A time 0 means the initial premium calculation at contract closing, later premium calculation times can be used to re-calculate the new premium after a contract change (possibly including an existing reserve)
Not to be called directly, but implicitly by the InsuranceContract object.
When getPremiumCoefficients is called, the values$premiums
array has NOT yet been filled! Instead, all premiums already calculated
(and required for the premium coefficients) are passed in the premiums
argument.
sumInsuredCalculation()
Calculate the sumInsured of the InsuranceContract given the
parameters and premiums given and teh , present values already calculated and
stored in the params and values lists.
InsuranceTarif$sumInsuredCalculation( params, values, calculationTime = values$int$premiumCalculationTime )
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
calculationTimethe time when the sumInsured should be recalculated from the given premium
Not to be called directly, but implicitly by the InsuranceContract object.
premiumCalculation()
Calculate the premiums of the InsuranceContract given the
parameters, present values and premium cofficients already calculated and
stored in the params and values lists.
InsuranceTarif$premiumCalculation( params, values, premiumCalculationTime = values$int$premiumCalculationTime )
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
premiumCalculationTimeThe time when the premiums should be (re-)calculated according to the equivalence principle. A time 0 means the initial premium calculation at contract closing, later premium calculation times can be used to re-calculate the new premium after a contract change (possibly including an existing reserve)
Not to be called directly, but implicitly by the InsuranceContract object.
reserveCalculation()
Calculate the reserves of the InsuranceContract given the
parameters, present values and premiums already calculated and stored in
the params and values lists.
InsuranceTarif$reserveCalculation(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
getBalanceSheetReserveFactor()
Calculate the (linear) interpolation factors for the balance sheet reserve (Dec. 31) between the yearly contract closing dates
InsuranceTarif$getBalanceSheetReserveFactor(method, params, years = 1)
methodThe method for the balance sheet interpolation (30/360, act/act, act/360, act/365 or a function(params, contractDates, balanceDates) or a numeric scalar or vector). The function needs to return a numeric vector with values from 0 to 1, which will be used as the interpolation factors between the contractual reserves of t-1 and t. Similarly, a numeric scalar or vector gives the constant interpolation factors.
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
yearshow many years to calculate (for some usances, the factor is different in leap years!)
Not to be called directly, but implicitly by the InsuranceContract object.
reserveCalculationBalanceSheet()
Calculate the reserves for the balance sheets at Dec. 31 of each year by interpolation from the contract values calculated for the yearly reference date of the contract
InsuranceTarif$reserveCalculationBalanceSheet(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
calculateProfitParticipation()
Calculate the profit participation given the contract parameters and the already calculated reserves of the contract.
InsuranceTarif$calculateProfitParticipation(params, ...)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
...Additional parameters for the profit participation calculation, passed
through to the profit participation scheme's ProfitParticipation$getProfitParticipation()
Not to be called directly, but implicitly by the InsuranceContract object.
reservesAfterProfit()
Calculate the reserves after profit participation for the given profit scenario
InsuranceTarif$reservesAfterProfit(profitScenario, params, values, ...)
profitScenarioThe ID of the profit scenario for which to calculate the reserves
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
...TODO
Not to be called directly, but implicitly by the InsuranceContract object.
getBasicDataTimeseries()
Return the time series of the basic contract
InsuranceTarif$getBasicDataTimeseries(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object.
premiumDecomposition()
Calculate the time series of the premium decomposition of the contract
InsuranceTarif$premiumDecomposition(params, values)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
Not to be called directly, but implicitly by the InsuranceContract object. All premiums, reserves and present values have already been calculated.
calculateFutureSums()
Generic function to calculate future sums of the values
InsuranceTarif$calculateFutureSums(cf, ...)
cfThe time series, for which future sums at all times are desired
...currently unused
calculatePresentValues()
Calculate all present values for a given time series. The mortalities are taken from the contract's parameters.
InsuranceTarif$calculatePresentValues(cf, params, values)
cfThe time series, for which future present values at all times are desired
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
...currently unused
evaluateFrequencyLoading()
Calculate the premium frequency loading, i.e. the surcharge on the premium for those cases where the premium is not paid yearly. Return values can be either a numeric value or a named list with all possible premium frequencies as keys.
InsuranceTarif$evaluateFrequencyLoading(loading, frequency, params, values)
loadingThe premiumFrequencyLoading parameter of the Contract or Tariff to be evaluated
frequencyThe premiumFrequency parameter of the contract
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (in the contract$Values
list) then this method is called by the contract object
clone()
The objects of this class are cloneable with this method.
InsuranceTarif$clone(deep = FALSE)
deepWhether to make a deep clone.
# Define an insurance tariff for 10-year endowments, using a guaranteed interest # rate of 1% and the Austrian population mortality table of the census 2011. # Premiums are paid monthly in advance during the whole contract period. MortalityTables::mortalityTables.load("Austria_Census") # Cost structure: # - 4% up-front acquisition costs (of premium sum) # - 1% collection cost of each premium paid # - 1%o yearly administration cost (of the sum insured) as long as premiums are paid # - 2%o yearly administration cost for paid-up contracts # - 10 Euro yearly unit costs (as long as premiums are paid) costs.endw = initializeCosts(alpha = 0.04, beta = 0.01, gamma = 0.001, gamma.paidUp = 0.002, gamma.premiumfree = 0.002, unitcosts = 10) endowment.AT1 = InsuranceTarif$new( name = "Endow AT 1%", type = "endowment", tarif = "Austrian Endowment", desc = "An endowment for Austrian insured with 1% interest and no profit participation", ContractPeriod = 10, i = 0.01, mortalityTable = mort.AT.census.2011.unisex, costs = costs.endw, premiumFrequency = 12) # The instantiation of the actual contract will provide the contract specific # information and immediately calculate all further values: ctr.end.AT1 = InsuranceContract$new(tarif = endowment.AT1, contractClosing = as.Date("2020-07-01"), age = 42) # All values for the contract are already calculated during construction and # stored in the ctr.end.AT1$Values list: ctr.end.AT1$Values$basicData ctr.end.AT1$Values$transitionProbabilities ctr.end.AT1$Values$cashFlowsCosts ctr.end.AT1$Values$presentValues ctr.end.AT1$Values$premiums ctr.end.AT1$Values$reserves ctr.end.AT1$Values$premiumComposition # etc. ## ------------------------------------------------ ## Method `InsuranceTarif$new` ## ------------------------------------------------ MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R") tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity", i = 0.01, mortalityTable = AVOe2005R.male) ## ------------------------------------------------ ## Method `InsuranceTarif$createModification` ## ------------------------------------------------ MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R") tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity", i = 0.01, mortalityTable = AVOe2005R.male) tarif.unisex = tarif.male$createModification(name = "Annuity unisex", mortalityTable = AVOe2005R.unisex) ## ------------------------------------------------ ## Method `InsuranceTarif$getParameters` ## ------------------------------------------------ tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity", i = 0.01, mortalityTable = AVOe2005R.male) tarif.male$getParameters()# Define an insurance tariff for 10-year endowments, using a guaranteed interest # rate of 1% and the Austrian population mortality table of the census 2011. # Premiums are paid monthly in advance during the whole contract period. MortalityTables::mortalityTables.load("Austria_Census") # Cost structure: # - 4% up-front acquisition costs (of premium sum) # - 1% collection cost of each premium paid # - 1%o yearly administration cost (of the sum insured) as long as premiums are paid # - 2%o yearly administration cost for paid-up contracts # - 10 Euro yearly unit costs (as long as premiums are paid) costs.endw = initializeCosts(alpha = 0.04, beta = 0.01, gamma = 0.001, gamma.paidUp = 0.002, gamma.premiumfree = 0.002, unitcosts = 10) endowment.AT1 = InsuranceTarif$new( name = "Endow AT 1%", type = "endowment", tarif = "Austrian Endowment", desc = "An endowment for Austrian insured with 1% interest and no profit participation", ContractPeriod = 10, i = 0.01, mortalityTable = mort.AT.census.2011.unisex, costs = costs.endw, premiumFrequency = 12) # The instantiation of the actual contract will provide the contract specific # information and immediately calculate all further values: ctr.end.AT1 = InsuranceContract$new(tarif = endowment.AT1, contractClosing = as.Date("2020-07-01"), age = 42) # All values for the contract are already calculated during construction and # stored in the ctr.end.AT1$Values list: ctr.end.AT1$Values$basicData ctr.end.AT1$Values$transitionProbabilities ctr.end.AT1$Values$cashFlowsCosts ctr.end.AT1$Values$presentValues ctr.end.AT1$Values$premiums ctr.end.AT1$Values$reserves ctr.end.AT1$Values$premiumComposition # etc. ## ------------------------------------------------ ## Method `InsuranceTarif$new` ## ------------------------------------------------ MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R") tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity", i = 0.01, mortalityTable = AVOe2005R.male) ## ------------------------------------------------ ## Method `InsuranceTarif$createModification` ## ------------------------------------------------ MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R") tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity", i = 0.01, mortalityTable = AVOe2005R.male) tarif.unisex = tarif.male$createModification(name = "Annuity unisex", mortalityTable = AVOe2005R.unisex) ## ------------------------------------------------ ## Method `InsuranceTarif$getParameters` ## ------------------------------------------------ tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity", i = 0.01, mortalityTable = AVOe2005R.male) tarif.male$getParameters()
Regular premium contracts are identified by the parameter premiumPeriod > 1.
isRegularPremiumContract(params, values)isRegularPremiumContract(params, values)
params |
The parameters of the contract. |
values |
Unused by default (already calculated values of the contract) |
TRUE or FALSE, indicating a contract with regular premiums
Single premium contracts are identified by the parameter premiumPeriod = 1.
isSinglePremiumContract(params, values)isSinglePremiumContract(params, values)
params |
The parameters of the contract. |
values |
Unused by default (already calculated values of the contract) |
TRUE or FALSE, indicating a single-premium contract or not
Uses a Shiny checkbox GUI if shiny is available (e.g., in RStudio), otherwise falls back to a text-based multi-select list.
LIC_debug_configure(title = "LifeInsureR debug options")LIC_debug_configure(title = "LifeInsureR debug options")
title |
Dialog title. |
Preselects options that are currently TRUE.
Provides Select all / Select none controls (Shiny UI).
Provides a Cancel button that exits without changes.
The selected options will be set to TRUE, all un-selected options will be set to FALSE.
Invisibly, a named logical vector of all keys and their values after setting; returns NULL if cancelled.
contractGrid()
The function makeContractGridDimname generates a short, human-readable
dimension label for the entries along the axes of a contractGrid().
The default is to use the value unchanged as the row-/columnname, but
for some parameter values (like a InsuranceTarif or mortalityTable)
a custom method of this function is needed to create the (short) human-readable
representation for the axes in the grid.
The function makeContractGridDimnames generate proper
dimnames for all entries of the axes of a contractGrid() by calling
makeContractGridDimname on each of the axes' values
makeContractGridDimname(value) makeContractGridDimnames(axes)makeContractGridDimname(value) makeContractGridDimnames(axes)
value |
the value along the axis, for which a name should be generated |
axes |
the axes with all names, for which a name should be generated |
The name of the entry in the dimnames of contractGrid()
an array of dimnames derived from the axes definitions of contractGrid()
makeContractGridDimname(): Create a short, human-readable dimensional name for an object (default S3 method)
makeContractGridDimnames(): Generate proper dimnames for all entries of the axes of a contractGrid()
library(MortalityTables) mortalityTables.load("Austria_Census") makeContractGridDimname(mort.AT.census.2011.unisex) makeContractGridDimnames(axes = list( age = seq(30,60,10), mortalityTable = c(mort.AT.census.2011.unisex, mort.AT.census.2011.male, mort.AT.census.2011.female)) )library(MortalityTables) mortalityTables.load("Austria_Census") makeContractGridDimname(mort.AT.census.2011.unisex) makeContractGridDimnames(axes = list( age = seq(30,60,10), mortalityTable = c(mort.AT.census.2011.unisex, mort.AT.census.2011.male, mort.AT.census.2011.female)) )
Pad a vector with 0 to a desired length
pad0(v, l, value = 0, start = 0, value.start = 0)pad0(v, l, value = 0, start = 0, value.start = 0)
v |
the vector to pad with 0 |
l |
the desired (resulting) length of the vector |
value |
the value to pad with (if padding is needed). Default to 0, but can be overridden to pad with any other value. |
start |
the first |
value.start |
the value to insert before the start index. |
returns the vector v padded to length l with value value (default 0).
pad0(1:5, 7) # Pad to length 7 with zeroes pad0(1:5, 3) # no padding, but cut at length 3 # 3 leading zeroes, then the vector start (10 elements of vector, no additional padding needed): pad0(1:10, 13, start = 3) # padding with value other than zero: pad0(1:5, 7, value = "pad")pad0(1:5, 7) # Pad to length 7 with zeroes pad0(1:5, 3) # no padding, but cut at length 3 # 3 leading zeroes, then the vector start (10 elements of vector, no additional padding needed): pad0(1:10, 13, start = 3) # padding with value other than zero: pad0(1:5, 7, value = "pad")
v to length l by repeating the last entry of the
vector.This function is just a trivial wrapper around pad0 and only calls pad0()
with the last element of the vector as padding value instead of the default 0.
padLast(v, ...)padLast(v, ...)
v |
the vector to pad by repeating the last element |
... |
arguments passed through to |
vector padded to the correct length
padLast(1:5, 7) # 5 is repeated twice padLast(1:5, 3) # no padding neededpadLast(1:5, 7) # 5 is repeated twice padLast(1:5, 3) # no padding needed
Enum to describe when a benefit or premium payment is due (in advance or in arrears)
Currently, only two values are allowed;
"in advance"
"in arrears"
While the package allows individual tariff object to be created and used, one can also register the tariffs for each company with the package.
prepare.tariff(Company, Tariff, type = "endowment", destfile = NULL)prepare.tariff(Company, Tariff, type = "endowment", destfile = NULL)
Company |
The (short) identifier for the company. Must contain only letters, digits and periods (i.e. a valid R identifier, given as string). |
Produkt |
The short product/tariff ID to identify the tariff. |
GV |
The (optional) profit group ("Gewinnverband") for the product. |
AV |
The (optional) profit sub-group ("Abrechnungsveband") for the product |
After registering the tariff/product with the function register.tariff(),
this function can be used to retrieve the InsuranceTarif object using
the given ID.
The InsuranceTarif object defining the tariff/product.
library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV") Tariff.ImmAnnuity = get.tariff("ExVAG", "ImmAnn1")library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV") Tariff.ImmAnnuity = get.tariff("ExVAG", "ImmAnn1")
Enum to define the different components of profit participation.
Profit participation schemes typically consist of different components, which are calculated independently. Typical components are interest profit to distribute investment gains to the customer, risk profit and expense profit to return security margins in the biometric risk and the expenses to the customer and sum profit, which aplies to contracts with higher sums insured, where charged expenses are calculated from the sum insured, while the actual expenses are more or less constant. Thus, high contracts are charged more, which causes profits that are returned as sum profit.
As a special case, part of the profits can be stored in a terminal bonus reserve and only distributed on maturity (or potentially on death), but not on surrender. Some (older) profit participation schemes add an independently calculated bonus on maturity (e.g. twice the total profit assignment of the last year) at maturity to give customers an additional incentive not to surrender a contract.
Possible values are (multiple can be given):
"interest"
"risk"
"expense"
"sum"
"terminal"
"TBF"
Base Class for Profit Participation Schemes
Base Class for Profit Participation Schemes
Base class for Profit Participation schemes (holding contract-independent values and providing methods to calculate the profit participation values from the given reserves).
The profit participation object is typically not used directly, but rather defined once and then passed on to an InsuranceTarif or InsuranceContract object, where it will be used internally when profit participation is calculated.
This class provides the technical implementation of a profit plan for traditional life insurance contracts with a guaranteed component (calculated before the profit scheme comes into play) and a discretionary profit on top.
This function is called when a new profit participation scheme
is created with a call to ProfitParticipation$new(...). Possible
parameters to the new-Call are all parameters from the ProfitParticipation sublist of the
InsuranceContract.ParameterStructure parameter
structure (which are understood as template values that can be overridden
per contract or even per profit participation scenario) and the components
of the Functions field defining the functions to calculate the individual
components of the profit participation (rates, calculation bases, calculation, benefits)
This method createModification returns a copy of the profit scheme
with all given arguments changed in the schmes's Parameters
parameter list.
As ProfitParticipation is a R6 class with reference logic, simply assigning the object to a new variable does not create a copy, but references the original profit scheme object. To create an actual copy, one needs to call this method, which first clones the whole object and then adjusts all parameters to the values passed to this method.
The InsuranceContract's param structure InsuranceContract.ParameterStructure
contains the field params$ProfitParticipation$advanceProfitParticipation,
which can either be numeric rate for advance profit participation, or
a function with signature function(params, values, ...) that
returns the advance profit participation rate when called with the
contract's parameters and the values calculated so far (cash flows and premiums)
The InsuranceContract's param structure InsuranceContract.ParameterStructure
contains the field params$ProfitParticipation$advanceProfitParticipationInclUnitCost,
which can either be numeric rate for advance profit participation, or
a function with signature function(params, values, ...) that
returns the advance profit participation rate when called with the
contract's parameters and the values calculated so far (cash flows and premiums)
This function provides an easy way to modify the whole set of profit rates after their initial setup. Possible applications are waiting periods, which can be implemented once for all rates rather than inside each individual calculation period.
nameThe human-readable name of the profit plan.
ParametersParameter template for profit-participation-specific
parameters, i.e. the ProfitParticipation element of the
InsuranceContract.ParameterStructure data structure.
All elements defined in the profit scheme can be overriden per contract
in the call to [InsuranceContract]$new or even in the explicit
call to InsuranceContract$profitScenario()
or InsuranceContract$addProfitScenario().
Functionslist of functions defined to calculate the individual components. For each of the profit components
interest profit
risk profit
expense profit
sum profit
terminal bonus
terminal bonus fund
a rate, a profit base and a calculation function can be defined, by assigning one of the pre-defined
ProfitParticipationFunctions or proving your own function with signature
function(rates, params, values, ...). Additionally, for each of the
benefit types (survival, death, surrender, premium waiver) a function can
be provided to calculate the benefit stemming from profit participation.
dummyDummy to allow commas in the previous method
new()
Create a new profit participation scheme
ProfitParticipation$new(name = NULL, ...)
nameThe name of the profit scheme (typicall the name of the profit plan and its version)
...profit participation parameters to be stored in the
Parameters field or calculation functions to be stored in the Functions'
field
setParameters()
Store all passed parameters in the Parameters field
ProfitParticipation$setParameters(...)
...any of the named fields defined in the ProfitParticipation sublist of the
InsuranceContract.ParameterStructure. All other arguments will be ignored
setFunctions()
Store all passed functions in the Functions field
ProfitParticipation$setFunctions(...)
...any of the functions defined in the Functions field. All other
arguments will be ignored
setFallbackParameters()
Fill all missing parameters with the default fall-back values
ProfitParticipation$setFallbackParameters()
createModification()
create a copy of a profit scheme with certain parameters changed
ProfitParticipation$createModification(name = NULL, ...)
nameThe new name for the cloned ProfitParticipation object
...Parameters for the InsuranceContract.ParameterStructure, defining the characteristics of the tariff.
getAdvanceProfitParticipation()
Calculate and return the advance profit participation (to be applied on the actuarial gross premium)
ProfitParticipation$getAdvanceProfitParticipation(params, values, ...)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (guaranteed component of the insurance contract, including cash flows, premiums, reserves etc.).
...optional parameters, to be passed to the advanceProfitParticipation field of the parameter structure (if that is a function)
Return either one numerical value (constant for the whole premium payment period) of a vector of numerical values for the whole contract period
getAdvanceProfitParticipationAfterUnitCosts()
Calculate and return the advance profit participation (to be applied after unit costs are added to the gross premium)
ProfitParticipation$getAdvanceProfitParticipationAfterUnitCosts( params, values, ... )
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (guaranteed component of the insurance contract, including cash flows, premiums, reserves etc.).
...optional parameters, to be passed to the advanceProfitParticipationInclUnitCost field of the parameter structure (if that is a function)
Return either one numerical value (constant for the whole premium payment period) of a vector of numerical values for the whole contract period
setupRates()
Set up the data.frame containing the profit participation rates
ProfitParticipation$setupRates(params, values, ...)
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (guaranteed component of the insurance contract, including cash flows, premiums, reserves etc.).
...additional parameters passed to the profit calculation functions
stored in the Functions field.
adjustRates()
Adjust the data.frame of profit participation rates after their setup
ProfitParticipation$adjustRates(rates, params, values)
ratesdata.frame of profit paticipation rates
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (guaranteed component of the insurance contract, including cash flows, premiums, reserves etc.).
getProfitParticipation()
Calculation the full time series of profit participation for the given contract values
ProfitParticipation$getProfitParticipation( calculateFrom = 0, profitScenario = NULL, params, values, ... )
calculateFromThe time from which to start calculating the profit
participation. When a contract is changed at some time t (possibly even
changing the profit scheme), all future profit participation needs to be
re-calculated from that time on, without changing past profit participation.
All values before calculateFrom will not be calculated.
profitScenarioprofit participation values from a previous calculation
(NULL if profit calculation is to be calculated from the contract inception).
Values before calculateFrom will be used from this data.frame.
paramsContract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract)
valuesContract values calculated so far (guaranteed component of the insurance contract, including cash flows, premiums, reserves etc.).
...additional parameters to be passed to ProfitParticipation$setupRates()
clone()
The objects of this class are cloneable with this method.
ProfitParticipation$clone(deep = FALSE)
deepWhether to make a deep clone.
Various helper functions for the ProfitParticipation class that
provide the building blocks for the individual components of profit participation,
the rates and how the assigned profit is calculated.
PP.base.NULL(rates, params, values, ...) PP.base.PreviousZillmerReserve(rates, params, values, ...) PP.base.ZillmerReserveT2(rates, params, values, ...) PP.base.contractualReserve(rates, params, values, ...) PP.base.previousContractualReserve(rates, params, values, ...) PP.base.meanContractualReserve(rates, params, values, ...) PP.base.meanZillmerReserve(rates, params, values, ...) PP.base.meanZillmerReserveForward(rates, params, values, ...) PP.base.ZillmerRiskPremium(rates, params, values, ...) PP.base.sumInsured(rates, params, values, ...) PP.base.totalProfitAssignment(res, ...) PP.rate.interestProfit(rates, ...) PP.rate.riskProfit(rates, ...) PP.rate.expenseProfit(rates, ...) PP.rate.sumProfit(rates, ...) PP.rate.terminalBonus(rates, ...) PP.rate.terminalBonusFund(rates, ...) PP.rate.interestProfitPlusGuarantee(rates, ...) PP.rate.interestProfit2PlusGuarantee(rates, ...) PP.rate.totalInterest(rates, ...) PP.rate.totalInterest2(rates, ...) PP.rate.interestProfit2(rates, ...) getTerminalBonusReserve( profits, rates, terminalBonus, terminalBonusAccount, params, values, ... ) PP.calculate.RateOnBase(base, rate, waiting, rates, params, values, ...) PP.calculate.RateOnBaseMin0(base, rate, waiting, rates, params, values, ...) PP.calculate.RatePlusGuaranteeOnBase( base, rate, waiting, rates, params, values, ... ) PP.calculate.RateOnBaseSGFFactor( base, rate, waiting, rates, params, values, ... ) sumProfits(profits, cols) PP.benefit.ProfitPlusTerminalBonusReserve(profits, ...) PP.benefit.Profit(profits, ...) PP.benefit.ProfitPlusGuaranteedInterest(profits, rates, ...) PP.benefit.ProfitPlusTotalInterest(profits, rates, params, values) PP.benefit.ProfitPlusHalfTotalInterest(profits, ...) PP.benefit.ProfitPlusHalfGuaranteedInterest(profits, rates, ...) PP.benefit.ProfitPlusInterestMinGuaranteeTotal(profits, rates, ...) PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal(profits, rates, ...) PP.benefit.ProfitGuaranteeSupporting(profits, rates, params, values, ...) PP.benefit.TerminalBonus5YearsProRata(profits, params, values, ...) PP.benefit.TerminalBonus5Years(profits, params, ...) PP.benefit.TerminalBonus(profits, params, ...) PP.benefit.None(profits, ...)PP.base.NULL(rates, params, values, ...) PP.base.PreviousZillmerReserve(rates, params, values, ...) PP.base.ZillmerReserveT2(rates, params, values, ...) PP.base.contractualReserve(rates, params, values, ...) PP.base.previousContractualReserve(rates, params, values, ...) PP.base.meanContractualReserve(rates, params, values, ...) PP.base.meanZillmerReserve(rates, params, values, ...) PP.base.meanZillmerReserveForward(rates, params, values, ...) PP.base.ZillmerRiskPremium(rates, params, values, ...) PP.base.sumInsured(rates, params, values, ...) PP.base.totalProfitAssignment(res, ...) PP.rate.interestProfit(rates, ...) PP.rate.riskProfit(rates, ...) PP.rate.expenseProfit(rates, ...) PP.rate.sumProfit(rates, ...) PP.rate.terminalBonus(rates, ...) PP.rate.terminalBonusFund(rates, ...) PP.rate.interestProfitPlusGuarantee(rates, ...) PP.rate.interestProfit2PlusGuarantee(rates, ...) PP.rate.totalInterest(rates, ...) PP.rate.totalInterest2(rates, ...) PP.rate.interestProfit2(rates, ...) getTerminalBonusReserve( profits, rates, terminalBonus, terminalBonusAccount, params, values, ... ) PP.calculate.RateOnBase(base, rate, waiting, rates, params, values, ...) PP.calculate.RateOnBaseMin0(base, rate, waiting, rates, params, values, ...) PP.calculate.RatePlusGuaranteeOnBase( base, rate, waiting, rates, params, values, ... ) PP.calculate.RateOnBaseSGFFactor( base, rate, waiting, rates, params, values, ... ) sumProfits(profits, cols) PP.benefit.ProfitPlusTerminalBonusReserve(profits, ...) PP.benefit.Profit(profits, ...) PP.benefit.ProfitPlusGuaranteedInterest(profits, rates, ...) PP.benefit.ProfitPlusTotalInterest(profits, rates, params, values) PP.benefit.ProfitPlusHalfTotalInterest(profits, ...) PP.benefit.ProfitPlusHalfGuaranteedInterest(profits, rates, ...) PP.benefit.ProfitPlusInterestMinGuaranteeTotal(profits, rates, ...) PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal(profits, rates, ...) PP.benefit.ProfitGuaranteeSupporting(profits, rates, params, values, ...) PP.benefit.TerminalBonus5YearsProRata(profits, params, values, ...) PP.benefit.TerminalBonus5Years(profits, params, ...) PP.benefit.TerminalBonus(profits, params, ...) PP.benefit.None(profits, ...)
rates |
data.frame of profit rates |
params |
Contract-specific, full set of parameters of the contract (merged parameters of the defaults, the tariff, the profit participation scheme and the contract) |
values |
Contract values calculated so far (guaranteed component of the insurance contract, including cash flows, premiums, reserves etc.). |
... |
Other values that might be used for the calculation (currently unused) |
res |
the data.frame of reserves. |
profits |
The array of profit participation component values |
terminalBonus |
The terminal bonus calculated |
terminalBonusAccount |
The terminal bonus account (like a bank account, where terminal bonuses are accrued, potentiall discounted from the maturity) |
base |
The profit calculation base, on which the rate is to be applied |
rate |
The profit participation rate |
waiting |
A possible waiting period |
cols |
The columns of the profit values array to be summed (columns given that do not exist in the profits array are ignired) |
PP.base.NULL(): Basis for profit: NONE (i.e. always returns 0)
PP.base.PreviousZillmerReserve(): Basis for profit: Previous Zillmer reserve (no administration cost reserve)
PP.base.ZillmerReserveT2(): Basis for profit: Zillmer reserve (no administration cost reserve) at time t-2
PP.base.contractualReserve(): Basis for profit: Contractual reserve (including administration costs) at time t
PP.base.previousContractualReserve(): Basis for profit: Contractual reserve (including administration costs) at time t-1
PP.base.meanContractualReserve(): Basis for profit: Contractual reserve (including administration costs) averaged over t and t-1
PP.base.meanZillmerReserve(): Basis for profit: Zillmer reserve (excluding administration costs) averaged over t and t-1
PP.base.meanZillmerReserveForward(): Basis for profit: Zillmer reserve (excluding administration costs) averaged over t+1 and t
PP.base.ZillmerRiskPremium(): Basis for risk/mortality profit: Zillmer Risk Premium of the past year
PP.base.sumInsured(): Basis for expense/sum profit: sum insured
PP.base.totalProfitAssignment(): Basis for Terminal Bonus Fund Assignment: total profit assignment of the year
PP.rate.interestProfit(): Returns the array of interest profit rates (keyed by year)
PP.rate.riskProfit(): Returns the array of risk profit rates (keyed by year)
PP.rate.expenseProfit(): Returns the array of expense profit rates (keyed by year)
PP.rate.sumProfit(): Returns the array of sum profit rates (keyed by year)
PP.rate.terminalBonus(): Returns the array of terminal bonus rates (keyed by year)
PP.rate.terminalBonusFund(): Returns the array of terminal bonus rates (keyed by year) as the terminal bonus fund ratio
PP.rate.interestProfitPlusGuarantee(): Rate for interest on past profits: total credited rate, but at least the guarantee
PP.rate.interestProfit2PlusGuarantee(): Rate for interest on past profits: total creditedrate2, but at least the guarantee
PP.rate.totalInterest(): Rate for interest on past profits: total interest rate
PP.rate.totalInterest2(): Rate for interest on past profits: second total interest rate
PP.rate.interestProfit2(): Rate for interest on past profits: second interest profit rate (not including guaranteed interest), keyed by year
getTerminalBonusReserve(): Calculate the terminal bonus reserve.
PP.calculate.RateOnBase(): Calculate profit by a simple rate applied on the basis (with an optional waiting vector of values 0 or 1)
PP.calculate.RateOnBaseMin0(): Calculate profit by a simple rate applied on the basis (with an optional waiting vector of values 0 or 1), bound below by 0
PP.calculate.RatePlusGuaranteeOnBase(): Calculate profit by a rate + guaranteed interest applied on the basis (with an optional waiting vector of values 0 or 1)
PP.calculate.RateOnBaseSGFFactor(): Calculate profit by a simple rate applied on the basis (with only (1-SGFFactor) put into profit participation, and an optional waiting vector of values 0 or 1)
sumProfits(): Extract the given columns of the profit participation array of values and sum
them up. Columns that do not exist, because the profit scheme does not
provide the corresponding profit component will be silently ignored.
This allows generic benefit calculation functions to be written that do
not need to distinguish e.g. whether an old-style terminal bonus or a terminal
bonus fund is provided.
This function is not meant to be called directly, but within a profit benefit calculation function.
PP.benefit.ProfitPlusTerminalBonusReserve(): Calculate survival benefit as total profit amount plus the terminal bonus reserve
PP.benefit.Profit(): Calculate benefit as total profit accrued so far
PP.benefit.ProfitPlusGuaranteedInterest(): Calculate accrued death benefit as total profit with (guaranteed) interest for one year
PP.benefit.ProfitPlusTotalInterest(): Calculate accrued death benefit as total profit with total interest (interest on profit rate) for one year
PP.benefit.ProfitPlusHalfTotalInterest(): Calculate accrued benefit as total profit with total interest (interest on profit rate) for half a year
PP.benefit.ProfitPlusHalfGuaranteedInterest(): Calculate death benefit as total profit with (guaranteed) interest for one year
PP.benefit.ProfitPlusInterestMinGuaranteeTotal(): Calculate accrued benefit as total profit with interest for one year (max of guarantee and total interest)
PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal(): Calculate accrued benefit as total profit with interest for half a year (max of guarantee and total interest)
PP.benefit.ProfitGuaranteeSupporting(): Calculate accrued benefit as regular profit, but used to cover initial Zillmerization
PP.benefit.TerminalBonus5YearsProRata(): Calculate benefit from terminal bonus as 1/n parts of the terminal bonus reserve during the last 5 years
PP.benefit.TerminalBonus5Years(): Terminal bonus is only paid out during the last 5 years of the contract (but never during the first 10 years)
PP.benefit.TerminalBonus(): Calculate benefit from terminal bonus (full bonus), either old-style terminal bonus reserve or Terminal Bonus Fund (TBF)
PP.benefit.None(): No benefit paid out
PVfactory (R6Class for present values with arbitrary dimensions)
PVfactory (R6Class for present values with arbitrary dimensions)
provides functions to calculate present values for survival, death, dread disease, invalidity and guaranteed benefits in various dimensions
new()
Initialize the present value factory with defaults for qx, interest and multiple payments per year
PVfactory$new(qx, m = 1, mCorrection = list(alpha = 1, beta = 0), v = 1)
qxthe vector of mortality / death probabilities
mthe number of yearly payments
mCorrectionthe list of alpha/beta to correct present values for multiple payments per year
vthe discount factor (1 / (1+i))
guaranteed()
Present values of guaranteed benefits (paid in advance or arrears, possible multiple times per year)
PVfactory$guaranteed( advance = NULL, arrears = NULL, start = 0, ..., m = private$m, mCorrection = private$mCorrection, v = private$v )
advancethe payment cashflows in advance
arrearsthe payment cashflows in arrears
startthe time index, where the PV calculation should be based
...other parameters (currently not used, for future use)
mthe number of yearly payments
mCorrectionthe list of alpha/beta to correct present values for multiple payments per year
vthe discount factor (1 / (1+i))
survival()
Present values of survival benefits (paid in advance or arrears, possible multiple times per year)
PVfactory$survival( advance = NULL, arrears = NULL, start = 0, ..., m = private$m, mCorrection = private$mCorrection, v = private$v )
advancethe payment cashflows in advance
arrearsthe payment cashflows in arrears
startthe time index, where the PV calculation should be based
...other parameters (currently not used, for future use)
mthe number of yearly payments
mCorrectionthe list of alpha/beta to correct present values for multiple payments per year
vthe discount factor (1 / (1+i))
death()
Present values of death benefits
PVfactory$death(benefits, start = 0, ..., v = private$v)
benefitsthe vector of death / invalidity / disease benefits
startthe time index, where the PV calculation should be based
...other parameters (currently not used, for future use)
vthe discount factor (1 / (1+i))
disease()
Present values of disease benefits
PVfactory$disease(benefits, start = 0, ..., v = private$v)
benefitsthe vector of death / invalidity / disease benefits
startthe time index, where the PV calculation should be based
...other parameters (currently not used, for future use)
vthe discount factor (1 / (1+i))
afterDeath()
Present values of guaranteed benefits after death (paid in advance or arrears, possible multiple times per year)
PVfactory$afterDeath( advance = NULL, arrears = NULL, start = 0, ..., m = private$m, mCorrection = private$mCorrection, v = private$v )
advancethe payment cashflows in advance
arrearsthe payment cashflows in arrears
startthe time index, where the PV calculation should be based
...other parameters (currently not used, for future use)
mthe number of yearly payments
mCorrectionthe list of alpha/beta to correct present values for multiple payments per year
vthe discount factor (1 / (1+i))
clone()
The objects of this class are cloneable with this method.
PVfactory$clone(deep = FALSE)
deepWhether to make a deep clone.
While the package allows individual tariff object to be created and used, one can also register the tariffs for each company with the package.
register.company(Company, ...)register.company(Company, ...)
Company |
The (short) identifier for the company. Must contain only letters, digits and periods (i.e. a valid R identifier, given as string). |
... |
Additional parameters to be used for creating tariff templates, etc.
Potential arguments are |
This function sets up the company data (including the short name) and other
parameters/features used for templating. Once a company is registered with a
short name (and optionally its long name and other parameters), one can register
tariffs/producs with the register.tariff() function.
None
register.company("ExVAG", name = "Example Versicherung AG")register.company("ExVAG", name = "Example Versicherung AG")
While the package allows individual tariff object to be created and used, one can also register the tariffs for each company with the package.
register.tariff(Tarif, Company, Produkt, GV = NULL, AV = NULL)register.tariff(Tarif, Company, Produkt, GV = NULL, AV = NULL)
Tarif |
The InsuranceTarif object defining the tariff/product. |
Company |
The (short) identifier for the company. Must contain only letters, digits and periods (i.e. a valid R identifier, given as string). |
Produkt |
The short product/tariff ID to identify the tariff. |
GV |
The (optional) profit group ("Gewinnverband") for the product. |
AV |
The (optional) profit sub-group ("Abrechnungsveband") for the product |
This function registers a InsuranceTarif object with the LiveInsureR
package using a given ID, so automated scripts can then retrieve the
products/tariffs based on those IDs (e.g. tariff IDs used in the policy
administration systems) using the function get.tariff().
The Tarif is returned, so this function can be chained to register the same object with multiple names or GV/AB combinations.
library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") Tariff.ImmAnnuity = InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV")library(MortalityTables) library(magrittr) mortalityTables.load("Austria_Annuities_AVOe2005R") Tariff.ImmAnnuity = InsuranceTarif$new( type = "annuity", # tarif = "Ann1", # desc = "An annuity with single-premium", premiumPeriod = 1, mortalityTable = AVOe2005R.unisex, i = 0.005 ) %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1") %>% register.tariff(Company = "ExVAG", Produkt = "ImmAnn1_BV")
Calculate the rolling mean of length 2
rollingmean(x)rollingmean(x)
x |
vector of values, for which the rolling mean is calculated |
rollingmean(1:10)rollingmean(1:10)
This function is a drop-in replacement for round that
uses mathematical rounding (round half away from zero) instead of
IEEE-754 "round to even" (banker's rounding).
round_half_up(x, digits = 0)round_half_up(x, digits = 0)
x |
A numeric vector, matrix, or array to be rounded. |
digits |
Integer indicating the number of decimal places to round to.
Positive values round to the right of the decimal point,
negative values to the left. Defaults to |
Values exactly halfway between two representable numbers (i.e. fractional
part of 0.5) are always rounded away from zero.
Apart from the tie-breaking rule, the behavior matches
round:
vectorised over x
supports positive and negative digits
preserves attributes (names, dimensions)
propagates NA, NaN, Inf
Base R's round() uses IEC 60559 / IEEE-754 rounding
("round to even") for numerical stability:
round(c(0.5, 1.5, 2.5)) # 0 2 2
This function instead implements round half away from zero:
round_half_up(c(0.5, 1.5, 2.5)) # 1 2 3
This behavior is often required in actuarial, financial, and regulatory contexts.
A numeric object of the same shape and attributes as x,
containing the rounded values.
round_half_up(1:10 + 0.5) round_half_up(c(-1.5, -0.5, 0.5, 1.5)) round_half_up(1.2345, digits = 3) round_half_up(149, digits = -1)round_half_up(1:10 + 0.5) round_half_up(c(-1.5, -0.5, 0.5, 1.5)) round_half_up(1.2345, digits = 3) round_half_up(149, digits = -1)
The class RoundingHelper provides the code and settings
to define numeric rounding rules for premiums, reserves, benefits etc. of
a life insurance contract. By default, no rounding it applied.
The helper is sets up with list of named entries, specifying rounding accuracy for each particular value/use-case. The arguments are "name = value" pairs, where "name" describes the purpose of the rounding (e.g. "net premium"), while the value determines rounding accuracy. value can either be an integer (describing the number of digits to round to, e.g. with value 2, two decimal places after the comma will be rounded, e.g. 3.14159265 -> 3.14). Alternatively, a function(val) can be given, which will be applied to value(s) to be rounded. That function should be vectorizable.
roundingThe (named) list containing all declared rounding definitions
new()
Initialize the rounding settings
RoundingHelper$new(...)
...named entries specifying rounding accuracy
Sets up the rounding helper by giving a list of named entries, specifying rounding accuracy for each particular value. The arguments are "name = value" pairs, where "name" describes the purpose of the rounding (e.g. "net premium"), while the value determines rounding accuracy. value can either be an integer (describing the number of digits to round to, e.g. with value 2, two decimal places after the comma will be rounded, e.g. 3.14159265 -> 3.14). Alternatively, a function(val) can be given, which will be applied to value(s) to be rounded. That function should be vectorizable.
rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4)
rounding$round("raw", c(1234.567891, 0.00012345, 1234))
rounding$round("hundred", c(1234.567891, 0.00012345, 1234))
rounding$round("accurate", c(1234.567891, 0.00012345, 1234))
rounding$round("non-existing", c(1234.567891, 0.00012345, 1234))
# Rounding with functions: Rounding to 5-cent steps, or rounding down to 10 cents:
rnd.5ct = function(value) { round_half_up(value * 20) / 20 }
rnd.down10ct = function(value) { round_half_up(value - 0.05, 1) }
rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct)
rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98))
rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10))
round()
Round the given values using the pre-defined accuracy
RoundingHelper$round(spec, value, ...)
specthe ID used for looking up the desired accuracy
valuethe values to be rounded according to 'spec'
...currently unused
Rounds the given values using the accuracies defined in the internal rounding list (set either via the 'initialize' function or via a call to 'setRounding'. The accuracies are defined using a 'spec' identifier, which allows to define different accuracies for different uses
rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4)
rounding$round("raw", c(1234.567891, 0.00012345, 1234))
rounding$round("hundred", c(1234.567891, 0.00012345, 1234))
rounding$round("accurate", c(1234.567891, 0.00012345, 1234))
# If the given spec does not exist, no rounding it applied
rounding$round("non-existing", c(1234.567891, 0.00012345, 1234))
# Rounding to 5-cent steps, or rounding down to 10 cents:
rnd.5ct = function(value) { round(value * 20) / 20 }
rnd.down10ct = function(value) { round(value - 0.05, 1) }
rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct)
rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98))
rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10))
setRounding()
Define rounding accuracy for a certain identifier
RoundingHelper$setRounding(key, spec, ...)
keythe ID used for looking up the desired accuracy
specthe rounding accuracy (number of digits)
...currently unused
Configures the rounding helper for a given named entry, specifying rounding accuracy for each particular value
rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4)
rounding$round("raw", c(1234.567891, 0.00012345, 1234))
rounding$round("hundred", c(1234.567891, 0.00012345, 1234))
rounding$round("accurate", c(1234.567891, 0.00012345, 1234))
# If the given spec does not exist, no rounding it applied
rounding$round("non-existing", c(1234.567891, 0.00012345, 1234))
# Add a new spec with different settings:
rounding$setRounding("non-existing", 1)
rounding$round("non-existing", c(1234.567891, 0.00012345, 1234))
getRounding()
Extract rounding accuracy for a certain identifier
RoundingHelper$getRounding(key, ...)
keythe ID used for looking up the desired accuracy
...currently unused
Read out the rounding for a given named entry.
rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4)
rounding$getRounding("hundred")
clone()
The objects of this class are cloneable with this method.
RoundingHelper$clone(deep = FALSE)
deepWhether to make a deep clone.
rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Rounding with functions: Rounding to 5-cent steps, or rounding down to 10 cents: rnd.5ct = function(value) { round_half_up(value * 20) / 20 } rnd.down10ct = function(value) { round_half_up(value - 0.05, 1) } rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct) rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98)) rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10)) ## ------------------------------------------------ ## Method `RoundingHelper$new` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Rounding with functions: Rounding to 5-cent steps, or rounding down to 10 cents: rnd.5ct = function(value) { round_half_up(value * 20) / 20 } rnd.down10ct = function(value) { round_half_up(value - 0.05, 1) } rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct) rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98)) rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10)) ## ------------------------------------------------ ## Method `RoundingHelper$round` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) # If the given spec does not exist, no rounding it applied rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Rounding to 5-cent steps, or rounding down to 10 cents: rnd.5ct = function(value) { round(value * 20) / 20 } rnd.down10ct = function(value) { round(value - 0.05, 1) } rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct) rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98)) rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10)) ## ------------------------------------------------ ## Method `RoundingHelper$setRounding` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) # If the given spec does not exist, no rounding it applied rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Add a new spec with different settings: rounding$setRounding("non-existing", 1) rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) ## ------------------------------------------------ ## Method `RoundingHelper$getRounding` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$getRounding("hundred")rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Rounding with functions: Rounding to 5-cent steps, or rounding down to 10 cents: rnd.5ct = function(value) { round_half_up(value * 20) / 20 } rnd.down10ct = function(value) { round_half_up(value - 0.05, 1) } rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct) rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98)) rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10)) ## ------------------------------------------------ ## Method `RoundingHelper$new` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Rounding with functions: Rounding to 5-cent steps, or rounding down to 10 cents: rnd.5ct = function(value) { round_half_up(value * 20) / 20 } rnd.down10ct = function(value) { round_half_up(value - 0.05, 1) } rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct) rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98)) rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10)) ## ------------------------------------------------ ## Method `RoundingHelper$round` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) # If the given spec does not exist, no rounding it applied rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Rounding to 5-cent steps, or rounding down to 10 cents: rnd.5ct = function(value) { round(value * 20) / 20 } rnd.down10ct = function(value) { round(value - 0.05, 1) } rounding = RoundingHelper$new("five-cent" = rnd.5ct, "down10cent" = rnd.down10ct) rounding$round("five-cent", c(1234.567891, 0.00012345, 1234.98)) rounding$round("down10cent", c(1234.567891, 0.00012345, 1234.98, 1234.10)) ## ------------------------------------------------ ## Method `RoundingHelper$setRounding` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$round("raw", c(1234.567891, 0.00012345, 1234)) rounding$round("hundred", c(1234.567891, 0.00012345, 1234)) rounding$round("accurate", c(1234.567891, 0.00012345, 1234)) # If the given spec does not exist, no rounding it applied rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) # Add a new spec with different settings: rounding$setRounding("non-existing", 1) rounding$round("non-existing", c(1234.567891, 0.00012345, 1234)) ## ------------------------------------------------ ## Method `RoundingHelper$getRounding` ## ------------------------------------------------ rounding = RoundingHelper$new(raw = 0, hundred = -2, accurate = 4) rounding$getRounding("hundred")
Insurance tariff costs are defined by a cost matrix with dimensions: {CostType, Basis, Period}, where:
alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts
SumInsured, SumPremiums, GrossPremium, NetPremium, Constant
once, PremiumPeriod, PremiumFree, PolicyPeriod, AfterDeath, FullContract
After creation (using the function initializeCosts()), the funciton setCost
can be used to modify a single entry. While initializeCosts() provides arguments
to set the most common types of cost parameters in one call, the setCost
function allows to modify any cost parameter.
setCost(costs, type, basis = "SumInsured", frequency = "PolicyPeriod", value)setCost(costs, type, basis = "SumInsured", frequency = "PolicyPeriod", value)
costs |
The cost definition matrix (usually created by |
type |
The cost type (alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts) |
basis |
The basis fo which the cost rate is applied (default is SumInsured) |
frequency |
How often / during which period the cost is charged (once, PremiumPeriod, PremiumFree, PolicyPeriod, FullContract) |
value |
The new cost value to set for the given type, basis and frequency |
This function modifies a copy of the cost structure and returns it, so this function can be chained as often as desired and final return value will contain all cost modifications.
The modified cost structure
costs = initializeCosts() setCost(costs, "alpha", "SumPremiums", "once", 0.05)costs = initializeCosts() setCost(costs, "alpha", "SumPremiums", "once", 0.05)
Enum to describe possible sexes in an insurance contract or tariff.
Currently, the only possible values are:
"unisex"
"male"
"female"
Display the values of the example calculation of the given insurance contract as required by the Austrian regulation (LV-VMGLV, "LV Versicherungsmathematische Grundlagen Verordnung").
showVmGlgExamples(contract, prf = 10, t = 10, t_prf = 12, file = "", ...)showVmGlgExamples(contract, prf = 10, t = 10, t_prf = 12, file = "", ...)
contract |
The insurance contract to calculate and show |
prf |
Time of premium waiver (premium-free) |
t |
Time for which to show all values (except premium-free values) |
t_prf |
Time for which to show all values after the premium waiver |
file |
If given, outputs all information to the file rather than the console |
... |
Further parameters for generating the contract for a tariff object |
Name of the output file (invisible) or empty if printed to console
library(MortalityTables) mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", mortalityTable = AVOe2005R.unisex, i=0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); showVmGlgExamples(contract) # Optionally output to a file rather than the console: showVmGlgExamples(contract, file = tempfile("annuity-example", fileext = ".txt"))library(MortalityTables) mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", mortalityTable = AVOe2005R.unisex, i=0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); showVmGlgExamples(contract) # Optionally output to a file rather than the console: showVmGlgExamples(contract, file = tempfile("annuity-example", fileext = ".txt"))
Possible values are:
Whole life or term annuity (periodic survival benefits) with flexible payouts (constand, increasing, decreasing, arbitrary, etc.)
A whole or term life insurance with only death benefits. The benefit can be constant, increasing, decreasing, described by a function, etc.
An endowment with death and survival benefits, potentially with different benefits.
A pure endowment with only a survival benefit at the end of the contract. Optionally, in case of death, all or part of the premiums paid may be refunded.
A terme-fix insurance with a fixed payout at the end of the contract, even if the insured dies before that time. Premiums are paid until death of the insured.
A dread-disease insurance, which pays in case of a severe illness (typically heart attacks, cancer, strokes, etc.), but not in case of death.
A combination of an endowment and a temporary dread-disease insurance. Benefits occur either on death, severe illness or survival, whichever comes first.
Compares the calculated profit participation values in an
InsuranceContract object with reference values (typically read from
an Excel sheet). The comparison is column-wise and uses
expect_equal_abs() to allow for small numeric deviations.
testProfitParticipation( contract = NULL, tolerance = 0.01, path = "RefValues.xlsx", sheet = contract$tarif$name, scenario = "default", ... )testProfitParticipation( contract = NULL, tolerance = 0.01, path = "RefValues.xlsx", sheet = contract$tarif$name, scenario = "default", ... )
contract |
Optional |
tolerance |
Numeric scalar giving the absolute tolerance allowed
for value comparisons (see |
path |
Character string giving the path to the Excel file containing
reference values. Default: |
sheet |
Character string giving the sheet name within the Excel file.
Defaults to |
scenario |
Character string identifying the profit scenario within
the contract. Defaults to |
... |
Additional arguments forwarded to
|
The function performs the following steps:
If no contract is provided, creates one using the supplied tariff
parameters via InsuranceContract$new(...).
If scenario is missing or not yet present in
contract$Values$profitScenarios, generates or adds it.
Reads reference data from the specified Excel sheet using
readxl::read_excel().
For each column present in both the reference data and the
scenario matrix, compares corresponding numeric values using
expect_equal_abs(), with the specified tolerance.
Columns not present in both datasets are ignored. Missing or malformed scenario matrices trigger a warning (to be implemented).
Invisibly returns contract. The function is primarily used
for validation inside testthat test suites; each column comparison
generates a testthat expectation.
expect_equal_abs(), readxl::read_excel(),
testthat::expect_equal()
## Not run: # Compare profit participation results to reference values testProfitParticipation( contract = my_contract, path = system.file("extdata", "RefValues.xlsx", package = "LifeInsureR"), sheet = "Tariff12", scenario = "Scenario1", tolerance = 0.001 ) # Create and test a new contract on the fly testProfitParticipation( tariff = "GB", startAge = 30, sumInsured = 100000, path = "RefValues.xlsx" ) ## End(Not run)## Not run: # Compare profit participation results to reference values testProfitParticipation( contract = my_contract, path = system.file("extdata", "RefValues.xlsx", package = "LifeInsureR"), sheet = "Tariff12", scenario = "Scenario1", tolerance = 0.001 ) # Create and test a new contract on the fly testProfitParticipation( tariff = "GB", startAge = 30, sumInsured = 100000, path = "RefValues.xlsx" ) ## End(Not run)
Check the values of the example calculation of the given insurance contract as required by the Austrian regulation (LV-VMGLV, "LV Versicherungsmathematische Grundlagen Verordnung"). Missing params not passed to the function call will be silently ignored and not cause unit test failures.
testVmGlgExample( contract, prf = 10, t = 10, t_prf = 12, net, Zillmer, gross, written, savings, risk, ZillmerRes, ZillmerRes.prf, VwKostenRes, VwKostenRes.prf, Bilanzreserve, Praemienuebertrag, Rueckkaufsreserve, Rueckkaufswert, Abschlusskostenruecktrag, Rueckkaufswert.prf, VS.prf, absTolerance = 0.015, ... )testVmGlgExample( contract, prf = 10, t = 10, t_prf = 12, net, Zillmer, gross, written, savings, risk, ZillmerRes, ZillmerRes.prf, VwKostenRes, VwKostenRes.prf, Bilanzreserve, Praemienuebertrag, Rueckkaufsreserve, Rueckkaufswert, Abschlusskostenruecktrag, Rueckkaufswert.prf, VS.prf, absTolerance = 0.015, ... )
contract |
The insurance contract to calculate and check |
prf |
Time of premium waiver (premium-free) |
t |
Time for which to check all values (except premium-free values) |
t_prf |
Time for which to check all values after the premium waiver |
net, Zillmer, gross, written, savings, risk, ZillmerRes, ZillmerRes.prf, VwKostenRes, VwKostenRes.prf, Bilanzreserve, Praemienuebertrag, Rueckkaufsreserve, Rueckkaufswert, Abschlusskostenruecktrag, Rueckkaufswert.prf, VS.prf
|
Values as printed out by showVmGlgExamples |
absTolerance |
If non-NULL, will ignore small floating point differences. It uses same algorithm as all.equal() |
... |
Further parameters for generating the contract for a tariff object |
The easiest way to write unit-tests is using the function vmGlgExample.generateTest
None
## Not run: library(MortalityTables) library(testthat) mortalityTables.load("Austria_Annuities_AVOe2005R") test_that("Testtarif", { # A trivial deferred annuity tariff with no costs: library(MortalityTables) mortalityTables.load("Austria_Annuities") tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", mortalityTable = AVOe2005R.unisex, i = 0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); testVmGlgExample( contract, t = 10, net = 850.09, # NOT_CHECKED: Zillmer = 950.09, gross = 850.09, written = 884.09, savings = 857.09, risk = -7.00, ZillmerRes = 9011.40, ZillmerRes.prf = 9205.96, VwKostenRes = 0.00, VwKostenRes.prf = 0.00, Bilanzreserve = 9250.35, Praemienuebertrag = 637.567, Rueckkaufsreserve = 9011.40, Rueckkaufswert = 9011.40, Abschlusskostenruecktrag = 0.00, Rueckkaufswert.prf = 9205.96, VS.prf = 684.117 ) }) ## End(Not run)## Not run: library(MortalityTables) library(testthat) mortalityTables.load("Austria_Annuities_AVOe2005R") test_that("Testtarif", { # A trivial deferred annuity tariff with no costs: library(MortalityTables) mortalityTables.load("Austria_Annuities") tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", mortalityTable = AVOe2005R.unisex, i = 0.01) contract = InsuranceContract$new( tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") ); testVmGlgExample( contract, t = 10, net = 850.09, # NOT_CHECKED: Zillmer = 950.09, gross = 850.09, written = 884.09, savings = 857.09, risk = -7.00, ZillmerRes = 9011.40, ZillmerRes.prf = 9205.96, VwKostenRes = 0.00, VwKostenRes.prf = 0.00, Bilanzreserve = 9250.35, Praemienuebertrag = 637.567, Rueckkaufsreserve = 9011.40, Rueckkaufswert = 9011.40, Abschlusskostenruecktrag = 0.00, Rueckkaufswert.prf = 9205.96, VS.prf = 684.117 ) }) ## End(Not run)
val is a function, evaluate it, otherwise return val
If val is a function, evaluate it, otherwise return val
valueOrFunction(val, ...)valueOrFunction(val, ...)
val |
Function or value |
... |
Argument passed to |
the value, potentially with the given function applied
valueOrFunction(3) # returns 3 valueOrFunction(`+`, 1, 2) # also returns 3 A = `+` valueOrFunction(A, 1, 2)valueOrFunction(3) # returns 3 valueOrFunction(`+`, 1, 2) # also returns 3 A = `+` valueOrFunction(A, 1, 2)
This function calculates the required reference values for the given insurance contract as required by the Austrian regulation (LV-VMGLV, "LV Versicherungsmathematische Grundlagen Verordnung") and generates the code for unit-testing the contract with these values. The code printed can be directly copied into a unit test file.
vmGlgExample.generateTest(contract, prf = 10, t = 10, t_prf = 12, ...)vmGlgExample.generateTest(contract, prf = 10, t = 10, t_prf = 12, ...)
contract |
The insurance contract to calculate and generate unit-testing code. If an InsuranceTarif object is given, a new contract with default values is generated. |
prf |
Time of premium waiver (premium-free) |
t |
Time for which to calculate all values (except premium-free values) |
t_prf |
Time for which to calculated all values after the premium waiver |
... |
Further parameters for generating the contract for a tariff object |
None (code is printed to the console, but no value returned)
library(MortalityTables) mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", mortalityTable = AVOe2005R.unisex, i=0.01) vmGlgExample.generateTest(tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") )library(MortalityTables) mortalityTables.load("Austria_Annuities_AVOe2005R") # A trivial deferred annuity tariff with no costs: tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", mortalityTable = AVOe2005R.unisex, i=0.01) vmGlgExample.generateTest(tariff, age = 35, YOB = 1981, policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15, sumInsured = 1000, contractClosing = as.Date("2016-10-01") )