diff options
| -rw-r--r-- | R/thetas-durations.R | 27 |
1 files changed, 12 insertions, 15 deletions
diff --git a/R/thetas-durations.R b/R/thetas-durations.R index e08f2ef9..916e68c0 100644 --- a/R/thetas-durations.R +++ b/R/thetas-durations.R @@ -1,6 +1,8 @@ library(ggplot2) library(lubridate) library(doParallel) +library(dplyr) +library(tidyr) if(.Platform$OS.type == "unix"){ root.dir <- "/home/share/CorpCDOs" @@ -19,18 +21,15 @@ 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"), onlymissing=TRUE){ - query1 <- sprintf(paste("select date, tenor, closeprice from index_quotes", - "where index=%s and series=%s"), sqlQuote(index), series) - if(onlymissing){ - query1 <- paste(query1, "and duration is Null") - } - query1 <- paste(query1, "order by date, tenor") - query2 <- sprintf("select unnest(%s::tenor[])",sqlQuote(sqlArray(tenors))) - arraystring2 <- paste(lapply(tenors, function(s)sprintf("\"%s\" float", s)), collapse=",") - stmt <- paste0("SELECT * from crosstab($1, $2) AS ct(date date, ", arraystring2, ")") - df <- dbGetQuery(serenitasdb, stmt, params=list(query1, query2)) - return( df ) +get.indexquotes.table <- function(indextype, series, tenors=c("3yr", "5yr", "7yr"), onlymissing=TRUE){ + stmt <- str_c("select date, tenor, closeprice from index_quotes ", + "where index=$1 and series=$2", + if(onlymissing) " and duration is Null" else NULL, + " order by date") + df <- dbGetQuery(serenitasdb, stmt, params = list(index, series)) + return( df %>% filter(tenor %in% tenors) + %>% mutate(tenor = factor(tenor, levels=tenors)) + %>% spread(tenor, closeprice) ) } get.indexmaturity <- function(index, series){ @@ -91,9 +90,7 @@ sqlstr.theta <- paste("UPDATE index_quotes set theta=$1 where date=$2 and index= for(index in c('IG', 'HY')){ recov <- if(index=='IG') 0.4 else 0.3 for(series in c(18, 19, 20, 21, 22, 23, 24)){ - indexquotes <- get.indexquotes(index, series) - indexquotes <- indexquotes[!(is.na(indexquotes[,"3yr"]) & is.na(indexquotes[,"5yr"]) - & is.na(indexquotes[,"7yr"])),] + indexquotes <- get.indexquotes.table(index, series) if(nrow(indexquotes)==0){ next } |
