aboutsummaryrefslogtreecommitdiffstats
path: root/R/yieldcurve.R
blob: 86da47c20ee4edfcdc0dc2c91290d010e69a70be (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
require(RQuantLib)
library(dplyr, quiet = T, warn.conflicts = F)
source("db.R")

getMarkitIRData <- function(date=Sys.Date(), currency=c("USD", "EUR")) {
    ## returns Markit rates from serenitasdb
    currency <- match.arg(currency)
    table_name <- paste(currency, "OIS", "rates", sep="_")
    serenitasdb <- dbConn("serenitasdb")
    return( serenitasdb %>% tbl(table_name)
           %>% filter(effective_date == date) %>% collect() )
}

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) {
    oisswaps <- list()
    for(k in names(MarkitData[2:length(MarkitData)])) {
        v <- MarkitData[[k]]
        oisswaps[[paste0("ois", tolower(k))]] <- v
    }
    return( oisswaps )
}

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)
}