aboutsummaryrefslogtreecommitdiffstats
path: root/python/notebooks/Curve Trades.ipynb
blob: a6ae0b7eac434db84791b50bf5614c1f763aafdc (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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import analytics.curve_trades as ct\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import graphics as g\n",
    "import globeop_reports as go\n",
    "\n",
    "from ipywidgets import widgets\n",
    "from analytics.scenarios import run_curve_scenarios\n",
    "from db import dbengine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w = widgets.Dropdown(\n",
    "    options=['IG', 'EU'],\n",
    "    value='IG',\n",
    "    description='Index:',\n",
    "    disabled=False,\n",
    ")\n",
    "w"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "index = w.value\n",
    "report_date = (pd.datetime.today() - pd.offsets.BDay(2)).normalize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#On the run spread differences\n",
    "spreads_diff = ct.curve_spread_diff(index, 6)\n",
    "spreads_diff.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Table of Spread Differences, and Z-score of current spread differences\n",
    "ct.spreads_diff_table(spreads_diff)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Theta per unit duration\n",
    "ct.theta_matrix_by_series(index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#on the run theta\n",
    "ct.on_the_run_theta(index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Curve Trade returns\n",
    "ct.curve_returns()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ct.cross_series_curve(index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Theta with 3-5-10 Strategy\n",
    "df = ct.ratio_within_series(param='duration')\n",
    "s = - df.theta2['3yr'] / df.duration_ratio_to_5yr['3yr'] \\\n",
    "    + 2 * df.theta2['5yr'] \\\n",
    "    - df.theta2['10yr'] / df.duration_ratio_to_5yr['10yr']\n",
    "s.dropna().unstack(-1).plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Theta with 5-10 Strategy: buy sell 5y, buy 10y\n",
    "s = df.theta2['5yr'] - df.theta2['10yr'] / df.duration_ratio_to_5yr['10yr']\n",
    "s.dropna().unstack(-1).plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Relative Spread Difference\n",
    "spread_ratio = ct.ratio_within_series(param = 'closespread')\n",
    "spread_ratio.groupby(level = ['date']).last()['closespread_ratio_to_5yr'].plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ct.curve_model('5yr', '10yr')\n",
    "model_results = ct.curve_model_results(model[0], model[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = ct.forward_spread(report_date, index)\n",
    "df.plot()\n",
    "plt.ylabel('spread')\n",
    "plt.xlabel('forward spread start date')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = ct.spot_forward(index)\n",
    "df = df.rename(columns={'1yr': 'Spot Spread - 1 Year Forward', 'current': 'Spot Spread - Today'})\n",
    "ax = df.plot(title = 'Credit Curve Roll Down')\n",
    "plt.ylabel('spread (bps)')\n",
    "ax.figure.savefig(\"/home/serenitas/edwin/PythonGraphs/curve_trades_roll_down.png\", bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "portf = ct.curve_pos(report_date, index)\n",
    "shock_min = -.5\n",
    "shock_max = .8\n",
    "spread_shock = np.arange(shock_min, shock_max, 0.05)\n",
    "sql_string = \"SELECT closespread FROM index_quotes where index = %s and series = %s and tenor = %s and date = %s\"\n",
    "spread_df = pd.read_sql_query(sql_string, dbengine('serenitasdb'),\n",
    "                              params=[index, ct.on_the_run(index), '5yr', report_date])\n",
    "spread_range = (1+ spread_shock) * spread_df.iloc[0][0]\n",
    "#need to max it at the closest maturity date\n",
    "date_range = pd.bdate_range(report_date, report_date + 180* pd.offsets.DateOffset(), freq='5B')\n",
    "curve_per = np.arange(.01, .99, .1)\n",
    "\n",
    "df = run_curve_scenarios(portf, spread_range, date_range, curve_per)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_plot = df[df.curve_per == curve_per[5]]\n",
    "g.plot_time_color_map(df_plot, spread_range, attr='pnl')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Scenario Anslysis on current position\n",
    "#curve_positions = ct.curve_pos(report_date, index)\n",
    "#origpv = curve_positions.pv\n",
    "#flat_curve = ct.curve_shape(report_date, index, percentile = .05)\n",
    "#for ind in curve_positions.indices:\n",
    "#    ind.spread = flat_curve((pd.to_datetime(ind.end_date) - report_date).days/365)\n",
    "#PNL in flattening to a 5% case\n",
    "#curve_positions.pv - origpv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "curve_positions = ct.curve_pos(report_date, index)\n",
    "df = ct.pos_pnl_abs(curve_positions, report_date)\n",
    "navs = go.get_net_navs()\n",
    "df_plot = df.pnl/navs.iloc[-1].endbooknav"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(df_plot.index, df_plot.values)\n",
    "ax.set(xlabel='date', ylabel='% of NAV',\n",
    "       title='PNL impact from spread curve scenario')\n",
    "plt.xticks(rotation=90)\n",
    "y_ticks = ax.get_yticks()\n",
    "ax.set_yticklabels(['{:.2f}%'.format(y*100) for y in y_ticks])\n",
    "plt.tight_layout()\n",
    "#ax.figure.savefig(\"/home/serenitas/edwin/PythonGraphs/curve_trades.png\", bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Historical PNL in a 5% case\n",
    "df.pnl.quantile(.05)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scen_table = ct.curve_scen_table(curve_positions)\n",
    "scen_table.pnl = scen_table.pnl/navs.iloc[-1].endbooknav *100\n",
    "scen_table.pivot(index='tighter', columns='wider')"
   ]
  },
  {
   "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.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}