aboutsummaryrefslogtreecommitdiffstats
path: root/R/backtest.R
blob: cef602cfa8721bd7b519471cd7c4e18d8eb9831a (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
## parse command line arguments
if(.Platform$OS.type == "unix"){
  root.dir <- "/home/share/CorpCDOs"
}else{
  root.dir <- "//WDSENTINEL/share/CorpCDOs"
}
library(ggplot2)

source(file.path(root.dir, "code", "R", "serenitasdb.R"))
source(file.path(root.dir, "code", "R", "cds_functions_generic.R"))
source(file.path(root.dir, "code", "R", "yieldcurve.R"))

get.indexquotes <- function(index, series, tenors=c("3yr", "5yr", "7yr")){
    arraystring1 <- paste0("Array[''", paste(tenors, collapse = "'', ''"), "'']::tenor[]")
    arraystring2 <- paste0('"', paste(tenors, collapse='" float, "'), '" float')
    sqlstr <- paste("select * from crosstab('select date, tenor, closeprice from index_quotes where index=''%s''",
                    "and series=%s order by date, tenor', 'select unnest(%s)')",
                    "AS ct(date date, %s)")
    stmt <- sprintf(sqlstr, index, series, arraystring1, arraystring2)
    df <- dbGetQuery(serenitasdb, stmt)
    return( df )
}

get.indexmaturity <- function(index, series){
    sqlstr <- paste("select maturity, coupon/cast(10000 as float)as running, tenor",
                    "from index_maturity where index='%s'",
                      "and series=%s order by maturity")
    stmt <- sprintf(sqlstr, index, series)
    df <- dbGetQuery(serenitasdb, stmt)
    return( df )
}

fastduration <- function(sc, cs, tradedate, maturities){
    startdate <- tradedate+1
    acc <- cdsAccrued(tradedate, 1)
    r <- numeric(length(maturities))
    for(i in seq_along(maturities)){
        if(startdate>maturities[i]){
            r[i] <- NA
        }else{
            r[i] <- couponleg(cs[cs$unadj.dates<=maturities[i],], sc,
                              startdate, accruedondefault=TRUE)
        }
    }
    r <- r-acc
    return( r )
}

fasttheta <- function(sc, cs, recov, tradedate, maturities, quotes){
    startdate <- tradedate+1
    acc <- cdsAccrued(tradedate, 1)
    r <- numeric(length(maturities))
    newmaturities <- maturities+years(-1)
    for(i in seq_along(newmaturities)){
        if(startdate>newmaturities[i]){
            r[i] <- NA
        }else{
            newcs <- cs[cs$unadj.dates<=newmaturities[i],]
            upfront <- (couponleg(newcs, sc, startdate, accruedondefault=TRUE)-acc)*0.05-
                defaultleg(newcs, sc, recov, startdate)
            r[i] <- upfront+quotes[i]+0.05
        }
    }
    return( r )
}

index <- 'HY'
tenors <- c("3yr", "5yr", "7yr")
recov <- 0.3
colnames(df) <- c("date", tenors)
sqlstr <- paste("UPDATE index_quotes set duration=%s, theta=%s where date='%s' and index='%s'",
                "and series=%s and tenor='%s'")

for(series in c(10, 11, 13, 15, 17, 19, 21, 23)){
    indexquotes <- get.indexquotes(index, series)
    maturities <- get.indexmaturity(index, series)
    maturities <- maturities[maturities$tenor %in% tenors,]
    durations <- matrix(0, nrow(indexquotes), length(tenors))
    thetas <- matrix(0, nrow(indexquotes), length(tenors))
    for (i in 1:nrow(indexquotes)){
        tradedate <- indexquotes[i, "date"]
        exportYC(tradedate)
        maturity <- maturities[nrow(maturities), "maturity"]
        cs <- couponSchedule(IMMDate(tradedate, noadj=TRUE), maturity,"Q", "FIXED", 1,
                             0, tradedate, IMMDate(tradedate, "prev"))
        quotes <- data.frame(upfront=(100-as.numeric(indexquotes[i,-1]))/100, maturities)
        sc <- cdshazardrate(quotes, recov, tradedate, cs)
        durations[i,] <- fastduration(sc, cs, tradedate, maturities$maturity)
        thetas[i,] <- fasttheta(sc, cs, recov, tradedate, maturities$maturity, quotes$upfront)
    }
    df.durations <- data.frame(date=indexquotes$date, durations)
    df.thetas <- data.frame(date=indexquotes$date, thetas)
    colnames(df.durations) <- c("date", tenors)
    colnames(df.thetas) <- c("date", tenors)
    for(i in 1:nrow(df.durations)){
        for(tenor in tenors){
            if(!is.na(df[i,tenor])){
                stmt <- sprintf(sqlstr, df.durations[i,tenor], df.thetas[i, tenor],
                                df[i,"date"], index, series, tenor)
                dbSendQuery(serenitasdb, stmt)
            }
        }
    }
    ## nice plot, now I'm just showing off
    ggplot(df, aes(x=date))+geom_line(aes(y=`3yr`, colour="3yr"))+
        geom_line(aes(y=`5yr`, colour="5yr"))+
            geom_line(aes(y=`7yr`, colour="7yr"))+ylab("duration")+labs(colour="tenor")
    ggsave(filename=paste0("HY", series, " durations.png"))
}