Last active
July 23, 2018 19:59
-
-
Save lrnv/f87961fbbbdb277aaec3024b06bb9aad to your computer and use it in GitHub Desktop.
check_model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(magrittr) | |
library(tidyverse) | |
library(ChainLadder) | |
############" Fits mack AND my model in parallel to check if it's ok : | |
check_model <- function(triangle){ | |
df <- triangle %>% | |
as.data.frame %>% | |
mutate( | |
weight = cbind(rep(NA,nrow(triangle)),triangle %>% as.matrix) %>% .[,1:nrow(triangle)] %>% as.vector, | |
f = value / weight, | |
phi.start = 1 | |
) %>% | |
drop_na | |
model <- lm(data = df,formula=f~factor(dev)+0,weights=weight/phi.start) | |
df %<>% mutate(estimated.f = model$fitted.values, | |
rez2 = weight * (f - estimated.f)^2) | |
model2 <- df %>% | |
filter(dev != nrow(triangle)) %>% | |
{lm(data =., formula = rez2 ~ factor(dev))} | |
df %<>% mutate( | |
estimated.phi = model2$fitted.values %>% {c(.,min(.[length(.)],.[length(.)-1],.[length(.)]^2/.[length(.)-1]))} | |
) | |
model3 <- lm(data = df,formula=f~factor(dev)+0,weights=weight/estimated.phi) | |
model4 <- MackChainLadder(triangle,est.sigma="Mack") | |
resultat <- | |
df %>% | |
group_by(dev) %>% | |
summarise(phi=mean(estimated.phi)) %>% | |
mutate( | |
mack = model4$sigma^2, | |
degree.of.freedom = max(dev) - dev, # correction for degree of freedom | |
phi = (phi * (degree.of.freedom+1)/(degree.of.freedom)) %>% .[1:(length(.)-1)] %>% {c(.,min(.[length(.)],.[length(.)-1],.[length(.)]^2/.[length(.)-1]))}, | |
f = model3$coefficients[1:(dim(triangle)[1]-1)], | |
f.cl = model4$f[1:(dim(triangle)[1]-1)] | |
) %>% | |
select(f,f.cl,phi,mack) %>% | |
as.data.frame | |
return(list(mod.f = model, mod.phi = model2, mod.final = model3,rez = resultat)) | |
} | |
data(ABC) | |
check_model(ABC) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment