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
|
import psycopg2
import os
import re
import csv
import datetime
import pdb
from common import root, sanitize_float
from db import conn, query_db
import sys
import uuid
from load_indicative import upload_cusip_data, upload_deal_data
fields = ['Asset Name', 'Issuer', 'Contributed Balance', 'Maturity Date', \
'Asset Subtype', 'Asset Type', 'Gross Coupon', 'Spread', \
'Frequency', 'Next Paydate', 'Second Lien', 'LoanX ID', 'CUSIP',
'Market Price', 'Market Price Source', 'Market Price Date', 'Fixed or Float', \
'Defaulted Flag', 'Security Sub-Category', 'Structured Finance Security', \
'Life Floor', 'Reinvest Collat', 'Native Currency']
def convertToNone(s):
return None if s=='' else s
def upload_data(conn, dealnames, workdate):
for dealname in dealnames:
#dealname, updatedate = line.rstrip().split()
# updatedate = datetime.datetime.strptime(updatedate, '%m/%d/%Y')
#dealname = dealname.upper() + ",AD.txt
with open( os.path.join(root, "data", "Collaterals_" + workdate, dealname.upper() + "_AD.txt"),
"r", encoding='windows-1252') as fh:
dr = csv.DictReader(fh, dialect = 'excel-tab')
missingfields = set(fields).union({'Gross Margin'}) - set(dr.fieldnames)
if "LoanX ID" in missingfields:
print("LoanX ID column is missing. Probably an error in exporting from intex")
pdb.set_trace()
data = {}
for line in dr:
for f in missingfields:
line[f] = None
try:
line['Fixed or Float'] = line['Fixed or Float'].upper()
line['LoanX ID'] = line['LoanX ID'].upper()
line['CUSIP'] = line['CUSIP'].upper()
line['Asset Subtype'] = line['Asset Subtype'].replace("Reinvest ", "")
line['Asset Subtype'] = line['Asset Subtype'].replace("Reinv ", "")
except AttributeError:
pass
else:
#sanity checks for loanxid and cusip
if len(line['LoanX ID']) > 8:
print("dubious id found: {0}".format(line['LoanX ID']))
line['LoanX ID'] = line['LoanX ID'][:8]
if len(line['CUSIP']) > 9:
print("dubious CUSIP found: {0}".format(line['CUSIP']))
line['CUSIP'] = line['CUSIP'][:9]
if len(line['Asset Subtype'])>10:
line['Asset Subtype'] = line['Asset Subtype'][:9]
if 'Reinvest Collat' not in missingfields and \
line['Reinvest Collat'].upper() == 'Y' or line['Issuer'] == '':
# assume it's a reinvestment asset
line['Reinvest Collat'] = True
line['Issuer'] = line['ID Number']
if not line['Spread']:
line['Spread'] = line['Gross Margin']
for field in ['Spread', 'Gross Coupon', 'Market Price', 'Contributed Balance']:
line[field] = sanitize_float(line[field])
if line['Market Price'] == 0:
line['Market Price'] = None
#we store the Libor Floor in the database, so Life Floor is really Libor Floor
if line['Life Floor'] == "No limit":
line['Life Floor'] = 0
elif line['Life Floor']:
try:
line['Life Floor'] = float(line['Life Floor']) - float(line['Spread'])
except ValueError:
line['Life Floor'] = float('Nan')
# we take care of reinvestment asset lines
if not line['Asset Name']:
line['Asset Name'] = 'Reinv'
r = [convertToNone(line[field]) for field in fields]
#sometimes the Asset Name is not unique (we add random tag in this case)
if r[0] in data:
r[0] = r[0] + str(uuid.uuid4())[:3]
data[r[0]] = r[1:]
sqlstr = "select distinct(updatedate) from et_collateral where dealname= %s"
old_update_dates = [date[0] for date in query_db(sqlstr, params=(dealname,), one=False)]
sqlstr = "select max(\"Latest Update\") from clo_universe where dealname= %s and \"Latest Update\"<=%s"
updatedate = query_db(sqlstr, params = (dealname, workdate))[0]
# sanity check if we already have the data
reinsert = False
if updatedate in old_update_dates:
sqlstr = "SELECT count(*) FROM et_collateral where dealname = %s and updatedate= %s"
currlen = query_db(sqlstr, params = (dealname, updatedate))[0]
if currlen != len(data): #then we delete and just reupload
print("{0} has {1} rows in the database and current collateral file has {2}".format(dealname, currlen, len(data)))
with conn.cursor() as c:
sqlstr = "DELETE FROM et_collateral where dealname = %s and updatedate = %s"
c.execute(sqlstr, (dealname, updatedate))
conn.commit()
reinsert = True
if reinsert or not old_update_dates or updatedate not in old_update_dates:
sql_fields = ["dealname", "updatedate", "name", "IssuerName", "CurrentBalance",
"Maturity", "AssetSubtype", "AssetType", "GrossCoupon",
"Spread", "Frequency", "NextPaydate", "SecondLien", "LoanXID",
"Cusip", "IntexPrice", "IntexPriceSource", "IntexPriceDate",
"FixedOrFloat", "DefaultedFlag", "CovLite", "isCDO",
"Liborfloor", "ReinvFlag", "Currency"]
sqlstr = "INSERT INTO ET_COLLATERAL({0}) VALUES({1})".format(",".join(sql_fields),
",".join(["%s"] * len(sql_fields)))
with conn.cursor() as c:
try:
c.executemany(sqlstr, [(dealname, updatedate, k) + tuple(v) for k, v in data.items()])
except (psycopg2.DataError, TypeError) as detail:
print(detail)
pdb.set_trace()
conn.commit()
if __name__ == "__main__":
if len(sys.argv) > 1:
workdate = sys.argv[1]
else:
workdate = str(datetime.date.today())
if len(sys.argv) > 2:
dealnames = sys.argv[2:]
else:
dealnames = [re.sub("_AD.txt", "", d).lower() for d in
os.listdir(os.path.join(root, "data", "Collaterals_" + workdate))]
files = [os.path.join(root, "data", "Indicative_" + workdate, f) for f in
os.listdir(os.path.join(root, "data", "Indicative_" + workdate))]
cusip_files = [f for f in files if "TrInfo" in f]
deal_files = [f for f in files if "TrInfo" not in f]
#first load deal data
for deal_file in deal_files:
upload_deal_data(deal_file)
#then load tranche data
for cusip_file in cusip_files:
upload_cusip_data(cusip_file)
upload_data(conn, dealnames, workdate)
conn.close()
print("done")
|