R/LossSimulator.R

#' Function For Simulating Losses From An ELT
#'
#' This function allows you to simulate losses from an event loss tables (ELTs).
#' @param elt The data frame or array containing the elt. The first column should contain the annual rate and the second the expected loss.
#' @param beta_0 The vector of beta_0 parameters for the dynamic rates
#' @param beta_1 The vector of beta_1 parameters for the dynamic rates
#' @param mixing_distribution The choice of mixing distribution. Takes values of "Lognormal" or "Bernoulli" or "Null"
#' @param no_of_years The number of years to simulate
#' @param thresholds Thresholds for the dispersion to be calculated for
#' @keywords ELT
#' @export
#' @examples
#' LossSimulator()
LossSimulator <- function(expected_loss = NULL, beta_0 = NULL, beta_1 = NULL, mixing_distribution = "normal", no_of_years = 10000, thresholds = NULL) {
  n <- no_of_years
  losses <- list()
  aggregate_loss <- c()
  max_loss <- c()
  counts_thresholded <- matrix(0, nrow = n, ncol = length(thresholds))
  if (mixing_distribution == "Bernoulli") {
    theta <- 0.5
    z <- rbinom(n, 1, theta)
    N <- rpois(n, lapply(z, function(x) sum(beta_0+beta_1 * x))) 
    for(yr in 1:no_of_years) {
      dynamic_rate <- sum(beta_0+beta_1 * z[yr])
      losses[[yr]] = sample(expected_loss, N[yr], replace = T, prob = dynamic_rate)
      aggregate_loss[r] = sum(losses[[r]])
      max_loss[r] = max(losses[[r]])
      dispersion[yr,] <- length(losses[[yr]] > thresholds)
    }
  } else if (mixing_distribution == "Lognormal") {
    z <- rnorm(n)
    N <- rpois(n, lapply(z, function(x) sum(exp(beta_0 + beta_1 * x))))
    for(yr in 1:no_of_years) {
      dynamic_rate <- exp(beta_0 + beta_1 * z[yr])
      losses[[yr]] = sample(expected_loss, N[yr], replace = T, prob = dynamic_rate)
      aggregate_loss[r] = sum(S5[[r]])
      max_loss[r] = max(S5[[r]])
      counts_thresholded[yr,] <- length(losses[[yr]] > thresholds)
    }
  }
  invisible(list(mixing_variable = z, simulated_events = N, aggregate_loss = aggregate_loss, max_loss = max_loss, counts_thresholded = counts_thresholded))
}
  
alasdairhunter/HazardLossModel documentation built on May 10, 2019, 8:50 a.m.