aboutsummaryrefslogtreecommitdiffstats
path: root/python/notebooks/Option Trades.ipynb
diff options
context:
space:
mode:
Diffstat (limited to 'python/notebooks/Option Trades.ipynb')
-rw-r--r--python/notebooks/Option Trades.ipynb312
1 files changed, 0 insertions, 312 deletions
diff --git a/python/notebooks/Option Trades.ipynb b/python/notebooks/Option Trades.ipynb
deleted file mode 100644
index 32cd5b04..00000000
--- a/python/notebooks/Option Trades.ipynb
+++ /dev/null
@@ -1,312 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import datetime\n",
- "import pandas as pd\n",
- "import numpy as np\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 db import dbengine\n",
- "\n",
- "from db import dbconn\n",
- "from analytics import init_ontr\n",
- "conn = dbconn('dawndb')\n",
- "init_ontr()\n",
- "pd.options.display.float_format = \"{:,.2f}\".format"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#Delta Chart: Red = Long Risk, Blue = Short Risk"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "#Trade Analysis - see if the trade is net positive gamma\n",
- "index = 'IG'\n",
- "series = 32\n",
- "option_delta = CreditIndex(index, series, '5yr') \n",
- "option_delta.spread = 64\n",
- "option1 = BlackSwaption(option_delta, datetime.date(2019, 7, 17), 60, option_type=\"payer\") \n",
- "option2 = BlackSwaption(option_delta, datetime.date(2019, 7, 17), 75, option_type=\"payer\") \n",
- "option1.sigma = .394 \n",
- "option2.sigma = .52\n",
- "option1.notional = 200_000_000 \n",
- "option2.notional = 200_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": [
- "portf"
- ]
- },
- {
- "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)] = vs[vs.list(option_type='payer')[-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, True]\n",
- " \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",
- " 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)] = vs[vs.list(option_type='payer')[-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": [
- "plot_trade_scenarios(portf)\n",
- "plot_trade_scenarios(portf, -.15, .8, vol_time_roll=False)"
- ]
- },
- {
- "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": [
- "#Current Positions\n",
- "today = datetime.date.today()\n",
- "swaption_sql_string = (\"select id, folder, expiration_date from swaptions where date(expiration_date) \"\n",
- " \"> %s and swap_type = 'CD_INDEX_OPTION' \"\n",
- " \"AND trade_date <= %s AND termination_date iS NULL\")\n",
- "index_sql_string = (\"SELECT id, folder, sum(notional * case when protection='Buyer' then -1 else 1 end) \"\n",
- " \"OVER (partition by security_id, attach) AS ntl_agg \"\n",
- " \"FROM cds WHERE swap_type='CD_INDEX' AND termination_cp IS null \"\n",
- " \"AND trade_date <= %s AND maturity > %s\")\n",
- "conn = dawn_engine.raw_connection()\n",
- "with conn.cursor() as c:\n",
- " c.execute(swaption_sql_string, (today, today))\n",
- " swaption_trades = [[dealid, f\"{folder}_{dealid}\", expiration_date] for dealid, folder, expiration_date in c]\n",
- " c.execute(index_sql_string, (today, today))\n",
- " index_trades = [[dealid, f\"{folder}_{dealid}\"] for dealid, folder, ntl in c if ntl != 0]\n",
- "conn.close()\n",
- "\n",
- "portf = Portfolio([BlackSwaption.from_tradeid(dealid) for dealid, _, _ in swaption_trades],\n",
- " [trade_id for _, trade_id, _ in swaption_trades])\n",
- "index_trades = list(filter(lambda x: \"CURVE\" not in x[1], index_trades))\n",
- "index_trades = list(filter(lambda x: \"SER_IGINDX\" not in x[1], index_trades))\n",
- "index_trades = list(filter(lambda x: \"HEDGE_MBS\" not in x[1], index_trades))\n",
- "index_trades = list(filter(lambda x: \"IGINX\" not in x[1], index_trades))\n",
- "\n",
- "for trade_id, name in index_trades:\n",
- " portf.add_trade(CreditIndex.from_tradeid(trade_id), name)\n",
- " \n",
- "portf.value_date = today\n",
- " \n",
- "results = calc_simple_scenario(portf, shock_min=-.3, shock_max=.3)"
- ]
- },
- {
- "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.3"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}