Skip to content

Instantly share code, notes, and snippets.

@mages
Created January 3, 2013 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mages/4444999 to your computer and use it in GitHub Desktop.
Save mages/4444999 to your computer and use it in GitHub Desktop.
## Ideas from: http://pirategrunt.wordpress.com/2013/01/02/you-cant-spell-loss-reserving-without-r/
library(ChainLadder)
## example triangle
data(RAA)
## transform triangles into data frames with prior and current columns
triangle2dat <- function(myTriangle){
Cumulative <- as.data.frame(as.triangle(myTriangle), na.rm=TRUE)
names(Cumulative)[3] <- "Cumulative"
PriorCumulative <- transform(Cumulative, dev=dev + 1)
names(PriorCumulative)[3] <- "PriorCumulative"
dat <- merge(Cumulative, PriorCumulative)
dat <- dat[order(dat$dev),]
dat <- transform(dat, dev=factor(dev))
return(dat)
}
dat <- triangle2dat(RAA)
head(dat,10)
tail(dat,10)
## Create design matrix
dm <- with(dat, model.matrix(PriorCumulative ~ dev + 0) * PriorCumulative)
delta <- 1
## Weighted linear regression through the origin to get chain ladder link ratios
Fit = with(dat, lm(Cumulative ~ dm + 0, weights=1/PriorCumulative^delta))
summary(Fit)
coef(Fit)
op <- par(mfrow=c(2,2))
plot(Fit)
par(op)
library(lattice)
xyplot(Cumulative/1000 ~ PriorCumulative/1000 | dev, groups=origin,
data=dat, auto.key=list(space="right",
title="origin\nyear",
cex.title=1),
main=paste0("Red line: Weighted linear regression though origin\n",
"Black line: Linear regression with intercept"),
as.table=TRUE,
panel=function(x,y,...){
panel.xyplot(x,y)
if(length(x)>1){
panel.abline(lm(y~x+0, weights=1/x), col="red")
panel.abline(lm(y~x))
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment