diff options
Diffstat (limited to 'python/exploration')
| -rw-r--r-- | python/exploration/portfolio_example.py | 36 | ||||
| -rw-r--r-- | python/exploration/portfolio_var.py | 2 | ||||
| -rw-r--r-- | python/exploration/swaption_calendar_spread.py | 93 | ||||
| -rw-r--r-- | python/exploration/tranches.py | 7 |
4 files changed, 20 insertions, 118 deletions
diff --git a/python/exploration/portfolio_example.py b/python/exploration/portfolio_example.py index ebaa6b3b..6b72a2c1 100644 --- a/python/exploration/portfolio_example.py +++ b/python/exploration/portfolio_example.py @@ -1,24 +1,8 @@ from analytics import (Portfolio, BlackSwaption, Index, - VolatilitySurface, Swaption) + BlackSwaptionVolSurface, Swaption) from analytics.scenarios import run_portfolio_scenarios import pandas as pd -from pandas.tseries.offsets import BDay import numpy as np -import datetime - -# option_delta = Index.from_tradeid(874) -# option1 = BlackSwaption.from_tradeid(7, option_delta) -# option2 = BlackSwaption.from_tradeid(8, option_delta) - -# portf = Portfolio([option1, option2, option_delta]) -# date_range = pd.bdate_range(option_delta.trade_date, -# pd.Timestamp('2017-05-01'), freq = 'B') -# pnl = [] -# for date in date_range: -# portf.trade_date = date.date() -# portf.mark(source_list=["BAML", "GS"], model="black") -# pnl.append(portf.pnl) -# df = pd.DataFrame({'pnl': pnl}, index=date_range) option_delta = Index.from_tradeid(870) option1 = BlackSwaption.from_tradeid(5, option_delta) @@ -26,22 +10,10 @@ option2 = BlackSwaption.from_tradeid(6, option_delta) portf = Portfolio([option1, option2, option_delta]) date_range = pd.bdate_range(option_delta.trade_date, - pd.Timestamp('2017-04-19'), freq = 'W') + pd.Timestamp('2017-04-19'), freq='W') vol_shock = np.arange(-0.15, 0.3, 0.01) spread_shock = np.arange(-0.2, 0.3, 0.01) -vs = VolatilitySurface("IG", 27, trade_date=option_delta.trade_date) -vol_surface = vs[vs.list(model="black")[-1]] +vs = BlackSwaptionVolSurface("IG", 27, trade_date=option_delta.trade_date) +vol_surface = vs[vs.list()[-1]] df = run_portfolio_scenarios(portf, date_range, spread_shock, vol_shock, vol_surface, ['pv', 'delta']) - -# pnl = [] -# for date in date_range: -# portf.trade_date = date.date() -# try: -# portf.mark(source_list=["BAML", "GS"], model="black") -# except ValueError: -# pnl.append(None) -# continue -# else: -# pnl.append(portf.pnl) -# df = pd.DataFrame({'pnl': pnl}, index=date_range) diff --git a/python/exploration/portfolio_var.py b/python/exploration/portfolio_var.py index 7fba2ba2..65b1f113 100644 --- a/python/exploration/portfolio_var.py +++ b/python/exploration/portfolio_var.py @@ -1,5 +1,5 @@ from index_data import get_index_quotes, index_returns, _serenitas_engine -from analytics import Swaption, BlackSwaption, Index, VolatilitySurface, Portfolio +from analytics import Index, Portfolio from db import dbengine, dbconn from pandas.tseries.offsets import BDay, BMonthEnd from copy import deepcopy diff --git a/python/exploration/swaption_calendar_spread.py b/python/exploration/swaption_calendar_spread.py index d703bbe7..e21ffd66 100644 --- a/python/exploration/swaption_calendar_spread.py +++ b/python/exploration/swaption_calendar_spread.py @@ -1,7 +1,8 @@ import sys #don't do this at home sys.path.append("..") -from analytics import Swaption, BlackSwaption, Index, VolatilitySurface, Portfolio +from analytics import (Swaption, BlackSwaption, BlackSwaptionVolSurface, + Index, ProbSurface, Portfolio) from analytics.scenarios import run_swaption_scenarios, run_index_scenarios, run_portfolio_scenarios from pandas.tseries.offsets import BDay import datetime @@ -9,19 +10,15 @@ import numpy as np import pandas as pd from scipy.interpolate import SmoothBivariateSpline -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.pyplot as plt - import os import numpy as np import matplotlib import matplotlib.pyplot as plt -from graphics import plot_time_color_map +from graphics import plot_time_color_map, plot_color_map from db import dbengine engine = dbengine('serenitasdb') - def plot_df(df, spread_shock, vol_shock, attr="pnl"): val_date = df.index[0].date() fig = plt.figure() @@ -37,44 +34,17 @@ def plot_df(df, spread_shock, vol_shock, attr="pnl"): ax.set_zlabel("PnL") ax.set_title('{} of Trade on {}'.format(attr.title(), val_date)) -def plot_color_map(df, spread_shock, vol_shock, attr="pnl", path=".", index ='IG'): - - val_date = df.index[0].date() - #rows are spread, columns are volatility surface shift - fig, ax = plt.subplots() - #We are plotting an image, so we have to sort from high to low on the Y axis - ascending = [False,False] if index == 'HY' else [True,False] - df.sort_values(by=['spread','vol_shock'], ascending = ascending, inplace = True) - series = df[attr] - - midpoint = 1 - series.max() / (series.max() + abs(series.min())) - shifted_cmap = shiftedColorMap(cm.RdYlGn, midpoint=midpoint, name='shifted') - - chart = ax.imshow(series.values.reshape(spread_shock.size, vol_shock.size).T, - extent=(spread_shock.min(), spread_shock.max(), - vol_shock.min(), vol_shock.max()), - aspect='auto', interpolation='bilinear', cmap=shifted_cmap) - - ax.set_xlabel('Price') if index == 'HY' else ax.set_xlabel('Spread') - ax.set_ylabel('Volatility shock') - ax.set_title('{} of Trade on {}'.format(attr.title(), val_date)) - - fig.colorbar(chart, shrink=.8) - #fig.savefig(os.path.join(path, "vol_spread_color_map"+ attr+ "_{}.png".format(val_date))) - -def plot_trade_scenarios(portf, shock_min=-.15, shock_max=.2, period = -1, vol_time_roll=True): - +def plot_trade_scenarios(portf, shock_min=-.15, shock_max=.2, period=-1, vol_time_roll=True): portf.reset_pv() earliest_date = min(portf.swaptions, key=lambda x: x.exercise_date).exercise_date - #earliest_date = max(portf.swaptions,key=attrgetter('exercise_date')).exercise_date - date_range = pd.bdate_range(portf.indices[0].trade_date, earliest_date - BDay(), freq = '3B') + date_range = pd.bdate_range(portf.indices[0].trade_date, + earliest_date - BDay(), freq='3B') vol_shock = np.arange(-0.15, 0.3, 0.01) spread_shock = np.arange(shock_min, shock_max, 0.01) index = portf.indices[0].name.split()[1] series = portf.indices[0].name.split()[3][1:] - vs = VolatilitySurface(index, series, trade_date=portf.indices[0].trade_date) - vol_select = vs.list(option_type='payer', model='black')[-1] - vol_surface = vs[vol_select] + vs = BlackSwaptionVolSurface(index, series, trade_date=portf.indices[0].trade_date) + vol_surface = vs[vs.list(option_type='payer')[-1]] df = run_portfolio_scenarios(portf, date_range, spread_shock, vol_shock, vol_surface, params=["pnl","delta"]) @@ -86,44 +56,11 @@ def plot_trade_scenarios(portf, shock_min=-.15, shock_max=.2, period = -1, vol_t plot_time_color_map(df[round(df.vol_shock,2)==0], shock, 'pnl', index=index) plot_time_color_map(df[round(df.vol_shock,2)==.2], shock, 'pnl', index=index) - #plot_time_color_map(df[round(df.vol_shock,2)==0], shock, 'delta', color_map = cm.coolwarm_r, index=index) plot_color_map(df.loc[date_range[period]], shock, vol_shock, 'pnl', index=index) - #plot_df(df.loc[date_range[period]], shock, vol_shock) return df def exercise_probability(): - - from analytics import Swaption, BlackSwaption, Index, VolatilitySurface, Portfolio, ProbSurface, QuoteSurface, VolSurface - from analytics.scenarios import run_swaption_scenarios, run_index_scenarios, run_portfolio_scenarios - import datetime - from operator import attrgetter - - import exploration.swaption_calendar_spread as spread - - import sys - #don't do this at home - from pandas.tseries.offsets import BDay - import datetime - import numpy as np - import pandas as pd - from scipy.interpolate import SmoothBivariateSpline - from matplotlib import cm - from mpl_toolkits.mplot3d import Axes3D - import matplotlib.pyplot as plt - from operator import attrgetter - - import os - import numpy as np - import matplotlib - import matplotlib.pyplot as plt - from mpl_toolkits.axes_grid1 import AxesGrid - - import re - from db import dbengine engine = dbengine('serenitasdb') - - #import swaption_calendar_spread as spread - #Ad hoc option_delta = Index.from_name('HY', 29, '5yr') option_delta.price = 107.875 @@ -141,18 +78,12 @@ def exercise_probability(): portf = Portfolio([option1, option2, option_delta]) portf.reset_pv() - earliest_date = min(portf.swaptions,key=attrgetter('exercise_date')).exercise_date - date_range = pd.bdate_range(portf.indices[0].trade_date, earliest_date - BDay(), freq = '5B') + earliest_date = min(portf.swaptions, key=lambda x: x.exercise_date).exercise_date + date_range = pd.bdate_range(portf.indices[0].trade_date, earliest_date - BDay(), freq='5B') vol_shock = np.arange(-0.15, 0.3, 0.01) spread_shock = np.arange(-0.15, 0.35, 0.01) index = portf.indices[0].name.split()[1] series = portf.indices[0].name.split()[3][1:] - vs = QuoteSurface(index, series, trade_date=portf.indices[0].trade_date) - - vs = VolatilitySurface(index, series, trade_date=portf.indices[0].trade_date) - vol_select = vs.list(option_type='payer', model='black')[-1] - vol_surface = vs[vol_select] - - prob = vs.prob_surf(vol_select) - vs.prob_plot(vol_select) + vs = ProbSurface(index, series, trade_date=portf.indices[0].trade_date) + vs.plot(vs.list()[-1]) diff --git a/python/exploration/tranches.py b/python/exploration/tranches.py index 094c3e9b..028d41b1 100644 --- a/python/exploration/tranches.py +++ b/python/exploration/tranches.py @@ -7,7 +7,7 @@ import analytics.basket_index as idx_bkt import numpy as np import pandas as pd -from analytics import Swaption, BlackSwaption, Index, VolatilitySurface, Portfolio +from analytics import Swaption, BlackSwaption, Index, BlackSwaptionVolSurface, Portfolio from analytics.scenarios import run_swaption_scenarios, run_index_scenarios, run_portfolio_scenarios import exploration.swaption_calendar_spread as spread from scipy.interpolate import interp1d @@ -164,9 +164,8 @@ def run_scen(trade_date = pd.Timestamp.today().normalize()- pd.offsets.BDay()): spread_shock = np.arange(shock_min, shock_max, 0.05) index = portf.indices[0].name.split()[1] series = portf.indices[0].name.split()[3][1:] - vs = VolatilitySurface(index, series, trade_date=trade_date) - vol_select = vs.list(option_type='payer', model='black')[-1] - vol_surface = vs[vol_select] + vs = BlackSwaptionVolaSurface(index, series, trade_date=trade_date) + vol_surface = vs[vs.list(option_type='payer')[-1]] df = run_portfolio_scenarios(portf, date_range, spread_shock, vol_shock, vol_surface, params=["pnl","delta"]) |
