aboutsummaryrefslogtreecommitdiffstats
path: root/python/exploration/swaption_calendar_spread.py
blob: 8eaaad0ad53019df2d4d218d95f4048d9b01bf3a (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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import sys
#don't do this at home
sys.path.append("..")
from analytics import Swaption, BlackSwaption, Index, VolatilitySurface
from analytics.scenarios import run_swaption_scenarios, run_index_scenarios
from pandas.tseries.offsets import BDay
import datetime
import numpy as np
import pandas as pd
from scipy.interpolate import SmoothBivariateSpline
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
    '''
    Function to offset the "center" of a colormap. Useful for
    data with a negative min and positive max and you want the
    middle of the colormap's dynamic range to be at zero

    Input
    -----
      cmap : The matplotlib colormap to be altered
      start : Offset from lowest point in the colormap's range.
          Defaults to 0.0 (no lower ofset). Should be between
          0.0 and `midpoint`.
      midpoint : The new center of the colormap. Defaults to
          0.5 (no shift). Should be between 0.0 and 1.0. In
          general, this should be  1 - vmax/(vmax + abs(vmin))
          For example if your data range from -15.0 to +5.0 and
          you want the center of the colormap at 0.0, `midpoint`
          should be set to  1 - 5/(5 + 15)) or 0.75
      stop : Offset from highets point in the colormap's range.
          Defaults to 1.0 (no upper ofset). Should be between
          `midpoint` and 1.0.
    '''
    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False),
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap

def plot_df(df, spread_shock, vol_shock, attr="pv"):
    val_date = df.index[0].date()
    fig = plt.figure()

    ax = fig.gca(projection='3d')
    ## use smoothing spline on a finer grid
    series = df[attr]
    f = SmoothBivariateSpline(df.vol_shock.values, df.spread_shock.values, series.values)
    xx, yy = np.meshgrid(vol_shock, spread_shock)
    surf = ax.plot_surface(xx, yy, f(vol_shock, spread_shock).T, cmap=cm.viridis)
    ax.set_xlabel("Volatility shock")
    ax.set_ylabel("Spread")
    ax.set_zlabel("PnL")
    ax.set_title('{} of Trade on {}'.format(attr.title(), val_date))

def plot_color_map(df, spread_shock, vol_shock, attr="pv", path="."):

    val_date = df.index[0].date()
    #rows are spread, columns are volatility surface shift
    fig, ax = plt.subplots()
    #We are plotting an image, so we have to sort from high to low on the Y axis
    df.sort_values(by=['spread_shock','vol_shock'], ascending = [True,False], inplace = True)
    series = df[attr]

    #import pdb; pdb.set_trace()
    midpoint = 1 - series.max() / (series.max() + abs(series.min()))
    shifted_cmap = shiftedColorMap(cm.RdYlGn, midpoint=midpoint, name='shifted')

    chart = ax.imshow(series.values.reshape(spread_shock.size, vol_shock.size).T,
                      extent=(spread_shock.min(), spread_shock.max(),
                              vol_shock.min(), vol_shock.max()),
                      aspect='auto', interpolation='bilinear', cmap=shifted_cmap)

    ax.set_xlabel('Spread')
    ax.set_ylabel('Volatility shock')
    ax.set_title('{} of Trade on {}'.format(attr.title(), val_date))

    fig.colorbar(chart, shrink=.8)
    fig.savefig(os.path.join(path, "payer_swap_", attr, "_{}.png".format(val_date)))

def plot_time_color_map(df, spread_shock, attr="pv", path=".", color_map = cm.RdYlGn):

    val_date = df.index[0].date()
    df = df.reset_index()
    df['days'] = (df['date'] - val_date).dt.days
    df.sort_values(by=['date','spread_shock'], ascending = [True,False], inplace = True)
    date_range = df.days.unique()

    fig, ax = plt.subplots()
    series = df[attr]
    midpoint = 1 - series.max() / (series.max() + abs(series.min()))
    shifted_cmap = shiftedColorMap(color_map, midpoint=midpoint, name='shifted')

    chart = ax.imshow(series.values.reshape(date_range.size, spread_shock.size).T,
                      extent=(date_range.min(), date_range.max(),
                              spread_shock.min(), spread_shock.max()),
                      aspect='auto', interpolation='bilinear', cmap=shifted_cmap)

    ax.set_xlabel('Days')
    ax.set_ylabel('Spread')
    ax.set_title('{} of Trade'.format(attr.title()))

    fig.colorbar(chart, shrink=.8)
    #fig.savefig(os.path.join(path, "payer_swap_", attr, "_{}.png".format(val_date)))

def april_may_2017_trade():
    option_delta = Index.from_tradeid(870)
    ref = option_delta.spread
    payer1 = BlackSwaption(option_delta, datetime.date(2017, 4, 19), 65)
    payer2 = BlackSwaption(option_delta, datetime.date(2017, 5, 17), 72.5)
    payer1.sigma = .348
    payer2.sigma = .466
    payer1.notional = 100_000_000
    payer2.notional = 100_000_000

    cost = 5000

    date_range = pd.bdate_range(option_delta.trade_date, pd.Timestamp('2017-04-19') - BDay(), freq = '5B')
    vol_shock = np.arange(-0.15, 0.3, 0.01)
    spread_shock = np.arange(-0.2, 0.3, 0.01)
    vs = VolatilitySurface("IG", 27, trade_date=option_delta.trade_date)
    vol_surface = vs[vs.list()[-1]]
    # #
    df1 = run_swaption_scenarios(payer1, date_range, spread_shock, vol_shock, vol_surface, ['pv','delta'])
    df2 = run_swaption_scenarios(payer2, date_range, spread_shock, vol_shock, vol_surface, ['pv','delta'])
    df3 = run_index_scenarios(option_delta, date_range, spread_shock)

    # #plot it
    week = -1
    df = df1.reset_index()
    df3 = df3.reset_index()
    df = df.merge(df3, on=['date','spread_shock'])
    df = df.set_index('date')
    df = df.assign(pv=df1.pv-df2.pv+df.pnl-cost)
    df = df.assign(delta=df1.delta*payer1.notional-df2.delta*payer2.notional+option_delta.notional)

    spread_plot_range = ref * (1 + np.arange(-0.2, 0.3, 0.001))
    vol_shock_range = np.arange(-0.15, 0.3, 0.001)
    plot_df(df.loc[date_range[week]], spread_plot_range, vol_shock_range)
    plot_color_map(df.loc[date_range[week]], ref * (1 + spread_shock), vol_shock)
    plot_time_color_map(df[round(df.vol_shock,2)==0], ref * (1 + spread_shock), 'delta')
    plot_time_color_map(df[round(df.vol_shock,2)==0], ref * (1 + spread_shock), 'pv')



option_delta = Index.from_name('ig', 28, '5yr')
option_delta.spread = 68

payer1 = BlackSwaption(option_delta, datetime.date(2017, 6, 21), 65)
payer2 = BlackSwaption(option_delta, datetime.date(2017, 5, 17), 75)
payer3 = BlackSwaption(option_delta, datetime.date(2017, 7, 19), 75)
payer1.sigma = .388
payer2.sigma = .503
payer3.sigma = .43
payer1.notional = 150_000_000
payer2.notional = -100_000_000
payer3.notional = 100_000_000 *0
vol_time_roll = False
no_delta = False

ref = option_delta.spread

if payer2.notional == 0:
    option_delta.notional = payer1.notional * payer1.delta
elif payer3.notional == 0:
    option_delta.notional = payer1.notional * payer1.delta + payer2.notional * payer2.delta
else:
    option_delta.notional = payer1.notional * payer1.delta + payer2.notional * payer2.delta + payer3.notional * payer3.delta

#option_delta.notional = -100_000_000
if option_delta.notional > 0: option_delta.direction = 'Seller'

if no_delta: option_delta.notional = 0.01
option_delta._original_clean_pv = option_delta._clean_pv
option_delta._original_trade_date = option_delta.trade_date
cost = payer1.pv + payer2.pv + payer3.pv

date_range = pd.bdate_range(option_delta.trade_date, pd.Timestamp('2017-05-16') - BDay(), freq = '3B')
vol_shock = np.arange(-0.15, 0.3, 0.01)
spread_shock = np.arange(-0.2, 0.3, 0.01)
vs = VolatilitySurface("IG", 28, trade_date=option_delta.trade_date)
vol_select = max([t for t in vs.list() if t[1] == 'BAML' and t[2] == 'payer' and t[3] == 'black'])
vol_surface = vs[vol_select]
# #

df1 = run_swaption_scenarios(payer1, date_range, spread_shock, vol_shock, vol_surface, ['pv','delta'], vol_time_roll)
if payer2.notional != 0: df2 = run_swaption_scenarios(payer2, date_range, spread_shock, vol_shock, vol_surface, ['pv','delta'], vol_time_roll)
if payer3.notional != 0: df3 = run_swaption_scenarios(payer3, date_range, spread_shock, vol_shock, vol_surface, ['pv','delta'], vol_time_roll)

dfdelta = run_index_scenarios(option_delta, date_range, spread_shock)

# #plot it
week = -4
df = df1.reset_index()
dfdelta = dfdelta.reset_index()
df = df.merge(dfdelta, on=['date','spread_shock'])
df = df.set_index('date')

if payer2.notional == 0:
    df = df.assign(pv=df1.pv+df.pnl-cost)
    df = df.assign(delta=df1.delta*payer1.notional+option_delta.notional)
elif payer3.notional == 0:
    df = df.assign(pv=df1.pv+df2.pv+df.pnl-cost)
    df = df.assign(delta=df1.delta*payer1.notional+df2.delta*payer2.notional+option_delta.notional)
else:
    df = df.assign(pv=df1.pv+df2.pv+df3.pv+df.pnl-cost)
    df = df.assign(delta=df1.delta*payer1.notional+df2.delta*payer2.notional+df3.delta*payer3.notional+option_delta.notional)

spread_plot_range = ref * (1 + np.arange(-0.2, 0.3, 0.001))
vol_shock_range = np.arange(-0.15, 0.3, 0.001)

#plot_df(df.loc[date_range[week]], spread_plot_range, vol_shock_range)
#plot_color_map(df.loc[date_range[week]], ref * (1 + spread_shock), vol_shock)
plot_time_color_map(df[round(df.vol_shock,2)==0], ref * (1 + spread_shock), 'pv')
plot_time_color_map(df[round(df.vol_shock,2)==0], ref * (1 + spread_shock), 'delta', color_map = cm.coolwarm)

#down 10% vol
#plot_time_color_map(df[round(df.vol_shock,2)==-.1], ref * (1 + spread_shock), 'pv')
#plot_time_color_map(df[round(df.vol_shock,2)==-.1], ref * (1 + spread_shock), 'delta')