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
|
require(RQuantLib)
root.dir <- if(.Platform$OS.type == "unix"){
"/home/share/CorpCDOs"
}else{
"//WDSENTINEL/share/CorpCDOs"
}
source(file.path(root.dir, "code", "R", "db.R"))
getMarkitIRData <- function(date=Sys.Date(), currency=c("USD", "EUR")) {
## returns Markit rates from serenitasdb
currency <- match.arg(currency)
sqlstr <- sprintf("SELECT * FROM %s_rates WHERE effective_date = $1", currency)
serenitasdb <- dbConn("serenitasdb")
return( dbGetQuery(serenitasdb, sqlstr, params = list(date)) )
}
thirdwed <- function(x) {
d <- x - as.POSIXlt(x)$mday + 1
n <- (3-as.POSIXlt(d)$wday) %% 7 + 1
d + 14 + n - 1
}
nextthirdwed <- function(x) {
y <- thirdwed(x)
thirdwed(y + 30 * (y < x))
}
buildMarkitYC <- function(MarkitData, currency=c("USD", "EUR"), futurequotes){
currency <- match.arg(currency)
deposits <- list()
futures <- list()
swaps <- list()
if(missing(futurequotes)){
for(k in names(MarkitData[2:7])) {
v <- MarkitData[[k]]
if(is.na(v)) {
next
}
deposits[[paste0("d", tolower(k))]] <- v
}
}else{
for(i in seq_along(futurequotes)){
futures[[paste0("fut",i)]] <- futurequotes[i]
}
## get last imm date
lastimmdate <- nextthirdwed(advance(dates=tradeDate, n=21, timeUnit=2, bdc=4))
lastfuturematurity <- advance(dates=lastimmdate, n=3, timeUnit=2, bdc=4)
## find out the 2 year swap rate maturity
s2ymaturity <- advance(calendar="UnitedKingdom", dates=settleDate, 2, 3)
if(s2ymaturity == lastfuturematurity){
futures[["fut8"]] <- NULL
}
}
for(k in names(MarkitData[8:length(MarkitData)])) {
v <- MarkitData[[k]]
if(is.na(v)) {
next
}
swaps[[paste0("s", tolower(k))]] <- v
}
tsQuotes <- c(deposits, futures, swaps)
return( tsQuotes )
}
exportYC <- function(tradedate=Sys.Date(), currency=c("USD", "EUR"), useFutures=FALSE){
## export the Yield Curve into the environment
currency <- match.arg(currency)
if(useFutures){
futurefile <- file.path(data.dir, "Yield Curves",
sprintf("futures-%s.csv", tradedate))
if(file.exists(futurefile)){
futurequotes <- read.csv(futurefile, header=F)
}
}
MarkitData <- getMarkitIRData(tradedate, currency)
setCalendarContext(calendar="WeekendsOnly", fixingDays=2,
settleDate=tradedate)
settings <- Settings$new()
settings$EvaluationDate <- tradedate
legparams <- switch(currency,
USD = list(fixFreq="Semiannual",
floatFreq="Quarterly",
dayCounter="Thirty360"),
EUR = list(fixFreq="Annual",
floatFreq="Semiannual",
dayCounter="Thirty360"))
cal <- Calendar$new("WeekendsOnly")
dc <- DayCounter$new("Actual365Fixed")
if(exists("futurequotes")){
tsQuotes <- buildMarkitYC(MarkitData, currency, futurequotes[,2])
}else{
tsQuotes <- buildMarkitYC(MarkitData, currency)
}
YC <<- YieldTermStructure$new("discount", "loglinear", 0L, cal,
dc, tsQuotes, legparams)
}
|