aboutsummaryrefslogtreecommitdiffstats
path: root/python/calibrate_tranches.py
blob: 0c4f1099686652c8600c8dfced15060a98022b74 (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
import numpy as np
from tranche_functions import *
from yieldcurve import YC
import yaml
import datetime
import os
import pandas as pd
import pdb

n_int = 500
n_credit = 100
Z, w = GHquad(n_int)

with open("../R/index_definitions.yml") as fh:
    indices = yaml.load(fh)
indices['hy21']['maturity'] = datetime.date(1970, 1, 1) + datetime.timedelta(indices['hy21']['maturity'])
hy21 = indices['hy21']
hy21["startdate"] = datetime.date(2013, 9, 20)
dates = [f[9:19] for f in os.listdir(os.path.join(os.environ['DATA_DIR'], "Backtest")) if "survprob" in f]

Rho = np.zeros((len(dates), 3))
for i, d in enumerate(dates):
    startdate = datetime.datetime.strptime(d, "%Y-%m-%d")
    ts = YC(startdate)
    with open(os.path.join(os.environ['DATA_DIR'], "Backtest", "recov_{0}.csv".format(d))) as fh:
        recov = np.array([float(e) for e in fh], dtype='double', order='F')

    with open(os.path.join(os.environ['DATA_DIR'], "Backtest", "survprob_{0}.csv".format(d))) as fh:
        fh.readline() ##skip header
        SurvProb = np.array([[float(e) for e in line.split(",")] for line in fh], dtype='double', order='F')

    defaultprob = 1 - SurvProb
    issuerweights = np.ones(100)/100

    rho = 0.4
    Ngrid = 101

    K = np.array([0, 0.15, 0.25, 0.35, 1])

    Kmod = adjust_attachments(K, hy21["loss"], hy21["factor"])
    quotes = pd.read_csv(os.path.join(os.environ['BASE_DIR'], "Scenarios", "Calibration",
                                      "hy21_tranches_{0}.csv".format(d)))
    quotes = quotes["Mid"]/100
    dK = np.diff(Kmod)
    quotes = np.cumsum(dK * (1-quotes))
    sched = creditSchedule(startdate, "5Yr", 0.05, ts, enddate=hy21["maturity"])
    acc = cdsAccrued(startdate, 0.05)
    for j, q in enumerate(quotes[:-1]):
        def aux(rho):
            L, R = BClossdist(defaultprob, issuerweights, recov, rho, Z, w, 101)
            cl = tranche_cl(L, R, sched, 0, Kmod[j+1])
            pl = tranche_pl(L, sched, 0, Kmod[j+1])
            return cl+pl+q-acc
        l, u = (0, 1)
        for _ in range(10):
            rho = (l+u)/2.
            if aux(rho) > 0:
                u = rho
            else:
                l = rho
        Rho[i, j] = (l+u)/2.
    print(Rho[i,:])