aboutsummaryrefslogtreecommitdiffstats
path: root/R/new_index_series.R
blob: d685466759912de226a14e0b1f3422adc3f21c01 (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
library(Rbbg)
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
dbCon <- dbConnect(drv, dbname="serenitasdb", user="serenitas_user", password="Serenitas1",
                   host="debian")

bbgConn <- blpConnect(host='192.168.1.108', port='8194')

## This script helps adding the necessary data for a new index series
newbasketID <- function(indextype='IG', series, newid){
    sqlstr <- "INSERT INTO index_version VALUES(%s, '%s', %s, '%s', '%s', 100, 0)"
    stmt <- sprintf(sqlstr, newid, indextype, series, 1, 100, 0, 'infinity')
    dbSendQuery(dbCon, stmt)
}
##TODO: fill the index
indextype <- 'IG'
oldseries <- 22
newseries <- 23
newid <- 338
newbasketID('IG', 23, 338)

oldindex <- bds(bbgConn, sprintf("CDX %s CDSI S%s 5Y Corp", indextype, oldseries), "INDX_MEMBERS")
newindex <- bds(bbgConn, sprintf("CDX %s CDSI S%s 5Y Corp", indextype, newseries), "INDX_MEMBERS")
oldtickers <- oldindex[,5]
tickers <- newindex[,5]

data <- bdp(bbgConn, paste(tickers, "Corp"), c("cds_company_id", "cds_restructuring_type", "cds_corp_tkr"))
olddata <- bdp(bbgConn, paste(oldtickers, "Corp"), c("cds_company_id", "cds_restructuring_type", "cds_corp_tkr"))
data <- cbind(tickers, data)
unique.tickers <- aggregate(data, by=list(data$cds_company_id), FUN=function(x)x[1])$tickers
cdscurves <- bds(bbgConn, paste(unique.tickers, "Curncy"), "CDS_CURVE_INFO")
curves <- aggregate(cdscurves[,2], by=list(cdscurves$ticker), FUN=function(x)x)
prep.data <- data.frame(Name=newindex[,1], company_id=data[,2], ticker=data[,4],
                        currency=newindex[,3], seniority=temp1[,4], doc_clause=data[,3])
newrowids <- which(!data[,'cds_company_id'] %in% olddata[,'cds_company_id'], 'cds_company_id')
newids <- data[!data[,'cds_company_id'] %in% olddata[,'cds_company_id'], 'cds_company_id']
sqlstr <- "INSERT INTO CDS_Issuers VALUES('%s', %s, '%s', '%s', '%s', '%s', '%s')"
with(prep.data,
     for(i in newids){
         stmt <- sprintf(sqlstr, gsub("'","''", Name[i]), company_id[i], ticker[i], currency[i],
                         seniority[i], doc_clause[i],
                         paste0("{\"", paste(curves[i,2], collapse="\",\""), "\"}"))
         dbSendQuery(dbCon, stmt)
     })

##fill index_list column
sqlstr <- "UPDATE CDS_Issuers SET index_list=index_list||%s where company_id=%s"
for(id in prep.data[,2]){
    dbSendQuery(dbCon, sprintf(sqlstr, newid, id))
}