aboutsummaryrefslogtreecommitdiffstats
path: root/python/load_cf.py
diff options
context:
space:
mode:
Diffstat (limited to 'python/load_cf.py')
-rw-r--r--python/load_cf.py77
1 files changed, 58 insertions, 19 deletions
diff --git a/python/load_cf.py b/python/load_cf.py
index 8ab0c31c..df892eea 100644
--- a/python/load_cf.py
+++ b/python/load_cf.py
@@ -5,12 +5,16 @@ from intex_scenarios import dealname_from_cusip
from zipfile import ZipFile
import re
import datetime
+from dateutil.relativedelta import relativedelta
from db import query_db
import yaml
-from quantlib.time.api import Schedule, Actual360, Period, Months, Calendar
-from quantlib.util.converter import pydate_to_qldate
+from quantlib.time.api import Schedule, Actual360, Period, Months, Calendar, Unadjusted
+from quantlib.util.converter import pydate_to_qldate, qldate_to_pydate
from quantlib.settings import Settings
from yieldcurve import YC
+import numpy as np
+from optimization import KLfit
+import pdb
if os.name =='nt':
root = "//WDsentinel/share/CorpCDOs"
@@ -18,14 +22,15 @@ elif os.name == 'posix':
root = '/home/share/CorpCDOs'
def sanitize_float(string):
- if isinstance(string, float):
- return string
- else:
+ try:
string = string.replace(",","")
if "(" in string:
return - float(string[1:-1])
else:
return float(string)
+ except AttributeError:
+ return string
+
def processzipfiles(workdate=datetime.date.today()):
pricesdir = os.path.join(root, "Scenarios", "Prices_" + str(workdate))
@@ -57,12 +62,17 @@ def get_configfile(dealname, workdate):
config = {"reinvflag": True}
return config
-def getdealcf(dealnames, cusips, zipfiles, workdate = datetime.date.today()):
+def basic_schedule(day_of_month, enddate, startdate=datetime.date.today()):
+ return Schedule(startdate, enddate, Period('1Mo'), Unadjusted)
+ #return pd.date_range(startdate, end=enddate, freq='MS') + datetime.timedelta(days=day_of_month-1)
+
+def getdealcf(dealnames, zipfiles, workdate = datetime.date.today()):
fiels = ["Cashflow", "Principal", "Interest"]
n_scenarios = 100
us_cal = Calendar.from_name('USA')
cfdata = {}
- m = YC()
+ m = YC(workdate)
+ fields = ["Cashflow", "Principal", "Interest"]
for dealname, i in dealnames.items():
zip = zipfiles[i]
cfdata[dealname]={}
@@ -71,23 +81,51 @@ def getdealcf(dealnames, cusips, zipfiles, workdate = datetime.date.today()):
sqlstr = "select \"Curr Collat Bal\", \"Reinv End Date\", \"Deal Next Pay Date\"," \
"maturity, \"Principal Bal\", \"Pay Day\" from historical_clo_universe(%s, %s)"
sqldata = query_db(sqlstr, (dealname, str(workdate)))
+ if sqldata["Pay Day"]:
+ sqldata["Pay Day"] = sqldata["Deal Next Pay Date"] + relativedelta(months=-3)
cfdata[dealname] = {"mv":mv, "currbal": sqldata["Curr Collat Bal"]}
config = get_configfile(dealname, workdate)
- prevpaydate = pydate_to_qldate(sqldata["Pay Day"])
- sched = Schedule(prevpaydate, pydate_to_qldate(sqldata["maturity"]), Period('1Mo'), us_cal)
- alldates = [day for day in sched if day > YC.settle_date]
- if (not sqldata["Reinv End Date"] or config["reinvflag"]):
- tranches = ["COLLAT"]
+ sched = Schedule(pydate_to_qldate(sqldata["Pay Day"]), pydate_to_qldate(sqldata["maturity"]),
+ Period('1Mo'), us_cal, Unadjusted)
+ pd_sched = [pd.to_datetime(str(day), format="%d/%m/%Y") for day in sched]
+
+ discounts = pd.Series([m.discount(day) if day > m.settle_date else 1 for day in sched],
+ index = pd_sched, name='df')
+
+ if (not sqldata["Reinv End Date"] or not config["reinvflag"]):
+ tranches = ["COLLAT"]
else:
tranches = ["COLLAT_INITIAL", "COLLAT_REINVEST"]
- for tranche in tranches:
- for i in range(1, scenarios+1):
- filename = "{0}-{1}-CF-Scen{2}.txt".format(dealname.upper(), tranche, "CF", i)
- data = pd.read_table(filename)
- cfdata[dealname][tranche]
+ cf = {}
+ for tranche in tranches:
+ scen = {}
+ for i in range(1, n_scenarios+1):
+ filename = "{0}-{1}-CF-Scen{2}.txt".format(dealname.upper(), tranche, i)
+ with ZipFile(zip) as myzip:
+ data = pd.read_table(myzip.open(filename), skiprows=[1, 2], parse_dates=[0],
+ thousands=",",
+ date_parser = lambda x: datetime.datetime.strptime(x, "%b %d, %Y"),
+ index_col=0)
+ for c in fields:
+ if data.dtypes[c] != np.dtype('float64'):
+ data[c] = data[c].apply(sanitize_float)
+ data = data[fields].join(discounts)
+ scen[i] = np.dot(data["df"], data[fields])
+ cf[tranche] = pd.DataFrame(scen).T
+ cf[tranche].columns = fields
+ pdb.set_trace()
+ pdb.set_trace()
+ cfdata[dealname]["panel"] = pd.Panel(cf)
+ cf = cfdata[dealname]["panel"].minor_xs("Cashflow").T.sum()
+ cfdata[dealname]["wapbasis"] = (cf.mean() - mv)/mv
+ pdb.set_trace()
+ program = KLfit(cf.T/1e8, np.ones(n_scenarios)/n_scenarios, mv/1e8)
+ cfdata[dealname]["weight"] = program["weight"]
+ print(dealname)
+ return cfdata
# fields = ["Price", "WAL", "Market Value", "Modified Duration"]
# dealdata = {}
@@ -107,5 +145,6 @@ def getdealcf(dealnames, cusips, zipfiles, workdate = datetime.date.today()):
# dealdata = pd.concat(dealdata)
if __name__=="__main__":
- pomme = processzipfiles()
- getdealcf(**pomme)
+ workdate = datetime.date.today()
+ params = processzipfiles()
+ pomme = getdealcf(params["dealnames"], params["zipfiles"], workdate)