# VaR and CVaR percentages in R - an UniWIBID example

Jul 24th, 2012
259
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # more: http://www.reakkt.com/2012/07/var-you-cannot-estimate-unknown.html
2.
3. TxtNum <- function(txt,num,d=4) {
4.
5.   return( paste(txt,format(num,digits=d)) )
6.
7. }
8.
9. VaR <- function(x,alpha) {
10.
11.   n <- length(x)
12.
13.   # 1% of the elements
14.   pct <- ceiling(n/100)
15.
16.   x.sorted <- sort(x)
17.
18.   # number of alpha coefficients
19.   alphaN <- length(alpha)
20.
21.   var  <- sapply(alpha, function(d) quantile(x,d))
22.
23.   cvar <- sapply(alpha*100, function(d) mean(head(x.sorted,d*pct)))
24.
25.   list(VaR=var, CVaR=cvar, min=min(x))
26.
27. }
28.
29. PlotVaR <- function(x) {
30.
31.   var.list <- VaR(x,c(0.05,0.01))
32.
33.   plot(density(x),main="Unit Returns Density + VaR")
34.
35.   mtext(paste(TxtNum("mean=",mean(x)),
36.               TxtNum("VaR 5%=",var.list\$VaR[1]),
37.               TxtNum("VaR 1%=",var.list\$VaR[2]),
38.               TxtNum("CVaR 5%=",var.list\$CVaR[1]),
39.               TxtNum("CVaR 1%=",var.list\$CVaR[2]),
40.               TxtNum("min=",var.list\$min)),
41.         line=0.5,cex=0.8)
42.
43.   abline(v=mean(x),col="Blue",lty="dotted")
44.
45.   abline(v=quantile(x,0.05),col="Red",lty="dotted")
46.   abline(v=quantile(x,0.01),col="DarkRed",lty="dotted")
47.
48. }
49.
50. # UniWIBID data available at http://www.union-investment.pl/praktyczne/wycena/index_wycena.html
52.
53. uniwibid.date   <- rev(as.Date(uniwibid.data[,1]))
54. uniwibid.price  <- rev(as.numeric(as.character(uniwibid.data[,2])))
55. uniwibid.change <- log(uniwibid.price[-1]/uniwibid.price[-length(uniwibid.price)])
56.
57. uniwibid <- cbind(uniwibid.date[-1],uniwibid.price[-1],uniwibid.change)
58. colnames(uniwibid) <- c("Date","Price","Change")
59.
60. uniwibidN <- nrow(uniwibid)
61.
62. shock.idx    <- which.min(uniwibid[,"Change"])
63. shock.change <- uniwibid[shock.idx,"Change"]
64.
65. shock.retreat.idx <- tail(which(uniwibid[1:(shock.idx-1),"Price"]<=uniwibid[shock.idx,"Price"]),1)
66.
67. as.Date(uniwibid[shock.idx,"Date"],origin="1970-01-01")
68. as.Date(uniwibid[shock.retreat.idx,"Date"],origin="1970-01-01")
69.
70. Fn <- ecdf(uniwibid[1:(shock.idx-1),"Change"])
71. Fn(0) # return <= 0 probability
72.
73. Fn <- ecdf(uniwibid[shock.idx:uniwibidN,"Change"])
74. Fn(0)
75.
76. Fn <- ecdf(uniwibid[,"Change"])
77. Fn(0)
78.
79. plot(uniwibid[1:(shock.idx-1),"Price"],type="l",main="UniWIBID Price",ylab="")
80. plot(uniwibid[shock.retreat.idx:uniwibidN,"Price"],type="l",main="UniWIBID Price",ylab="")
81.
82. PlotVaR(uniwibid[1:(shock.idx-1),"Change"])
83.
84. PlotVaR(uniwibid[shock.idx:uniwibidN,"Change"])
85.
86. PlotVaR(uniwibid[shock.retreat.idx:uniwibidN,"Change"])
87.
88. PlotVaR(uniwibid[,"Change"])