aboutsummaryrefslogtreecommitdiffstats
path: root/calibrate_tranches.R
blob: 2b684d8c8dedc58be28ee531f261ac465f208b3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
library("parallel")
setwd("//WDSENTINEL/share/CorpCDOs/R")
source("cds_utils.R")
source("cds_functions_generic.R")
source("index_definitions.R")
source("tranche_functions.R")
source("yieldcurve.R")
source("optimization.R")

cl <- makeCluster(6)

MarkitData <- getMarkitIRData()
L1m <- buildMarkitYC(MarkitData, dt = 1/12)
L2m <- buildMarkitYC(MarkitData, dt = 1/6)
L3m <-  buildMarkitYC(MarkitData)
L6m <- buildMarkitYC(MarkitData, dt = 1/2)
setEvaluationDate(as.Date(MarkitData$effectiveasof))

## calibrate HY17
## calibrate the single names curves
singlenames.data <- read.table(file="clipboard", sep="\t", header=T)
nondefaulted <- singlenames.data[!singlenames.data$ticker %in% hy17$defaulted,]
bps <- 1e-4

cdsdates <- as.Date(character(0))
for(tenor in paste0(1:5, "y")){
    cdsdates <- c(cdsdates, cdsMaturity(tenor))
}

## clusterEvalQ(cl, {setClass("abstractcurve")
##                   setClass("defaultcurve", contains="abstractcurve",
##                            representation(dates="Date", hazardrates="numeric"))
##                   setClass("creditcurve", representation(issuer="character", startdate="Date",
##                                                          recovery="numeric", curve="defaultcurve"))})
## clusterExport(cl, list("nondefaulted", "cdsdates", "cdshazardrate", "today",
##                        "bps", "couponSchedule", "nextIMMDate", "DiscountCurve", "L3m"))
## test <- parSapply(cl, 1:nrow(nondefaulted), parf)

## parf <- function(i){
##     SC <- new("creditcurve",
##               recovery=nondefaulted$recovery[i]/100,
##               startdate=today(),
##               issuer=as.character(nondefaulted$ticker[i]))
##     quotes <- data.frame(maturity=cdsdates, upfront = as.numeric(nondefaulted[i,5:9])*0.01,
##                          running = rep(nondefaulted$running[i]*bps,5))
##     return( cdshazardrate(quotes, nondefaulted$recovery[i]/100))
## }

hy17portfolio <- c()
for(i in 1:nrow(nondefaulted)){
    SC <- new("creditcurve",
              recovery=nondefaulted$recovery[i]/100,
              startdate=today(),
              issuer=as.character(nondefaulted$ticker[i]))
    quotes <- data.frame(maturity=cdsdates, upfront = as.numeric(nondefaulted[i,5:9])*0.01,
                         running=rep(nondefaulted$running[i]*bps, 5))
    SC@curve <- cdshazardrate(quotes, nondefaulted$recovery[i]/100)
    hy17portfolio <- c(hy17portfolio, SC)
}
issuerweights <- rep(1/length(hy17portfolio), length(hy17portfolio))
hy17$indexref <- 1.0275
hy17portfolio.tweaked <- tweakcurves(hy17portfolio, hy17)

SurvProb <- SPmatrix(hy17portfolio.tweaked, hy17)
## load common parameters
K <- c(0, 0.15, 0.25, 0.35, 1)
Kmodified <- adjust.attachments(K, hy17$loss, hy17$factor)
tranche.upf <- c(48, 93.125, 105.8125, 114.625)
tranche.running <- c(0.05, 0.05, 0.05, 0.05)


lu <- 0.01
recov <- sapply(hy17portfolio.tweaked, attr, "recovery")
cs <- couponSchedule(nextIMMDate(today()), hy17$maturity,"Q", "FIXED", 0.05, 0)

## calibrate the tranches using base correlation
rhovec <- c()
f <- function(rho, ...){
    temp <- BClossdistC(SurvProb, issuerweights, recov, rho, lu, 100)
    return( abs(tranche.upf[i-1]-1/(Kmodified[i]-Kmodified[i-1])*
                (tranche.bp(temp$L, temp$R, cs, 0, Kmodified[i])*Kmodified[i]-
                 tranche.bp(oldtemp$L, oldtemp$R, cs, 0, Kmodified[i-1])*Kmodified[i-1])) )
}
for(i in 2:length(Kmodified)){
    rho <- optimize(f, interval=c(0,1),
                    SurvProb, issuerweights, recov, lu, tranche.upf, Kmodified, cs, oldtemp)$minimum
    oldtemp <- BClossdistC(SurvProb, issuerweights, recov, rho, lu)
    rhovec <- c(rhovec, rho)
}

#calibrate by modifying the factor distribution
bottomup <- 1:3
topdown <- 2:4
n.int <- 100
n.credit <- 96
errvec <- c()
quadrature <- gauss.quad.prob(n.int, "normal")
w <- quadrature$weights
Z <- quadrature$nodes
w.mod <- w
defaultprob <- 1 - SurvProb
p <- defaultprob
rho <- 0.45

clusterExport(cl, list("shockprob", "issuerweights", "rho", "Z", "lossrecovdist.term",
                       "lossrecovdist", "lossdistribC", "lu",
                       "tranche.bpvec", "tranche.bp", "tranche.pl", "tranche.cl",
                       "trancheloss", "trancherecov", "pos", "Kmodified", "cs"))

parf <- function(i){
    pshocked <- apply(p, 2, shockprob, rho=rho, Z=Z[i])
    S <- 1 - Rstoch[i,,]
    dist <- lossrecovdist.term(pshocked, 0, issuerweights, S, lu)
    return( tranche.bpvec(Kmodified, dist$L, dist$R, cs))
}

for(l in 1:100){
    Rstoch <- array(0, dim=c(n.int, n.credit, ncol(SurvProb)))
    for(t in 1:ncol(SurvProb)){
        for(i in 1:n.credit){
            Rstoch[,i,t] <- stochasticrecov(recov[i], 0, Z, w.mod, rho, defaultprob[i,t], p[i,t])
        }
    }
    clusterExport(cl, list("Rstoch", "p"))
    result <- parSapply(cl, 1:n.int, parf)
    ## solve the optimization problem
    program <- KLfit(result[topdown,], w, tranche.upf[topdown])

    err <- 0
    for(i in 1:n.credit){
        for(j in 1:ncol(p)){
            err <- err + abs(crossprod(shockprob(p[i,j], rho, Z), program$weight) - defaultprob[i,j])
        }
    }

    ## update the new probabilities
    for(i in 1:n.credit){
        for(j in 1:ncol(p)){
            p[i,j] <- fit.prob(Z, program$weight, rho, defaultprob[i,j])
        }
    }

    errvec <- c(errvec, err)
    w.mod <- program$weight
    cat(err,"\n")
}