aboutsummaryrefslogtreecommitdiffstats
path: root/python/notebooks/Dispersion.ipynb
blob: 59e986477e71872d4ded9c043f604e8b6ddba05e (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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import datetime\n",
    "import exploration.dispersion as disp\n",
    "import matplotlib.pyplot as plt\n",
    "import statsmodels.formula.api as smf\n",
    "\n",
    "from analytics.basket_index import MarkitBasketIndex\n",
    "from analytics import on_the_run\n",
    "from statsmodels.graphics.regressionplots import plot_fit\n",
    "from pygam import LinearGAM, s, f, GAM\n",
    "from utils.db import dbengine\n",
    "\n",
    "serenitas_engine = dbengine('serenitasdb')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "value_date = (pd.datetime.today() - pd.offsets.BDay(1)).date()\n",
    "index_type = 'HY'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Get Gini factor\n",
    "date_range = pd.bdate_range(end=value_date, freq='5B',periods=52*.5)\n",
    "risk = disp.get_tranche_data(index_type, date_range, serenitas_engine)\n",
    "gini_model, gini_calc = disp.create_gini_models(risk)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "to_plot_gini = gini_calc.loc(axis=0)[:,:,:,'5yr',0].groupby(['date', 'series']).nth(-1)\n",
    "to_plot_gini['gini_spread'].unstack().plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "today = gini_calc.loc(axis=0)[value_date,:,33,'5yr',:]\n",
    "today[['exp_percentage', 'predict_N', 'predict_preN', 'mispricing']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "to_plot = gini_calc.loc(axis=0)[:,:,:,'5yr',0]['mispricing']\n",
    "to_plot.reset_index(['index','tenor','attach'], drop=True).unstack().plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_fit(gini_model[0], 'np.log(index_duration)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Run a particular gini scenario\n",
    "scenario = gini_calc.loc(axis=0)[value_date,'HY',33,'5yr',0]\n",
    "scenario['gini_spread'] = .6\n",
    "scenario_disp = np.exp(gini_model[0].predict(scenario))\n",
    "mispricing = (scenario['exp_percentage'] - scenario_disp) * \\\n",
    "             scenario['index_expected_loss'] / \\\n",
    "             (scenario['detach_adj'] - scenario['attach_adj']) / \\\n",
    "             scenario['indexfactor'] * 10000\n",
    "mispricing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Let's use a GAM model instead?\n",
    "#only use the 5yr point for modeling\n",
    "equity = gini_calc.loc(axis=0)[:,:,[25,27,29,31,33],'5yr',0]\n",
    "X = np.array(equity[['gini_spread', 'duration', 'moneyness']])\n",
    "y = np.array(equity['exp_percentage'])\n",
    "\n",
    "#Fit for Lamda\n",
    "gam_model = GAM(s(0, n_splines=5) +\n",
    "                  s(1, n_splines=5) +\n",
    "                  s(2, n_splines=5))\n",
    "lam = np.logspace(-3, 5, 5, base=3)\n",
    "lams = [lam] * 3\n",
    "gam_model.gridsearch(X, y, lam=lams)\n",
    "\n",
    "gam_model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## plotting\n",
    "fig, axs = plt.subplots(1,3);\n",
    "\n",
    "titles = ['gini_spread', 'duration', 'moneyness']\n",
    "for i, ax in enumerate(axs):\n",
    "    XX = gam_model.generate_X_grid(term=i)\n",
    "    ax.plot(XX[:, i], gam_model.partial_dependence(term=i, X=XX))\n",
    "    ax.plot(XX[:, i], gam_model.partial_dependence(term=i, X=XX, width=.95)[1], c='r', ls='--')\n",
    "    if i == 0:\n",
    "        ax.set_ylim(-30,30)\n",
    "    ax.set_title(titles[i]);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(y, gam_model.predict(X))\n",
    "plt.xlabel('actual correlation')\n",
    "plt.ylabel('predicted correlation')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "today = gini_calc.loc(axis=0)[value_date,'HY',33,'5yr',0]\n",
    "predict_HY33 = gam_model.predict(np.array(today[['gini_spread', 'duration', 'moneyness']]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "today, predict_HY33"
   ]
  }
 ],
 "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.8.1-final"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}