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
|
import sys
sys.path.append("..")
from graphics import plot_time_color_map
import analytics.tranche_functions as tch
import analytics.tranche_basket as bkt
import analytics.basket_index as idx_bkt
import numpy as np
import pandas as pd
from analytics import Swaption, BlackSwaption, Index, BlackSwaptionVolSurface, Portfolio, ProbSurface
from analytics.scenarios import run_swaption_scenarios, run_index_scenarios, run_portfolio_scenarios, run_tranche_scenarios
import exploration.swaption_calendar_spread as spread
from scipy.interpolate import interp1d
from datetime import date
from db import dbengine
engine = dbengine('serenitasdb')
def rv_calc1():
#let's do IG27 from IG29, need to get the quotes from risk_numbers_new not just random ones
#Get IG29-1 year shortened rho with TLP, compare to IG27 5y rho
index = 'IG'
series = 29
series2 = series -2
tenor = '5yr'
shortened = 4
method = 'TLP'
#Read existing results, find which ones need to run
try:
results = pd.read_csv(f"/home/serenitas/edwin/Python/rv_{index}{series}.csv",
parse_dates=['date'], index_col=['date'])
except IOError:
results = pd.DataFrame()
sql_string = "select distinct date from risk_numbers_new where index = %s and series = %s order by date desc"
df = pd.read_sql_query(sql_string, engine, params=(index, series), parse_dates=['date'])
df1 = pd.read_sql_query(sql_string, engine, params=(index, series2), parse_dates=['date'])
df = df.merge(df1, on=['date'])
df = df[~df.date.isin(results.index)]
rho_tlp, pv_tlp, rho_prev_index, pv_prev_index = [], [], [], []
tranche = bkt.TrancheBasket('IG', series, '5yr')
tranche2 = bkt.TrancheBasket('IG', series2, '5yr')
for trade_date in df.date:
tranche.trade_date = trade_date
tranche2.trade_date = trade_date
tranche.build_skew()
tranche.rho = tranche.map_skew(tranche, method, 4)
pv = tranche.tranche_pvs().bond_price
rho_tlp.append(tranche.rho[1:-1])
pv_tlp.append(pv)
tranche2.build_skew()
rho_prev_index.append(tranche2.rho[1:-1])
tranche.rho = tranche2.rho
pv = tranche.tranche_pvs(shortened=4).bond_price
pv_prev_index.append(pv)
temp1 = pd.DataFrame(rho_tlp, index=df.date, columns=['3_rho_tlp', '7_rho_tlp', '15_rho_tlp'])
temp2 = pd.DataFrame(pv_tlp, index=df.date, columns=['03_pv_tlp', '37_pv_tlp', '715_pv_tlp', '15100_pv_tlp'])
temp3 = pd.DataFrame(rho_prev_index, index=df.date, columns=['3_rho_ig27', '7_rho_ig27', '15_rho_ig27'])
temp4 = pd.DataFrame(pv_prev_index, index=df.date, columns=['03_pv_ig27', '37_pv_ig27', '715_pv_ig27', '15100_pv_ig27'])
results = results.append(pd.concat([temp1, temp2, temp3, temp4], axis=1))
result.to_csv("/home/serenitas/edwin/Python/rv_" + index + series + ".csv")
def dispersion():
from quantlib.time.api import Schedule, Rule, Date, Period, WeekendsOnly
from quantlib.settings import Settings
curves = {}
maturities = {}
settings = Settings()
for series in [24, 25, 26, 27, 28, 29]:
index_temp = idx_bkt.MarkitBasketIndex('IG', series, ["5yr",], trade_date=trade_date)
maturities[series] = index_temp.maturities[0]
cds_schedule = Schedule.from_rule(settings.evaluation_date, Date.from_datetime(maturities[series]),
Period('3M'), WeekendsOnly(), date_generation_rule=Rule.CDS2015)
sm, tickers = index_temp.survival_matrix(cds_schedule.to_npdates().view('int') + 134774)
curves[series] = pd.DataFrame(1 - sm, index=tickers, columns=cds_schedule)
#temp = (pd.to_datetime(maturities[series]) - datetime.datetime(1970,1,1)).days + 134774
#curves[series] = pd.concat([c.to_series() for _,_, c in index_temp.items()], axis=1)
curve_df = pd.concat(curves).stack()
curve_df.index.rename(['series', 'maturity', 'name'], inplace=True)
disp = {}
for series in [24, 25, 26, 27, 28, 29]:
temp = curve_df.xs([series, maturities[series].strftime('%Y-%m-%d')])
temp = temp[pd.qcut(temp, 10, labels=False) == 9]
disp[series] = temp.std()/temp.mean()
dispersion = pd.concat(disp)
curve_df.groupby(['series', 'maturity']).mean()
curve_df.groupby(['series', 'maturity']).std()
def run_scen(portf, tranche, spread_shock):
#Start with swaptions
index = portf.indices[0].index_type
series = portf.indices[0].series
trade_date=portf.indices[0].trade_date
earliest_expiry = min(portf.swaptions, key=lambda x: x.exercise_date).exercise_date
date_range = pd.bdate_range(trade_date, earliest_expiry - pd.offsets.BDay(), freq='5B')
vs = BlackSwaptionVolSurface(index,series, trade_date=trade_date)
ps = ProbSurface(index,series, trade_date=trade_date)
vol_surface = vs[vs.list(option_type='payer')[-1]]
df = run_portfolio_scenarios(portf, date_range, spread_shock, np.array([0]),
vol_surface, params=["pnl", "delta"])
df['frac_year'] = (df.index - pd.to_datetime(trade_date)).days/365
df['prob'] = df.apply(lambda df: ps.tail_prob(df.frac_year, df.spread, ps.list()[-1]), axis=1)
#now do the tranches
spread_range = (1+ spread_shock) * portf.indices[0].spread
results = run_tranche_scenarios(tranche, spread_range, date_range)
results.date = pd.to_datetime(results.date)
notional = 10000000
results['delta_tranche'] = -notional * (results['0-3_delta'] - 6* results['7-15_delta'])
results['pnl_tranche'] = notional * (results['0-3_pnl'] + results['0-3_carry'] -
6* (results['7-15_pnl'] + results['7-15_carry']))
results.index.name = 'spread'
#combine
df = df.reset_index().merge(results.reset_index(), on=['date', 'spread'])
df['final_pnl'] = df.pnl_tranche + df.pnl
df['final_delta'] = df.delta_tranche + df.delta
return df
def set_port():
#Construct Portfolio
option_delta = Index.from_name('IG', 30, '5yr')
option_delta.spread = 59
option1 = BlackSwaption(option_delta, date(2018, 6, 20), 80, option_type="payer")
option1.sigma = .621
option1.direction = 'Short'
option1.notional = 150_000_000
option_delta.notional = 1
portf = Portfolio([option1, option_delta])
portf.reset_pv()
trade_date = (pd.datetime.today() - pd.offsets.BDay(1)).normalize()
tranche = bkt.TrancheBasket('IG', 29, '5yr', trade_date=trade_date)
return portf, tranche
def set_df():
portf, tranche = set_port()
shock_min = -.3
shock_max = .8
spread_shock = np.arange(shock_min, shock_max, 0.05)
shock_range = (1+ spread_shock) * portf.indices[0].spread
results = run_scen(portf, tranche, spread_shock)
results = results.set_index('date')
return results, shock_range
def plot_scenarios():
df, shock_range = set_df()
plot_time_color_map(df, shock_range, attr="final_pnl")
plot_time_color_map(df, shock_range, attr="final_delta", color_map= 'rainbow', centered = False)
|