diff options
Diffstat (limited to 'python')
| -rw-r--r-- | python/exploration/swaption_calendar_spread.py | 87 | ||||
| -rw-r--r-- | python/exploration/tranches.py | 91 | ||||
| -rw-r--r-- | python/grahphics.py | 84 |
3 files changed, 90 insertions, 172 deletions
diff --git a/python/exploration/swaption_calendar_spread.py b/python/exploration/swaption_calendar_spread.py index 7d6083ce..834fa9e6 100644 --- a/python/exploration/swaption_calendar_spread.py +++ b/python/exploration/swaption_calendar_spread.py @@ -8,71 +8,19 @@ 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 +from graphics import plot_time_color_map -import re from db import dbengine engine = dbengine('serenitasdb') -def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): - ''' - Function to offset the "center" of a colormap. Useful for - data with a negative min and positive max and you want the - middle of the colormap's dynamic range to be at zero - - Input - ----- - cmap : The matplotlib colormap to be altered - start : Offset from lowest point in the colormap's range. - Defaults to 0.0 (no lower ofset). Should be between - 0.0 and `midpoint`. - midpoint : The new center of the colormap. Defaults to - 0.5 (no shift). Should be between 0.0 and 1.0. In - general, this should be 1 - vmax/(vmax + abs(vmin)) - For example if your data range from -15.0 to +5.0 and - you want the center of the colormap at 0.0, `midpoint` - should be set to 1 - 5/(5 + 15)) or 0.75 - stop : Offset from highets point in the colormap's range. - Defaults to 1.0 (no upper ofset). Should be between - `midpoint` and 1.0. - ''' - cdict = { - 'red': [], - 'green': [], - 'blue': [], - 'alpha': [] - } - - # regular index to compute the colors - reg_index = np.linspace(start, stop, 257) - - # shifted index to match the data - shift_index = np.hstack([ - np.linspace(0.0, midpoint, 128, endpoint=False), - np.linspace(midpoint, 1.0, 129, endpoint=True) - ]) - - for ri, si in zip(reg_index, shift_index): - r, g, b, a = cmap(ri) - - cdict['red'].append((si, r, r)) - cdict['green'].append((si, g, g)) - cdict['blue'].append((si, b, b)) - cdict['alpha'].append((si, a, a)) - - newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict) - plt.register_cmap(cmap=newcmap) - - return newcmap def plot_df(df, spread_shock, vol_shock, attr="pnl"): val_date = df.index[0].date() @@ -114,39 +62,10 @@ def plot_color_map(df, spread_shock, vol_shock, attr="pnl", path=".", index ='IG fig.colorbar(chart, shrink=.8) #fig.savefig(os.path.join(path, "vol_spread_color_map"+ attr+ "_{}.png".format(val_date))) -def plot_time_color_map(df, spread_shock, attr="pnl", path=".", color_map=cm.RdYlGn, index='IG'): - - val_date = df.index[0].date() - df = df.reset_index() - df['days'] = (df['date'] - val_date).dt.days - ascending = [True,True] if index == 'HY' else [True,False] - df.sort_values(by=['date','spread'], ascending = ascending, inplace = True) - date_range = df.days.unique() - - #plt.style.use('seaborn-whitegrid') - fig, ax = plt.subplots() - series = df[attr] - midpoint = 1 - series.max() / (series.max() + abs(series.min())) - shifted_cmap = shiftedColorMap(color_map, midpoint=midpoint, name='shifted') - - chart = ax.imshow(series.values.reshape(date_range.size, spread_shock.size).T, - extent=(date_range.min(), date_range.max(), - spread_shock.min(), spread_shock.max()), - aspect='auto', interpolation='bilinear', cmap=shifted_cmap) - - #chart = ax.contour(date_range, spread_shock, series.values.reshape(date_range.size, spread_shock.size).T) - - ax.set_xlabel('Days') - ax.set_ylabel('Price') if index == 'HY' else ax.set_ylabel('Spread') - ax.set_title('{} of Trade'.format(attr.title())) - - fig.colorbar(chart, shrink=.8) - #fig.savefig(os.path.join(path, "spread_time_color_map_"+ attr+ "_{}.png".format(val_date))) - 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=attrgetter('exercise_date')).exercise_date + 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') vol_shock = np.arange(-0.15, 0.3, 0.01) diff --git a/python/exploration/tranches.py b/python/exploration/tranches.py index 4cb1c4c3..2de7e53c 100644 --- a/python/exploration/tranches.py +++ b/python/exploration/tranches.py @@ -1,3 +1,6 @@ +import sys +sys.path.append("..") +from graphics import plot_time_color_map import analytics.tranche_functions as tch import analytics.tranche_basket as bkt import analytics.basket_index as idx_bkt @@ -7,14 +10,8 @@ import pandas as pd from analytics import Swaption, BlackSwaption, Index, VolatilitySurface, Portfolio from analytics.scenarios import run_swaption_scenarios, run_index_scenarios, run_portfolio_scenarios import exploration.swaption_calendar_spread as spread -from operator import attrgetter from scipy.interpolate import interp1d -import matplotlib -import matplotlib.pyplot as plt -from matplotlib import cm - - from datetime import date from db import dbengine engine = dbengine('serenitasdb') @@ -213,85 +210,3 @@ def plot_pnl(): plot_time_color_map(b, shock_range, attr="pnl") #plot Tranche and Swaption PNL plot_time_color_map(b, shock_range, attr="total_pnl") - - -def plot_time_color_map(df, spread_shock, attr="pnl", path=".", color_map=cm.RdYlGn, index='IG'): - - val_date = df.index[0].date() - df = df.reset_index() - df['days'] = (df['date'] - val_date).dt.days - ascending = [True,True] if index == 'HY' else [True,False] - df.sort_values(by=['date','spread'], ascending = ascending, inplace = True) - date_range = df.days.unique() - - #plt.style.use('seaborn-whitegrid') - fig, ax = plt.subplots() - series = df[attr] - midpoint = 1 - series.max() / (series.max() + abs(series.min())) - shifted_cmap = shiftedColorMap(color_map, midpoint=midpoint, name='shifted') - - chart = ax.imshow(series.values.reshape(date_range.size, spread_shock.size).T, - extent=(date_range.min(), date_range.max(), - spread_shock.min(), spread_shock.max()), - aspect='auto', interpolation='bilinear', cmap=shifted_cmap) - - #chart = ax.contour(date_range, spread_shock, series.values.reshape(date_range.size, spread_shock.size).T) - - ax.set_xlabel('Days') - ax.set_ylabel('Price') if index == 'HY' else ax.set_ylabel('Spread') - ax.set_title('{} of Trade'.format(attr.title())) - - fig.colorbar(chart, shrink=.8) - #fig.savefig(os.path.join(path, "spread_time_color_map_"+ attr+ "_{}.png".format(val_date))) - -def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): - ''' - Function to offset the "center" of a colormap. Useful for - data with a negative min and positive max and you want the - middle of the colormap's dynamic range to be at zero - - Input - ----- - cmap : The matplotlib colormap to be altered - start : Offset from lowest point in the colormap's range. - Defaults to 0.0 (no lower ofset). Should be between - 0.0 and `midpoint`. - midpoint : The new center of the colormap. Defaults to - 0.5 (no shift). Should be between 0.0 and 1.0. In - general, this should be 1 - vmax/(vmax + abs(vmin)) - For example if your data range from -15.0 to +5.0 and - you want the center of the colormap at 0.0, `midpoint` - should be set to 1 - 5/(5 + 15)) or 0.75 - stop : Offset from highets point in the colormap's range. - Defaults to 1.0 (no upper ofset). Should be between - `midpoint` and 1.0. - ''' - cdict = { - 'red': [], - 'green': [], - 'blue': [], - 'alpha': [] - } - - # regular index to compute the colors - reg_index = np.linspace(start, stop, 257) - - # shifted index to match the data - shift_index = np.hstack([ - np.linspace(0.0, midpoint, 128, endpoint=False), - np.linspace(midpoint, 1.0, 129, endpoint=True) - ]) - - for ri, si in zip(reg_index, shift_index): - r, g, b, a = cmap(ri) - - cdict['red'].append((si, r, r)) - cdict['green'].append((si, g, g)) - cdict['blue'].append((si, b, b)) - cdict['alpha'].append((si, a, a)) - - newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict) - plt.register_cmap(cmap=newcmap) - - return newcmap - diff --git a/python/grahphics.py b/python/grahphics.py new file mode 100644 index 00000000..0f348a04 --- /dev/null +++ b/python/grahphics.py @@ -0,0 +1,84 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib import cm + +def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): + ''' + Function to offset the "center" of a colormap. Useful for + data with a negative min and positive max and you want the + middle of the colormap's dynamic range to be at zero + + Input + ----- + cmap : The matplotlib colormap to be altered + start : Offset from lowest point in the colormap's range. + Defaults to 0.0 (no lower ofset). Should be between + 0.0 and `midpoint`. + midpoint : The new center of the colormap. Defaults to + 0.5 (no shift). Should be between 0.0 and 1.0. In + general, this should be 1 - vmax/(vmax + abs(vmin)) + For example if your data range from -15.0 to +5.0 and + you want the center of the colormap at 0.0, `midpoint` + should be set to 1 - 5/(5 + 15)) or 0.75 + stop : Offset from highets point in the colormap's range. + Defaults to 1.0 (no upper ofset). Should be between + `midpoint` and 1.0. + ''' + cdict = { + 'red': [], + 'green': [], + 'blue': [], + 'alpha': [] + } + + # regular index to compute the colors + reg_index = np.linspace(start, stop, 257) + + # shifted index to match the data + shift_index = np.hstack([ + np.linspace(0.0, midpoint, 128, endpoint=False), + np.linspace(midpoint, 1.0, 129, endpoint=True) + ]) + + for ri, si in zip(reg_index, shift_index): + r, g, b, a = cmap(ri) + + cdict['red'].append((si, r, r)) + cdict['green'].append((si, g, g)) + cdict['blue'].append((si, b, b)) + cdict['alpha'].append((si, a, a)) + + newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict) + plt.register_cmap(cmap=newcmap) + + return newcmap + + +def plot_time_color_map(df, spread_shock, attr="pnl", path=".", color_map=cm.RdYlGn, index='IG'): + + val_date = df.index[0].date() + df = df.reset_index() + df['days'] = (df['date'] - val_date).dt.days + ascending = [True,True] if index == 'HY' else [True,False] + df.sort_values(by=['date','spread'], ascending = ascending, inplace = True) + date_range = df.days.unique() + + #plt.style.use('seaborn-whitegrid') + fig, ax = plt.subplots() + series = df[attr] + midpoint = 1 - series.max() / (series.max() + abs(series.min())) + shifted_cmap = shiftedColorMap(color_map, midpoint=midpoint, name='shifted') + + chart = ax.imshow(series.values.reshape(date_range.size, spread_shock.size).T, + extent=(date_range.min(), date_range.max(), + spread_shock.min(), spread_shock.max()), + aspect='auto', interpolation='bilinear', cmap=shifted_cmap) + + #chart = ax.contour(date_range, spread_shock, series.values.reshape(date_range.size, spread_shock.size).T) + + ax.set_xlabel('Days') + ax.set_ylabel('Price') if index == 'HY' else ax.set_ylabel('Spread') + ax.set_title('{} of Trade'.format(attr.title())) + + fig.colorbar(chart, shrink=.8) + #fig.savefig(os.path.join(path, "spread_time_color_map_"+ attr+ "_{}.png".format(val_date))) |
