aboutsummaryrefslogtreecommitdiffstats
path: root/R/load_cf.R
blob: 22c5386af14e059d7a3627d8f394be6f095dad02 (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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
library(RPostgreSQL)
library(RQuantLib)
if(.Platform$OS.type == "unix"){
  root.dir <- "/home/share/CorpCDOs"
}else{
  root.dir <- "//WDSENTINEL/share/CorpCDOs"
}

source(file.path(root.dir, "code", "R", "etdb.R"))
source(file.path(root.dir, "code", "R", "yieldcurve.R"))
source(file.path(root.dir, "code", "R", "cds_utils.R"))
source(file.path(root.dir, "code", "R", "intex_deal_functions.R"))
source(file.path(root.dir, "code", "R", "optimization.R"))

workdate <- as.Date("2013-02-11")

MarkitData <- getMarkitIRData(workdate)
L1m <- buildMarkitYC(MarkitData, dt = 1/12)
L2m <- buildMarkitYC(MarkitData, dt = 1/6)
L3m <-  buildMarkitYC(MarkitData)
L6m <- buildMarkitYC(MarkitData, dt = 1/2)
L12m <- buildMarkitYC(MarkitData, dt = 1)
setEvaluationDate(as.Date(MarkitData$effectiveasof))

sanitize.column <- function(vec){
  vec <- gsub(",", "", vec)
  index <- grep("\\(", vec)
  for(l in index){
    vec[l] <- -as.numeric(substr(vec[l], 2, nchar(vec[l])-1))
  }
  return( as.numeric(vec) )
}

allfiles <- list.files(file.path(root.dir, "Scenarios", paste0("Prices_", workdate)), "*.txt")
allfiles <- unique(sapply(strsplit(allfiles, "-"), function(x) x[1]))
allfiles <- allfiles[!(allfiles=="Total")]
dealnames <- list.files(file.path(root.dir, "Scenarios", paste0("Prices_", workdate)), "*COLLAT_INITIAL-CF-Scen1*")
dealnames <- unique(sapply(strsplit(dealnames, "-"), function(x) x[1]))
cusips <- setdiff(allfiles, dealnames)
dealnames <- tolower(dealnames)

getdealcf <- function(dealnames, workdate=Sys.Date()){
    cfdata <- list()
    tranches <- c("COLLAT_REINVEST", "COLLAT_INITIAL")
    fields <-  c("Cashflow", "Principal", "Interest")
    flag <- FALSE
    n.scenarios <- 100
    for(dealname in dealnames){
        cfdata[[dealname]] <- list()
        r <- matrix(0, n.scenarios, 3)
        colnames(r) <- fields
        sqlstring <- sprintf("select marketvalue from latest_deal_model_numbers where dealname='%s'", dealname)
        mv <- dbGetQuery(dbCon, sqlstring)$marketvalue
        sqlstring <- sprintf("select \"Curr Collat Bal\" from latest_clo_universe where dealname='%s'", dealname)
        currbal <- dbGetQuery(dbCon, sqlstring)$"Curr Collat Bal"
        cfdata[[dealname]]$mv <- mv
        cfdata[[dealname]]$currbal <- currbal
        for(tranche in tranches){
            for(i in 1:n.scenarios){
                filename <- paste0(paste(toupper(dealname), tranche, "CF", paste0("Scen", i), sep="-"), ".txt")
                ## we catch the error if there is an error reading the file
                ## happen if the tranche is missing in intex
                data <- tryCatch(
                        read.table(file.path(root.dir, "Scenarios", paste0("Prices_", workdate), filename),
                                   sep="\t", header=F, skip=3, colClasses="character", comment.char=""),
                        error = function(e) e)
                if(inherits(data, "error")){
                    cat(sprintf("file: %s, tranche: %s can't be loaded", dealname, tranche), "\n")
                    flag <- TRUE
                    break
                }
                data <- data[,1:4]
                colnames(data) <- c("Date", "Cashflow", "Principal", "Interest")
                data$Date <- as.Date(data$Date, "%b %d, %Y")
                if(any(is.na(data$Date))){
                    cat(sprintf("file: %s is messed up", filename), "\n")
                    flag <- TRUE
                    break
                }
                futuredates <- data$Date[data$Date>=L3m$params$tradeDate]
                pastdates <- data$Date[data$Date<L3m$params$tradeDate]
                if(i==1||length(futuredates)>length(DC$times)){
                    DC <- DiscountCurve(L3m$params, L3m$tsQuotes, yearFrac(L3m$params$tradeDate, futuredates))
                }
                pv <- c()
                for(field in fields){
                    cleanfield <- tryCatch(sanitize.column(data[,field]),
                                           warning = function(w) w)
                    if(inherits(cleanfield, "warning")){
                        cat("garbled", dealname, i, "\n")
                        flag <- TRUE
                        break
                    }else{
                        data[,field] <- cleanfield
                    }
                    if(length(futuredates) == 0){
                        df <- rep(1, length(pastdates))
                    }else{
                        df <- c(rep(1, length(pastdates)), DC$discounts[1:length(futuredates)])
                    }
                    if(nrow(data)>0){
                        pv <- c(pv, crossprod(df, data[,field]))
                    }else{
                        pv <- c(pv, 0)
                    }
                }
                if(flag){
                    break
                }else{
                    r[i,] <- pv
                }
            }
            if(flag){
                cfdata[[dealname]] <- NULL
                flag <- FALSE
                break
            }else{
                cfdata[[dealname]][[tranche]]<- r
            }
        }
        if(is.null(cfdata[[dealname]])){
            next
        }
        cf <- cfdata[[dealname]][["COLLAT_REINVEST"]][,"Cashflow"] +
            cfdata[[dealname]][["COLLAT_INITIAL"]][,"Cashflow"]
        cfdata[[dealname]]$wapbasis <- (mean(cf)- cfdata[[dealname]]$mv)/cfdata[[dealname]]$mv
        cat(dealname, "\n")
        program <- KLfit(t(cf)/1e8, rep(1/n.scenarios, n.scenarios),
                         cfdata[[dealname]]$mv/1e8)
        cfdata[[dealname]]$weight <- program$weight
    }
    return( cfdata )
}

getcusipcf <- function(cusips, cfdata, workdate=Sys.Date()){
    flag <- FALSE
    cusipdata <- list()
    dealnames <- dealnamefromcusip(cusips)
    n.scenarios <- 100
    intexfields <-  c("Cashflow", "Principal", "Interest", "Balance")
    fields <-  c("Cashflow", "Principal", "Interest")
    for(i in 1:length(cusips)){
        cusip <- cusips[i]
        dealdata <- getdealdata(dealnames[i])
        schedule <- getdealschedule(dealdata)
        r <- matrix(0, n.scenarios, 5)
        colnames(r) <- c(fields, "wal", "duration")
        sqlstring <- sprintf("select curr_balance, spread from cusip_universe where cusip = '%s'", cusip)
        indicdata <- dbGetQuery(dbCon, sqlstring)
        cusipdata[[cusip]]$currbal <- indicdata$curr_balance
        cusipdata[[cusip]]$spread <- indicdata$spread
        for(j in 1:n.scenarios){
            filename <- sprintf("%s-CF-Scen%s.txt", cusip, j)
            if(!file.exists(file.path(root.dir, "Scenarios", paste0("Prices_", workdate), filename))){
                next
            }
            data <- read.table(file.path(root.dir, "Scenarios", paste0("Prices_", workdate), filename),
                               sep = "\t", header=F, colClasses="character", skip = 3, comment.char="")
            data <- data[, 1:5]
            colnames(data) <- c("Date", intexfields)
            data$Date <- as.Date(data$Date, "%b %d, %Y")
            if(any(is.na(data$Date))){
                cat(sprintf("file: %s is messed up", filename), "\n")
                flag <- TRUE
                break
            }
            futuredates <- data$Date[data$Date >= L3m$params$tradeDate]
            pastdates <- data$Date[data$Date < L3m$params$tradeDate]
            if(i==1||length(futuredates)>length(DC$times)){
                DC <- DiscountCurve(L3m$params, L3m$tsQuotes, yearFrac(L3m$params$tradeDate, futuredates))
            }
            if(length(futuredates) == 0){
                df <- rep(1, length(pastdates))
            }else{
                df <- c(rep(1, length(pastdates)), DC$discounts[1:length(futuredates)])
            }
            pv <- c()
            for(field in fields){
                cleanfield <- tryCatch(sanitize.column(data[,field]),
                                       warning = function(w)w)
                if(inherits(cleanfield, "warning")||any(is.na(cleanfield))){
                    cat(sprintf("file: %s is messed up", filename), "\n")
                    flag <- TRUE
                    break
                }else{
                    data[,field] <- cleanfield
                }
                if(length(futuredates) == 0){
                    df <- rep(1, length(pastdates))
                }else{
                    df <- c(rep(1, length(pastdates)), DC$discounts[1:length(futuredates)])
                }
                if(nrow(data)>0){
                    pv <- c(pv, crossprod(df, data[,field]))
                }else{
                    pv <- c(pv, 0)
                }
            }
            if(flag){
                break
            }else{
                data[,"Balance" ] <- tryCatch(sanitize.column(data[,"Balance"]),
                                              warning = function(w){cat("garbled", dealname, i)})
                wal <- crossprod(yearFrac(workdate, data$Date)[-1], -diff(data[,"Balance"]))/
                    indicdata$curr_balance
                if(pv[1] == 0){
                    duration <- 0
                }else{
                    duration <- crossprod(data[,"Cashflow"], df * yearFrac(workdate, data$Date))/pv[1]
                }
                tryCatch(r[j,] <- c(pv, wal, duration),
                         error =function(e) browser())
            }
        }

        if(flag){
            cusipdata[[cusip]] <- NULL
            flag <- FALSE
        }else{
            cat("done", cusip, "\n")
            cusipdata[[cusip]]$fields <- r
            cusipdata[[cusip]]$price <- 100 * crossprod(cfdata[[dealnames[i]]]$weight,
                                                        cusipdata[[cusip]]$fields[,"Cashflow"])/cusipdata[[cusip]]$currbal
            cusipdata[[cusip]]$wal <- crossprod(cfdata[[dealnames[i]]]$weight,
                                                cusipdata[[cusip]]$fields[,"wal"])
            cusipdata[[cusip]]$duration <- crossprod(cfdata[[dealnames[i]]]$weight,
                                                     cusipdata[[cusip]]$fields[,"duration"])
        }
    }
    return(cusipdata)
}

cfdata <- getdealcf(dealnames, workdate)
availablecusips <- cusips[dealnamefromcusip(cusips) %in% names(cfdata)]
cusipdata <- getcusipcf(availablecusips, cfdata, workdate)
## upload wapbasis
for(dealname in names(cfdata)){
    sqlstring <- sprintf(paste0("UPDATE et_deal_model_numbers SET ",
                   "wapbasis = '%s' WHERE dealname= '%s' AND updatedate = '%s'"),
                         cfdata[[dealname]]$wapbasis*100,
                         dealname,
                         strftime(workdate))
    dbSendQuery(dbCon, sqlstring)
}

## upload model data
for(cusip in names(cusipdata)){
    columns <- c("Cusip", "price", "wal", "duration", "updatedate")
    values <- c(cusip, cusipdata[[cusip]]$price, cusipdata[[cusip]]$wal,
                cusipdata[[cusip]]$duration, strftime(workdate))
    colstring <- paste(columns[!is.na(values)], collapse=",")
    valstring <-  paste(values[!is.na(values)], collapse="','")
    sqlstring <- sprintf(paste0("INSERT INTO et_cusip_model_numbers",
                                "(%s) VALUES('%s')"),
                         colstring, valstring)
    dbSendQuery(dbCon, sqlstring)
}