aboutsummaryrefslogtreecommitdiffstats
path: root/python/notebooks/swaption_scenarios.ipynb
blob: 6399d8e473c07c8de0342e9798770bf3d4095837 (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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import analytics\n",
    "import math\n",
    "\n",
    "from graphics import plot_color_map\n",
    "from analytics import Swaption, BlackSwaption, BlackSwaptionVolSurface, CreditIndex, Portfolio\n",
    "from analytics.scenarios import run_swaption_scenarios, run_index_scenarios, run_portfolio_scenarios, run_portfolio_scenarios_module\n",
    "from scipy.interpolate import SmoothBivariateSpline\n",
    "from utils.db import dbconn, dbengine\n",
    "from risk.swaptions import get_swaption_portfolio\n",
    "from scipy.optimize import brentq\n",
    "from pandas.tseries.offsets import BDay\n",
    "\n",
    "conn = dbconn('dawndb')\n",
    "dawn_engine = dbengine('dawndb')\n",
    "conn.autocommit=True\n",
    "analytics.init_ontr()\n",
    "pd.options.display.float_format = \"{:,.2f}\".format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "############# Current portfolio one day PNL/Delta scenario\n",
    "portf = get_swaption_portfolio(datetime.date.today() - pd.offsets.BDay(), conn, source_list=['GS'])\n",
    "\n",
    "hedges = pd.read_sql_query(\"SELECT security_desc, notional FROM list_cds_positions_by_strat(%s) \"\n",
    "                           \"WHERE folder in ('IGOPTDEL', 'HYOPTDEL')\",\n",
    "                           conn, params=(datetime.date.today(),))\n",
    "\n",
    "for i, r in hedges.iterrows():\n",
    "    portf.add_trade(CreditIndex(r['security_desc'].split(\" \")[1],\n",
    "                                r['security_desc'].split(\" \")[3][1:],\n",
    "                                '5yr', value_date=datetime.date.today() - pd.offsets.BDay(),\n",
    "                                notional = r['notional']), ('delta', i))\n",
    "\n",
    "vol_surface = {}\n",
    "for trade in portf.swaptions:\n",
    "    vs = BlackSwaptionVolSurface(trade.index.index_type, trade.index.series, \n",
    "                                 value_date=datetime.date.today(), interp_method = \"bivariate_linear\")\n",
    "    vol_surface[(trade.index.index_type, trade.index.series, trade.option_type)] = vs[vs.list(source='GS', option_type=trade.option_type)[-1]]\n",
    "\n",
    "#Set original_pv as of yesterday's EOD levels, don't reset PV after this time\n",
    "portf.mark(interp_method=\"bivariate_linear\", source_list=['GS'])\n",
    "portf.reset_pv()\n",
    "\n",
    "#set ref to today's levels\n",
    "portf.value_date = datetime.date.today()\n",
    "portf.mark(interp_method=\"bivariate_linear\", source_list=['GS'])\n",
    "\n",
    "spread_shock = np.round(np.arange(-.1, .1, .01), 4)\n",
    "scens = run_portfolio_scenarios(portf, [datetime.datetime.now()], params=['pnl', 'hy_equiv'],\n",
    "                                spread_shock=spread_shock,\n",
    "                                vol_shock=[0],\n",
    "                                corr_shock=[0],\n",
    "                                vol_surface=vol_surface)\n",
    "pnl = scens.xs('pnl', level = 2, axis=1).sum(axis=1)\n",
    "hy_equiv = scens.xs('hy_equiv', level = 2, axis=1).sum(axis=1)\n",
    "\n",
    "ig = CreditIndex('IG', 32, '5yr')\n",
    "ig.mark()\n",
    "\n",
    "pnl.index = pnl.index.set_levels((1+pnl.index.get_level_values('spread_shock')) * ig.spread, level = 'spread_shock')\n",
    "hy_equiv.index = pnl.index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pnl, hy_equiv\n",
    "#plot_trade_scenarios(portf)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#breakeven calc\n",
    "index = 'HY'\n",
    "series = 32\n",
    "value_date = datetime.date.today()\n",
    "option_delta = CreditIndex(index, series, '5yr')\n",
    "#option_delta.spread = 56.5\n",
    "option_delta.price = 106.0\n",
    "option1 = BlackSwaption(option_delta, datetime.date(2019, 12, 16), 106.5, option_type=\"receiver\") \n",
    "option1.sigma = .35\n",
    "option1.notional = 100_000_000 \n",
    "option_delta.notional = -option1.delta * option1.notional\n",
    "portf = Portfolio([option1, option_delta], trade_ids=['opt1', 'delta'])\n",
    "portf.value_date = value_date\n",
    "portf.reset_pv()\n",
    "portf.value_date = value_date + BDay(1)\n",
    "orig_ref = portf.ref\n",
    "\n",
    "def get_pnl(portf, x):\n",
    "    portf.ref = x\n",
    "    portf.sigma = float(vs[surface_id](self.T, np.log(self.moneyness)))\n",
    "    return portf.pnl\n",
    "\n",
    "if index == 'IG':\n",
    "    widening = brentq(lambda x: get_pnl(portf, x), portf.ref, portf.ref + 10)\n",
    "    portf.ref = orig_ref\n",
    "    tightening = brentq(lambda x: get_pnl(portf, x), portf.ref-10, portf.ref)\n",
    "    portf.ref = orig_ref\n",
    "else: \n",
    "    widening = brentq(lambda x: get_pnl(portf, x), portf.ref-3, portf.ref)\n",
    "    portf.ref = orig_ref\n",
    "    tightening = brentq(lambda x: get_pnl(portf, x), portf.ref, portf.ref + 3)\n",
    "    portf.ref = orig_ref\n",
    "\n",
    "tightening, orig_ref, widening"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Trade Analysis - pre-trade analytics\n",
    "index = 'IG'\n",
    "series = 32\n",
    "option_delta = CreditIndex(index, series, '5yr') \n",
    "option_delta.spread = 55\n",
    "option1 = BlackSwaption(option_delta, datetime.date(2019, 10, 16), 50, option_type=\"receiver\") \n",
    "option2 = BlackSwaption(option_delta, datetime.date(2019, 10, 16), 77.5, option_type=\"payer\") \n",
    "option1.sigma = .4\n",
    "option2.sigma = .63\n",
    "option1.notional = 100_000_000 \n",
    "option2.notional = 100_000_000 \n",
    "option1.direction = 'Long' \n",
    "option2.direction = 'Short' \n",
    "option_delta.notional = -option1.delta * option1.notional - option2.delta * option2.notional\n",
    "portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "date_range = pd.bdate_range(portf.value_date, portf.value_date + pd.tseries.offsets.BDay(30), freq='3B')\n",
    "vol_shock = np.arange(-.15, .31, 0.01)\n",
    "spread_shock = np.arange(-.2, 2, 0.01)\n",
    "vol_surface = {}\n",
    "for trade in portf.swaptions:\n",
    "    vs = BlackSwaptionVolSurface(trade.index.index_type, trade.index.series, \n",
    "                             value_date=portf.value_date, interp_method = \"bivariate_linear\")\n",
    "    vol_surface[(trade.index.index_type, trade.index.series, trade.option_type)] = vs[vs.list(source='GS', option_type=trade.option_type)[-1]]\n",
    "\n",
    "df = run_portfolio_scenarios(portf, date_range, params=[\"pnl\"],\n",
    "                             spread_shock = spread_shock,\n",
    "                             vol_shock = vol_shock,\n",
    "                             vol_surface = vol_surface)\n",
    "df = df.reset_index()\n",
    "df.vol_shock = df.vol_shock.round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_trade_scenarios(portf, shock_min=-.15, shock_max=.2, vol_time_roll=True):\n",
    "    portf.reset_pv()\n",
    "    end_date = min(portf.swaptions, key=lambda x: x.exercise_date).exercise_date\n",
    "    date_range = pd.bdate_range(portf.value_date,\n",
    "                                end_date - pd.tseries.offsets.BDay(), freq='3B')\n",
    "    vol_shock = np.arange(-.15, .31, 0.01)\n",
    "    spread_shock = np.arange(shock_min, shock_max, 0.01)\n",
    "    index = portf.indices[0].index_type\n",
    "    vol_surface = {}\n",
    "    for trade in portf.swaptions:\n",
    "        vs = BlackSwaptionVolSurface(trade.index.index_type, trade.index.series, \n",
    "                                 value_date=portf.value_date, interp_method = \"bivariate_linear\")\n",
    "        vol_surface[(trade.index.index_type, trade.index.series, trade.option_type)] = vs[vs.list(option_type=trade.option_type)[-1]]\n",
    "    \n",
    "    df = run_portfolio_scenarios(portf, date_range, params=[\"pnl\",\"delta\"],\n",
    "                                 spread_shock = spread_shock,\n",
    "                                 vol_shock = vol_shock,\n",
    "                                 vol_surface = vol_surface)\n",
    "    df = df.reset_index()\n",
    "    df.vol_shock = df.vol_shock.round(2)\n",
    "\n",
    "    if index == 'HY':\n",
    "        df['price'] = 100 + (500 - portf.indices[0].spread * (1 + df.spread_shock)) \\\n",
    "                    * abs(portf.indices[0].DV01) / portf.indices[0].notional * 100\n",
    "        df = df.set_index(['date', 'price', 'vol_shock'])\n",
    "        sort_order = [True, False]\n",
    "    else:\n",
    "        df['spread'] = portf.indices[0].spread * (1 +  df.spread_shock)\n",
    "        df = df.set_index(['date', 'spread', 'vol_shock'])\n",
    "        sort_order = [True, False]\n",
    "    \n",
    "    #If the multilevels index contains strategy drop it\n",
    "    if df.columns.nlevels == 3: \n",
    "        df.columns = df.columns.droplevel(level=0)\n",
    "    pnl = df.xs('pnl', axis=1, level=1).sum(axis=1)\n",
    "    for trade_id, t in portf.items():\n",
    "        if isinstance(t, BlackSwaption):\n",
    "            if len(trade_id) == 2:\n",
    "                trade_id = trade_id[1]\n",
    "            df[(trade_id, 'delta')] *= -t.notional \n",
    "    delta = df.xs('delta', axis=1, level=1).sum(axis=1).xs(0, level='vol_shock')\n",
    "    delta += sum([x.notional * -1 if x.direction == 'Buyer' else 1 for x in portf.indices])\n",
    "\n",
    "    pnl.name = 'pnl'\n",
    "    delta.name = 'delta'\n",
    "\n",
    "    plot_color_map(pnl.xs(0, level='vol_shock'), sort_order)\n",
    "    plot_color_map(delta, sort_order)\n",
    "    plot_color_map(pnl.loc[date_range[-1]], sort_order)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calc_simple_scenario(portf, shock_min=-.15, shock_max=.2):\n",
    "    portf.reset_pv()\n",
    "    end_date = min(portf.swaptions, key=lambda x: x.exercise_date).exercise_date\n",
    "    date_range = pd.bdate_range(portf.value_date,\n",
    "                                end_date - pd.tseries.offsets.BDay(), freq='3B')\n",
    "    vol_shock = [0]\n",
    "    spread_shock = np.arange(shock_min, shock_max, 0.01)\n",
    "    index = portf.indices[0].index_type\n",
    "    vol_surface = {}\n",
    "    for trade in portf.swaptions:\n",
    "        vs = BlackSwaptionVolSurface(trade.index.index_type, trade.index.series, \n",
    "                                 value_date=portf.value_date, interp_method = \"bivariate_linear\")\n",
    "        vol_surface[(trade.index.index_type, trade.index.series, trade.option_type)] = vs[vs.list(option_type=trade.option_type)[-1]]\n",
    "\n",
    "    df = run_portfolio_scenarios(portf, date_range, params=[\"pnl\"],\n",
    "                                 spread_shock = spread_shock,\n",
    "                                 vol_shock = vol_shock,\n",
    "                                 vol_surface = vol_surface)\n",
    "\n",
    "    return df.xs('pnl', axis=1, level=1).sum(axis=1) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Dec Jan 2017 Trade\n",
    "option_delta = CreditIndex.from_tradeid(864)\n",
    "option1 = BlackSwaption.from_tradeid(3, option_delta)\n",
    "option2 = BlackSwaption.from_tradeid(4, option_delta)\n",
    "portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])\n",
    "#plot_trade_scenarios(portf)\n",
    "\n",
    "#Feb 2017: Sell May Buy April Calendar Trade\n",
    "option_delta = CreditIndex.from_tradeid(870)\n",
    "option1 = BlackSwaption.from_tradeid(5, option_delta)\n",
    "option2 = BlackSwaption.from_tradeid(6, option_delta)\n",
    "portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])\n",
    "#plot_trade_scenarios(portf)\n",
    "\n",
    "#April 2017: Sell May Buy June Calendar Trade\n",
    "option_delta = CreditIndex.from_tradeid(874)\n",
    "option1 = BlackSwaption.from_tradeid(7, option_delta)\n",
    "option2 = BlackSwaption.from_tradeid(8, option_delta)\n",
    "portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])\n",
    "#plot_trade_scenarios(portf)\n",
    "\n",
    "#June July 2017 Calendar Trade\n",
    "option_delta_pf = CreditIndex.from_tradeid(874)\n",
    "option_delta2_pf = CreditIndex.from_tradeid(879)\n",
    "\n",
    "option1_pf = BlackSwaption.from_tradeid(7, option_delta_pf)\n",
    "option2_pf = BlackSwaption.from_tradeid(9, option_delta_pf)\n",
    "option_delta_pf.notional = 50_335_169\n",
    "\n",
    "portf = Portfolio([option1_pf, option2_pf, option_delta_pf], trade_ids=['opt1', 'opt2', 'delta'])\n",
    "portf.value_date = datetime.date(2017, 5, 17)\n",
    "portf.mark()\n",
    "#plot_trade_scenarios(portf)\n",
    "\n",
    "#July 2017: Buy Sept HY payer spread\n",
    "option_delta = CreditIndex.from_tradeid(891)\n",
    "option1 = BlackSwaption.from_tradeid(10, option_delta)\n",
    "option2 = BlackSwaption.from_tradeid(11, option_delta)\n",
    "portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])\n",
    "#plot_trade_scenarios(portf)\n",
    "\n",
    "#March 2019: May Bull Risky\n",
    "option_delta = CreditIndex.from_tradeid(1063)\n",
    "option1 = BlackSwaption.from_tradeid(41, option_delta)\n",
    "option2 = BlackSwaption.from_tradeid(40, option_delta)\n",
    "portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])\n",
    "results = calc_simple_scenario(portf, shock_min=-.3, shock_max=.3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Look at steepness of volatility - 30 days, .85 vs .15 payer deltas on HY\n",
    "days = 30\n",
    "delta1 = .85\n",
    "delta2 = .15\n",
    "index = 'HY'\n",
    "\n",
    "sql_str = \"select b.quotedate, b.ref, b.ref_id, b.expiry, a.delta_pay, a.vol from \" \\\n",
    "          \"swaption_quotes a join swaption_ref_quotes b on a.ref_id = b.ref_id and index = %s\"\n",
    "df = pd.read_sql_query(sql_str, dbengine('serenitasdb'), \n",
    "     index_col=['quotedate'], parse_dates={'quotedate': {'utc': True}}, params=[index])\n",
    "df['days_expiry'] =  (df.expiry - df.index.date).dt.days\n",
    "r_1 = []\n",
    "for i, g in df.groupby(pd.Grouper(freq='D', level='quotedate')):\n",
    "    r = []\n",
    "    for i_1, g_1 in g.groupby(['days_expiry', 'delta_pay']):\n",
    "        r.append([i_1[0], i_1[1], g_1['vol'].mean()])\n",
    "    if len(r) > 0:\n",
    "        temp = np.dstack(r)\n",
    "        f = SmoothBivariateSpline(temp[0][0], temp[0][1], temp[0][2])\n",
    "        r = (f(days, delta1) - f(days, delta2))[0][0]\n",
    "        r_1.append([i, r])\n",
    "    else:\n",
    "        pass\n",
    "df_1 = pd.DataFrame(r_1, columns=['date', 'steepness'])\n",
    "df_1.set_index('date').plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}