library(RPostgreSQL) drv <- dbDriver("PostgreSQL") mlpdbCon <- dbConnect(drv, dbname="mlpdb", user="mlpdb_user", password="Serenitas1", host="debian") nameToBasketID <- function(name, date=Sys.Date()){ sqlstr <- "SELECT * from nametobasketid('%s', '%s')" r <- dbGetQuery(mlpdbCon, sprintf(sqlstr, name, date)) return(as.integer(r)) } load.index <- function(name, date=Sys.Date(), tenor="5yr"){ id <- nameToBasketID(name, date) sqlstr <- "SELECT indexfactor, cumulativeloss, maturity from index_desc where basketid=%s and tenor='%s'" r <- as.list(dbGetQuery(mlpdbCon, sprintf(sqlstr, id, tenor))) return(list(coupon=0.05, factor=r$indexfactor/100, maturity=r$maturity, loss=r$cumulativeloss/100, recovery=0.4, name=name)) } cdslist <- function(indexname, date=Sys.Date()){ basketid <- nameToBasketID(indexname, date) sqlstr <- "select * from CDS_Issuers where index_list @> '{%s}'" return( dbGetQuery(mlpdbCon, sprintf(sqlstr, basketid))) } arr.convert <- function(arr){ arr <- unlist(lapply(arr, function(x)strsplit(substr(x,2,nchar(x)-1),",",fixed=TRUE))) arr[arr=="NULL"] <- NA arr <- matrix(as.numeric(arr), nrow=length(arr)/8, ncol=8, byrow=T) colnames(arr) <- c("6m", "1y", "2y", "3y", "4y", "5y", "7y", "10y") return(arr) } get.indexquotes <- function(indexname, date=Sys.Date()){ r <- dbGetQuery(mlpdbCon, sprintf("select * from curve_quotes('%s', '%s')", indexname, date)) quotes <- list(tickers=r[,1], spread_curve = arr.convert(r$spread_curve), upfront_curve =arr.convert(r$upfront_curve), recovery_curve = arr.convert(r$recovery_curve)) return( quotes ) }