{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from analytics.curve_trades import curve_pos, on_the_run\n", "from analytics.index_data import get_index_quotes\n", "from analytics.scenarios import run_portfolio_scenarios\n", "from analytics import Swaption, BlackSwaption, CreditIndex, BlackSwaptionVolSurface, Portfolio, ProbSurface, DualCorrTranche\n", "from db import dbconn\n", "\n", "import datetime\n", "import exploration.VaR as var\n", "import pandas as pd\n", "\n", "conn = dbconn('dawndb')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "date = (datetime.date.today() - pd.tseries.offsets.BDay(1)).date()\n", "report_date = (date + pd.tseries.offsets.BMonthEnd(-1)).date()\n", "index_type = \"IG\"\n", "quantile = .025" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#IG Curve VaR\n", "portf = curve_pos(date, index_type)\n", "ig_curve_var = abs(var.hist_var(portf, quantile=quantile, years=5))\n", "ig_curve_var" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#EU Curve VaR\n", "index_type = \"EU\"\n", "portf = curve_pos(date, index_type)\n", "eu_curve_var = abs(var.hist_var(portf, quantile=quantile, years=5))\n", "eu_curve_var" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Mortgage Hedge VaR - use IG spread relative move for VaR\n", "df = var.get_pos(date, 'HEDGE_MBS')\n", "portf = Portfolio([CreditIndex(row.p_index, row.p_series, row.tenor,\n", " report_date, -row.notional)\n", " for row in df[['p_index', 'tenor', 'p_series', 'notional']].\n", " itertuples(index=False)])\n", "portf.mark()\n", "mort_hedge_var = abs(var.hist_var(portf, index_type = \"IG\", quantile=quantile, years=3))\n", "mort_hedge_var" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Import the IM at the FCM account: calculate the IM share of different strategies as a share of VaR\n", "filename = date.strftime('%Y%m%d') + \"_OTC_MARGIN.csv\"\n", "margin_df = pd.read_csv(\"/home/serenitas/Daily/SG_reports/\" + filename, index_col='System Currency')\n", "mortg_hedge_im = mort_hedge_var + mort_hedge_var/(mort_hedge_var + ig_curve_var) * margin_df.loc[('USD', 'SG Settlement Margin')]\n", "mortg_hedge_im" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Oct ME Bond HY Equiv\n", "bond_HY_equiv = -.12088\n", "percentile = .95" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Calculate amount of stress for reports\n", "df = get_index_quotes('HY', list(range(on_the_run('HY') - 10, on_the_run('HY') + 1)),\n", " tenor=['5yr'], years=5)\n", "df = df.xs('5yr', level='tenor')['close_spread'].groupby(['date', 'series']).last()\n", "\n", "widen, tighten = [], []\n", "#approximately 1,3,6 months move (22 each months)\n", "for days in [22, 66, 132]: \n", " calc = df.unstack().pct_change(freq= str(days)+'B').stack().groupby('date').last()\n", " widen.append(calc.max())\n", " tighten.append(calc.min())\n", "pd.DataFrame([widen, tighten], columns=['1M', '3M', '6M'], index=['widen', 'tighten'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Current tranche and swaptions positions\n", "t_sql_string = (\"SELECT id, 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_TRANCHE' AND termination_cp IS NULL \"\n", " \"AND trade_date <= %s\")\n", "swaption_sql_string = (\"select id, security_desc from swaptions where date(expiration_date) \"\n", " \"> %s and swap_type = 'CD_INDEX_OPTION' \"\n", " \"AND trade_date <= %s\")\n", "index_sql_string = (\"SELECT id, 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 folder = 'IGOPTDEL' OR folder = 'HYOPTDEL' \"\n", " \"AND trade_date <= %s\")\n", "conn = dbconn('dawndb')\n", "with conn.cursor() as c:\n", " #Get Tranche Trade Ids\n", " c.execute(t_sql_string, (date,))\n", " t_trade_ids = [dealid for dealid, ntl in c if ntl != 0]\n", " #Get Swaption Trade Ids\n", " c.execute(swaption_sql_string, (date, date))\n", " swaption_trades = c.fetchall()\n", " #Get Index/deltas Trade Ids\n", " c.execute(index_sql_string, (date,))\n", " index_trade_ids = [dealid for dealid, ntl in c if ntl != 0]\n", " \n", "portf = Portfolio([DualCorrTranche.from_tradeid(dealid) for dealid in t_trade_ids],\n", " t_trade_ids)\n", "for row in swaption_trades:\n", " option_delta = CreditIndex(row[1].split()[1], row[1].split()[3][1:], '5yr', date)\n", " option_delta.mark()\n", " portf.add_trade(BlackSwaption.from_tradeid(row[0], option_delta), 'opt_' + str(row[0]))\n", "for index_id in index_trade_ids:\n", " portf.add_trade(CreditIndex.from_tradeid(index_id), 'index_' + str(index_id))\n", " \n", "#Update manually - positive notional = long risk\n", "non_trancheSwap_risk_notional = 33763230\n", "portf.add_trade(CreditIndex('HY', on_the_run('HY'), '5yr', value_date = date, notional = -non_trancheSwap_risk_notional), 'port')\n", " \n", "portf.value_date = date\n", "portf.mark()\n", "portf.reset_pv()\n", " \n", "vs = BlackSwaptionVolSurface(portf.swaptions[0].index.index_type, portf.swaptions[0].index.series, value_date=date)\n", "vol_surface = vs[vs.list(option_type='payer')[-1]]\n", "vol_shock = [0]\n", "corr_shock = [0]\n", "spread_shock = widen + tighten\n", "date_range = [pd.Timestamp(date)]\n", "\n", "scens = run_portfolio_scenarios(portf, date_range, params=[\"pnl\"],\n", " spread_shock=spread_shock,\n", " vol_shock=vol_shock,\n", " corr_shock=corr_shock,\n", " vol_surface=vol_surface)\n", "\n", "scens.sum(axis=1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "var.cleared_cds_margins(report_date)" ] } ], "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.0" } }, "nbformat": 4, "nbformat_minor": 2 }