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(tolower(currency), "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){ 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) }