aboutsummaryrefslogtreecommitdiffstats
path: root/R/yieldcurve.R
blob: f5adc987b8b9f3ea30ae84bf37f95972de8ff903 (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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
require(RQuantLib)

if(.Platform$OS.type == "unix"){
  data.dir <- "/home/share/CorpCDOs/data"
}else{
  data.dir <- "//WDSENTINEL/share/CorpCDOs/data"
}

getMarkitIRData <- function(date=Sys.Date(), currency="USD") {
    ## downloads the latest available interest rates data from Markit
    ## before date and returns the parsed file into a list
    require(XML)
    i <- 0
    while( TRUE ) {
        lastdate <- format(date-i, "%Y%m%d")
        filename <- paste("InterestRates", currency, lastdate, sep="_")
        filename.ext <- paste0(filename,".xml")
        if( filename.ext %in% dir(file.path(data.dir, "Yield Curves"))){
            return( xmlToList(file.path(data.dir, "Yield Curves", filename.ext)) )
        }else{
            temp <- tempfile(tmpdir = file.path(data.dir, "Yield Curves"))
            download.file(paste("http://www.markit.com/news/", filename, ".zip", sep=""), temp, quiet=T)
            con <- file(temp, "r")
            firstline <- readLines(con, 1, warn=FALSE)
            ## Markit returns a plain text file if there is no data.
            if(firstline == "Interest Rates not available, please check date entered") {
                i <- i + 1
                close(con)
                unlink(temp)
            } else {
                cat("downloaded data for:", lastdate,"\n")
                close(con)
                ## we unzip it
                unzip(temp, exdir = file.path(data.dir, "Yield Curves"))
                unlink(temp)
                return( xmlToList(file.path(data.dir, "Yield Curves", filename.ext)) )
            }
        }
    }
    return( xmlToList(paste(filename,".xml", sep="")) )
}

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="USD", futurequotes){
    deposits <- list()
    futures <- list()
    swaps <- list()
    if(missing(futurequotes)){
        keys <- unlist(lapply(MarkitData$deposits[5:length(MarkitData$deposits)],
                              function(x)paste0("d",tolower(x$tenor))), use.names=FALSE)
        for(i in seq_along(keys)){
            deposits[[keys[i]]] <- as.numeric(MarkitData$deposits[i+4]$curvepoint$parrate)
        }
    }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
        }
    }
    if(length(MarkitData$swaps)>8){## swaps quotes probably missing
        keys <- unlist(lapply(MarkitData$swaps[8:length(MarkitData$swaps)],
                              function(x) paste0("s", tolower(x$tenor))),use.names=FALSE)
        for(i in seq_along(keys)){
            swaps[[keys[i]]] <- as.numeric(MarkitData$swaps[i+7]$curvepoint$parrate)
        }
        if(.Platform$OS.type != "unix"){
            for(missingtenor in c("s4y", "s6y", "s7y", "s8y", "s9y", "s12y", "s25y")){
                swaps[[missingtenor]] <- NULL
            }
        }
    }
    tsQuotes <- c(deposits, futures, swaps)
    return( tsQuotes )
}

exportYC <- function(tradedate=Sys.Date(), currency="USD", useFutures=FALSE){
    ## export the Yield Curve into the environment
    require(RQuantLib)
    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-1, currency)
    evaldate <- as.Date(MarkitData$effectiveasof)
    setEvaluationDate(tradedate)
    if(evaldate!=tradedate){
        stop("wrong date")
    }
    setEvaluationDate(evaldate)
    settleDate <- as.Date(MarkitData$deposits$spotdate)
    curveType <- sprintf("%s/%s", "Markit", currency)
    if(.Platform$OS.type == "unix"){
        setCalendarContext(calendar="WeekendsOnly", fixingDays=2,
                           settleDate=as.Date(MarkitData$deposits$spotdate),
                           curveType=curveType)
    }else{
         setCalendarContext(calendar="UnitedKingdom", fixingDays=2,
                           settleDate=as.Date(MarkitData$deposits$spotdate))
     }

    params <- list(tradeDate=as.Date(MarkitData$effectiveasof),
                   settleDate=settleDate,
                   interpWhat="discount",
                   interpHow="loglinear")
    if(exists("futurequotes")){
        quotes <- buildMarkitYC(MarkitData, currency, futurequotes[,2])
    }else{
        quotes <- buildMarkitYC(MarkitData, currency)
    }
    L1m <- L2m <- L3m <- L6m <- L12m <- list(params=params, tsQuotes=quotes)
    L1m$params$dt <- 1/12
    L2m$params$dt <- 1/6
    L3m$params$dt <- 1/4
    L6m$params$dt <- 1/2
    L12m$params$dt <- 1
    assign("L1m", L1m, env = parent.env(environment()))
    assign("L2m", L2m, env = parent.env(environment()))
    assign("L3m", L3m, env = parent.env(environment()))
    assign("L6m", L6m, env = parent.env(environment()))
    assign("L12m", L12m, env = parent.env(environment()))
}