aboutsummaryrefslogtreecommitdiffstats
path: root/R/cds_tester.R
blob: 4b65ab4bbe7c508a4261ac594112639e1df0fcb1 (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
library(XML)
source("cds_utils.R")
source("yieldcurve.R")
source("cds_functions_generic.R")

currency <- "USD"
basedir <- "/home/share/CorpCDOs/grids"
download.grids <- function(currency=currency, basedir=basedir){
    address <- "http://www.cdsmodel.com/cdsmodel/assets/cds-model/test-grids/"
    grids <- as.character(readHTMLTable(paste0(address, currency), skip.rows=c(1,2,23))[[1]]$V2)
    for(f in grids){
        download.file(paste0(address, currency, "/", f),
                      quiet = TRUE,
                      destfile=file.path(basedir, f))
    }
}
grids <- dir(basedir)
f <- grids[1]
filename <- sub("\\.[^.]*$", ".csv", f)
con <- unz(file.path(basedir, f), filename)
data <- read.csv(con)
data[,"Trade.Date"] <- as.Date(strptime(data[,"Trade.Date"], format="%Y%m%d"))
data[,"Maturity.Date"] <- as.Date(strptime(data[,"Maturity.Date"], format="%Y%m%d"))
for(i in 1:nrow(data)){
    tradedate <- data[i, "Trade.Date"]
    exportYC(tradedate)
    coupon <- data[i, "Coupon"]*1e-4
    spread <- data[i, "Quoted.Spread"]*1e-4
    R <- data[i, "Recovery"]
    maturity <- data[i, "Maturity.Date"]
    cs <- couponSchedule(IMMDate(tradedate, noadj=TRUE), maturity,
                         "Q", "FIXED", coupon, 0, tradedate, IMMDate(tradedate, "prev"))
    h <- spread/(1-R)
    sc <- new("flatcurve", h = h)
    startdate <- tradedate + 1
    cds.pv <- couponleg(cs, sc, startdate) - defaultleg(cs, sc, R, startdate)
}

couponleg2 <- function(h, cs){
    T <- yearFrac(startdate, cs$unadj.dates)
    PD <- exp(-h*T)
    PDshift <- c(1, PD)
    DT <- diff(c(0, T))
    crossprod(cs$df*DT, PD)-crossprod(DFmid*DT/2, diff(PDshift))
}

protectionleg2 <- function(cs, h, R, startdate){
    T <- yearFrac(startdate, cs$dates)
    B <- exp(-h*T) * cs$df
    f <- -diff(c(0, log(cs$df)))/diff(c(0, T))
    return( -(1-R)*crossprod(diff(c(1, B)), h/(f+h)) )
}

defaultleg(cs, sc, R, startdate)