aboutsummaryrefslogtreecommitdiffstats
path: root/python/notebooks/swaption_risk.ipynb
blob: 1f023e393a7b4f880972baaecadd5673b9b78511 (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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "source_hidden": true
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# better formatting for large floats\n",
    "import pandas as pd\n",
    "pd.options.display.float_format = \"{:,.2f}\".format\n",
    "from ipywidgets import widgets\n",
    "import os\n",
    "os.environ[\"SERENITAS_APP_NAME\"] = \"notebook\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "source_hidden": true
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from risk.swaptions import get_swaption_portfolio\n",
    "import datetime\n",
    "from serenitas.analytics.base import Trade\n",
    "from serenitas.utils.pool import dawn_pool\n",
    "from serenitas.analytics.option import BlackSwaption\n",
    "value_date = datetime.date.today()\n",
    "Trade.init_ontr(value_date)\n",
    "BlackSwaption.clear_cache()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "with dawn_pool.connection() as conn:\n",
    "    portf = get_swaption_portfolio(value_date, conn, override={k: 0.8 for k in [430, 431, 432, 433, 422, 423, 424, 425, 426, 427, 428, 429, 430]})\n",
    "portf.index_formatter = lambda t: (t[2], t[1])\n",
    "df = portf._todf().dropna(axis=1, how=\"all\")\n",
    "df.index.names = [\"fund\", \"trade_id\"]\n",
    "df = df.reset_index()\n",
    "df = df.set_index([\"Expiry\", \"Desc\", \"Strike\", \"fund\"]).sort_index()\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "greeks = df.assign(Delta=lambda df: df.Delta * df.Notional, Gamma=lambda df: df.Gamma * df.Notional).groupby([\"Desc\", \"fund\"], group_keys=False)[[\"Delta\", \"Gamma\", \"Vega\"]].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "source_hidden": true
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "hedges = {}\n",
    "with dawn_pool.connection() as conn:\n",
    "    for fund in [\"SERCGMAST\", \"BOWDST\", \"ISOSEL\"]:\n",
    "        hedges[fund] = pd.read_sql_query(\"SELECT security_desc, notional FROM list_cds_positions_by_strat(%s, %s) \"\n",
    "                                         \"WHERE folder in ('IGOPTDEL', 'HYOPTDEL')\",\n",
    "                                         conn, params=(value_date, fund))\n",
    "hedges = pd.concat(hedges, names=[\"fund\"])\n",
    "hedges = hedges.groupby([\"security_desc\", \"fund\"]).sum()\n",
    "def f(s):\n",
    "    l = s.split(\" \")\n",
    "    return f\"{l[1]}{l[3][1:]} {l[4].lower()}r\"\n",
    "\n",
    "hedges = hedges.reset_index(\"security_desc\")\n",
    "hedges[\"security_desc\"] = hedges[\"security_desc\"].apply(f)\n",
    "hedges = hedges.rename(columns={\"notional\": \"current hedge\", \"security_desc\": \"Desc\"}).set_index(\"Desc\", append=True).swaplevel()\n",
    "risk = pd.concat([hedges, greeks], axis=1)\n",
    "risk = risk.assign(net_delta=risk[\"current hedge\"] + risk.Delta)\n",
    "risk.swaplevel().sort_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "portf._todf().groupby(level=0)[[\"Theta\"]].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "sr = np.linspace(65, 80, 100)\n",
    "rec= []\n",
    "for s in sr:\n",
    "    delta = 0.\n",
    "    gamma = 0.\n",
    "    for t in portf.trades:\n",
    "        if t.index.index_type == \"IG\":\n",
    "            t.index.mark(ref=s)\n",
    "            delta += t.delta * t.notional\n",
    "            gamma += t.gamma\n",
    "    rec.append((s, gamma, delta))\n",
    "df = pd.DataFrame.from_records(rec, columns=['spread', 'gamma', 'delta'])\n",
    "df = df.set_index('spread')\n",
    "df.delta += risk.loc['IG37 5yr', 'current hedge']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib import pyplot as plt\n",
    "def get_newaxes(num):\n",
    "    plt.close(num)\n",
    "    fix, axes = plt.subplots(figsize=(10,5), num=num)\n",
    "    return axes\n",
    "\n",
    "axes = get_newaxes(1)\n",
    "df.delta.plot(ax=axes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "axes = get_newaxes(2)\n",
    "df.gamma.plot(ax=axes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "portf.pv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}