diff --git a/FinancePyManual.pdf b/FinancePyManual.pdf index b24e53ad..63e4353c 100644 Binary files a/FinancePyManual.pdf and b/FinancePyManual.pdf differ diff --git a/financepy/__init__.py b/financepy/__init__.py index f54acc71..a5fe49b3 100644 --- a/financepy/__init__.py +++ b/financepy/__init__.py @@ -1,7 +1,7 @@ cr = "\n" s = "####################################################################" + cr -s += "# FINANCEPY BETA Version " + str('0.34') + " - This build: 19 Feb 2024 at 21:02 #" + cr +s += "# FINANCEPY BETA Version " + str('0.350') + " - This build: 22 Feb 2024 at 19:25 #" + cr s += "# This software is distributed FREE AND WITHOUT ANY WARRANTY #" + cr s += "# Report bugs as issues at https://github.com/domokane/FinancePy #" + cr s += "####################################################################" diff --git a/financepy/__init__.template b/financepy/__init__.template index 5edf7f50..d1651882 100644 --- a/financepy/__init__.template +++ b/financepy/__init__.template @@ -1,7 +1,7 @@ cr = "\n" s = "####################################################################" + cr -s += "# FINANCEPY BETA Version " + str(__version__) + " - This build: __dateandtime__ #" + cr +s += "# FINANCEPY BETA Version " + str(__version__) + " - This build: __dateandtime__ #" + cr s += "# This software is distributed FREE AND WITHOUT ANY WARRANTY #" + cr s += "# Report bugs as issues at https://github.com/domokane/FinancePy #" + cr s += "####################################################################" diff --git a/financepy/market/curves/discount_curve.py b/financepy/market/curves/discount_curve.py index 9cda9747..f611699a 100644 --- a/financepy/market/curves/discount_curve.py +++ b/financepy/market/curves/discount_curve.py @@ -1,6 +1,6 @@ -############################################################################## +############################################################################### # Copyright (C) 2018, 2019, 2020 Dominic O'Kane -############################################################################## +############################################################################### import numpy as np @@ -9,7 +9,7 @@ from ...utils.date import Date from ...utils.error import FinError -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.frequency import annual_frequency, FrequencyTypes from ...utils.day_count import DayCount, DayCountTypes from ...utils.math import test_monotonicity @@ -89,7 +89,7 @@ def value_dt(self): ########################################################################### def _zero_to_df(self, - value_dt: Date, # TODO: why is value_date not used ? + value_dt: Date, # TODO: why is value_dt not used ? rates: (float, np.ndarray), times: (float, np.ndarray), freq_type: FrequencyTypes, @@ -101,7 +101,7 @@ def _zero_to_df(self, if isinstance(times, float): times = np.array([times]) - t = np.maximum(times, gSmall) + t = np.maximum(times, g_small) f = annual_frequency(freq_type) @@ -147,17 +147,17 @@ def _df_to_zero(self, if len(date_list) != len(df_list): raise FinError("Date list and df list do not have same length") - num_dts = len(date_list) + num_dates = len(date_list) zero_rates = [] times = times_from_dates( date_list, self._value_dt, dc_type) - for i in range(0, num_dts): + for i in range(0, num_dates): df = df_list[i] - t = max(times[i], gSmall) + t = max(times[i], g_small) if freq_type == FrequencyTypes.CONTINUOUS: r = -np.log(df) / t @@ -269,7 +269,7 @@ def swap_rate(self, pv01 += alpha * df prev_dt = next_dt - if abs(pv01) < gSmall: + if abs(pv01) < g_small: par_rate = 0.0 else: df_start = self.df(effective_dt) @@ -424,9 +424,9 @@ def fwd_rate(self, day_count = DayCount(dc_type) - num_dts = len(start_dts) + num_dates = len(start_dts) fwd_rates = [] - for i in range(0, num_dts): + for i in range(0, num_dates): dt1 = start_dts[i] if isinstance(date_or_tenor, str): diff --git a/financepy/market/curves/discount_curve_ns.py b/financepy/market/curves/discount_curve_ns.py index 86db0efa..25f3e307 100644 --- a/financepy/market/curves/discount_curve_ns.py +++ b/financepy/market/curves/discount_curve_ns.py @@ -6,7 +6,7 @@ from ...utils.date import Date from ...utils.frequency import FrequencyTypes -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small from ...utils.error import FinError from ...market.curves.discount_curve import DiscountCurve from ...utils.helpers import check_argument_types @@ -101,7 +101,7 @@ def _zero_rate(self, """ Zero rate for Nelson-Siegel curve parametrisation. This means that the t vector must use the curve day count.""" - t = np.maximum(times, gSmall) + t = np.maximum(times, g_small) theta = t / self._tau e = np.exp(-theta) diff --git a/financepy/market/curves/discount_curve_nss.py b/financepy/market/curves/discount_curve_nss.py index 7e3b351e..99be05ee 100644 --- a/financepy/market/curves/discount_curve_nss.py +++ b/financepy/market/curves/discount_curve_nss.py @@ -6,7 +6,7 @@ from ...utils.date import Date from ...utils.frequency import FrequencyTypes -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small from ...utils.helpers import label_to_string from ...utils.error import FinError from ...market.curves.discount_curve import DiscountCurve @@ -112,7 +112,7 @@ def _zero_rate(self, times. This function can return a single zero rate or a vector of zero rates. The compounding frequency must be provided. """ - t = np.maximum(times, gSmall) + t = np.maximum(times, g_small) theta_1 = t / self._tau_1 theta_2 = t / self._tau_2 diff --git a/financepy/market/curves/discount_curve_poly.py b/financepy/market/curves/discount_curve_poly.py index 81aca4ec..60c88d05 100644 --- a/financepy/market/curves/discount_curve_poly.py +++ b/financepy/market/curves/discount_curve_poly.py @@ -6,7 +6,7 @@ from ...utils.date import Date from ...utils.error import FinError -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small from ...utils.helpers import label_to_string from ...market.curves.discount_curve import DiscountCurve from ...utils.helpers import check_argument_types @@ -89,7 +89,7 @@ def _zero_rate(self, use. The compounding frequency defaults to that specified in the constructor of the curve object. Which may be annual to continuous. """ - t = np.maximum(times, gSmall) + t = np.maximum(times, g_small) zero_rate = 0.0 for n in range(0, len(self._coefficients)): diff --git a/financepy/market/curves/discount_curve_pwf.py b/financepy/market/curves/discount_curve_pwf.py index 981dee6a..ac9344ea 100644 --- a/financepy/market/curves/discount_curve_pwf.py +++ b/financepy/market/curves/discount_curve_pwf.py @@ -6,7 +6,7 @@ from ...utils.date import Date from ...utils.error import FinError -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small from ...utils.math import test_monotonicity from ...utils.frequency import FrequencyTypes from ...utils.helpers import label_to_string @@ -69,7 +69,7 @@ def _zero_rate(self, if np.any(times < 0.0): raise FinError("All times must be positive") - times = np.maximum(times, gSmall) + times = np.maximum(times, g_small) zero_rates = [] diff --git a/financepy/market/curves/interpolator.py b/financepy/market/curves/interpolator.py index 52a7203e..d4a63599 100644 --- a/financepy/market/curves/interpolator.py +++ b/financepy/market/curves/interpolator.py @@ -8,13 +8,12 @@ from scipy.interpolate import PchipInterpolator from scipy.interpolate import CubicSpline from ...utils.error import FinError -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small ############################################################################### class InterpTypes(Enum): - ''' Types of interpolation ''' FLAT_FWD_RATES = 1 LINEAR_FWD_RATES = 2 LINEAR_ZERO_RATES = 4 @@ -223,7 +222,7 @@ def fit(self, elif self._interp_type == InterpTypes.PCHIP_ZERO_RATES: - g_small_vector = np.ones(len(self._times)) * gSmall + g_small_vector = np.ones(len(self._times)) * g_small zero_rates = -np.log(self._dfs) / (self._times + g_small_vector) if self._times[0] == 0.0: @@ -243,7 +242,7 @@ def fit(self, """ Second derivatives at left is zero and first derivative at right is clamped to zero. """ - g_small_vector = np.ones(len(self._times)) * gSmall + g_small_vector = np.ones(len(self._times)) * g_small zero_rates = -np.log(self._dfs) / (self._times + g_small_vector) if self._times[0] == 0.0: @@ -262,7 +261,7 @@ def fit(self, elif self._interp_type == InterpTypes.NATCUBIC_ZERO_RATES: """ Second derivatives are clamped to zero at end points """ - g_small_vector = np.ones(len(self._times)) * gSmall + g_small_vector = np.ones(len(self._times)) * g_small zero_rates = -np.log(self._dfs) / (self._times + g_small_vector) if self._times[0] == 0.0: @@ -294,7 +293,7 @@ def interpolate(self, print(t) raise FinError("Interpolate times must all be >= 0") - if np.abs(t) < gSmall: + if np.abs(t) < g_small: return 1.0 tvec = np.array([t]) diff --git a/financepy/market/volatility/equity_vol_surface.py b/financepy/market/volatility/equity_vol_surface.py index 2c4f08f0..e74009d4 100644 --- a/financepy/market/volatility/equity_vol_surface.py +++ b/financepy/market/volatility/equity_vol_surface.py @@ -158,7 +158,7 @@ def vol_function(vol_function_type_value, params, f, k, t): if vol_function_type_value == VolFuncTypes.SSVI.value: vol = vol_function_ssvi(params, f, k, t) return vol - + return 0.0 ############################################################################### @@ -194,7 +194,7 @@ def _delta_fit(k, *args): ############################################################################### -#@njit(float64(float64, float64, float64, float64, int64, int64, float64, +# @njit(float64(float64, float64, float64, float64, int64, int64, float64, # float64, float64[:]), fastmath=True) def _solver_for_smile_strike(s, t, r, q, option_type_value, @@ -238,8 +238,8 @@ def __init__(self, expiry_dts: (list), strikes: (list, np.ndarray), volatility_grid: (list, np.ndarray), - volatility_function_type = VolFuncTypes.CLARK, - fin_solver_type = FinSolverTypes.NELDER_MEAD): + vol_func_type=VolFuncTypes.CLARK, + fin_solver_type=FinSolverTypes.NELDER_MEAD): """ Create the EquitySurface object by passing in market vol data for a list of strikes and expiry dates. """ @@ -251,13 +251,13 @@ def __init__(self, self._discount_curve = discount_curve self._dividend_curve = dividend_curve - num_expiry_dates = len(expiry_dts) + num_expiry_dts = len(expiry_dts) num_strikes = len(strikes) n = len(volatility_grid) m = len(volatility_grid[0]) - if n != num_expiry_dates: - raise FinError("1st dim of vol grid is not num_expiry_dates") + if n != num_expiry_dts: + raise FinError("1st dim of vol grid is not num_expiry_dts") if m != num_strikes: raise FinError("2nd dim of the vol matrix is not num_strikes") @@ -266,16 +266,16 @@ def __init__(self, self._num_strikes = len(strikes) self._expiry_dts = expiry_dts - self._num_expiry_dates = len(expiry_dts) + self._num_expiry_dts = len(expiry_dts) self._volatility_grid = volatility_grid - self._volatility_function_type = volatility_function_type + self._vol_func_type = vol_func_type self._build_vol_surface(fin_solver_type=fin_solver_type) ############################################################################### - def vol_from_strike_dt(self, K, expiry_dt): + def vol_from_strike_date(self, K, expiry_dt): """ Interpolates the Black-Scholes volatility from the volatility surface given call option strike and expiry date. Linear interpolation is done in variance space. The smile strikes at bracketed dates are @@ -288,12 +288,12 @@ def vol_from_strike_dt(self, K, expiry_dt): t_exp = (expiry_dt - self._value_dt) / gDaysInYear - vol_type_value = self._volatility_function_type.value + vol_type_value = self._vol_func_type.value index0 = 0 # lower index in bracket index1 = 0 # upper index in bracket - num_curves = self._num_expiry_dates + num_curves = self._num_expiry_dts if num_curves == 1: @@ -365,7 +365,7 @@ def vol_from_strike_dt(self, K, expiry_dt): # t_exp = (expiry_dt - self._value_dt) / gDaysInYear - # vol_type_value = self._volatility_function_type.value + # vol_type_value = self._vol_func_type.value # s = self._spot_fx_rate @@ -453,7 +453,7 @@ def vol_from_strike_dt(self, K, expiry_dt): ############################################################################### - def vol_from_delta_dt(self, call_delta, expiry_dt, delta_method=None): + def vol_from_delta_date(self, call_delta, expiry_dt, delta_method=None): """ Interpolates the Black-Scholes volatility from the volatility surface given a call option delta and expiry date. Linear interpolation is done in variance space. The smile strikes at bracketed dates are @@ -466,14 +466,14 @@ def vol_from_delta_dt(self, call_delta, expiry_dt, delta_method=None): t_exp = (expiry_dt - self._value_dt) / gDaysInYear - vol_type_value = self._volatility_function_type.value + vol_type_value = self._vol_func_type.value s = self._stock_price index0 = 0 # lower index in bracket index1 = 0 # upper index in bracket - num_curves = self._num_expiry_dates + num_curves = self._num_expiry_dts # If there is only one time horizon then assume flat vol to this time if num_curves == 1: @@ -567,46 +567,46 @@ def _build_vol_surface(self, fin_solver_type=FinSolverTypes.NELDER_MEAD): s = self._stock_price - num_expiry_dates = self._num_expiry_dates + num_expiry_dts = self._num_expiry_dts - if self._volatility_function_type == VolFuncTypes.CLARK: + if self._vol_func_type == VolFuncTypes.CLARK: num_parameters = 3 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.SABR_BETA_ONE: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.SABR_BETA_ONE: num_parameters = 3 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.SABR_BETA_HALF: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.SABR_BETA_HALF: num_parameters = 3 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.BBG: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.BBG: num_parameters = 3 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.SABR: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.SABR: num_parameters = 4 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.CLARK5: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.CLARK5: num_parameters = 5 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.SVI: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.SVI: num_parameters = 5 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) - elif self._volatility_function_type == VolFuncTypes.SSVI: + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + elif self._vol_func_type == VolFuncTypes.SSVI: num_parameters = 5 - self._parameters = np.zeros([num_expiry_dates, num_parameters]) + self._parameters = np.zeros([num_expiry_dts, num_parameters]) self._parameters[:, 0] = 0.2 # sigma self._parameters[:, 1] = 0.8 # gamma self._parameters[:, 2] = -0.7 # rho self._parameters[:, 3] = 0.3 self._parameters[:, 4] = 0.048 else: - print(self._volatility_function_type) + print(self._vol_func_type) raise FinError("Unknown Model Type") - self._t_exp = np.zeros(num_expiry_dates) + self._t_exp = np.zeros(num_expiry_dts) - self._F0T = np.zeros(num_expiry_dates) - self._r = np.zeros(num_expiry_dates) - self._q = np.zeros(num_expiry_dates) + self._F0T = np.zeros(num_expiry_dts) + self._r = np.zeros(num_expiry_dts) + self._q = np.zeros(num_expiry_dts) ####################################################################### # TODO: ADD SPOT DAYS @@ -614,7 +614,7 @@ def _build_vol_surface(self, fin_solver_type=FinSolverTypes.NELDER_MEAD): spot_dt = self._value_dt - for i in range(0, num_expiry_dates): + for i in range(0, num_expiry_dts): expiry_dt = self._expiry_dts[i] t_exp = (expiry_dt - spot_dt) / gDaysInYear @@ -632,13 +632,13 @@ def _build_vol_surface(self, fin_solver_type=FinSolverTypes.NELDER_MEAD): # THE ACTUAL COMPUTATION LOOP STARTS HERE ####################################################################### - vol_type_value = self._volatility_function_type.value + vol_type_value = self._vol_func_type.value x_inits = [] x_init = np.zeros(num_parameters) x_inits.append(x_init) - for i in range(0, num_expiry_dates): + for i in range(0, num_expiry_dts): t = self._t_exp[i] r = self._r[i] @@ -671,7 +671,7 @@ def check_calibration(self, verbose: bool): print("STOCK PRICE:", self._stock_price) print("==========================================================") - for i in range(0, self._num_expiry_dates): + for i in range(0, self._num_expiry_dts): expiry_dt = self._expiry_dts[i] print("==========================================================") @@ -680,7 +680,7 @@ def check_calibration(self, verbose: bool): strike = self._strikes[j] - fitted_vol = self.vol_from_strike_dt(strike, + fitted_vol = self.vol_from_strike_date(strike, expiry_dt) mkt_vol = self._volatility_grid[i][j] @@ -701,7 +701,7 @@ def implied_dbns(self, lowS, highS, num_intervals): dbns = [] - for iTenor in range(0, self._num_expiry_dates): + for iTenor in range(0, self._num_expiry_dts): f = self._F0T[iTenor] t = self._t_exp[iTenor] @@ -721,7 +721,7 @@ def implied_dbns(self, lowS, highS, num_intervals): k = lowS + iK*dS - vol = vol_function(self._volatility_function_type.value, + vol = vol_function(self._vol_func_type.value, self._parameters[iTenor], f, k, t) @@ -744,10 +744,10 @@ def plot_vol_curves(self): """ Generates a plot of each of the vol discount implied by the market and fitted. """ - lowK = self._strikes[0] * 0.9 - highK = self._strikes[-1] * 1.1 + low_k = self._strikes[0] * 0.9 + high_k = self._strikes[-1] * 1.1 - for tenor_index in range(0, self._num_expiry_dates): + for tenor_index in range(0, self._num_expiry_dts): expiry_dt = self._expiry_dts[tenor_index] plt.figure() @@ -756,13 +756,13 @@ def plot_vol_curves(self): fitted_vols = [] num_intervals = 30 - K = lowK - dK = (highK - lowK)/num_intervals + K = low_k + dK = (high_k - low_k)/num_intervals for _ in range(0, num_intervals): ks.append(K) - fitted_vol = self.vol_from_strike_dt(K, expiry_dt) * 100. + fitted_vol = self.vol_from_strike_date(K, expiry_dt) * 100. fitted_vols.append(fitted_vol) K = K + dK @@ -776,7 +776,7 @@ def plot_vol_curves(self): plt.xlabel("Strike") plt.ylabel("Volatility") - title = str(self._volatility_function_type) + title = str(self._vol_func_type) plt.title(title) plt.legend() @@ -786,9 +786,9 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VALUE DATE", self._value_dt) s += label_to_string("STOCK PRICE", self._stock_price) - s += label_to_string("VOL FUNCTION", self._volatility_function_type) + s += label_to_string("VOL FUNCTION", self._vol_func_type) - for i in range(0, self._num_expiry_dates): + for i in range(0, self._num_expiry_dts): s += label_to_string("EXPIRY DATE", self._expiry_dts[i]) for i in range(0, self._num_strikes): diff --git a/financepy/market/volatility/fx_vol_surface.py b/financepy/market/volatility/fx_vol_surface.py index a791284c..c40108fb 100644 --- a/financepy/market/volatility/fx_vol_surface.py +++ b/financepy/market/volatility/fx_vol_surface.py @@ -397,15 +397,15 @@ def __init__(self, spot_fx_rate: float, currency_pair: str, notional_currency: str, - dom_discount_curve: DiscountCurve, - for_discount_curve: DiscountCurve, + domestic_curve: DiscountCurve, + foreign_curve: DiscountCurve, tenors: (list), atm_vols: (list, np.ndarray), ms25DeltaVols: (list, np.ndarray), rr25DeltaVols: (list, np.ndarray), - atmMethod: FinFXATMMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL, + atm_method: FinFXATMMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL, delta_method: FinFXDeltaMethod = FinFXDeltaMethod.SPOT_DELTA, - volatility_function_type: VolFuncTypes = VolFuncTypes.CLARK): + vol_func_type: VolFuncTypes = VolFuncTypes.CLARK): """ Create the FinFXVolSurface object by passing in market vol data for ATM and 25 Delta Market Strangles and Risk Reversals. """ @@ -418,12 +418,12 @@ def __init__(self, if len(currency_pair) != 6: raise FinError("Currency pair must be 6 characters.") - self._forName = self._currency_pair[0:3] - self._domName = self._currency_pair[3:6] + self._for_name = self._currency_pair[0:3] + self._dom_name = self._currency_pair[3:6] self._notional_currency = notional_currency - self._dom_discount_curve = dom_discount_curve - self._for_discount_curve = for_discount_curve + self._domestic_curve = domestic_curve + self._foreign_curve = foreign_curve self._num_vol_curves = len(tenors) if len(atm_vols) != self._num_vol_curves: @@ -443,7 +443,7 @@ def __init__(self, self._ms25DeltaVols = np.array(ms25DeltaVols)/100.0 self._rr25DeltaVols = np.array(rr25DeltaVols)/100.0 - self._atmMethod = atmMethod + self._atm_method = atm_method self._delta_method = delta_method if self._delta_method == FinFXDeltaMethod.SPOT_DELTA: @@ -457,7 +457,7 @@ def __init__(self, else: raise FinError("Unknown Delta Type") - self._vol_func_type = volatility_function_type + self._vol_func_type = vol_func_type self._tenor_index = 0 self._expiry_dts = [] @@ -585,8 +585,8 @@ def build_vol_surface(self): expiry_dt = self._expiry_dts[i] t_exp = (expiry_dt - spot_dt) / gDaysInYear - dom_df = self._dom_discount_curve._df(t_exp) - for_df = self._for_discount_curve._df(t_exp) + dom_df = self._domestic_curve._df(t_exp) + for_df = self._foreign_curve._df(t_exp) f = s * for_df/dom_df self._t_exp[i] = t_exp @@ -597,13 +597,13 @@ def build_vol_surface(self): atm_vol = self._atm_vols[i] # This follows exposition in Clarke Page 52 - if self._atmMethod == FinFXATMMethod.SPOT: + if self._atm_method == FinFXATMMethod.SPOT: self._K_ATM[i] = s - elif self._atmMethod == FinFXATMMethod.FWD: + elif self._atm_method == FinFXATMMethod.FWD: self._K_ATM[i] = f - elif self._atmMethod == FinFXATMMethod.FWD_DELTA_NEUTRAL: + elif self._atm_method == FinFXATMMethod.FWD_DELTA_NEUTRAL: self._K_ATM[i] = f * np.exp(atm_vol*atm_vol*t_exp/2.0) - elif self._atmMethod == FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ: + elif self._atm_method == FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ: self._K_ATM[i] = f * np.exp(-atm_vol*atm_vol*t_exp/2.0) else: raise FinError("Unknown Delta Type") @@ -740,7 +740,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): print("==========================================================") print("VALUE DATE:", self._value_dt) print("SPOT FX RATE:", self._spot_fx_rate) - print("ATM METHOD:", self._atmMethod) + print("ATM METHOD:", self._atm_method) print("DELTA METHOD:", self._delta_method) print("==========================================================") @@ -813,14 +813,14 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -832,7 +832,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THESE STRIKES ARE DETERMINED BY SETTING DELTA TO 0.25/-0.25 ################################################################### - msVol = self._atm_vols[i] + self._ms25DeltaVols[i] + ms_vol = self._atm_vols[i] + self._ms25DeltaVols[i] if verbose: @@ -843,44 +843,44 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): call._strike_fx_rate = self._k_25d_c_ms[i] put._strike_fx_rate = self._k_25d_p_ms[i] - model = BlackScholes(msVol) + model = BlackScholes(ms_vol) delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: - print("k_25d_c_ms: %9.6f ATM + MSVOL: %9.6f %% DELTA: %9.6f" - % (self._k_25d_c_ms[i], 100.0*msVol, delta_call)) + print("k_25d_c_ms: %9.6f ATM + ms_vol: %9.6f %% DELTA: %9.6f" + % (self._k_25d_c_ms[i], 100.0*ms_vol, delta_call)) - print("k_25d_p_ms: %9.6f ATM + MSVOL: %9.6f %% DELTA: %9.6f" - % (self._k_25d_p_ms[i], 100.0*msVol, delta_put)) + print("k_25d_p_ms: %9.6f ATM + ms_vol: %9.6f %% DELTA: %9.6f" + % (self._k_25d_p_ms[i], 100.0*ms_vol, delta_put)) call_value = call.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] put_value = put.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] - mktStrangleValue = call_value + put_value + mkt_strangle_value = call_value + put_value if verbose: print("CALL_VALUE: %9.6f PUT_VALUE: %9.6f MS_VALUE: % 9.6f" - % (call_value, put_value, mktStrangleValue)) + % (call_value, put_value, mkt_strangle_value)) ################################################################### # NOW WE ASSIGN A DIFFERENT VOLATILITY TO THE MS STRIKES @@ -897,15 +897,15 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): model = BlackScholes(sigma_k_25d_c_ms) call_value = call.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] # THIS IS NOT GOING TO BE 0.25 AS WE HAVE USED A DIFFERENT SKEW VOL delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] # PUT @@ -918,18 +918,18 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): model = BlackScholes(sigma_k_25d_p_ms) put_value = put.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] # THIS IS NOT GOING TO BE -0.25 AS WE HAVE USED A DIFFERENT SKEW VOL delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] - mktStrangleValueSkew = call_value + put_value + mkt_strangle_value_skew = call_value + put_value if verbose: print("k_25d_c_ms: %9.6f SURFACE_VOL: %9.6f %% DELTA: %9.6f" @@ -939,12 +939,12 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): % (self._k_25d_p_ms[i], 100.0*sigma_k_25d_p_ms, delta_put)) print("CALL_VALUE: %9.6f PUT_VALUE: %9.6f MS_SKEW_VALUE: % 9.6f" - % (call_value, put_value, mktStrangleValueSkew)) + % (call_value, put_value, mkt_strangle_value_skew)) - diff = mktStrangleValue - mktStrangleValueSkew + diff = mkt_strangle_value - mkt_strangle_value_skew if np.abs(diff) > tol: print("FAILED FIT TO 25D MS VAL: %9.6f OUT: %9.6f DIFF: % 9.6f" % - (mktStrangleValue, mktStrangleValueSkew, diff)) + (mkt_strangle_value, mkt_strangle_value_skew, diff)) ################################################################### # NOW WE SHIFT STRIKES SO THAT DELTAS NOW EQUAL 0.25, -0.25 @@ -964,8 +964,8 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THIS DELTA SHOULD BE +0.25 delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] sigma_k_25d_p = vol_function(self._vol_func_type.value, @@ -979,8 +979,8 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THIS DELTA SHOULD BE -0.25 delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -1021,8 +1021,8 @@ def implied_dbns(self, low_fx, high_fx, num_intervals): dFX = (high_fx - low_fx) / num_intervals - dom_df = self._dom_discount_curve.df(t_exp) - for_df = self._for_discount_curve.df(t_exp) + dom_df = self._domestic_curve.df(t_exp) + for_df = self._foreign_curve.df(t_exp) r_d = -np.log(dom_df) / t_exp r_f = -np.log(for_df) / t_exp @@ -1063,17 +1063,17 @@ def plot_vol_curves(self): for tenor_index in range(0, self._num_vol_curves): atm_vol = self._atm_vols[tenor_index]*100 - msVol = self._ms25DeltaVols[tenor_index]*100 - rrVol = self._rr25DeltaVols[tenor_index]*100 + ms_vol = self._ms25DeltaVols[tenor_index]*100 + rr_vol = self._rr25DeltaVols[tenor_index]*100 - lowK = self._k_25d_p[tenor_index] * 0.75 - highK = self._k_25d_c[tenor_index] * 1.25 + low_k = self._k_25d_p[tenor_index] * 0.75 + high_k = self._k_25d_c[tenor_index] * 1.25 strikes = [] vols = [] num_intervals = 30 - K = lowK - dK = (highK - lowK)/num_intervals + K = low_k + dK = (high_k - low_k)/num_intervals params = self._parameters[tenor_index] t = self._t_exp[tenor_index] f = self._F0T[tenor_index] @@ -1086,8 +1086,8 @@ def plot_vol_curves(self): label_str = self._tenors[tenor_index] label_str += " ATM: " + str(atm_vol)[0:6] - label_str += " MS: " + str(msVol)[0:6] - label_str += " RR: " + str(rrVol)[0:6] + label_str += " MS: " + str(ms_vol)[0:6] + label_str += " RR: " + str(rr_vol)[0:6] plt.plot(strikes, vols, label=label_str) plt.xlabel("Strike") @@ -1132,7 +1132,7 @@ def __repr__(self): s += label_to_string("CCY PAIR", self._currency_pair) s += label_to_string("NOTIONAL CCY", self._notional_currency) s += label_to_string("NUM TENORS", self._num_vol_curves) - s += label_to_string("ATM METHOD", self._atmMethod) + s += label_to_string("ATM METHOD", self._atm_method) s += label_to_string("DELTA METHOD", self._delta_method) s += label_to_string("VOL FUNCTION", self._vol_func_type) diff --git a/financepy/market/volatility/fx_vol_surface_plus.py b/financepy/market/volatility/fx_vol_surface_plus.py index 4e20e492..b2ecd307 100644 --- a/financepy/market/volatility/fx_vol_surface_plus.py +++ b/financepy/market/volatility/fx_vol_surface_plus.py @@ -461,7 +461,7 @@ def _solve_to_horizon(s, t, rd, rf, alpha, x_inits, ginits, - finSolverType, + fin_solver_type, tol): ########################################################################### @@ -566,20 +566,20 @@ def _solve_to_horizon(s, t, rd, rf, # to converge, so for those cases try again with CG # Numba version is quicker, but can be slightly away from CG output try: - if finSolverType == FinSolverTypes.NELDER_MEAD_NUMBA: + if fin_solver_type == FinSolverTypes.NELDER_MEAD_NUMBA: xopt = nelder_mead(_obj, np.array(x_inits), bounds=np.array( [[], []]).T, args=args, tol_f=tol, tol_x=tol, max_iter=1000) - elif finSolverType == FinSolverTypes.NELDER_MEAD: + elif fin_solver_type == FinSolverTypes.NELDER_MEAD: opt = minimize(_obj, x_inits, args, method="Nelder-Mead", tol=tol) xopt = opt.x - elif finSolverType == FinSolverTypes.CONJUGATE_GRADIENT: + elif fin_solver_type == FinSolverTypes.CONJUGATE_GRADIENT: opt = minimize(_obj, x_inits, args, method="CG", tol=tol) xopt = opt.x except Exception: # If convergence fails try again with CG if necessary - if finSolverType != FinSolverTypes.CONJUGATE_GRADIENT: + if fin_solver_type != FinSolverTypes.CONJUGATE_GRADIENT: print('Failed to converge, will try CG') opt = minimize(_obj, x_inits, args, method="CG", tol=tol) @@ -869,8 +869,8 @@ def __init__(self, spot_fx_rate: float, currency_pair: str, notional_currency: str, - dom_discount_curve: DiscountCurve, - for_discount_curve: DiscountCurve, + domestic_curve: DiscountCurve, + foreign_curve: DiscountCurve, tenors: (list), atm_vols: (list, np.ndarray), ms25DeltaVols: (list, np.ndarray), @@ -880,8 +880,8 @@ def __init__(self, alpha: float, atmMethod: FinFXATMMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL, delta_method: FinFXDeltaMethod = FinFXDeltaMethod.SPOT_DELTA, - volatility_function_type: VolFuncTypes = VolFuncTypes.CLARK, - finSolverType: FinSolverTypes = FinSolverTypes.NELDER_MEAD, + vol_func_type: VolFuncTypes = VolFuncTypes.CLARK, + fin_solver_type: FinSolverTypes = FinSolverTypes.NELDER_MEAD, tol: float = 1e-8): """ Create the FinFXVolSurfacePlus object by passing in market vol data for ATM, 25 Delta and 10 Delta strikes. The alpha weight shifts the @@ -910,12 +910,12 @@ def __init__(self, if len(currency_pair) != 6: raise FinError("Currency pair must be 6 characters.") - self._forName = self._currency_pair[0:3] - self._domName = self._currency_pair[3:6] + self._for_name = self._currency_pair[0:3] + self._dom_name = self._currency_pair[3:6] self._notional_currency = notional_currency - self._dom_discount_curve = dom_discount_curve - self._for_discount_curve = for_discount_curve + self._domestic_curve = domestic_curve + self._foreign_curve = foreign_curve self._num_vol_curves = len(tenors) self._tenors = tenors @@ -982,7 +982,7 @@ def __init__(self, self._alpha = alpha - self._atmMethod = atmMethod + self._atm_method = atmMethod self._delta_method = delta_method if self._delta_method == FinFXDeltaMethod.SPOT_DELTA: @@ -996,7 +996,7 @@ def __init__(self, else: raise FinError("Unknown Delta Type") - self._vol_func_type = volatility_function_type + self._vol_func_type = vol_func_type self._tenor_index = 0 self._expiry_dts = [] @@ -1004,11 +1004,11 @@ def __init__(self, expiry_dt = value_dt.add_tenor(tenors[i]) self._expiry_dts.append(expiry_dt) - self._build_vol_surface(finSolverType=finSolverType, tol=tol) + self._build_vol_surface(fin_solver_type=fin_solver_type, tol=tol) ############################################################################### - def vol_from_strike_dt(self, K, expiry_dt): + def vol_from_strike_date(self, K, expiry_dt): """ Interpolates the Black-Scholes volatility from the volatility surface given call option strike and expiry date. Linear interpolation is done in variance space. The smile strikes at bracketed dates are @@ -1191,9 +1191,9 @@ def delta_to_strike(self, call_delta, expiry_dt, delta_method): ############################################################################### - def vol_from_delta_dt(self, call_delta, - expiry_dt, - delta_method=None): + def vol_from_delta_date(self, call_delta, + expiry_dt, + delta_method=None): """ Interpolates the Black-Scholes volatility from the volatility surface given a call option delta and expiry date. Linear interpolation is done in variance space. The smile strikes at bracketed dates are @@ -1314,7 +1314,7 @@ def vol_from_delta_dt(self, call_delta, ############################################################################### - def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD, + def _build_vol_surface(self, fin_solver_type=FinSolverTypes.NELDER_MEAD, tol=1e-8): """ Main function to construct the vol surface. """ @@ -1374,8 +1374,8 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD, expiry_dt = self._expiry_dts[i] t_exp = (expiry_dt - spot_dt) / gDaysInYear - dom_df = self._dom_discount_curve.df(expiry_dt) - for_df = self._for_discount_curve.df(expiry_dt) + dom_df = self._domestic_curve.df(expiry_dt) + for_df = self._foreign_curve.df(expiry_dt) f = s * for_df / dom_df self._t_exp[i] = t_exp @@ -1386,13 +1386,13 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD, atm_vol = self._atm_vols[i] # This follows exposition in Clarke Page 52 - if self._atmMethod == FinFXATMMethod.SPOT: + if self._atm_method == FinFXATMMethod.SPOT: self._K_ATM[i] = s - elif self._atmMethod == FinFXATMMethod.FWD: + elif self._atm_method == FinFXATMMethod.FWD: self._K_ATM[i] = f - elif self._atmMethod == FinFXATMMethod.FWD_DELTA_NEUTRAL: + elif self._atm_method == FinFXATMMethod.FWD_DELTA_NEUTRAL: self._K_ATM[i] = f * np.exp(atm_vol*atm_vol*t_exp/2.0) - elif self._atmMethod == FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ: + elif self._atm_method == FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ: self._K_ATM[i] = f * np.exp(-atm_vol*atm_vol*t_exp/2.0) else: raise FinError("Unknown Delta Type") @@ -1555,7 +1555,7 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD, self._alpha, x_inits[i], ginits[i], - finSolverType, + fin_solver_type, tol) (self._parameters[i, :], self._strikes[i, :], self._gaps[i:], @@ -1578,7 +1578,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): print("VALUE DATE:", self._value_dt) print("SPOT FX RATE:", self._spot_fx_rate) print("ALPHA WEIGHT:", self._alpha) - print("ATM METHOD:", self._atmMethod) + print("ATM METHOD:", self._atm_method) print("DELTA METHOD:", self._delta_method) print("==========================================================") @@ -1662,14 +1662,14 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -1698,14 +1698,14 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -1717,21 +1717,21 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): call_value = call.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] put_value = put.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] - mktStrangleValue = call_value + put_value + mkt_strangle_value = call_value + put_value if verbose: print("CALL_VALUE: %9.6f PUT_VALUE: %9.6f MS_VALUE: % 9.6f" - % (call_value, put_value, mktStrangleValue)) + % (call_value, put_value, mkt_strangle_value)) ############################################################### # NOW WE ASSIGN A DIFFERENT VOLATILITY TO THE MS STRIKES @@ -1750,15 +1750,15 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): model = BlackScholes(sigma_K_25D_C_MS) call_value = call.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] # THIS IS NOT GOING TO BE 0.25 AS WE USED A DIFFERENT SKEW VOL delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] # PUT @@ -1773,18 +1773,18 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): model = BlackScholes(sigma_K_25D_P_MS) put_value = put.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] # THIS IS NOT GOING TO BE -0.25 AS WE USED A DIFFERENT SKEW VOL delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] - mktStrangleValueSkew = call_value + put_value + mkt_strangle_value_skew = call_value + put_value if verbose: print("K_25D_C_MS: %9.6f SURFACE_VOL: %9.6f %% DELTA: %9.6f" @@ -1794,12 +1794,12 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): % (self._K_25D_P_MS[i], 100.0*sigma_K_25D_P_MS, delta_put)) print("CALL_VALUE: %9.6f PUT_VALUE: %9.6f MS_SKEW_VALUE: % 9.6f" - % (call_value, put_value, mktStrangleValueSkew)) + % (call_value, put_value, mkt_strangle_value_skew)) - diff = mktStrangleValue - mktStrangleValueSkew + diff = mkt_strangle_value - mkt_strangle_value_skew if np.abs(diff) > tol: print("FAILED FIT TO 25D MS VAL: %9.6f OUT: %9.6f DIFF: % 9.6f" % - (mktStrangleValue, mktStrangleValueSkew, diff)) + (mkt_strangle_value, mkt_strangle_value_skew, diff)) ############################################################### # NOW WE SHIFT STRIKES SO THAT DELTAS NOW EQUAL 0.25, -0.25 @@ -1821,8 +1821,8 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THIS DELTA SHOULD BE +0.25 delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] sigma_K_25D_P = vol_function(self._vol_func_type.value, @@ -1838,8 +1838,8 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THIS DELTA SHOULD BE -0.25 delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -1887,14 +1887,14 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -1906,21 +1906,21 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): call_value = call.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] put_value = put.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] - mktStrangleValue = call_value + put_value + mkt_strangle_value = call_value + put_value if verbose: print("CALL_VALUE: %9.6f PUT_VALUE: %9.6f MS_VALUE: % 9.6f" - % (call_value, put_value, mktStrangleValue)) + % (call_value, put_value, mkt_strangle_value)) ############################################################### # NOW WE ASSIGN A DIFFERENT VOLATILITY TO THE MS STRIKES @@ -1939,15 +1939,15 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): model = BlackScholes(sigma_K_10D_C_MS) call_value = call.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] # THIS IS NOT GOING TO BE 0.10 AS WE HAVE USED A DIFFERENT SKEW VOL delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] # PUT @@ -1962,18 +1962,18 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): model = BlackScholes(sigma_K_10D_P_MS) put_value = put.value(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)['v'] # THIS IS NOT GOING TO BE -0.10 AS WE HAVE USED A DIFFERENT SKEW VOL delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] - mktStrangleValueSkew = call_value + put_value + mkt_strangle_value_skew = call_value + put_value if verbose: print("K_10D_C_MS: %9.6f SURFACE_VOL: %9.6f %% DELTA: %9.6f" @@ -1983,12 +1983,12 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): % (self._K_10D_P_MS[i], 100.0*sigma_K_10D_P_MS, delta_put)) print("CALL_VALUE: %9.6f PUT_VALUE: %9.6f MS_SKEW_VALUE: % 9.6f" - % (call_value, put_value, mktStrangleValueSkew)) + % (call_value, put_value, mkt_strangle_value_skew)) - diff = mktStrangleValue - mktStrangleValueSkew + diff = mkt_strangle_value - mkt_strangle_value_skew if np.abs(diff) > tol: print("FAILED FIT TO 10D MS VAL: %9.6f OUT: %9.6f DIFF: % 9.6f" % - (mktStrangleValue, mktStrangleValueSkew, diff)) + (mkt_strangle_value, mkt_strangle_value_skew, diff)) ############################################################### # NOW WE SHIFT STRIKES SO THAT DELTAS NOW EQUAL 0.10, -0.10 @@ -2010,8 +2010,8 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THIS DELTA SHOULD BE +0.25 delta_call = call.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] sigma_K_10D_P = vol_function(self._vol_func_type.value, @@ -2027,8 +2027,8 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # THIS DELTA SHOULD BE -0.25 delta_put = put.delta(self._value_dt, self._spot_fx_rate, - self._dom_discount_curve, - self._for_discount_curve, + self._domestic_curve, + self._foreign_curve, model)[self._delta_method_string] if verbose: @@ -2069,8 +2069,8 @@ def implied_dbns(self, lowFX, highFX, num_intervals): dFX = (highFX - lowFX) / num_intervals - dom_df = self._dom_discount_curve.df(t) - for_df = self._for_discount_curve.df(t) + dom_df = self._domestic_curve.df(t) + for_df = self._foreign_curve.df(t) r_d = -np.log(dom_df) / t r_f = -np.log(for_df) / t @@ -2110,7 +2110,7 @@ def plot_vol_curves(self): plt.figure() - volTypeVal = self._vol_func_type.value + vol_type_val = self._vol_func_type.value for tenor_index in range(0, self._num_vol_curves): @@ -2123,21 +2123,21 @@ def plot_vol_curves(self): gaps = self._gaps[tenor_index] - lowK = self._K_10D_P[tenor_index] * 0.90 - highK = self._K_10D_C_MS[tenor_index] * 1.10 + low_K = self._K_10D_P[tenor_index] * 0.90 + high_k = self._K_10D_C_MS[tenor_index] * 1.10 ks = [] vols = [] num_intervals = 30 - K = lowK - dK = (highK - lowK)/num_intervals + K = low_K + dK = (high_k - low_K)/num_intervals params = self._parameters[tenor_index] t = self._t_exp[tenor_index] f = self._F0T[tenor_index] for i in range(0, num_intervals): - sigma = vol_function(volTypeVal, params, strikes, gaps, + sigma = vol_function(vol_type_val, params, strikes, gaps, f, K, t) * 100.0 ks.append(K) vols.append(sigma) @@ -2163,7 +2163,7 @@ def plot_vol_curves(self): key_vols = [] for K in key_strikes: - sigma = vol_function(volTypeVal, params, + sigma = vol_function(vol_type_val, params, strikes, gaps, f, K, t) * 100.0 @@ -2180,7 +2180,7 @@ def plot_vol_curves(self): key_vols = [] for K in key_strikes: - sigma = vol_function(volTypeVal, params, + sigma = vol_function(vol_type_val, params, strikes, gaps, f, K, t) * 100.0 @@ -2196,7 +2196,7 @@ def plot_vol_curves(self): key_vols = [] for K in key_strikes: - sigma = vol_function(volTypeVal, params, + sigma = vol_function(vol_type_val, params, strikes, gaps, f, K, t) * 100.0 key_vols.append(sigma) @@ -2215,7 +2215,7 @@ def __repr__(self): s += label_to_string("CCY PAIR", self._currency_pair) s += label_to_string("NOTIONAL CCY", self._notional_currency) s += label_to_string("NUM TENORS", self._num_vol_curves) - s += label_to_string("ATM METHOD", self._atmMethod) + s += label_to_string("ATM METHOD", self._atm_method) s += label_to_string("DELTA METHOD", self._delta_method) s += label_to_string("ALPHA WEIGHT", self._alpha) s += label_to_string("VOL FUNCTION", self._vol_func_type) diff --git a/financepy/market/volatility/ibor_cap_vol_curve.py b/financepy/market/volatility/ibor_cap_vol_curve.py index c9380e7e..651882ae 100644 --- a/financepy/market/volatility/ibor_cap_vol_curve.py +++ b/financepy/market/volatility/ibor_cap_vol_curve.py @@ -57,6 +57,7 @@ def __init__(self, self._cap_sigmas = np.array(cap_sigmas) self._caplet_gammas = [] + self._caplet_vols = [] # Basic validation of dates prev_dt = self._curve_dt @@ -90,7 +91,7 @@ def generate_caplet_vols(self): day_counter = DayCount(self._dc_type) prev_dt = self._curve_dt - numCaps = len(self._cap_maturity_dts) + num_caps = len(self._cap_maturity_dts) for dt in self._cap_maturity_dts: t = (dt - self._curve_dt) / gDaysInYear @@ -99,25 +100,25 @@ def generate_caplet_vols(self): self._taus.append(tau) prev_dt = dt - fwd_rateVol = self._cap_sigmas[0] - self._caplet_gammas = np.zeros(numCaps) + fwd_rate_vol = self._cap_sigmas[0] + self._caplet_gammas = np.zeros(num_caps) self._caplet_gammas[0] = 0.0 - cumIbor2Tau = (fwd_rateVol**2) * self._taus[0] + cum_ibor2_tau = (fwd_rate_vol**2) * self._taus[0] - sumTau = 0.0 + sum_tau = 0.0 for i in range(1, len(self._cap_maturity_dts)): t = self._times[i] tau = self._taus[i] - sumTau += tau - volCap = self._cap_sigmas[i] - volIbor2 = ((volCap**2) * sumTau - cumIbor2Tau) / tau + sum_tau += tau + vol_cap = self._cap_sigmas[i] + vol_ibor2 = ((vol_cap**2) * sum_tau - cum_ibor2_tau) / tau - if volIbor2 < 0.0: + if vol_ibor2 < 0.0: raise FinError("Error due to negative caplet variance.") - volIbor = np.sqrt(volIbor2) - self._caplet_gammas[i] = volIbor - cumIbor2Tau += volIbor2 * self._taus[i] + vol_ibor = np.sqrt(vol_ibor2) + self._caplet_gammas[i] = vol_ibor + cum_ibor2_tau += vol_ibor2 * self._taus[i] ############################################################################### @@ -188,10 +189,10 @@ def __repr__(self): for i in range(0, num_times): t = self._times[i] tau = self._taus[i] - volCap = self._cap_sigmas[i] - fwdIborVol = self._capletVols[i] + vol_cap = self._cap_sigmas[i] + fwd_ibor_vol = self._caplet_vols[i] s += label_to_string("%7.4f %6.4f %9.4f %9.4f" - % (t, tau, volCap*100.0, fwdIborVol*100.0)) + % (t, tau, vol_cap*100.0, fwd_ibor_vol*100.0)) return s diff --git a/financepy/market/volatility/swaption_vol_surface.py b/financepy/market/volatility/swaption_vol_surface.py index 094bdec4..eaf82226 100644 --- a/financepy/market/volatility/swaption_vol_surface.py +++ b/financepy/market/volatility/swaption_vol_surface.py @@ -107,18 +107,18 @@ def _obj(params, *args): f = args[1] strikes_grid = args[2] index = args[3] - volatility_grid = args[4] + vol_grid = args[4] vol_type_value = args[5] tot = 0.0 - num_strikes = len(volatility_grid) + num_strikes = len(vol_grid) for i in range(0, num_strikes): k = strikes_grid[i][index] fitted_vol = vol_function(vol_type_value, params, f, k, t) - mkt_vol = volatility_grid[i][index] + mkt_vol = vol_grid[i][index] diff = fitted_vol - mkt_vol tot += diff**2 @@ -132,10 +132,10 @@ def _obj(params, *args): def _solve_to_horizon(t, f, strikes_grid, time_index, - volatility_grid, + vol_grid, vol_type_value, x_inits, - finSolverType): + fin_solver_type): ########################################################################### # Determine parameters of vol surface using minimisation @@ -143,26 +143,26 @@ def _solve_to_horizon(t, f, tol = 1e-6 - args = (t, f, strikes_grid, time_index, volatility_grid, vol_type_value) + args = (t, f, strikes_grid, time_index, vol_grid, vol_type_value) # Nelder-Mead (both SciPy amd Numba) is quicker, but occasionally fails # to converge, so for those cases try again with CG # Numba version is quicker, but can be slightly away from CG output try: - if finSolverType == FinSolverTypes.NELDER_MEAD_NUMBA: + if fin_solver_type == FinSolverTypes.NELDER_MEAD_NUMBA: xopt = nelder_mead(_obj, np.array(x_inits), bounds=np.array([[], []]).T, args=args, tol_f=tol, tol_x=tol, max_iter=1000) - elif finSolverType == FinSolverTypes.NELDER_MEAD: + elif fin_solver_type == FinSolverTypes.NELDER_MEAD: opt = minimize(_obj, x_inits, args, method="Nelder-Mead", tol=tol) xopt = opt.x - elif finSolverType == FinSolverTypes.CONJUGATE_GRADIENT: + elif fin_solver_type == FinSolverTypes.CONJUGATE_GRADIENT: opt = minimize(_obj, x_inits, args, method="CG", tol=tol) xopt = opt.x except Exception: # If convergence fails try again with CG if necessary - if finSolverType != FinSolverTypes.CONJUGATE_GRADIENT: + if fin_solver_type != FinSolverTypes.CONJUGATE_GRADIENT: print('Failed to converge, will try CG') opt = minimize(_obj, x_inits, args, method="CG", tol=tol) xopt = opt.x @@ -374,9 +374,9 @@ def __init__(self, expiry_dts: (list), fwd_swap_rates: (list, np.ndarray), strike_grid: (np.ndarray), - volatility_grid: (np.ndarray), - volatility_function_type: VolFuncTypes = VolFuncTypes.SABR, - finSolverType: FinSolverTypes = FinSolverTypes.NELDER_MEAD): + vol_grid: (np.ndarray), + vol_func_type: VolFuncTypes = VolFuncTypes.SABR, + fin_solver_type: FinSolverTypes = FinSolverTypes.NELDER_MEAD): """ Create the FinSwaptionVolSurface object by passing in market vol data for a list of strikes and expiry dates. """ @@ -387,32 +387,40 @@ def __init__(self, if len(strike_grid.shape) != 2: raise FinError("Strike grid must be a 2D grid of values") - if len(volatility_grid.shape) != 2: + if len(vol_grid.shape) != 2: raise FinError("Volatility grid must be a 2D grid of values") - if len(strike_grid) != len(volatility_grid): + if len(strike_grid) != len(vol_grid): raise FinError( "Strike grid and volatility grid must have same size") - if len(strike_grid[0]) != len(volatility_grid[0]): + if len(strike_grid[0]) != len(vol_grid[0]): raise FinError( "Strike grid and volatility grid must have same size") - if len(expiry_dts) != len(volatility_grid[0]): + if len(expiry_dts) != len(vol_grid[0]): raise FinError("Expiry dates not same size as volatility grid") - self._numExpiryDates = len(volatility_grid[0]) - self._num_strikes = len(volatility_grid) + self._num_expiry_dts = len(vol_grid[0]) + self._num_strikes = len(vol_grid) self._strike_grid = strike_grid - self._volatility_grid = volatility_grid + self._vol_grid = vol_grid self._expiry_dts = expiry_dts - self._volatility_function_type = volatility_function_type + self._vol_func_type = vol_func_type self._fwd_swap_rates = fwd_swap_rates - self._build_vol_surface(finSolverType=finSolverType) + self._build_vol_surface(fin_solver_type=fin_solver_type) + + self._F0T = [] + self._stock_price = None + self._atm_method = None + self._atm_vols = [] + self._delta_method = None + self._strikes = [] + self._vol_grid = [] ############################################################################### @@ -429,12 +437,12 @@ def vol_from_strike_dt(self, K, expiry_dt): t_exp = (expiry_dt - self._value_dt) / gDaysInYear - vol_type_value = self._volatility_function_type.value + vol_type_value = self._vol_func_type.value index0 = 0 # lower index in bracket index1 = 0 # upper index in bracket - num_curves = self._numExpiryDates + num_curves = self._num_expiry_dts if num_curves == 1: @@ -508,7 +516,7 @@ def vol_from_strike_dt(self, K, expiry_dt): # t_exp = (expiry_dt - self._value_dt) / gDaysInYear - # vol_type_value = self._volatility_function_type.value + # vol_type_value = self._vol_func_type.value # s = self._spot_fx_rate @@ -610,7 +618,7 @@ def vol_from_strike_dt(self, K, expiry_dt): # t_exp = (expiry_dt - self._value_dt) / gDaysInYear - # vol_type_value = self._volatility_function_type.value + # vol_type_value = self._vol_func_type.value # s = self._spot_fx_rate @@ -715,39 +723,39 @@ def vol_from_strike_dt(self, K, expiry_dt): ############################################################################### - def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD): + def _build_vol_surface(self, fin_solver_type=FinSolverTypes.NELDER_MEAD): """ Main function to construct the vol surface. """ - if self._volatility_function_type == VolFuncTypes.CLARK: + if self._vol_func_type == VolFuncTypes.CLARK: num_parameters = 3 - elif self._volatility_function_type == VolFuncTypes.SABR_BETA_ONE: + elif self._vol_func_type == VolFuncTypes.SABR_BETA_ONE: num_parameters = 3 - elif self._volatility_function_type == VolFuncTypes.SABR_BETA_HALF: + elif self._vol_func_type == VolFuncTypes.SABR_BETA_HALF: num_parameters = 3 - elif self._volatility_function_type == VolFuncTypes.BBG: + elif self._vol_func_type == VolFuncTypes.BBG: num_parameters = 3 - elif self._volatility_function_type == VolFuncTypes.SABR: + elif self._vol_func_type == VolFuncTypes.SABR: num_parameters = 4 - elif self._volatility_function_type == VolFuncTypes.CLARK5: + elif self._vol_func_type == VolFuncTypes.CLARK5: num_parameters = 5 - elif self._volatility_function_type == VolFuncTypes.SVI: + elif self._vol_func_type == VolFuncTypes.SVI: num_parameters = 5 - elif self._volatility_function_type == VolFuncTypes.SSVI: + elif self._vol_func_type == VolFuncTypes.SSVI: num_parameters = 5 else: - print(self._volatility_function_type) + print(self._vol_func_type) raise FinError("Unknown Model Type") - numExpiryDates = self._numExpiryDates + num_expiry_dts = self._num_expiry_dts - self._parameters = np.zeros([numExpiryDates, num_parameters]) - self._t_exp = np.zeros(numExpiryDates) + self._parameters = np.zeros([num_expiry_dts, num_parameters]) + self._t_exp = np.zeros(num_expiry_dts) ####################################################################### # TODO: ADD SPOT DAYS ####################################################################### - for i in range(0, numExpiryDates): + for i in range(0, num_expiry_dts): expiry_dt = self._expiry_dts[i] t_exp = (expiry_dt - self._value_dt) / gDaysInYear @@ -757,13 +765,13 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD): # THE ACTUAL COMPUTATION LOOP STARTS HERE ####################################################################### - vol_type_value = self._volatility_function_type.value + vol_type_value = self._vol_func_type.value x_inits = [] x_init = np.zeros(num_parameters) x_inits.append(x_init) - for i in range(0, numExpiryDates): + for i in range(0, num_expiry_dts): t = self._t_exp[i] f = self._fwd_swap_rates[i] @@ -771,10 +779,10 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD): res = _solve_to_horizon(t, f, self._strike_grid, i, - self._volatility_grid, + self._vol_grid, vol_type_value, x_inits[i], - finSolverType) + fin_solver_type) self._parameters[i, :] = res @@ -795,7 +803,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): print("STOCK PRICE:", self._stock_price) print("==========================================================") - for i in range(0, self._numExpiryDates): + for i in range(0, self._num_expiry_dts): expiry_dt = self._expiry_dts[i] print("==========================================================") @@ -806,7 +814,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): fitted_vol = self.vol_from_strike_dt(strike, expiry_dt) - mkt_vol = self._volatility_grid[j][i] + mkt_vol = self._vol_grid[j][i] diff = fitted_vol - mkt_vol @@ -827,7 +835,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # dbns = [] - # for iTenor in range(0, self._numExpiryDates): + # for iTenor in range(0, self._num_expiry_dts): # f = self._fwd_swap_rates[iTenor] # t = self._t_exp[iTenor] @@ -847,7 +855,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6): # k = lowS + iK*dS - # vol = vol_function(self._volatility_function_type.value, + # vol = vol_function(self._vol_func_type.value, # self._parameters[iTenor], # f, k, t) @@ -870,10 +878,10 @@ def plot_vol_curves(self): """ Generates a plot of each of the vol discount implied by the market and fitted. """ - for tenor_index in range(0, self._numExpiryDates): + for tenor_index in range(0, self._num_expiry_dts): - lowK = self._strike_grid[0][tenor_index] * 0.9 - highK = self._strike_grid[-1][tenor_index] * 1.1 + low_k = self._strike_grid[0][tenor_index] * 0.9 + high_k = self._strike_grid[-1][tenor_index] * 1.1 expiry_dt = self._expiry_dts[tenor_index] plt.figure() @@ -881,8 +889,8 @@ def plot_vol_curves(self): ks = [] num_intervals = 30 - K = lowK - dK = (highK - lowK)/num_intervals + K = low_k + dK = (high_k - low_k)/num_intervals fitted_vols = [] @@ -897,14 +905,14 @@ def plot_vol_curves(self): plt.plot(ks, fitted_vols, label=label_str) label_str = "MARKET AT " + str(self._expiry_dts[tenor_index]) - mkt_vols = self._volatility_grid[:, tenor_index] * 100.0 + mkt_vols = self._vol_grid[:, tenor_index] * 100.0 plt.plot(self._strike_grid[:, tenor_index], mkt_vols, 'o', label=label_str) plt.xlabel("Strike") plt.ylabel("Volatility") - title = str(self._volatility_function_type) + title = str(self._vol_func_type) plt.title(title) plt.legend() @@ -915,25 +923,24 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VALUE DATE", self._value_dt) s += label_to_string("STOCK PRICE", self._stock_price) - s += label_to_string("ATM METHOD", self._atmMethod) + s += label_to_string("ATM METHOD", self._atm_method) s += label_to_string("DELTA METHOD", self._delta_method) - s += label_to_string("VOL FUNCTION", self._volatility_function_type) + s += label_to_string("VOL FUNCTION", self._vol_func_type) - for i in range(0, self._numExpiryDates): + for i in range(0, self._num_expiry_dts): s += "\n" s += label_to_string("EXPIRY DATE", self._expiry_dts[i]) s += label_to_string("TIME (YRS)", self._t_exp[i]) s += label_to_string("FWD FX", self._F0T[i]) - s += label_to_string("ATM VOLS", self._atm_vols[i]*100.0) for j in range(0, self._num_strikes): expiry_dt = self._expiry_dts[i] k = self._strikes[j] - vol = self._volGrid[i][j] + vol = self._vol_grid[i][j] print(expiry_dt, k, vol) return s diff --git a/financepy/models/bachelier.py b/financepy/models/bachelier.py index 8dc37f8f..a50b2196 100644 --- a/financepy/models/bachelier.py +++ b/financepy/models/bachelier.py @@ -17,11 +17,12 @@ class Bachelier(): - """ Bachelier's Model which prices call and put options in the forward - measure assuming the underlying rate follows a normal process. """ + """Bachelier's Model which prices call and put options in the forward + measure assuming the underlying rate follows a normal process. + """ def __init__(self, volatility): - """ Create FinModel black using parameters. """ + """Create FinModel black using parameters.""" self._volatility = volatility ############################################################################### @@ -32,8 +33,7 @@ def value(self, time_to_expiry, # Time to Expiry (years) df, # Discount Factor to expiry date call_or_put): # Call or put - """ Price a call or put option using Bachelier's model. """ - + """Price a call or put option using Bachelier's model.""" f = forward_rate t = time_to_expiry k = strike_rate diff --git a/financepy/models/bdt_tree.py b/financepy/models/bdt_tree.py index 1d6753c5..5adb6373 100644 --- a/financepy/models/bdt_tree.py +++ b/financepy/models/bdt_tree.py @@ -10,7 +10,7 @@ from ..market.curves.interpolator import InterpTypes, _uinterpolate from ..utils.helpers import label_to_string from ..utils.global_types import FinExerciseTypes -from ..utils.global_vars import gSmall +from ..utils.global_vars import g_small INTERP_TYPE = InterpTypes.FLAT_FWD_RATES.value @@ -37,7 +37,6 @@ def option_exercise_types_to_int(option_exercise_type): @njit(float64(float64, int64, float64[:, :], float64[:, :], float64, float64, float64), fastmath=True, cache=True) def f(x0, m, q_matrix, rt, df_end, dt, sigma): - # x is the middle value on the short-rate on the tree midm = int(m/2) rt[m, midm] = x0 @@ -64,7 +63,6 @@ def f(x0, m, q_matrix, rt, df_end, dt, sigma): @njit(float64(float64, int64, float64[:, :], float64[:, :], float64, float64, float64), fastmath=True, cache=True) def search_root(x0, m, q_matrix, rt, df_end, dt, sigma): - # print("Searching for root", x0) max_iter = 10 max_error = 1e-8 @@ -104,11 +102,10 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, _df_values, _tree_times, _Q, _rt, _dt): - """ Option to enter into a swap that can be exercised on coupon payment + """Option to enter into a swap that can be exercised on coupon payment dates after the start of the exercise period. Due to non-analytical bond price we need to extend tree out to bond maturity and take into account - cash flows through time. """ - + cash flows through time.""" pu = 0.50 pd = 0.50 @@ -145,10 +142,10 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, for n in range(1, len(_tree_times)): - accdAtExpiry = 0.0 + accd_at_expiry = 0.0 if _tree_times[n-1] < t_exp and _tree_times[n] >= t_exp: mapped_times = np.append(mapped_times, t_exp) - mapped_amounts = np.append(mapped_amounts, accdAtExpiry) + mapped_amounts = np.append(mapped_amounts, accd_at_expiry) if fixed_leg_flows[n] > 0.0: mapped_times = np.append(mapped_times, _tree_times[n]) @@ -164,7 +161,7 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if fixed_leg_flows[m] > gSmall: + if fixed_leg_flows[m] > g_small: accrued[m] = fixed_leg_flows[m] * face_amount ####################################################################### @@ -227,7 +224,7 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, pay_values[m, k] = max(pay_exercise, hold_pay) rec_values[m, k] = max(rec_exercise, hold_rec) - elif exercise_type_int == 2 and flow > gSmall and m > expiry_step: + elif exercise_type_int == 2 and flow > g_small and m > expiry_step: pay_values[m, k] = max(pay_exercise, hold_pay) rec_values[m, k] = max(rec_exercise, hold_rec) @@ -300,14 +297,14 @@ def american_bond_option_tree_fast(t_exp, t_mat, # mapped_times = np.zeros(0) # CHANGE # mapped_amounts = np.zeros(0) # CHANGE # for n in range(0, len(_tree_times)): - # if treeFlows[n] > 0.0: + # if tree_flows[n] > 0.0: # mapped_times = np.append(mapped_times, _tree_times[n]) - # mapped_amounts = np.append(mapped_amounts, treeFlows[n]) + # mapped_amounts = np.append(mapped_amounts, tree_flows[n]) # if DEBUG: # print("MAPPED TIMES", mapped_times) # print("MAPPED AMOUNTS", mapped_amounts) # - # if mapped_times[0] > gSmall: + # if mapped_times[0] > g_small: # raise FinError("Mapped times [0] must be <= 0 for first coupon > 0") # ########################################################################### @@ -324,7 +321,7 @@ def american_bond_option_tree_fast(t_exp, t_mat, # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if tree_flows[m] > gSmall: + if tree_flows[m] > g_small: accrued[m] = tree_flows[m] * face_amount if DEBUG: @@ -368,7 +365,8 @@ def american_bond_option_tree_fast(t_exp, t_mat, clean_price = dirty_price - accrued[m] if DEBUG: - print(m, _tree_times[m], accrued[m], dirty_price, clean_price, 0, 0) + print(m, _tree_times[m], accrued[m], + dirty_price, clean_price, 0, 0) # Now step back to today from the expiry date considering early exercise for m in range(expiry_step, -1, -1): @@ -407,18 +405,18 @@ def american_bond_option_tree_fast(t_exp, t_mat, call_exercise = max(clean_price - strike_price, 0.0) put_exercise = max(strike_price - clean_price, 0.0) - holdCall = call_option_values[m, k] - holdPut = put_option_values[m, k] + hold_call = call_option_values[m, k] + hold_put = put_option_values[m, k] if m == expiry_step: - call_option_values[m, k] = max(call_exercise, holdCall) - put_option_values[m, k] = max(put_exercise, holdPut) + call_option_values[m, k] = max(call_exercise, hold_call) + put_option_values[m, k] = max(put_exercise, hold_put) elif exercise_type_int == 3 and m < expiry_step: - call_option_values[m, k] = max(call_exercise, holdCall) - put_option_values[m, k] = max(put_exercise, holdPut) + call_option_values[m, k] = max(call_exercise, hold_call) + put_option_values[m, k] = max(put_exercise, hold_put) if DEBUG: print(m, _tree_times[m], accrued[m], dirty_price, clean_price, @@ -514,7 +512,7 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, # Value the bond by backward induction starting at bond maturity ########################################################################### - callPutBondValues = np.zeros(shape=(num_time_steps, num_nodes)) + call_put_bond_values = np.zeros(shape=(num_time_steps, num_nodes)) bond_values = np.zeros(shape=(num_time_steps, num_nodes)) DEBUG = False @@ -542,7 +540,7 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, for k in range(0, nm+1): bond_values[m, k] = (1.0 + tree_flows[m]) * face_amount - callPutBondValues[m, k] = value + call_put_bond_values[m, k] = value for m in range(maturity_step-1, -1, -1): nm = m @@ -562,16 +560,16 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, bond_values[m, k] = v bond_values[m, k] += flow - vu = callPutBondValues[m+1, k+1] - vd = callPutBondValues[m+1, k] + vu = call_put_bond_values[m+1, k+1] + vd = call_put_bond_values[m+1, k] vhold = (pu*vu + pd*vd) * df # Need to make add on coupons paid if we hold vhold = vhold + flow value = min(max(vhold - accrued[m], vput), vcall) + accrued[m] - callPutBondValues[m, k] = value + call_put_bond_values[m, k] = value - return {'bondwithoption': callPutBondValues[0, 0], + return {'bondwithoption': call_put_bond_values[0, 0], 'bondpure': bond_values[0, 0]} ############################################################################### @@ -668,13 +666,17 @@ def __init__(self, self._Q = None self._rt = None self._tree_times = None + self._df_times = None self._pu = 0.50 self._pd = 0.50 self._discount_curve = None + self._dt = None + ############################################################################### - def build_tree(self, treeMat, df_times, df_values): + + def build_tree(self, tree_mat, df_times, df_values): if isinstance(df_times, np.ndarray) is False: raise FinError("DF TIMES must be a numpy vector") @@ -684,23 +686,24 @@ def build_tree(self, treeMat, df_times, df_values): interp = InterpTypes.FLAT_FWD_RATES.value - treeMaturity = treeMat * (self._num_time_steps+1)/self._num_time_steps - tree_times = np.linspace(0.0, treeMaturity, self._num_time_steps + 2) + tree_maturity = tree_mat * \ + (self._num_time_steps+1)/self._num_time_steps + tree_times = np.linspace(0.0, tree_maturity, self._num_time_steps + 2) self._tree_times = tree_times - dfTree = np.zeros(shape=(self._num_time_steps+2)) - dfTree[0] = 1.0 + df_tree = np.zeros(shape=(self._num_time_steps+2)) + df_tree[0] = 1.0 for i in range(1, self._num_time_steps+2): t = tree_times[i] - dfTree[i] = _uinterpolate(t, df_times, df_values, interp) + df_tree[i] = _uinterpolate(t, df_times, df_values, interp) self._df_times = df_times self._dfs = df_values self._Q, self._rt, self._dt \ = build_tree_fast(self._sigma, - tree_times, self._num_time_steps, dfTree) + tree_times, self._num_time_steps, df_tree) return @@ -755,7 +758,7 @@ def bermudan_swaption(self, t_exp, t_mat, strike, face_amount, ####################################################################### - payValue, recValue \ + pay_value, rec_value \ = bermudan_swaption_tree_fast(t_exp, t_mat, strike, face_amount, cpn_times, cpn_flows, @@ -765,7 +768,7 @@ def bermudan_swaption(self, t_exp, t_mat, strike, face_amount, self._rt, self._dt) - return {'pay': payValue, 'rec': recValue} + return {'pay': pay_value, 'rec': rec_value} ############################################################################### diff --git a/financepy/models/bk_tree.py b/financepy/models/bk_tree.py index b639dce2..2e298e40 100644 --- a/financepy/models/bk_tree.py +++ b/financepy/models/bk_tree.py @@ -1,6 +1,6 @@ -############################################################################## +############################################################################### # Copyright (C) 2018, 2019, 2020 Dominic O'Kane -############################################################################## +############################################################################### import numpy as np from numba import njit, float64, int64 @@ -11,7 +11,7 @@ from ..market.curves.interpolator import InterpTypes, _uinterpolate from ..utils.helpers import label_to_string from ..utils.global_types import FinExerciseTypes -from ..utils.global_vars import gSmall +from ..utils.global_vars import g_small interp = InterpTypes.FLAT_FWD_RATES.value @@ -28,13 +28,12 @@ ############################################################################### -def option_exercise_types_to_int(optionExerciseType): - - if optionExerciseType == FinExerciseTypes.EUROPEAN: +def option_exercise_types_to_int(option_exercise_type): + if option_exercise_type == FinExerciseTypes.EUROPEAN: return 1 - if optionExerciseType == FinExerciseTypes.BERMUDAN: + if option_exercise_type == FinExerciseTypes.BERMUDAN: return 2 - if optionExerciseType == FinExerciseTypes.AMERICAN: + if option_exercise_type == FinExerciseTypes.AMERICAN: return 3 else: raise FinError("Unknown option exercise type.") @@ -44,11 +43,10 @@ def option_exercise_types_to_int(optionExerciseType): @njit(float64(float64, int64, float64[:], float64, float64, float64, int64), fastmath=True, cache=True) -def f(alpha, nm, Q, P, dX, dt, N): - +def f(alpha, nm, Q, P, dx, dt, N): sum_qz = 0.0 for j in range(-nm, nm+1): - x = alpha + j*dX + x = alpha + j*dx rdt = np.exp(x)*dt sum_qz += Q[j+N] * np.exp(-rdt) @@ -60,11 +58,10 @@ def f(alpha, nm, Q, P, dX, dt, N): @njit(float64(float64, int64, float64[:], float64, float64, float64, int64), fastmath=True, cache=True) -def fprime(alpha, nm, Q, P, dX, dt, N): - +def fprime(alpha, nm, Q, P, dx, dt, N): sum_q_zd_z = 0.0 for j in range(-nm, nm+1): - x = alpha + j*dX + x = alpha + j*dx rdt = np.exp(x)*dt sum_q_zd_z += Q[j+N] * np.exp(-rdt) * np.exp(x) @@ -79,15 +76,14 @@ def fprime(alpha, nm, Q, P, dX, dt, N): @njit(float64(float64, int64, float64[:], float64, float64, float64, int64), fastmath=True, cache=True) -def search_root(x0, nm, Q, P, dX, dt, N): - +def search_root(x0, nm, Q, P, dx, dt, N): # print("Searching for root", x0) max_iter = 50 max_error = 1e-8 x1 = x0 * 1.0001 - f0 = f(x0, nm, Q, P, dX, dt, N) - f1 = f(x1, nm, Q, P, dX, dt, N) + f0 = f(x0, nm, Q, P, dx, dt, N) + f1 = f(x1, nm, Q, P, dx, dt, N) for _ in range(0, max_iter): @@ -99,7 +95,7 @@ def search_root(x0, nm, Q, P, dX, dt, N): x = x1 - f1 * (x1 - x0) / df x0, f0 = x1, f1 x1 = x - f1 = f(x1, nm, Q, P, dX, dt, N) + f1 = f(x1, nm, Q, P, dx, dt, N) if abs(f1) <= max_error: return x1 @@ -114,19 +110,19 @@ def search_root(x0, nm, Q, P, dX, dt, N): @njit(float64(float64, int64, float64[:], float64, float64, float64, int64), fastmath=True, cache=True) -def search_root_deriv(x0, nm, Q, P, dX, dt, N): +def search_root_deriv(x0, nm, Q, P, dx, dt, N): max_iter = 50 max_error = 1e-8 for _ in range(0, max_iter): - fval = f(x0, nm, Q, P, dX, dt, N) + fval = f(x0, nm, Q, P, dx, dt, N) if abs(fval) <= max_error: return x0 - fderiv = fprime(x0, nm, Q, P, dX, dt, N) + fderiv = fprime(x0, nm, Q, P, dx, dt, N) if abs(fderiv) == 0.0: print(x0, fval, fderiv) @@ -223,10 +219,10 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, mapped_amounts = np.array([0.0]) for n in range(1, len(_tree_times)): - accdAtExpiry = 0.0 + accd_at_expiry = 0.0 if _tree_times[n-1] < t_exp and _tree_times[n] >= t_exp: mapped_times = np.append(mapped_times, t_exp) - mapped_amounts = np.append(mapped_amounts, accdAtExpiry) + mapped_amounts = np.append(mapped_amounts, accd_at_expiry) if fixed_leg_flows[n] > 0.0: mapped_times = np.append(mapped_times, _tree_times[n]) @@ -242,7 +238,7 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if fixed_leg_flows[m] > gSmall: + if fixed_leg_flows[m] > g_small: accrued[m] = fixed_leg_flows[m] * face_amount ####################################################################### @@ -348,7 +344,7 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, pay_values[m, kN] = max(pay_exercise, hold_pay) rec_values[m, kN] = max(rec_exercise, hold_rec) - elif exercise_type_int == 2 and flow > gSmall and m > expiry_step: + elif exercise_type_int == 2 and flow > g_small and m > expiry_step: pay_values[m, kN] = max(pay_exercise, hold_pay) rec_values[m, kN] = max(rec_exercise, hold_rec) @@ -427,7 +423,7 @@ def american_bond_option_tree_fast(t_exp, t_mat, # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if tree_flows[m] > gSmall: + if tree_flows[m] > g_small: accrued[m] = tree_flows[m] * face_amount if DEBUG: @@ -487,7 +483,8 @@ def american_bond_option_tree_fast(t_exp, t_mat, bond_values[m, kN] += flow if DEBUG: - print(m, _tree_times[m], accrued[m], dirty_price, clean_price, 0, 0) + print(m, _tree_times[m], accrued[m], + dirty_price, clean_price, 0, 0) # Now consider exercise of the option on and before the expiry date for m in range(expiry_step, -1, -1): @@ -569,18 +566,18 @@ def american_bond_option_tree_fast(t_exp, t_mat, call_exercise = max(clean_price - strike_price, 0.0) put_exercise = max(strike_price - clean_price, 0.0) - holdCall = call_option_values[m, kN] - holdPut = put_option_values[m, kN] + hold_call = call_option_values[m, kN] + hold_put = put_option_values[m, kN] if m == expiry_step: - call_option_values[m, kN] = max(call_exercise, holdCall) - put_option_values[m, kN] = max(put_exercise, holdPut) + call_option_values[m, kN] = max(call_exercise, hold_call) + put_option_values[m, kN] = max(put_exercise, hold_put) elif exercise_type_int == 3 and m < expiry_step: # AMERICAN - call_option_values[m, kN] = max(call_exercise, holdCall) - put_option_values[m, kN] = max(put_exercise, holdPut) + call_option_values[m, kN] = max(call_exercise, hold_call) + put_option_values[m, kN] = max(put_exercise, hold_put) if DEBUG: print(m, _tree_times[m], accrued[m], dirty_price, clean_price, @@ -674,7 +671,7 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, # Value the bond by backward induction starting at bond maturity ########################################################################### - callPutBondValues = np.zeros(shape=(num_time_steps, num_nodes)) + call_put_bond_values = np.zeros(shape=(num_time_steps, num_nodes)) bond_values = np.zeros(shape=(num_time_steps, num_nodes)) DEBUG = False @@ -703,7 +700,7 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, for k in range(-nm, nm+1): kN = k + j_max bond_values[m, kN] = (1.0 + tree_flows[m]) * face_amount - callPutBondValues[m, kN] = value + call_put_bond_values[m, kN] = value for m in range(maturity_step-1, -1, -1): nm = min(m, j_max) @@ -737,25 +734,25 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, bond_values[m, kN] += flow if k == j_max: - vu = callPutBondValues[m+1, kN] - vm = callPutBondValues[m+1, kN-1] - vd = callPutBondValues[m+1, kN-2] + vu = call_put_bond_values[m+1, kN] + vm = call_put_bond_values[m+1, kN-1] + vd = call_put_bond_values[m+1, kN-2] elif k == -j_max: - vu = callPutBondValues[m+1, kN+2] - vm = callPutBondValues[m+1, kN+1] - vd = callPutBondValues[m+1, kN] + vu = call_put_bond_values[m+1, kN+2] + vm = call_put_bond_values[m+1, kN+1] + vd = call_put_bond_values[m+1, kN] else: - vu = callPutBondValues[m+1, kN+1] - vm = callPutBondValues[m+1, kN] - vd = callPutBondValues[m+1, kN-1] + vu = call_put_bond_values[m+1, kN+1] + vm = call_put_bond_values[m+1, kN] + vd = call_put_bond_values[m+1, kN-1] vhold = (pu*vu + pm*vm + pd*vd) * df # Need to make add on coupons paid if we hold vhold = vhold + flow value = min(max(vhold - accrued[m], vput), vcall) + accrued[m] - callPutBondValues[m, kN] = value + call_put_bond_values[m, kN] = value - return {'bondwithoption': callPutBondValues[0, j_max], + return {'bondwithoption': call_put_bond_values[0, j_max], 'bondpure': bond_values[0, j_max]} ############################################################################### @@ -765,8 +762,8 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, def build_tree_fast(a, sigma, tree_times, num_time_steps, discount_factors): """ Calibrate the tree to a term structure of interest rates. """ - treeMaturity = tree_times[-1] - dt = treeMaturity / (num_time_steps+1) + tree_maturity = tree_times[-1] + dt = tree_maturity / (num_time_steps+1) dX = sigma * np.sqrt(3.0 * dt) j_max = ceil(0.1835/(a * dt)) @@ -910,23 +907,23 @@ def build_tree(self, t_mat, df_times, df_values): interp = InterpTypes.FLAT_FWD_RATES.value - treeMaturity = t_mat * (self._num_time_steps+1)/self._num_time_steps - tree_times = np.linspace(0.0, treeMaturity, self._num_time_steps + 2) + tree_maturity = t_mat * (self._num_time_steps+1)/self._num_time_steps + tree_times = np.linspace(0.0, tree_maturity, self._num_time_steps + 2) self._tree_times = tree_times - dfTree = np.zeros(shape=(self._num_time_steps+2)) - dfTree[0] = 1.0 + df_tree = np.zeros(shape=(self._num_time_steps+2)) + df_tree[0] = 1.0 for i in range(1, self._num_time_steps+2): t = tree_times[i] - dfTree[i] = _uinterpolate(t, df_times, df_values, interp) + df_tree[i] = _uinterpolate(t, df_times, df_values, interp) self._df_times = df_times self._dfs = df_values self._Q, self._pu, self._pm, self._pd, self._rt, self._dt \ = build_tree_fast(self._a, self._sigma, - tree_times, self._num_time_steps, dfTree) + tree_times, self._num_time_steps, df_tree) return @@ -982,7 +979,7 @@ def bermudan_swaption(self, t_exp, t_mat, strike_price, face_amount, ####################################################################### - payValue, recValue \ + pay_value, rec_value \ = bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, @@ -993,7 +990,7 @@ def bermudan_swaption(self, t_exp, t_mat, strike_price, face_amount, self._rt, self._dt, self._a) - return {'pay': payValue, 'rec': recValue} + return {'pay': pay_value, 'rec': rec_value} ############################################################################### diff --git a/financepy/models/black.py b/financepy/models/black.py index f9eb997e..a78d1919 100644 --- a/financepy/models/black.py +++ b/financepy/models/black.py @@ -10,7 +10,7 @@ from numba import njit, float64 from ..utils.math import n_vect, n_prime_vect -from ..utils.global_vars import gSmall +from ..utils.global_vars import g_small from ..utils.helpers import label_to_string from ..utils.global_types import OptionTypes from ..utils.error import FinError @@ -78,10 +78,10 @@ def value(self, ############################################################################### def delta(self, - forward_rate, # Forward rate F - strike_rate, # Strike Rate K + forward_rate, # Forward rate + strike_rate, # Strike Rate time_to_expiry, # Time to Expiry (years) - df, # RFR to expiry date + df, # Discount factor to expiry date option_type): # Call or put """ Calculate delta using Black's model which values in the forward measure following a change of measure. """ @@ -227,7 +227,7 @@ def vega(self, def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VOLATILITY", self._volatility) - s += label_to_string("IMPLEMENTATION", self._implementation) + s += label_to_string("IMPLEMENTATION", self._implementation_type) s += label_to_string("NUMSTEPS", self._num_steps) return s @@ -291,10 +291,10 @@ def black_theta(fwd, t, k, r, v, option_type): cache=True) def calculate_d1_d2(f, t, k, v): - t = np.maximum(t, gSmall) - vol = np.maximum(v, gSmall) - k = np.maximum(k, gSmall) - sqrtT = np.sqrt(t) + t = np.maximum(t, g_small) + vol = np.maximum(v, g_small) + k = np.maximum(k, g_small) + sqrt_t = np.sqrt(t) if f <= 0.0: raise FinError("Forward is zero.") @@ -302,8 +302,8 @@ def calculate_d1_d2(f, t, k, v): if k <= 0.0: raise FinError("Strike is zero.") - d1 = (np.log(f/k) + vol * vol * t / 2.0) / (vol * sqrtT) - d2 = d1 - vol * sqrtT + d1 = (np.log(f/k) + vol * vol * t / 2.0) / (vol * sqrt_t) + d2 = d1 - vol * sqrt_t return np.array([d1, d2]) @@ -364,7 +364,7 @@ def _estimate_vol_from_price(fwd, t, k, european_option_type, european_price): else: raise FinError("Option type must be a European Call or Put") sigma_guess = price / (0.398 * np.sqrt(t) * fwd * np.exp(-r*t)) - if t < gSmall: # avoid zero division + if t < g_small: # avoid zero division sigma_guess = 0.0 return sigma_guess diff --git a/financepy/models/black_scholes.py b/financepy/models/black_scholes.py index d9aa91d1..14daba4e 100644 --- a/financepy/models/black_scholes.py +++ b/financepy/models/black_scholes.py @@ -4,6 +4,8 @@ # TODO Fix this +from enum import Enum + import numpy as np from ..utils.global_types import OptionTypes @@ -24,9 +26,6 @@ from .finite_difference_PSOR import black_scholes_fd_PSOR -from enum import Enum - - class BlackScholesTypes(Enum): DEFAULT = 0 ANALYTICAL = 1 @@ -42,8 +41,6 @@ class BlackScholesTypes(Enum): class BlackScholes(Model): - ########################################################################### - def __init__(self, volatility: (float, np.ndarray), bs_type: BlackScholesTypes = BlackScholesTypes.DEFAULT, @@ -62,6 +59,8 @@ def __init__(self, self._seed = seed self._use_sobol = use_sobol self._params = params if params else {} + self._poly_degree = None + self._fit_type = None ########################################################################### @@ -146,7 +145,7 @@ def value(self, option_type_value=option_type.value, strike_price=strike_price, poly_degree=poly_degree, - fit_type=fit_type, + fit_type_value=fit_type.value, use_sobol=self._use_sobol, seed=self._seed) diff --git a/financepy/models/black_scholes_analytic.py b/financepy/models/black_scholes_analytic.py index 662a9d89..6217a6a6 100644 --- a/financepy/models/black_scholes_analytic.py +++ b/financepy/models/black_scholes_analytic.py @@ -6,7 +6,7 @@ from numba import float64, int64, vectorize, njit from ..utils.global_types import OptionTypes -from ..utils.global_vars import gSmall +from ..utils.global_vars import g_small from ..utils.math import N, n_vect, n_prime_vect from ..utils.error import FinError from ..utils.solver_1d import bisection, newton, newton_secant @@ -19,7 +19,7 @@ @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_value(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ + """Price a derivative using Black-Scholes model.""" if option_type_value == OptionTypes.EUROPEAN_CALL.value: phi = 1.0 @@ -28,9 +28,9 @@ def bs_value(s, t, k, r, q, v, option_type_value): else: raise FinError("Unknown option type value") - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) v_sqrt_t = v * np.sqrt(t) ss = s * np.exp(-q*t) @@ -47,8 +47,7 @@ def bs_value(s, t, k, r, q, v, option_type_value): @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_delta(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ - + """Price a derivative using Black-Scholes model.""" if option_type_value == OptionTypes.EUROPEAN_CALL.value: phi = +1.0 elif option_type_value == OptionTypes.EUROPEAN_PUT.value: @@ -57,9 +56,9 @@ def bs_delta(s, t, k, r, q, v, option_type_value): raise FinError("Unknown option type value") return 0.0 - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) v_sqrt_t = v * np.sqrt(t) ss = s * np.exp(-q*t) @@ -74,11 +73,11 @@ def bs_delta(s, t, k, r, q, v, option_type_value): @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_gamma(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ + """Price a derivative using Black-Scholes model.""" - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) v_sqrt_t = v * np.sqrt(t) ss = s * np.exp(-q*t) @@ -93,11 +92,10 @@ def bs_gamma(s, t, k, r, q, v, option_type_value): @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_vega(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ - - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + """Price a derivative using Black-Scholes model.""" + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) sqrt_t = np.sqrt(t) v_sqrt_t = v * sqrt_t @@ -113,16 +111,16 @@ def bs_vega(s, t, k, r, q, v, option_type_value): @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_theta(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ + """Price a derivative using Black-Scholes model.""" if option_type_value == OptionTypes.EUROPEAN_CALL.value: phi = 1.0 elif option_type_value == OptionTypes.EUROPEAN_PUT.value: phi = -1.0 - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) sqrt_t = np.sqrt(t) v_sqrt_t = v * sqrt_t @@ -141,16 +139,16 @@ def bs_theta(s, t, k, r, q, v, option_type_value): @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_rho(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ + """Price a derivative using Black-Scholes model.""" if option_type_value == OptionTypes.EUROPEAN_CALL.value: phi = 1.0 elif option_type_value == OptionTypes.EUROPEAN_PUT.value: phi = -1.0 - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) sqrt_t = np.sqrt(t) v_sqrt_t = v * sqrt_t @@ -167,11 +165,11 @@ def bs_rho(s, t, k, r, q, v, option_type_value): @vectorize([float64(float64, float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_vanna(s, t, k, r, q, v, option_type_value): - """ Price a derivative using Black-Scholes model. """ + """Price a derivative using Black-Scholes model.""" - k = np.maximum(k, gSmall) - t = np.maximum(t, gSmall) - v = np.maximum(v, gSmall) + k = np.maximum(k, g_small) + t = np.maximum(t, g_small) + v = np.maximum(v, g_small) sqrt_t = np.sqrt(t) v_sqrt_t = v * sqrt_t @@ -196,8 +194,8 @@ def _f(sigma, args): price = args[5] option_type_value = int(args[6]) - bsPrice = bs_value(s, t, k, r, q, sigma, option_type_value) - obj = bsPrice - price + bs_price = bs_value(s, t, k, r, q, sigma, option_type_value) + obj = bs_price - price return obj ############################################################################## @@ -221,8 +219,8 @@ def _fvega(sigma, args): @vectorize([float64(float64, float64, float64, float64, float64, int64)], fastmath=True, cache=True) def bs_intrinsic(s, t, k, r, q, option_type_value): - """ Calculate the Black-Scholes implied volatility of a European - vanilla option using Newton with a fallback to bisection. """ + """Calculate the Black-Scholes implied volatility of a European + vanilla option using Newton with a fallback to bisection.""" fwd = s * np.exp((r-q)*t) @@ -236,11 +234,11 @@ def bs_intrinsic(s, t, k, r, q, option_type_value): ############################################################################### -# @vectorize([float64(float64, float64, float64, float64, float64, float64, -# int64)], fastmath=True, cache=True, forceobj=True) +@vectorize([float64(float64, float64, float64, float64, float64, float64, + int64)], fastmath=True, cache=True, forceobj=True) def bs_implied_volatility(s, t, k, r, q, price, option_type_value): - """ Calculate the Black-Scholes implied volatility of a European - vanilla option using Newton with a fallback to bisection. """ + """Calculate the Black-Scholes implied volatility of a European + vanilla option using Newton with a fallback to bisection.""" fwd = s * np.exp((r-q)*t) @@ -268,11 +266,11 @@ def bs_implied_volatility(s, t, k, r, q, price, option_type_value): else: intrinsic_value = np.exp(-r*t) * max(k - fwd, 0.0) - timeValue = price - intrinsic_value + time_value = price - intrinsic_value # Add a tolerance in case it is just numerical imprecision - if timeValue < 0.0: - print("Time value", timeValue) + if time_value < 0.0: + print("Time value", time_value) raise FinError("Option Price is below the intrinsic value") ########################################################################### @@ -318,8 +316,7 @@ def bs_implied_volatility(s, t, k, r, q, price, option_type_value): gamma = 2.0 arg = (2*call+X-S)**2 - gamma * (S+X)*(S-X)*(S-X) / pi / S - if arg < 0.0: - arg = 0.0 + arg = max(arg, 0.0) hsigma = (2 * call + X - S + np.sqrt(arg)) hsigma = hsigma * np.sqrt(2.0*pi) / 2.0 / (S+X) @@ -361,7 +358,7 @@ def bs_implied_volatility(s, t, k, r, q, price, option_type_value): @njit(fastmath=True, cache=True) def _fcall(si, *args): - """ Function to determine ststar for pricing American call options. """ + """Function to determine ststar for pricing American call options.""" t = args[0] k = args[1] @@ -389,7 +386,7 @@ def _fcall(si, *args): @njit(fastmath=True, cache=True) def _fput(si, *args): - """ Function to determine sstar for pricing American put options. """ + """Function to determine sstar for pricing American put options.""" t = args[0] k = args[1] @@ -417,8 +414,8 @@ def _fput(si, *args): @njit(fastmath=True) def baw_value(s, t, k, r, q, v, phi): - """ American Option Pricing Approximation using the Barone-Adesi-Whaley - approximation for the Black Scholes Model """ + """American Option Pricing Approximation using the Barone-Adesi-Whaley + approximation for the Black Scholes Model""" b = r - q @@ -441,18 +438,14 @@ def baw_value(s, t, k, r, q, v, phi): if s < sstar: return bs_value(s, t, k, r, q, v, OptionTypes.EUROPEAN_CALL.value) + A2 * ((s/sstar)**q2) - else: - return s - k + + return s - k elif phi == -1: argtuple = (t, k, r, q, v) -# sstar = optimize.newton(_fput, x0=s, fprime=None, args=argtuple, -# tol=1e-7, maxiter=50, fprime2=None) - - sstar = newton_secant(_fput, x0=s, args=argtuple, - tol=1e-7, maxiter=50) + sstar = newton_secant(_fput, x0=s, args=argtuple, tol=1e-7, maxiter=50) v2 = v * v @@ -464,7 +457,8 @@ def baw_value(s, t, k, r, q, v, phi): a1 = -(sstar / q1) * (1 - np.exp(-q * t) * n_vect(-d1)) if s > sstar: - return bs_value(s, t, k, r, q, v, OptionTypes.EUROPEAN_PUT.value) + a1 * ((s/sstar)**q1) + bsv = bs_value(s, t, k, r, q, v, OptionTypes.EUROPEAN_PUT.value) + return bsv + a1 * ((s/sstar)**q1) else: return k - s @@ -477,8 +471,8 @@ def baw_value(s, t, k, r, q, v, phi): @njit(fastmath=True) def bjerksund_stensland_value(s, t, k, r, q, v, option_type_value): - """ Price American Option using the Bjerksund-Stensland - approximation (1993) for the Black Scholes Model """ + """Price American Option using the Bjerksund-Stensland + approximation (1993) for the Black Scholes Model""" if option_type_value == OptionTypes.AMERICAN_CALL.value: pass elif option_type_value == OptionTypes.AMERICAN_PUT.value: @@ -488,16 +482,18 @@ def bjerksund_stensland_value(s, t, k, r, q, v, option_type_value): return 0.0 def phi(S, T, gamma, H, X): - """ The function corresponding to Eq.(13) - in Bjerksund-Stensland approximation (1993)""" + """Eq.(13) in Bjerksund-Stensland approximation (1993).""" nonlocal r, q - lambda0 = (-r + gamma * q + 0.5 * gamma * (gamma - 1.0) * v**2) * T - d = - (np.log(S/H) + (q + (gamma - 0.5) * v**2) * T) / (v * np.sqrt(t)) + lambda0 = (-r + gamma * q + 0.5 * gamma * + (gamma - 1.0) * v**2) * T + d = - (np.log(S/H) + (q + (gamma - 0.5) * v**2) * T) / \ + (v * np.sqrt(t)) kappa = (2.0 * gamma - 1.0) + (2.0 * q) / v**2 return ( np.exp(lambda0) * (S ** gamma) * (N(d) - N(d - (2.0 * np.log(X/S)/v/np.sqrt(T))) * ((X/S)**kappa)) ) + # calc trigger price x_t beta = (0.5 - q/(v**2)) + np.sqrt((0.5 - q/(v**2))**2 + 2.0 * r/(v**2)) # avoid division by zero @@ -511,11 +507,10 @@ def phi(S, T, gamma, H, X): x_t = b_0 + (b_infty - b_0) * (1.0 - np.exp(h_t)) # calc option value alpha = (x_t - k) * x_t ** (-beta) - value = ( - alpha * (s**beta) - alpha * phi(s, t, beta, x_t, x_t) - + phi(s, t, 1.0, x_t, x_t) - phi(s, t, 1.0, k, x_t) - - k * phi(s, t, 0.0, x_t, x_t) + k * phi(s, t, 0.0, k, x_t) - ) + value = (alpha * (s**beta) - alpha * phi(s, t, beta, x_t, x_t) + + phi(s, t, 1.0, x_t, x_t) - phi(s, t, 1.0, k, x_t) + - k * phi(s, t, 0.0, x_t, x_t) + k * phi(s, t, 0.0, k, x_t)) + return value ############################################################################### diff --git a/financepy/models/black_scholes_mc_tests.py b/financepy/models/black_scholes_mc_tests.py index 497be501..48f78ee5 100644 --- a/financepy/models/black_scholes_mc_tests.py +++ b/financepy/models/black_scholes_mc_tests.py @@ -14,7 +14,6 @@ def value_mc1(s0, t, k, r, q, v, num_paths, seed): - v_sqrt_t = v * sqrt(t) st = s0 * exp((r - q - v*v / 2.0) * t) diff --git a/financepy/models/cir_mc.py b/financepy/models/cir_montecarlo.py similarity index 96% rename from financepy/models/cir_mc.py rename to financepy/models/cir_montecarlo.py index 5a7c8924..0c1a2fd6 100644 --- a/financepy/models/cir_mc.py +++ b/financepy/models/cir_montecarlo.py @@ -1,348 +1,347 @@ -############################################################################## -# Copyright (C) 2018, 2019, 2020 Dominic O'Kane -############################################################################## - -from numba import njit, float64, int64 -import numpy as np -from ..utils.helpers import label_to_string - -############################################################################### -# CIR Process -# dr = a(b-r) + sigma sqrt(r) dW -# Note that r can hit zero if 2.0 * a * b < sigma*sigma: -############################################################################### - -# TO DO - DECIDE WHETHER TO OO MODEL -# CAN DO Z SCALING INSIDE NUMPY ? -# ANTITHETICS - -from enum import Enum - - -class CIRNumericalScheme(Enum): - EULER = 1 - LOGNORMAL = 2 - MILSTEIN = 3 - KAHLJACKEL = 4 - EXACT = 5 # SAMPLES EXACT DISTRIBUTION - - -############################################################################### - -# THIS CLASS IS NOT USED BUT MAY BE USED IF WE CREATE AN OO FRAMEWORK - - -class CIR_MC(): - ''' This is a Monte Carlo implementation of the Cox-Ingersoll-Ross Model''' - - def __init__(self, a, b, sigma): - self._a = a - self._b = b - self._sigma = sigma - - def __repr__(self): - """ Return string with class details. """ - - s = label_to_string("OBJECT TYPE", type(self).__name__) - s += label_to_string("Sigma", self._sigma) - s += label_to_string("a", self._a) - s += label_to_string("b", self._b) - return s - - -############################################################################### - -@njit(fastmath=True, cache=True) -def meanr(r0, a, b, t): - """ Mean value of a CIR process after time t """ - mr = r0 * np.exp(-a * t) + b * (1.0 - np.exp(-a * t)) - return mr - - -############################################################################### - - -@njit(fastmath=True, cache=True) -def variancer(r0, a, b, sigma, t): - """ Variance of a CIR process after time t """ - vr = r0 * sigma * sigma * (np.exp(-a * t) - np.exp(-2.0 * a * t)) / a - vr += b * sigma * sigma * ((1.0 - np.exp(-a * t)) ** 2) / 2.0 / a - return vr - - -############################################################################### - - -@njit( - float64( - float64, - float64, - float64, - float64, - float64), - fastmath=True, - cache=True) -def zero_price(r0, a, b, sigma, t): - """ Price of a zero coupon bond in CIR model. """ - h = np.sqrt(a * a + 2.0 * sigma * sigma) - denom = 2.0 * h + (a + h) * (np.exp(h * t) - 1.0) - aa = (2.0 * h * np.exp((a + h) * t / 2.0) / - denom) ** (2.0 * a * b / sigma / sigma) - bb = 2.0 * (np.exp(h * t) - 1.0) / denom - zcb = aa * np.exp(-r0 * bb) - return zcb - -############################################################################### - - -@njit( - float64( - float64, - float64, - float64, - float64, - float64), - fastmath=True, - cache=True) -def draw(rt, a, b, sigma, dt): - """ Draw a next rate from the CIR model in Monte Carlo. """ - sigma2 = sigma * sigma - d = 4.0 * a * b / sigma2 - ll = 4.0 * a * np.exp(-a * dt) / sigma2 / (1.0 - np.exp(-a * dt)) * rt - c = sigma2 * (1.0 - np.exp(-a * dt)) / 4.0 / a - - if d > 1: - z = np.random.normal() - x = np.random.chisquare(d - 1) - r = c * (x + (z + np.sqrt(ll)) ** 2) - else: - n = np.random.poisson(ll / 2.0) - x = np.random.chisquare(d + 2 * n) - r = c * x - - return r - - -############################################################################### - - -@njit( - float64[:]( - float64, - float64, - float64, - float64, - float64, - float64, - int64, - int64)) -def rate_path_mc(r0, a, b, sigma, t, dt, seed, scheme): - """ Generate a path of CIR rates using a number of numerical schemes. """ - - np.random.seed(seed) - num_steps = int(t / dt) - rate_path = np.zeros(num_steps) - rate_path[0] = r0 - num_paths = 1 - - if scheme == CIRNumericalScheme.EULER.value: - - sigmasqrt_dt = sigma * np.sqrt(dt) - - for i_path in range(0, num_paths): - - r = r0 - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - r = r + a * (b - r) * dt + \ - z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(r, 0.0)) - rate_path[i_step] = r - - elif scheme == CIRNumericalScheme.LOGNORMAL.value: - - x = np.exp(-a * dt) - y = 1.0 - x - - for i_path in range(0, num_paths): - - r = r0 - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - mean = x * r + b * y - var = sigma * sigma * y * (x * r + 0.50 * b * y) / a - sig = np.sqrt(np.log(1.0 + var / (mean * mean))) - r = mean * np.exp(-0.5 * sig * sig + sig * z[i_step - 1]) - rate_path[i_step] = r - - elif scheme == CIRNumericalScheme.MILSTEIN.value: - - sigmasqrt_dt = sigma * np.sqrt(dt) - sigma2dt = sigma * sigma * dt / 4.0 - - for i_path in range(0, num_paths): - - r = r0 - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - r = r + a * (b - r) * dt + \ - z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(0.0, r)) - r = r + sigma2dt * (z[i_step - 1] ** 2 - 1.0) - rate_path[i_step] = r - - elif scheme == CIRNumericalScheme.KAHLJACKEL.value: - - bhat = b - sigma * sigma / 4.0 / a - sqrt_dt = np.sqrt(dt) - - for i_path in range(0, num_paths): - - r = r0 - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - beta = z[i_step - 1] / sqrt_dt - rootr = np.sqrt(max(r, 1e-8)) - c = 1.0 + (sigma * beta - 2.0 * a * rootr) * dt / 4.0 / rootr - r = r + (a * (bhat - r) + sigma * beta * rootr) * c * dt - rate_path[i_step] = r - - elif scheme == CIRNumericalScheme.EXACT.value: - - for i_path in range(0, num_paths): - - r = r0 - - for i_step in range(1, num_steps): - r = draw(r, a, b, sigma, dt) - rate_path[i_step] = r - - return rate_path - - -############################################################################### - - -@njit( - float64( - float64, - float64, - float64, - float64, - float64, - float64, - int64, - int64, - int64)) -def zero_price_mc(r0, a, b, sigma, t, dt, num_paths, seed, scheme): - """ Determine the CIR zero price using Monte Carlo. """ - - if t == 0.0: - return 1.0 - - np.random.seed(seed) - - num_steps = int(t / dt) - zcb = 0.0 - - if scheme == CIRNumericalScheme.EULER.value: - - sigmasqrt_dt = sigma * np.sqrt(dt) - - for i_path in range(0, num_paths): - - r = r0 - rsum = r - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - r_prev = r - r = r + a * (b - r) * dt + \ - z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(r, 0.0)) - rsum += (r + r_prev) - - zcb += np.exp(-0.50 * rsum * dt) - - elif scheme == CIRNumericalScheme.LOGNORMAL.value: - - x = np.exp(-a * dt) - y = 1.0 - x - - for i_path in range(0, num_paths): - - r = r0 - rsum = r0 - - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - mean = x * r + b * y - var = sigma * sigma * y * (x * r + 0.50 * b * y) / a - sig = np.sqrt(np.log(1.0 + var / (mean * mean))) - r_prev = r - r = mean * np.exp(-0.5 * sig * sig + sig * z[i_step - 1]) - rsum += (r + r_prev) - - zcb += np.exp(-0.5 * rsum * dt) - - elif scheme == CIRNumericalScheme.MILSTEIN.value: - - sigmasqrt_dt = sigma * np.sqrt(dt) - sigma2dt = sigma * sigma * dt / 4.0 - - for i_path in range(0, num_paths): - - r = r0 - rsum = r - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - r_prev = r - r = r + a * (b - r) * dt + \ - z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(0.0, r)) - r = r + sigma2dt * (z[i_step - 1] ** 2 - 1.0) - rsum += (r + r_prev) - - zcb += np.exp(-0.50 * rsum * dt) - - elif scheme == CIRNumericalScheme.KAHLJACKEL.value: - - bhat = b - sigma * sigma / 4.0 / a - sqrt_dt = np.sqrt(dt) - - for i_path in range(0, num_paths): - - r = r0 - rsum = r - z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) - - for i_step in range(1, num_steps): - beta = z[i_step - 1] / sqrt_dt - rootr = np.sqrt(max(r, 1e-8)) - c = 1.0 + (sigma * beta - 2.0 * a * rootr) * dt / 4.0 / rootr - r_prev = r - r = r + (a * (bhat - r) + sigma * beta * rootr) * c * dt - rsum += (r + r_prev) - - zcb += np.exp(-0.50 * rsum * dt) - - elif scheme == CIRNumericalScheme.EXACT.value: - - for i_path in range(0, num_paths): - - r = r0 - rsum = r - - for i_step in range(1, num_steps): - r_prev = r - r = draw(r, a, b, sigma, dt) - rsum += (r + r_prev) - - zcb += np.exp(-0.50 * rsum * dt) - - zcb /= num_paths - return zcb - -############################################################################### +############################################################################## +# Copyright (C) 2018, 2019, 2020 Dominic O'Kane +############################################################################## + +from enum import Enum +from numba import njit, float64, int64 +import numpy as np +from ..utils.helpers import label_to_string + +############################################################################### +# CIR Process +# dr = a(b-r) + sigma sqrt(r) dW +# Note that r can hit zero if 2.0 * a * b < sigma*sigma: +############################################################################### + +# TO DO - DECIDE WHETHER TO OO MODEL +# CAN DO Z SCALING INSIDE NUMPY ? +# ANTITHETICS + + + +class CIRNumericalScheme(Enum): + EULER = 1 + LOGNORMAL = 2 + MILSTEIN = 3 + KAHLJACKEL = 4 + EXACT = 5 # SAMPLES EXACT DISTRIBUTION + + +############################################################################### + +# THIS CLASS IS NOT USED BUT MAY BE USED IF WE CREATE AN OO FRAMEWORK + + +class CIRMonteCarlo(): + ''' This is a Monte Carlo implementation of the Cox-Ingersoll-Ross Model''' + + def __init__(self, a, b, sigma): + self._a = a + self._b = b + self._sigma = sigma + + def __repr__(self): + """ Return string with class details. """ + s = label_to_string("OBJECT TYPE", type(self).__name__) + s += label_to_string("Sigma", self._sigma) + s += label_to_string("a", self._a) + s += label_to_string("b", self._b) + return s + + +############################################################################### + +@njit(fastmath=True, cache=True) +def meanr(r0, a, b, t): + """ Mean value of a CIR process after time t """ + mr = r0 * np.exp(-a * t) + b * (1.0 - np.exp(-a * t)) + return mr + + +############################################################################### + + +@njit(fastmath=True, cache=True) +def variancer(r0, a, b, sigma, t): + """ Variance of a CIR process after time t """ + vr = r0 * sigma * sigma * (np.exp(-a * t) - np.exp(-2.0 * a * t)) / a + vr += b * sigma * sigma * ((1.0 - np.exp(-a * t)) ** 2) / 2.0 / a + return vr + + +############################################################################### + + +@njit( + float64( + float64, + float64, + float64, + float64, + float64), + fastmath=True, + cache=True) +def zero_price(r0, a, b, sigma, t): + """ Price of a zero coupon bond in CIR model. """ + h = np.sqrt(a * a + 2.0 * sigma * sigma) + denom = 2.0 * h + (a + h) * (np.exp(h * t) - 1.0) + aa = (2.0 * h * np.exp((a + h) * t / 2.0) / + denom) ** (2.0 * a * b / sigma / sigma) + bb = 2.0 * (np.exp(h * t) - 1.0) / denom + zcb = aa * np.exp(-r0 * bb) + return zcb + +############################################################################### + + +@njit( + float64( + float64, + float64, + float64, + float64, + float64), + fastmath=True, + cache=True) +def draw(rt, a, b, sigma, dt): + """ Draw a next rate from the CIR model in Monte Carlo. """ + sigma2 = sigma * sigma + d = 4.0 * a * b / sigma2 + ll = 4.0 * a * np.exp(-a * dt) / sigma2 / (1.0 - np.exp(-a * dt)) * rt + c = sigma2 * (1.0 - np.exp(-a * dt)) / 4.0 / a + + if d > 1: + z = np.random.normal() + x = np.random.chisquare(d - 1) + r = c * (x + (z + np.sqrt(ll)) ** 2) + else: + n = np.random.poisson(ll / 2.0) + x = np.random.chisquare(d + 2 * n) + r = c * x + + return r + + +############################################################################### + + +@njit( + float64[:]( + float64, + float64, + float64, + float64, + float64, + float64, + int64, + int64)) +def rate_path_mc(r0, a, b, sigma, t, dt, seed, scheme): + """ Generate a path of CIR rates using a number of numerical schemes. """ + + np.random.seed(seed) + num_steps = int(t / dt) + rate_path = np.zeros(num_steps) + rate_path[0] = r0 + num_paths = 1 + + if scheme == CIRNumericalScheme.EULER.value: + + sigmasqrt_dt = sigma * np.sqrt(dt) + + for i_path in range(0, num_paths): + + r = r0 + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + r = r + a * (b - r) * dt + \ + z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(r, 0.0)) + rate_path[i_step] = r + + elif scheme == CIRNumericalScheme.LOGNORMAL.value: + + x = np.exp(-a * dt) + y = 1.0 - x + + for i_path in range(0, num_paths): + + r = r0 + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + mean = x * r + b * y + var = sigma * sigma * y * (x * r + 0.50 * b * y) / a + sig = np.sqrt(np.log(1.0 + var / (mean * mean))) + r = mean * np.exp(-0.5 * sig * sig + sig * z[i_step - 1]) + rate_path[i_step] = r + + elif scheme == CIRNumericalScheme.MILSTEIN.value: + + sigmasqrt_dt = sigma * np.sqrt(dt) + sigma2dt = sigma * sigma * dt / 4.0 + + for i_path in range(0, num_paths): + + r = r0 + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + r = r + a * (b - r) * dt + \ + z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(0.0, r)) + r = r + sigma2dt * (z[i_step - 1] ** 2 - 1.0) + rate_path[i_step] = r + + elif scheme == CIRNumericalScheme.KAHLJACKEL.value: + + bhat = b - sigma * sigma / 4.0 / a + sqrt_dt = np.sqrt(dt) + + for i_path in range(0, num_paths): + + r = r0 + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + beta = z[i_step - 1] / sqrt_dt + rootr = np.sqrt(max(r, 1e-8)) + c = 1.0 + (sigma * beta - 2.0 * a * rootr) * dt / 4.0 / rootr + r = r + (a * (bhat - r) + sigma * beta * rootr) * c * dt + rate_path[i_step] = r + + elif scheme == CIRNumericalScheme.EXACT.value: + + for i_path in range(0, num_paths): + + r = r0 + + for i_step in range(1, num_steps): + r = draw(r, a, b, sigma, dt) + rate_path[i_step] = r + + return rate_path + + +############################################################################### + + +@njit( + float64( + float64, + float64, + float64, + float64, + float64, + float64, + int64, + int64, + int64)) +def zero_price_mc(r0, a, b, sigma, t, dt, num_paths, seed, scheme): + """ Determine the CIR zero price using Monte Carlo. """ + + if t == 0.0: + return 1.0 + + np.random.seed(seed) + + num_steps = int(t / dt) + zcb = 0.0 + + if scheme == CIRNumericalScheme.EULER.value: + + sigmasqrt_dt = sigma * np.sqrt(dt) + + for i_path in range(0, num_paths): + + r = r0 + rsum = r + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + r_prev = r + r = r + a * (b - r) * dt + \ + z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(r, 0.0)) + rsum += (r + r_prev) + + zcb += np.exp(-0.50 * rsum * dt) + + elif scheme == CIRNumericalScheme.LOGNORMAL.value: + + x = np.exp(-a * dt) + y = 1.0 - x + + for i_path in range(0, num_paths): + + r = r0 + rsum = r0 + + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + mean = x * r + b * y + var = sigma * sigma * y * (x * r + 0.50 * b * y) / a + sig = np.sqrt(np.log(1.0 + var / (mean * mean))) + r_prev = r + r = mean * np.exp(-0.5 * sig * sig + sig * z[i_step - 1]) + rsum += (r + r_prev) + + zcb += np.exp(-0.5 * rsum * dt) + + elif scheme == CIRNumericalScheme.MILSTEIN.value: + + sigmasqrt_dt = sigma * np.sqrt(dt) + sigma2dt = sigma * sigma * dt / 4.0 + + for i_path in range(0, num_paths): + + r = r0 + rsum = r + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + r_prev = r + r = r + a * (b - r) * dt + \ + z[i_step - 1] * sigmasqrt_dt * np.sqrt(max(0.0, r)) + r = r + sigma2dt * (z[i_step - 1] ** 2 - 1.0) + rsum += (r + r_prev) + + zcb += np.exp(-0.50 * rsum * dt) + + elif scheme == CIRNumericalScheme.KAHLJACKEL.value: + + bhat = b - sigma * sigma / 4.0 / a + sqrt_dt = np.sqrt(dt) + + for i_path in range(0, num_paths): + + r = r0 + rsum = r + z = np.random.normal(0.0, 1.0, size=(num_steps - 1)) + + for i_step in range(1, num_steps): + beta = z[i_step - 1] / sqrt_dt + rootr = np.sqrt(max(r, 1e-8)) + c = 1.0 + (sigma * beta - 2.0 * a * rootr) * dt / 4.0 / rootr + r_prev = r + r = r + (a * (bhat - r) + sigma * beta * rootr) * c * dt + rsum += (r + r_prev) + + zcb += np.exp(-0.50 * rsum * dt) + + elif scheme == CIRNumericalScheme.EXACT.value: + + for i_path in range(0, num_paths): + + r = r0 + rsum = r + + for i_step in range(1, num_steps): + r_prev = r + r = draw(r, a, b, sigma, dt) + rsum += (r + r_prev) + + zcb += np.exp(-0.50 * rsum * dt) + + zcb /= num_paths + return zcb + +############################################################################### diff --git a/financepy/models/equity_barrier_models.py b/financepy/models/equity_barrier_models.py index e17bf50b..55b4e476 100644 --- a/financepy/models/equity_barrier_models.py +++ b/financepy/models/equity_barrier_models.py @@ -15,41 +15,64 @@ @vectorize([float64(float64, float64, float64, float64, float64, float64, float64, int64, int64)], fastmath=True, cache=True) -def value_bs(t, k, h, s, r, q, v, option_type, nobs): - """ This values a single option. Because of its structure it cannot +def value_barrier(t, k, h, s, r, q, v, option_type, nobs): + """ This values a single barrier option. Because of its structure it cannot easily be vectorised which is why it has been wrapped. # number of observations per year """ - lnS0k = np.log(s / k) - sqrtT = np.sqrt(t) + ln_s0_k = np.log(s / k) + sqrt_t = np.sqrt(t) - sigma_rt_t = v * sqrtT + sigma_rt_t = v * sqrt_t v2 = v * v mu = r - q - d1 = (lnS0k + (mu + v2 / 2.0) * t) / sigma_rt_t - d2 = (lnS0k + (mu - v2 / 2.0) * t) / sigma_rt_t + d1 = (ln_s0_k + (mu + v2 / 2.0) * t) / sigma_rt_t + d2 = (ln_s0_k + (mu - v2 / 2.0) * t) / sigma_rt_t df = np.exp(-r * t) dq = np.exp(-q * t) c = s * dq * N(d1) - k * df * N(d2) p = k * df * N(-d2) - s * dq * N(-d1) - if option_type == EquityBarrierTypes.DOWN_AND_OUT_CALL.value and s <= h: - return 0.0 - elif option_type == EquityBarrierTypes.UP_AND_OUT_CALL.value and s >= h: - return 0.0 - elif option_type == EquityBarrierTypes.UP_AND_OUT_PUT.value and s >= h: - return 0.0 - elif option_type == EquityBarrierTypes.DOWN_AND_OUT_PUT.value and s <= h: - return 0.0 - elif option_type == EquityBarrierTypes.DOWN_AND_IN_CALL.value and s <= h: - return c - elif option_type == EquityBarrierTypes.UP_AND_IN_CALL.value and s >= h: - return c - elif option_type == EquityBarrierTypes.UP_AND_IN_PUT.value and s >= h: - return p - elif option_type == EquityBarrierTypes.DOWN_AND_IN_PUT.value and s <= h: - return p + if s >= h: + + if option_type == EquityBarrierTypes.UP_AND_OUT_CALL.value: + return 0.0 + if option_type == EquityBarrierTypes.UP_AND_OUT_PUT.value: + return 0.0 + if option_type == EquityBarrierTypes.UP_AND_IN_CALL.value: + return c + if option_type == EquityBarrierTypes.UP_AND_IN_PUT.value: + return p + + else: + + if option_type == EquityBarrierTypes.DOWN_AND_OUT_CALL.value: + return 0.0 + elif option_type == EquityBarrierTypes.DOWN_AND_OUT_PUT.value: + return 0.0 + elif option_type == EquityBarrierTypes.DOWN_AND_IN_CALL.value: + return c + elif option_type == EquityBarrierTypes.DOWN_AND_IN_PUT.value: + return p + + if 1 == 0: + if option_type == EquityBarrierTypes.DOWN_AND_OUT_CALL.value and s <= h: + return 0.0 + elif option_type == EquityBarrierTypes.UP_AND_OUT_CALL.value and s >= h: + return 0.0 + elif option_type == EquityBarrierTypes.UP_AND_OUT_PUT.value and s >= h: + return 0.0 + elif option_type == EquityBarrierTypes.DOWN_AND_OUT_PUT.value and s <= h: + return 0.0 + elif option_type == EquityBarrierTypes.DOWN_AND_IN_CALL.value and s <= h: + return c + elif option_type == EquityBarrierTypes.UP_AND_IN_CALL.value and s >= h: + return c + elif option_type == EquityBarrierTypes.UP_AND_IN_PUT.value and s >= h: + return p + elif option_type == EquityBarrierTypes.DOWN_AND_IN_PUT.value and s <= h: + return p num_observations = 1 + t * nobs @@ -75,8 +98,7 @@ def value_bs(t, k, h, s, r, q, v, option_type, nobs): elif option_type == EquityBarrierTypes.DOWN_AND_IN_PUT.value: h_adj = h * np.exp(-0.5826 * v * np.sqrt(t)) else: - raise FinError("Unknown barrier option type." + - str(option_type)) + raise FinError("Unknown barrier option type." + str(option_type)) h = h_adj @@ -87,94 +109,93 @@ def value_bs(t, k, h, s, r, q, v, option_type, nobs): y = np.log(h * h / (s * k)) / sigma_rt_t + ll * sigma_rt_t x1 = np.log(s / h) / sigma_rt_t + ll * sigma_rt_t y1 = np.log(h / s) / sigma_rt_t + ll * sigma_rt_t - hOverS = h / s + h_over_s = h / s if option_type == EquityBarrierTypes.DOWN_AND_OUT_CALL.value: if h >= k: c_do = s * dq * N(x1) - k * df * N(x1 - sigma_rt_t) \ - - s * dq * pow(hOverS, 2.0 * ll) * N(y1) \ - + k * df * pow(hOverS, 2.0 * ll - 2.0) * N(y1 - sigma_rt_t) + - s * dq * pow(h_over_s, 2.0 * ll) * N(y1) \ + + k * df * pow(h_over_s, 2.0 * ll - 2.0) * N(y1 - sigma_rt_t) price = c_do else: - c_di = s * dq * pow(hOverS, 2.0 * ll) * N(y) \ - - k * df * pow(hOverS, 2.0 * ll - 2.0) * N(y - sigma_rt_t) + c_di = s * dq * pow(h_over_s, 2.0 * ll) * N(y) \ + - k * df * pow(h_over_s, 2.0 * ll - 2.0) * N(y - sigma_rt_t) price = c - c_di elif option_type == EquityBarrierTypes.DOWN_AND_IN_CALL.value: if h <= k: - c_di = s * dq * pow(hOverS, 2.0 * ll) * N(y) \ - - k * df * pow(hOverS, 2.0 * ll - 2.0) * N(y - sigma_rt_t) + c_di = s * dq * pow(h_over_s, 2.0 * ll) * N(y) \ + - k * df * pow(h_over_s, 2.0 * ll - 2.0) * N(y - sigma_rt_t) price = c_di else: c_do = s * dq * N(x1) \ - - k * df * N(x1 - sigma_rt_t) \ - - s * dq * pow(hOverS, 2.0 * ll) * N(y1) \ - + k * df * pow(hOverS, 2.0 * ll - 2.0) * N(y1 - sigma_rt_t) + - k * df * N(x1 - sigma_rt_t) \ + - s * dq * pow(h_over_s, 2.0 * ll) * N(y1) \ + + k * df * pow(h_over_s, 2.0 * ll - 2.0) * N(y1 - sigma_rt_t) price = c - c_do elif option_type == EquityBarrierTypes.UP_AND_IN_CALL.value: if h >= k: c_ui = s * dq * N(x1) - k * df * N(x1 - sigma_rt_t) \ - - s * dq * pow(hOverS, 2.0 * ll) * (N(-y) - N(-y1)) \ - + k * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(-y + sigma_rt_t) - N(-y1 + sigma_rt_t)) + - s * dq * pow(h_over_s, 2.0 * ll) * (N(-y) - N(-y1)) \ + + k * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(-y + sigma_rt_t) - N(-y1 + sigma_rt_t)) price = c_ui else: price = c elif option_type == EquityBarrierTypes.UP_AND_OUT_CALL.value: if h > k: c_ui = s * dq * N(x1) - k * df * N(x1 - sigma_rt_t) \ - - s * dq * pow(hOverS, 2.0 * ll) * (N(-y) - N(-y1)) \ - + k * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(-y + sigma_rt_t) - N(-y1 + sigma_rt_t)) + - s * dq * pow(h_over_s, 2.0 * ll) * (N(-y) - N(-y1)) \ + + k * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(-y + sigma_rt_t) - N(-y1 + sigma_rt_t)) price = c - c_ui else: price = 0.0 elif option_type == EquityBarrierTypes.UP_AND_IN_PUT.value: if h > k: - p_ui = -s * dq * pow(hOverS, 2.0 * ll) * N(-y) \ - + k * df * pow(hOverS, 2.0 * ll - 2.0) * N(-y + sigma_rt_t) + p_ui = -s * dq * pow(h_over_s, 2.0 * ll) * N(-y) \ + + k * df * pow(h_over_s, 2.0 * ll - 2.0) * N(-y + sigma_rt_t) price = p_ui else: p_uo = -s * dq * N(-x1) \ - + k * df * N(-x1 + sigma_rt_t) \ - + s * dq * pow(hOverS, 2.0 * ll) * N(-y1) \ - - k * df * pow(hOverS, 2.0 * ll - 2.0) * \ - N(-y1 + sigma_rt_t) + + k * df * N(-x1 + sigma_rt_t) \ + + s * dq * pow(h_over_s, 2.0 * ll) * N(-y1) \ + - k * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(-y1 + sigma_rt_t) price = p - p_uo elif option_type == EquityBarrierTypes.UP_AND_OUT_PUT.value: if h >= k: - p_ui = -s * dq * pow(hOverS, 2.0 * ll) * N(-y) \ - + k * df * pow(hOverS, 2.0 * ll - 2.0) * N(-y + sigma_rt_t) + p_ui = -s * dq * pow(h_over_s, 2.0 * ll) * N(-y) \ + + k * df * pow(h_over_s, 2.0 * ll - 2.0) * N(-y + sigma_rt_t) price = p - p_ui else: p_uo = -s * dq * N(-x1) \ - + k * df * N(-x1 + sigma_rt_t) \ - + s * dq * pow(hOverS, 2.0 * ll) * N(-y1) \ - - k * df * pow(hOverS, 2.0 * ll - 2.0) * \ - N(-y1 + sigma_rt_t) + + k * df * N(-x1 + sigma_rt_t) \ + + s * dq * pow(h_over_s, 2.0 * ll) * N(-y1) \ + - k * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(-y1 + sigma_rt_t) price = p_uo elif option_type == EquityBarrierTypes.DOWN_AND_OUT_PUT.value: if h >= k: price = 0.0 else: p_di = -s * dq * N(-x1) \ - + k * df * N(-x1 + sigma_rt_t) \ - + s * dq * pow(hOverS, 2.0 * ll) * (N(y) - N(y1)) \ - - k * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(y - sigma_rt_t) - N(y1 - sigma_rt_t)) + + k * df * N(-x1 + sigma_rt_t) \ + + s * dq * pow(h_over_s, 2.0 * ll) * (N(y) - N(y1)) \ + - k * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(y - sigma_rt_t) - N(y1 - sigma_rt_t)) price = p - p_di elif option_type == EquityBarrierTypes.DOWN_AND_IN_PUT.value: if h >= k: price = p else: p_di = -s * dq * N(-x1) \ - + k * df * N(-x1 + sigma_rt_t) \ - + s * dq * pow(hOverS, 2.0 * ll) * (N(y) - N(y1)) \ - - k * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(y - sigma_rt_t) - N(y1 - sigma_rt_t)) + + k * df * N(-x1 + sigma_rt_t) \ + + s * dq * pow(h_over_s, 2.0 * ll) * (N(y) - N(y1)) \ + - k * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(y - sigma_rt_t) - N(y1 - sigma_rt_t)) price = p_di else: - raise FinError("Unknown barrier option type." + - str(option_type)) + raise FinError("Unknown barrier option type." + str(option_type)) return price diff --git a/financepy/models/equity_crr_tree.py b/financepy/models/equity_crr_tree.py index 9d97fc1c..b4ad9228 100644 --- a/financepy/models/equity_crr_tree.py +++ b/financepy/models/equity_crr_tree.py @@ -27,9 +27,7 @@ def crr_tree_val(stock_price, """ Value an American option using a Binomial Treee """ num_steps = int(num_steps_per_year * time_to_expiry) - - if num_steps < 30: - num_steps = 30 + num_steps = max(num_steps, 30) # OVERRIDE JUST TO SEE num_steps = num_steps_per_year @@ -54,20 +52,20 @@ def crr_tree_val(stock_price, option_values = np.zeros(num_nodes) u = np.exp(volatility * np.sqrt(dt)) d = 1.0 / u - sLow = stock_price + s_low = stock_price probs = np.zeros(num_steps) - periodDiscountFactors = np.zeros(num_steps) + period_dfs = np.zeros(num_steps) # store time independent information for later use in tree for i_time in range(0, num_steps): a = np.exp((r - q) * dt) probs[i_time] = (a - d) / (u - d) - periodDiscountFactors[i_time] = np.exp(-r * dt) + period_dfs[i_time] = np.exp(-r * dt) for i_time in range(1, num_steps + 1): - sLow *= d - s = sLow + s_low *= d + s = s_low for i_node in range(0, i_time + 1): index = 0.5 * i_time * (i_time + 1) stock_values[int(index + i_node)] = s @@ -109,27 +107,27 @@ def crr_tree_val(stock_price, elif option_type == OptionTypes.AMERICAN_PUT.value: exercise_value = np.maximum(strike_price - s, 0.0) - nextIndex = int(0.5 * (i_time + 1) * (i_time + 2)) + next_index = int(0.5 * (i_time + 1) * (i_time + 2)) - next_node_dn = nextIndex + i_node - next_node_up = nextIndex + i_node + 1 + next_node_dn = next_index + i_node + next_node_up = next_index + i_node + 1 - vUp = option_values[next_node_up] - vDn = option_values[next_node_dn] - future_expected_value = probs[i_time] * vUp - future_expected_value += (1.0 - probs[i_time]) * vDn - holdValue = periodDiscountFactors[i_time] * future_expected_value + v_up = option_values[next_node_up] + v_dn = option_values[next_node_dn] + future_expected_value = probs[i_time] * v_up + future_expected_value += (1.0 - probs[i_time]) * v_dn + hold_value = period_dfs[i_time] * future_expected_value if option_type == OptionTypes.EUROPEAN_CALL.value: - option_values[index + i_node] = holdValue + option_values[index + i_node] = hold_value elif option_type == OptionTypes.EUROPEAN_PUT.value: - option_values[index + i_node] = holdValue + option_values[index + i_node] = hold_value elif option_type == OptionTypes.AMERICAN_CALL.value: option_values[index + - i_node] = np.maximum(exercise_value, holdValue) + i_node] = np.maximum(exercise_value, hold_value) elif option_type == OptionTypes.AMERICAN_PUT.value: option_values[index + - i_node] = np.maximum(exercise_value, holdValue) + i_node] = np.maximum(exercise_value, hold_value) # We calculate all of the important Greeks in one go price = option_values[0] diff --git a/financepy/models/equity_lsmc.py b/financepy/models/equity_lsmc.py index 41dca5b3..5bb3cbf5 100644 --- a/financepy/models/equity_lsmc.py +++ b/financepy/models/equity_lsmc.py @@ -4,10 +4,9 @@ # https://people.math.ethz.ch/~hjfurrer/teaching/LongstaffSchwartzAmericanOptionsLeastSquareMonteCarlo.pdf -import numpy as np - from enum import Enum, auto +import numpy as np from ..utils.global_types import OptionTypes from ..utils.polyfit import fit_poly, eval_polynomial from ..models.finite_difference import option_payoff diff --git a/financepy/models/finite_difference.py b/financepy/models/finite_difference.py index 8c31e14c..04f8840d 100644 --- a/financepy/models/finite_difference.py +++ b/financepy/models/finite_difference.py @@ -6,10 +6,11 @@ from ..utils.math import band_matrix_multiplication from ..utils.math import solve_tridiagonal_matrix from ..utils.math import transpose_tridiagonal_matrix -from financepy.utils.global_types import OptionTypes - +from ..utils.global_types import OptionTypes # @njit + + def dx(x, wind=0): # Intermediate rows # Note: As first and last rows are handled separately diff --git a/financepy/models/finite_difference_PSOR.py b/financepy/models/finite_difference_PSOR.py index c87c7ad4..9a252108 100644 --- a/financepy/models/finite_difference_PSOR.py +++ b/financepy/models/finite_difference_PSOR.py @@ -4,7 +4,7 @@ from numba import njit from ..utils.math import band_matrix_multiplication -from financepy.utils.global_types import OptionTypes +from ..utils.global_types import OptionTypes from .finite_difference import option_payoff, calculate_fd_matrix diff --git a/financepy/models/gauss_copula.py b/financepy/models/gauss_copula.py index 15cbec37..447648fe 100644 --- a/financepy/models/gauss_copula.py +++ b/financepy/models/gauss_copula.py @@ -15,7 +15,7 @@ def default_times_gc(issuer_curves, - correlation_matrix, + corr_matrix, num_trials, seed): """ Generate a matrix of default times by credit and trial using a @@ -24,7 +24,7 @@ def default_times_gc(issuer_curves, np.random.seed(seed) num_credits = len(issuer_curves) x = np.random.normal(0.0, 1.0, size=(num_credits, num_trials)) - c = np.linalg.cholesky(correlation_matrix) + c = np.linalg.cholesky(corr_matrix) y = np.dot(c, x) corr_times = np.empty(shape=(num_credits, 2 * num_trials)) diff --git a/financepy/models/gauss_copula_lhp.py b/financepy/models/gauss_copula_lhp.py index 5172ba94..1647ddae 100644 --- a/financepy/models/gauss_copula_lhp.py +++ b/financepy/models/gauss_copula_lhp.py @@ -33,19 +33,19 @@ def tr_surv_prob_lhp(k1, raise FinError("K1 >= K2") p = 0.0 - portfolioEL = 0.0 + portfolio_el = 0.0 for i_credit in range(0, num_credits): pd = (1.0 - survival_probs[i_credit]) p += pd - portfolioEL += pd * (1.0 - recovery_rates[i_credit]) + portfolio_el += pd * (1.0 - recovery_rates[i_credit]) if p == 0.0: return 1.0 p = p / num_credits - portfolioEL = portfolioEL / num_credits + portfolio_el = portfolio_el / num_credits - recovery = 1.0 - portfolioEL / p + recovery = 1.0 - portfolio_el / p elk1 = exp_min_lk(k1, p, recovery, 1.0, beta) elk2 = exp_min_lk(k2, p, recovery, 1.0, beta) value = 1.0 - (elk2 - elk1) / (k2 - k1) @@ -59,19 +59,19 @@ def portfolio_cdf_lhp(k, num_credits, qvector, recovery_rates, beta, num_points): p = 0.0 - portfolioEL = 0.0 + portfolio_el = 0.0 for j in range(0, num_credits): p += (1.0 - qvector[j]) - portfolioEL += (1.0 - recovery_rates[j]) * (1 - qvector[j]) + portfolio_el += (1.0 - recovery_rates[j]) * (1 - qvector[j]) p = p / num_credits - portfolioEL /= num_credits + portfolio_el /= num_credits if p == 0: return 0.0 - recovery = 1.0 - portfolioEL / p + recovery = 1.0 - portfolio_el / p if beta == 0: beta = 0.0000000001 diff --git a/financepy/models/gauss_copula_lhplus.py b/financepy/models/gauss_copula_lhplus.py index 66cb1add..7bcf7e35 100644 --- a/financepy/models/gauss_copula_lhplus.py +++ b/financepy/models/gauss_copula_lhplus.py @@ -73,17 +73,17 @@ def exp_min_lk_integral(self, K, dK): cdf0 = 1.0 cdf1 = 0.0 exp_min_lk = 0.0 - checkSum = 0.0 + check_sum = 0.0 for _ in range(0, num_steps): k0 += dK cdf1 = self.prob_loss_gt_k(k0) pdf = cdf0 - cdf1 cdf0 = cdf1 - checkSum += pdf + check_sum += pdf exp_min_lk += pdf * k0 - checkSum += cdf1 + check_sum += cdf1 exp_min_lk += cdf1 * K return exp_min_lk diff --git a/financepy/models/gauss_copula_onefactor.py b/financepy/models/gauss_copula_onefactor.py index 0af5741a..0ba4fa97 100644 --- a/financepy/models/gauss_copula_onefactor.py +++ b/financepy/models/gauss_copula_onefactor.py @@ -7,10 +7,10 @@ ########################################################################## -from ..utils.math import norminvcdf, N, INVROOT2PI +from ..utils.math import norminvcdf, N, inv_root_two_pi from ..utils.error import FinError from .loss_dbn_builder import indep_loss_dbn_recursion_gcd -from .loss_dbn_builder import indep_loss_dbn_heterogeneous_adj_binomial +from .loss_dbn_builder import indep_loss_dbn_hetero_adj_binomial from .loss_dbn_builder import portfolio_gcd ############################################################################### @@ -76,7 +76,7 @@ def loss_dbn_recursion_gcd(num_credits, z += dz for i_loss_unit in range(0, int(num_loss_units)): - uncond_loss_dbn[i_loss_unit] *= INVROOT2PI * dz + uncond_loss_dbn[i_loss_unit] *= inv_root_two_pi * dz return uncond_loss_dbn @@ -121,10 +121,10 @@ def homog_basket_loss_dbn(survival_probs, default_probs[i_credit] = 1.0 - survival_probs[i_credit] loss_dbn = loss_dbn_recursion_gcd(num_credits, - default_probs, - loss_units, - beta_vector, - num_integration_steps) + default_probs, + loss_units, + beta_vector, + num_integration_steps) return loss_dbn @@ -150,13 +150,13 @@ def tranche_surv_prob_recursion(k1, if k1 >= k2: raise FinError("K1 >= K2") - commonRecoveryFlag = 1 + common_recovery_flag = 1 loss_amounts = np.zeros(num_credits) for i_credit in range(0, num_credits): loss_amounts[i_credit] = (1.0 - recovery_rates[i_credit]) / num_credits if loss_amounts[i_credit] != loss_amounts[0]: - commonRecoveryFlag = 0 + common_recovery_flag = 0 gcd = 0.0 @@ -168,7 +168,7 @@ def tranche_surv_prob_recursion(k1, if m > 0.8: num_integration_steps *= 2 - if commonRecoveryFlag == 1: + if common_recovery_flag == 1: gcd = loss_amounts[0] else: gcd = portfolio_gcd(loss_amounts) @@ -186,18 +186,18 @@ def tranche_surv_prob_recursion(k1, default_probs[i_credit] = 1.0 - survival_probs[i_credit] loss_dbn = loss_dbn_recursion_gcd(num_credits, - default_probs, - loss_units, - beta_vector, - num_integration_steps) + default_probs, + loss_units, + beta_vector, + num_integration_steps) - trancheEL = 0.0 + tranche_el = 0.0 for i_loss_unit in range(0, int(num_loss_units)): loss = i_loss_unit * gcd - trancheLoss = min(loss, k2) - min(loss, k1) - trancheEL = trancheEL + trancheLoss * loss_dbn[i_loss_unit] + tranche_loss = min(loss, k2) - min(loss, k1) + tranche_el = tranche_el + tranche_loss * loss_dbn[i_loss_unit] - q = 1.0 - trancheEL / (k2 - k1) + q = 1.0 - tranche_el / (k2 - k1) return q ############################################################################### @@ -214,13 +214,16 @@ def gauss_approx_tranche_loss(k1, k2, mu, sigma): if mu > k2: gauss_approx_tranche_loss += (mu - k2) else: - + d1 = (mu - k1) / sigma d2 = (mu - k2) / sigma - gauss_approx_tranche_loss = ((mu - k1) * N(d1) - (mu - k2) * N(d2) - + sigma * np.exp(-0.5 * d1 * d1) * INVROOT2PI - - sigma * np.exp(-0.5 * d2 * d2) * INVROOT2PI) + expd1 = np.exp(-0.5 * d1 * d1) + expd2 = np.exp(-0.5 * d2 * d2) + + gauss_approx_tranche_loss = ((mu - k1) * N(d1) - (mu - k2) * N(d2) + + sigma * expd1 * inv_root_two_pi + - sigma * expd2 * inv_root_two_pi) return gauss_approx_tranche_loss @@ -284,7 +287,7 @@ def tranch_surv_prob_gaussian(k1, v += el * gauss_wt z += dz - v *= INVROOT2PI * dz + v *= inv_root_two_pi * dz q = 1.0 - v / (k2 - k1) return q @@ -314,18 +317,19 @@ def loss_dbn_hetero_adj_binomial(num_credits, dz = 2.0 * abs(MIN_Z) / num_integration_steps z = MIN_Z - for i_step in range(0, num_integration_steps): + for _ in range(0, num_integration_steps): + for i_credit in range(0, num_credits): beta = beta_vector[i_credit] denom = np.sqrt(1.0 - beta * beta) argz = (thresholds[i_credit] - beta * z) / denom cond_default_probs[i_credit] = N(argz) - indep_dbn = indep_loss_dbn_heterogeneous_adj_binomial(num_credits, - cond_default_probs, - loss_ratio) + indep_dbn = indep_loss_dbn_hetero_adj_binomial(num_credits, + cond_default_probs, + loss_ratio) - gauss_wt = np.exp(-(z**2) / 2.0) + gauss_wt = np.exp(-z*z / 2.0) for i_loss_unit in range(0, num_loss_units): uncond_loss_dbn[i_loss_unit] += indep_dbn[i_loss_unit] * gauss_wt @@ -333,7 +337,7 @@ def loss_dbn_hetero_adj_binomial(num_credits, z = z + dz for i_loss_unit in range(0, num_loss_units): - uncond_loss_dbn[i_loss_unit] *= INVROOT2PI * dz + uncond_loss_dbn[i_loss_unit] *= inv_root_two_pi * dz return uncond_loss_dbn @@ -364,31 +368,31 @@ def tranche_surv_prob_adj_binomial(k1, for i_credit in range(0, num_credits): default_probs[i_credit] = 1.0 - survival_probs[i_credit] - totalLoss = 0.0 + total_loss = 0.0 for i_credit in range(0, num_credits): - totalLoss += (1.0 - recovery_rates[i_credit]) - totalLoss /= num_credits + total_loss += (1.0 - recovery_rates[i_credit]) + total_loss /= num_credits - avgLoss = totalLoss / num_credits + avg_loss = total_loss / num_credits loss_ratio = np.zeros(num_credits) for i_credit in range(0, num_credits): loss_ratio[i_credit] = ( - 1.0 - recovery_rates[i_credit]) / num_credits / avgLoss + 1.0 - recovery_rates[i_credit]) / num_credits / avg_loss loss_dbn = loss_dbn_hetero_adj_binomial(num_credits, - default_probs, - loss_ratio, - beta_vector, - num_integration_steps) - trancheEL = 0.0 + default_probs, + loss_ratio, + beta_vector, + num_integration_steps) + tranche_el = 0.0 num_loss_units = num_credits + 1 for i_loss_unit in range(0, num_loss_units): - loss = i_loss_unit * avgLoss - trancheLoss = min(loss, k2) - min(loss, k1) - trancheEL += trancheLoss * loss_dbn[i_loss_unit] + loss = i_loss_unit * avg_loss + tranche_loss = min(loss, k2) - min(loss, k1) + tranche_el += tranche_loss * loss_dbn[i_loss_unit] - q = 1.0 - trancheEL / (k2 - k1) + q = 1.0 - tranche_el / (k2 - k1) return q ############################################################################### diff --git a/financepy/models/heston.py b/financepy/models/heston.py index 406c76d0..c0a79bb9 100644 --- a/financepy/models/heston.py +++ b/financepy/models/heston.py @@ -45,8 +45,8 @@ def get_paths(s0, r, q, v0, kappa, theta, sigma, rho, t, dt, num_paths, np.random.seed(seed) num_steps = int(t / dt) - sPaths = np.zeros(shape=(num_paths, num_steps)) - sPaths[:, 0] = s0 + s_paths = np.zeros(shape=(num_paths, num_steps)) + s_paths[:, 0] = s0 sdt = np.sqrt(dt) rhohat = np.sqrt(1.0 - rho * rho) sigma2 = sigma * sigma @@ -67,7 +67,7 @@ def get_paths(s0, r, q, v0, kappa, theta, sigma, rho, t, dt, num_paths, rtvplus * zV + 0.25 * sigma2 * (zV * zV - dt) s += (r - q) * s * dt + rtvplus * s * \ zS + 0.5 * s * vplus * (zV * zV - dt) - sPaths[i_path, i_step] = s + s_paths[i_path, i_step] = s elif scheme == HestonNumericalScheme.EULERLOG.value: # Basic scheme to first order with truncation on variance @@ -82,7 +82,7 @@ def get_paths(s0, r, q, v0, kappa, theta, sigma, rho, t, dt, num_paths, x += (r - q - 0.5 * vplus) * dt + rtvplus * zS v += kappa * (theta - vplus) * dt + sigma * \ rtvplus * zV + sigma2 * (zV * zV - dt) / 4.0 - sPaths[i_path, i_step] = exp(x) + s_paths[i_path, i_step] = exp(x) elif scheme == HestonNumericalScheme.QUADEXP.value: # Due to Leif Andersen(2006) @@ -136,12 +136,12 @@ def get_paths(s0, r, q, v0, kappa, theta, sigma, rho, t, dt, num_paths, x += mu * dt + K0 + (K1 * vn + K2 * vnp) + \ np.sqrt(K3 * vn + K4 * vnp) * zS - sPaths[i_path, i_step] = exp(x) + s_paths[i_path, i_step] = exp(x) vn = vnp else: raise FinError("Unknown FinHestonNumericalSchme") - return sPaths + return s_paths ############################################################################### @@ -180,24 +180,24 @@ def value_mc(self, dt = 1.0 / num_steps_per_year schemeValue = float(scheme.value) - sPaths = get_paths(stock_price, - interest_rate, - dividend_yield, - self._v0, - self._kappa, - self._theta, - self._sigma, - self._rho, - tau, - dt, - num_paths, - seed, - schemeValue) + s_paths = get_paths(stock_price, + interest_rate, + dividend_yield, + self._v0, + self._kappa, + self._theta, + self._sigma, + self._rho, + tau, + dt, + num_paths, + seed, + schemeValue) if option._option_type == OptionTypes.EUROPEAN_CALL: - path_payoff = np.maximum(sPaths[:, -1] - K, 0.0) + path_payoff = np.maximum(s_paths[:, -1] - K, 0.0) elif option._option_type == OptionTypes.EUROPEAN_PUT: - path_payoff = np.maximum(K - sPaths[:, -1], 0.0) + path_payoff = np.maximum(K - s_paths[:, -1], 0.0) else: raise FinError("Unknown option type.") @@ -224,9 +224,9 @@ def value_lewis(self, r = interest_rate q = dividend_yield - S0 = stock_price + s0 = stock_price K = option._strike_price - F = S0 * exp((r - q) * tau) + F = s0 * exp((r - q) * tau) V = sigma * sigma def phi(k_in,): @@ -250,7 +250,7 @@ def integrand(k): return 2.0 * np.real(np.exp(-1j * k * x) x = log(F / K) I1 = phi_transform(x) / (2.0 * pi) v1 = F * exp(-r * tau) - np.sqrt(K * F) * exp(-r * tau) * I1 -# v2 = S0 * exp(-q*tau) - K * exp(-r*tau) * I1 +# v2 = s0 * exp(-q*tau) - K * exp(-r*tau) * I1 return v1 ############################################################################### @@ -283,16 +283,16 @@ def f(k_in): q = V * tau / 2.0 Q = np.exp(-e * q) H = np.exp((2.0 * kappa * theta / V) * (q * g - np.log((1.0 - - h * Q) / (1.0 - h))) + v0 * g * (1.0 - Q) / (1.0 - h * Q)) + h * Q) / (1.0 - h))) + v0 * g * (1.0 - Q) / (1.0 - h * Q)) integrand = H * np.exp(-1j * k * X) / (k * k - 1j * k) return integrand.real - S0 = stock_price - F = S0 * exp((r - q) * tau) + s0 = stock_price + F = s0 * exp((r - q) * tau) K = option._strike_price X = log(F / K) integral = integrate.quad(f, 0.0, np.inf)[0] * (1.0 / pi) - v = S0 * exp(-q * tau) - K * exp(-r * tau) * integral + v = s0 * exp(-q * tau) - K * exp(-r * tau) * integral return (v) ############################################################################### @@ -316,7 +316,7 @@ def value_weber(self, q = dividend_yield r = interest_rate - S0 = stock_price + s0 = stock_price K = option._strike_price V = sigma**2 @@ -330,13 +330,13 @@ def integrand(u): A = kappa * ((beta - d) * tau - 2.0 * np.log((1.0 - g * Q) / (1.0 - g))) / V v = np.exp(A * theta + B * v0 + 1j * u * - np.log(S0 / (K * np.exp(-(r - q) * tau)))) / (u * 1j) + np.log(s0 / (K * np.exp(-(r - q) * tau)))) / (u * 1j) return v.real area = 0.50 + (1.0 / pi) * integrate.quad(integrand, 0, np.inf)[0] return area - v = S0 * exp(-q * tau) * f(1.0, kappa - rho * sigma) - \ + v = s0 * exp(-q * tau) * f(1.0, kappa - rho * sigma) - \ exp(-r * tau) * K * f(-1.0, kappa) return v @@ -363,9 +363,9 @@ def value_gatheral(self, q = dividend_yield r = interest_rate - S0 = stock_price + s0 = stock_price K = option._strike_price - F = S0 * exp((r - q) * tau) + F = s0 * exp((r - q) * tau) x0 = log(F / K) def ff(j): @@ -388,7 +388,7 @@ def integrand(u): area = 0.50 + 1.0 / pi * integrate.quad(integrand, 0.0, np.inf)[0] return area - v = S0 * exp(-q * tau) * ff(1) - K * exp(-r * tau) * ff(0) + v = s0 * exp(-q * tau) * ff(1) - K * exp(-r * tau) * ff(0) return v ############################################################################### diff --git a/financepy/models/hw_tree.py b/financepy/models/hw_tree.py index 0638a1e5..1ae63791 100644 --- a/financepy/models/hw_tree.py +++ b/financepy/models/hw_tree.py @@ -2,18 +2,19 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################## +from math import ceil + from enum import Enum import numpy as np from scipy import optimize from numba import njit -from math import ceil from ..utils.error import FinError from ..utils.math import N, accrued_interpolator from ..market.curves.interpolator import InterpTypes, _uinterpolate from ..utils.helpers import label_to_string from ..utils.global_types import FinExerciseTypes -from ..utils.global_vars import gSmall +from ..utils.global_vars import g_small interp = InterpTypes.FLAT_FWD_RATES.value @@ -37,13 +38,13 @@ class FinHWEuropeanCalcType(Enum): ############################################################################### -def option_exercise_types_to_int(optionExerciseType): +def option_exercise_types_to_int(option_exercise_type): - if optionExerciseType == FinExerciseTypes.EUROPEAN: + if option_exercise_type == FinExerciseTypes.EUROPEAN: return 1 - if optionExerciseType == FinExerciseTypes.BERMUDAN: + if option_exercise_type == FinExerciseTypes.BERMUDAN: return 2 - if optionExerciseType == FinExerciseTypes.AMERICAN: + if option_exercise_type == FinExerciseTypes.AMERICAN: return 3 else: raise FinError("Unknown option exercise type.") @@ -81,8 +82,8 @@ def p_fast(t, T, r_t, delta, pt, ptd, pT, _sigma, _a): @njit(fastmath=True, cache=True) def build_tree_fast(a, sigma, tree_times, num_time_steps, discount_factors): """ Fast tree construction using Numba. """ - treeMaturity = tree_times[-1] - dt = treeMaturity / (num_time_steps+1) + tree_maturity = tree_times[-1] + dt = tree_maturity / (num_time_steps+1) dR = sigma * np.sqrt(3.0 * dt) j_max = ceil(0.1835/(a * dt)) N = j_max @@ -128,11 +129,11 @@ def build_tree_fast(a, sigma, tree_times, num_time_steps, discount_factors): for m in range(0, num_time_steps + 1): nm = min(m, j_max) - sumQZ = 0.0 + sum_qz = 0.0 for j in range(-nm, nm+1): rdt = j*dR*dt - sumQZ += Q[m, j+N] * np.exp(-rdt) - alpha[m] = np.log(sumQZ/discount_factors[m+1]) / dt + sum_qz += Q[m, j+N] * np.exp(-rdt) + alpha[m] = np.log(sum_qz/discount_factors[m+1]) / dt for j in range(-nm, nm+1): jN = j + N @@ -196,7 +197,7 @@ def american_bond_option_tree_fast(t_exp, # Want to add coupons before expiry to the grid so that we can value # their impact on the decision to exercise the option early - treeFlows = np.zeros(num_time_steps) + tree_flows = np.zeros(num_time_steps) num_cpns = len(cpn_times) # Flows that fall on the expiry date included. The tree only goes out to @@ -208,7 +209,7 @@ def american_bond_option_tree_fast(t_exp, ttree = _tree_times[n] df_flow = _uinterpolate(tcpn, _df_times, _df_values, interp) df_tree = _uinterpolate(ttree, _df_times, _df_values, interp) - treeFlows[n] += cpn_amounts[i] * 1.0 * df_flow / df_tree + tree_flows[n] += cpn_amounts[i] * 1.0 * df_flow / df_tree ########################################################################### # Mapped times stores the mapped times and flows and is used to calculate @@ -221,9 +222,9 @@ def american_bond_option_tree_fast(t_exp, mapped_times = np.zeros(0) # CHANGE mapped_amounts = np.zeros(0) # CHANGE for n in range(0, len(_tree_times)): - if treeFlows[n] > 0.0: + if tree_flows[n] > 0.0: mapped_times = np.append(mapped_times, _tree_times[n]) - mapped_amounts = np.append(mapped_amounts, treeFlows[n]) + mapped_amounts = np.append(mapped_amounts, tree_flows[n]) # Need future cash flows which are exact time and size for accrued at t_exp for n in range(0, num_cpns): @@ -245,12 +246,12 @@ def american_bond_option_tree_fast(t_exp, # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if treeFlows[m] > 0.0: - accrued[m] = treeFlows[m] * face_amount + if tree_flows[m] > 0.0: + accrued[m] = tree_flows[m] * face_amount if DEBUG: for i in range(0, expiry_step+1): - print(i, treeFlows[i], accrued[i]) + print(i, tree_flows[i], accrued[i]) ########################################################################### @@ -312,7 +313,7 @@ def american_bond_option_tree_fast(t_exp, # Now step back to today considering exercise at expiry and before for m in range(expiry_step-1, -1, -1): nm = min(m, j_max) - flow = treeFlows[m] * face_amount + flow = tree_flows[m] * face_amount for k in range(-nm, nm+1): kN = k + j_max @@ -388,17 +389,17 @@ def american_bond_option_tree_fast(t_exp, call_exercise = max(clean_price - strike_price, 0.0) put_exercise = max(strike_price - clean_price, 0.0) - holdCall = call_option_values[m, kN] + hold_call = call_option_values[m, kN] holdPut = put_option_values[m, kN] if m == expiry_step: - call_option_values[m, kN] = max(call_exercise, holdCall) + call_option_values[m, kN] = max(call_exercise, hold_call) put_option_values[m, kN] = max(put_exercise, holdPut) elif exercise_typeInt == 3 and m < expiry_step: # AMERICAN - call_option_values[m, kN] = max(call_exercise, holdCall) + call_option_values[m, kN] = max(call_exercise, hold_call) put_option_values[m, kN] = max(put_exercise, holdPut) if DEBUG: @@ -424,7 +425,7 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, num_time_steps, num_nodes = _Q.shape j_max = ceil(0.1835/(_a * _dt)) expiry_step = int(t_exp/_dt + 0.50) - maturityStep = int(t_mat/_dt + 0.50) + maturity_step = int(t_mat/_dt + 0.50) ########################################################################### @@ -453,10 +454,10 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, for n in range(1, len(_tree_times)): - accdAtExpiry = 0.0 + accd_at_expiry = 0.0 if _tree_times[n-1] < t_exp and _tree_times[n] >= t_exp: mapped_times = np.append(mapped_times, t_exp) - mapped_amounts = np.append(mapped_amounts, accdAtExpiry) + mapped_amounts = np.append(mapped_amounts, accd_at_expiry) if fixed_leg_flows[n] > 0.0: mapped_times = np.append(mapped_times, _tree_times[n]) @@ -465,14 +466,14 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, ########################################################################### accrued = np.zeros(num_time_steps) - for m in range(0, maturityStep+1): + for m in range(0, maturity_step+1): ttree = _tree_times[m] accrued[m] = accrued_interpolator(ttree, mapped_times, mapped_amounts) accrued[m] *= face_amount # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if fixed_leg_flows[m] > gSmall: + if fixed_leg_flows[m] > g_small: accrued[m] = fixed_leg_flows[m] * face_amount ########################################################################### @@ -486,13 +487,13 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, # Star_t with the value of the bond at maturity for k in range(0, num_nodes): - flow = 1.0 + fixed_leg_flows[maturityStep] - fixed_leg_values[maturityStep, k] = flow * face_amount + flow = 1.0 + fixed_leg_flows[maturity_step] + fixed_leg_values[maturity_step, k] = flow * face_amount N = j_max # Now step back to today considering early exercise - for m in range(maturityStep-1, -1, -1): + for m in range(maturity_step-1, -1, -1): nm = min(m, j_max) flow = fixed_leg_flows[m] * face_amount @@ -578,7 +579,7 @@ def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, pay_values[m, kN] = max(pay_exercise, hold_pay) rec_values[m, kN] = max(rec_exercise, hold_rec) - elif exercise_typeInt == 2 and flow > gSmall and m >= expiry_step: + elif exercise_typeInt == 2 and flow > g_small and m >= expiry_step: pay_values[m, kN] = max(pay_exercise, hold_pay) rec_values[m, kN] = max(rec_exercise, hold_rec) @@ -623,13 +624,13 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, dt = _dt j_max = ceil(0.1835/(_a * dt)) t_mat = cpn_times[-1] - maturityStep = int(t_mat/dt + 0.50) + maturity_step = int(t_mat/dt + 0.50) ########################################################################### # Map coupons onto tree while preserving their present value ########################################################################### - treeFlows = np.zeros(num_time_steps) + tree_flows = np.zeros(num_time_steps) num_cpns = len(cpn_times) for i in range(0, num_cpns): @@ -638,9 +639,9 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, ttree = _tree_times[n] df_flow = _uinterpolate(tcpn, _df_times, _df_values, interp) df_tree = _uinterpolate(ttree, _df_times, _df_values, interp) - treeFlows[n] += cpn_flows[i] * 1.0 * df_flow / df_tree + tree_flows[n] += cpn_flows[i] * 1.0 * df_flow / df_tree -# print("Tree flows:", treeFlows) +# print("Tree flows:", tree_flows) ########################################################################### # Mapped times stores the mapped times and flows and is used to calculate @@ -652,9 +653,9 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, mapped_amounts = np.array([0.0]) for n in range(1, len(_tree_times)): - if treeFlows[n] > 0.0: + if tree_flows[n] > 0.0: mapped_times = np.append(mapped_times, _tree_times[n]) - mapped_amounts = np.append(mapped_amounts, treeFlows[n]) + mapped_amounts = np.append(mapped_amounts, tree_flows[n]) accrued = np.zeros(num_time_steps) for m in range(0, num_time_steps): @@ -664,8 +665,8 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, # This is a bit of a hack for when the interpolation does not put the # full accrued on flow date. Another scheme may work but so does this - if treeFlows[m] > 0.0: - accrued[m] = treeFlows[m] * face + if tree_flows[m] > 0.0: + accrued[m] = tree_flows[m] * face ########################################################################### # map call onto tree - must have no calls at high value @@ -690,19 +691,19 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, # Value the bond by backward induction star_ting at bond maturity ########################################################################### - callPutBondValues = np.zeros(shape=(num_time_steps, num_nodes)) + call_put_bond_values = np.zeros(shape=(num_time_steps, num_nodes)) bond_values = np.zeros(shape=(num_time_steps, num_nodes)) DEBUG = True if DEBUG: df = 1.0 px = 0.0 - for i in range(0, maturityStep+1): - flow = treeFlows[i] + for i in range(0, maturity_step+1): + flow = tree_flows[i] t = _tree_times[i] df = _uinterpolate(t, _df_times, _df_values, interp) - if flow > gSmall: + if flow > g_small: pv = flow * df px += pv @@ -712,23 +713,23 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, # Now step back to today considering early exercise ########################################################################### - m = maturityStep - nm = min(maturityStep, j_max) + m = maturity_step + nm = min(maturity_step, j_max) vcall = tree_call_value[m] vput = tree_put_value[m] - vhold = (1.0 + treeFlows[m]) * face + vhold = (1.0 + tree_flows[m]) * face vclean = vhold - accrued[m] value = min(max(vclean, vput), vcall) + accrued[m] for k in range(-nm, nm+1): kN = k + j_max - bond_values[m, kN] = (1.0 + treeFlows[m]) * face - callPutBondValues[m, kN] = value + bond_values[m, kN] = (1.0 + tree_flows[m]) * face + call_put_bond_values[m, kN] = value # Now step back to today considering early put and call - for m in range(maturityStep-1, -1, -1): + for m in range(maturity_step-1, -1, -1): nm = min(m, j_max) - flow = treeFlows[m] * face + flow = tree_flows[m] * face vcall = tree_call_value[m] vput = tree_put_value[m] @@ -758,25 +759,25 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, bond_values[m, kN] += flow if k == j_max: - vu = callPutBondValues[m+1, kN] - vm = callPutBondValues[m+1, kN-1] - vd = callPutBondValues[m+1, kN-2] + vu = call_put_bond_values[m+1, kN] + vm = call_put_bond_values[m+1, kN-1] + vd = call_put_bond_values[m+1, kN-2] elif k == -j_max: - vu = callPutBondValues[m+1, kN+2] - vm = callPutBondValues[m+1, kN+1] - vd = callPutBondValues[m+1, kN] + vu = call_put_bond_values[m+1, kN+2] + vm = call_put_bond_values[m+1, kN+1] + vd = call_put_bond_values[m+1, kN] else: - vu = callPutBondValues[m+1, kN+1] - vm = callPutBondValues[m+1, kN] - vd = callPutBondValues[m+1, kN-1] + vu = call_put_bond_values[m+1, kN+1] + vm = call_put_bond_values[m+1, kN] + vd = call_put_bond_values[m+1, kN-1] vhold = (pu*vu + pm*vm + pd*vd) * df # Need to make add on coupons paid if we hold vhold = vhold + flow value = min(max(vhold - accrued[m], vput), vcall) + accrued[m] - callPutBondValues[m, kN] = value + call_put_bond_values[m, kN] = value - return {'bondwithoption': callPutBondValues[0, j_max], + return {'bondwithoption': call_put_bond_values[0, j_max], 'bondpure': bond_values[0, j_max]} ############################################################################### @@ -846,7 +847,7 @@ def __init__(self, sigma, a, num_time_steps=100, - europeanCalcType=FinHWEuropeanCalcType.EXPIRY_TREE): + european_calc_type=FinHWEuropeanCalcType.EXPIRY_TREE): """ Constructs the Hull-White rate model. The speed of mean reversion a and volatility are passed in. The shor_t rate process is given by dr = (theta(t) - ar) * dt + sigma * dW. The model will switch to use @@ -862,7 +863,7 @@ def __init__(self, self._sigma = sigma self._a = a self._num_time_steps = num_time_steps - self._europeanCalcType = europeanCalcType + self._european_calc_type = european_calc_type self._Q = None self._r = None @@ -871,7 +872,7 @@ def __init__(self, self._pm = None self._pd = None self._discount_curve = None - self._treeBuilt = False + self._tree_built = False ############################################################################### @@ -906,7 +907,8 @@ def option_on_zcb(self, h = np.log((face_amount*pt_mat)/(strike * pt_exp)) / \ sigmap + sigmap / 2.0 - call_value = face_amount * pt_mat * N(h) - strike * pt_exp * N(h - sigmap) + call_value = face_amount * pt_mat * \ + N(h) - strike * pt_exp * N(h - sigmap) put_value = strike * pt_exp * \ N(-h + sigmap) - face_amount * pt_mat * N(-h) @@ -1039,11 +1041,11 @@ def european_bond_option_expiry_only(self, pv = pv - accrued # print(accrued) - putPayoff = max(strike_price - pv * face_amount, 0.0) - callPayoff = max(pv * face_amount - strike_price, 0.0) + put_payoff = max(strike_price - pv * face_amount, 0.0) + call_payoff = max(pv * face_amount - strike_price, 0.0) - put_value += q * putPayoff - call_value += q * callPayoff + put_value += q * put_payoff + call_value += q * call_payoff ####################################################################### @@ -1093,10 +1095,10 @@ def option_on_zero_coupon_bond_tree(self, r_t, dt, pt_exp, ptdelta, pt_mat, self._sigma, self._a) - putPayoff = max(strike_price - zcb * face_amount, 0.0) - callPayoff = max(zcb * face_amount - strike_price, 0.0) - put_value += q * putPayoff - call_value += q * callPayoff + put_payoff = max(strike_price - zcb * face_amount, 0.0) + call_payoff = max(zcb * face_amount - strike_price, 0.0) + put_value += q * put_payoff + call_value += q * call_payoff return {'call': call_value, 'put': put_value} @@ -1120,7 +1122,7 @@ def bermudan_swaption(self, t_exp, t_mat, strike, face, ####################################################################### - payValue, recValue \ + pay_value, rec_value \ = bermudan_swaption_tree_fast(t_exp, t_mat, strike, face, cpn_times, cpn_flows, exercise_typeInt, @@ -1130,7 +1132,7 @@ def bermudan_swaption(self, t_exp, t_mat, strike, face, self._r_t, self._dt, self._a) - return {'pay': payValue, 'rec': recValue} + return {'pay': pay_value, 'rec': rec_value} ############################################################################### @@ -1145,7 +1147,7 @@ def bond_option(self, t_exp, strike_price, face_amount, if exercise_typeInt == 1: - if self._europeanCalcType == FinHWEuropeanCalcType.JAMSHIDIAN: + if self._european_calc_type == FinHWEuropeanCalcType.JAMSHIDIAN: v = self.european_bond_option_jamshidian(t_exp, strike_price, @@ -1158,7 +1160,7 @@ def bond_option(self, t_exp, strike_price, face_amount, call_value = v['call'] put_value = v['put'] - elif self._europeanCalcType == FinHWEuropeanCalcType.EXPIRY_ONLY: + elif self._european_calc_type == FinHWEuropeanCalcType.EXPIRY_ONLY: v = self.european_bond_option_expiry_only(t_exp, strike_price, @@ -1169,7 +1171,7 @@ def bond_option(self, t_exp, strike_price, face_amount, call_value = v['call'] put_value = v['put'] - elif self._europeanCalcType == FinHWEuropeanCalcType.EXPIRY_TREE: + elif self._european_calc_type == FinHWEuropeanCalcType.EXPIRY_TREE: call_value, put_value \ = american_bond_option_tree_fast(t_exp, @@ -1255,18 +1257,18 @@ def df_tree(self, t_mat): if abs(fn1 - fn2) > 1e-6: raise FinError("Time not on tree time grid") - timeStep = int(t_mat / self._dt) + 1 + time_step = int(t_mat / self._dt) + 1 p = 0.0 for i in range(0, num_nodes): - ad = self._Q[timeStep, i] + ad = self._Q[time_step, i] p += ad zero_rate = -np.log(p)/t_mat return p, zero_rate ############################################################################### - def build_tree(self, treeMat, df_times, df_values): + def build_tree(self, tree_mat, df_times, df_values): """ Build the trinomial tree. """ if isinstance(df_times, np.ndarray) is False: @@ -1276,27 +1278,27 @@ def build_tree(self, treeMat, df_times, df_values): raise FinError("DF VALUES must be a numpy vector") # I wish to add on an additional time to the tree so that the second - # last time corresponds to a maturity treeMat. For this reason I scale + # last time corresponds to a maturity tree_mat. For this reason I scale # up the maturity date of the tree as follows - treeMaturity = treeMat * (self._num_time_steps+1)/self._num_time_steps + tree_maturity = tree_mat * (self._num_time_steps+1)/self._num_time_steps # The vector of times goes out to this maturity - tree_times = np.linspace(0.0, treeMaturity, self._num_time_steps + 2) + tree_times = np.linspace(0.0, tree_maturity, self._num_time_steps + 2) self._tree_times = tree_times - dfTree = np.zeros(shape=(self._num_time_steps+2)) - dfTree[0] = 1.0 + df_tree = np.zeros(shape=(self._num_time_steps+2)) + df_tree[0] = 1.0 for i in range(1, self._num_time_steps+2): t = tree_times[i] - dfTree[i] = _uinterpolate(t, df_times, df_values, interp) + df_tree[i] = _uinterpolate(t, df_times, df_values, interp) self._df_times = df_times self._dfs = df_values self._Q, self._pu, self._pm, self._pd, self._r_t, self._dt \ = build_tree_fast(self._a, self._sigma, - tree_times, self._num_time_steps, dfTree) + tree_times, self._num_time_steps, df_tree) return @@ -1309,7 +1311,7 @@ def __repr__(self): s += label_to_string("Sigma", self._sigma) s += label_to_string("a", self._a) s += label_to_string("num_time_steps", self._num_time_steps) - s += label_to_string("EuropeanCalcTypes", self._europeanCalcType) + s += label_to_string("european_calc_types", self._european_calc_type) return s ############################################################################### diff --git a/financepy/models/lmm_mc.py b/financepy/models/lmm_mc.py index 9bce6338..87065b25 100644 --- a/financepy/models/lmm_mc.py +++ b/financepy/models/lmm_mc.py @@ -20,8 +20,8 @@ ############################################################################### """ This module manages the Ibor Market Model and so stores a specific MC - forward rate simulation of a 3D matrix of num_paths x numForwards - x (numForwards-1)/2 elements. This is a lognormal model although a shifted + forward rate simulation of a 3D matrix of num_paths x num_fwds + x (num_fwds-1)/2 elements. This is a lognormal model although a shifted Lognormal rate is also allowed. Implementations include 1 factor, M factor where the volatility curve per factor is provided and a full N-factor corr- elation matrix where a Cholesky is done to decompose the N factors. """ @@ -107,7 +107,7 @@ def lmm_swaption_vol_approx(a, b, fwd0, taus, zetas, rho): for i in range(a, b): wts[i] = taus[i] * p[i] / pv01ab - swaptionVar = 0.0 + swaption_var = 0.0 for i in range(a, b): for j in range(a, b): wti = wts[i] @@ -120,7 +120,7 @@ def lmm_swaption_vol_approx(a, b, fwd0, taus, zetas, rho): intsigmaij += zetas[i] * zetas[j] * taus[k] term = wti * wtj * fi * fj * rho[i][j] * intsigmaij / (sab**2) - swaptionVar += term + swaption_var += term taua = 0.0 for i in range(0, a): @@ -130,8 +130,8 @@ def lmm_swaption_vol_approx(a, b, fwd0, taus, zetas, rho): for i in range(0, b): taub += taus[i] - swaptionVol = np.sqrt(swaptionVar/taua) - return swaptionVol + swaption_vol = np.sqrt(swaption_var/taua) + return swaption_vol ############################################################################### @@ -144,16 +144,16 @@ def lmm_sim_swaption_vol(a, b, fwd0, fwds, taus): simulation to see how it compares to Rebonatto estimate. """ num_paths = len(fwds) - numForwards = len(fwds[0]) + num_fwds = len(fwds[0]) - if a > numForwards: - raise FinError("NumPeriods > numForwards") + if a > num_fwds: + raise FinError("NumPeriods > num_fwds") if a >= b: raise FinError("Swap maturity is before expiry date") - fwdSwapRateMean = 0.0 - fwdSwapRateVar = 0.0 + fwd_swap_rate_mean = 0.0 + fwd_swap_rate_var = 0.0 for i_path in range(0, num_paths): # changed from prange @@ -171,35 +171,35 @@ def lmm_sim_swaption_vol(a, b, fwd0, fwds, taus): df = df / (1.0 + tau * f) pv01 = pv01 + tau * df - fwdSwapRate = (1.0 - df) / pv01 + fwd_swap_rate = (1.0 - df) / pv01 - fwdSwapRateMean += fwdSwapRate - fwdSwapRateVar += fwdSwapRate**2 + fwd_swap_rate_mean += fwd_swap_rate + fwd_swap_rate_var += fwd_swap_rate**2 taua = 0.0 for i in range(0, a): taua += taus[i] - fwdSwapRateMean /= num_paths - fwdSwapRateVar = fwdSwapRateVar/num_paths - fwdSwapRateMean**2 - fwdSwapRateVol = np.sqrt(fwdSwapRateVar/taua) - fwdSwapRateVol /= fwdSwapRateMean - return fwdSwapRateVol + fwd_swap_rate_mean /= num_paths + fwd_swap_rate_var = fwd_swap_rate_var/num_paths - fwd_swap_rate_mean**2 + fwd_swap_rate_vol = np.sqrt(fwd_swap_rate_var/taua) + fwd_swap_rate_vol /= fwd_swap_rate_mean + return fwd_swap_rate_vol ############################################################################### @njit(float64[:, :](int64, int64, int64, float64[:, :, :]), cache=True, fastmath=True) -def lmm_fwd_fwd_correlation(numForwards, num_paths, i_time, fwds): +def lmm_fwd_fwd_correlation(num_fwds, num_paths, i_time, fwds): """ Extract forward forward correlation matrix at some future time index from the simulated forward rates and return the matrix. """ - size = numForwards - i_time - fwdCorr = np.zeros((size, size)) + size = num_fwds - i_time + fwd_corr = np.zeros((size, size)) - for iFwd in range(i_time, numForwards): - for jFwd in range(iFwd, numForwards): + for i_fwd in range(i_time, num_fwds): + for j_fwd in range(i_fwd, num_fwds): sumfwdi = 0.0 sumfwdj = 0.0 @@ -208,8 +208,8 @@ def lmm_fwd_fwd_correlation(numForwards, num_paths, i_time, fwds): sumfwdjfwdj = 0.0 for p in range(0, num_paths): # changed from prange - dfwdi = fwds[p, i_time, iFwd] - fwds[p, i_time-1, iFwd] - dfwdj = fwds[p, i_time, jFwd] - fwds[p, i_time-1, jFwd] + dfwdi = fwds[p, i_time, i_fwd] - fwds[p, i_time-1, i_fwd] + dfwdj = fwds[p, i_time, j_fwd] - fwds[p, i_time-1, j_fwd] sumfwdi += dfwdi sumfwdj += dfwdj sumfwdifwdi += dfwdi * dfwdi @@ -228,13 +228,13 @@ def lmm_fwd_fwd_correlation(numForwards, num_paths, i_time, fwds): corr = covij / np.sqrt(covii*covjj) if abs(covii*covjj) > 1e-20: - fwdCorr[iFwd-i_time][jFwd-i_time] = corr - fwdCorr[jFwd-i_time][iFwd-i_time] = corr + fwd_corr[i_fwd-i_time][j_fwd-i_time] = corr + fwd_corr[j_fwd-i_time][i_fwd-i_time] = corr else: - fwdCorr[iFwd-i_time][jFwd-i_time] = 0.0 - fwdCorr[jFwd-i_time][iFwd-i_time] = 0.0 + fwd_corr[i_fwd-i_time][j_fwd-i_time] = 0.0 + fwd_corr[j_fwd-i_time][i_fwd-i_time] = 0.0 - return fwdCorr + return fwd_corr ############################################################################### @@ -246,15 +246,15 @@ def lmm_price_caps_black(fwd0, volCaplet, p, K, taus): of the LMM model. The prices can be compared with the LMM model prices. """ caplet = np.zeros(p+1) - discFwd = np.zeros(p+1) + disc_fwd = np.zeros(p+1) if K <= 0.0: raise FinError("Negative strike not allowed.") # Set up initial term structure - discFwd[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + disc_fwd[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) for i in range(1, p): - discFwd[i] = discFwd[i-1] / (1.0 + fwd0[i] * taus[i]) + disc_fwd[i] = disc_fwd[i-1] / (1.0 + fwd0[i] * taus[i]) # Price ATM caplets t_exp = 0.0 @@ -267,7 +267,7 @@ def lmm_price_caps_black(fwd0, volCaplet, p, K, taus): F = fwd0[i] d1 = (np.log(F/K) + vol * vol * t_exp / 2.0) / vol / np.sqrt(t_exp) d2 = d1 - vol * np.sqrt(t_exp) - caplet[i] = (F * N(d1) - K * N(d2)) * taus[i] * discFwd[i] + caplet[i] = (F * N(d1) - K * N(d2)) * taus[i] * disc_fwd[i] return caplet @@ -315,17 +315,17 @@ def lmm_simulate_fwds_nf(num_fwds, num_paths, fwd0, zetas, correl, taus, seed): # Even number of paths for antithetics num_paths = 2 * int(num_paths/2) - halfNumPaths = int(num_paths/2) + half_num_paths = int(num_paths/2) fwd = np.empty((num_paths, num_fwds, num_fwds)) fwdB = np.zeros(num_fwds) - discFwd = np.zeros(num_fwds) + disc_fwd = np.zeros(num_fwds) # Set up initial term structure - discFwd[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + disc_fwd[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) for ix in range(1, num_fwds): - discFwd[ix] = discFwd[ix-1] / (1.0 + fwd0[ix] * taus[ix]) + disc_fwd[ix] = disc_fwd[ix-1] / (1.0 + fwd0[ix] * taus[ix]) corr = [None] # from 0 to p-1 factors = [None] # from 0 to p-1 @@ -342,14 +342,14 @@ def lmm_simulate_fwds_nf(num_fwds, num_paths, fwd0, zetas, correl, taus, seed): ########################################################################### if 1 == 1: - gMatrix = np.empty((num_paths, num_fwds, num_fwds)) - for i_path in range(0, halfNumPaths): + g_matrix = np.empty((num_paths, num_fwds, num_fwds)) + for i_path in range(0, half_num_paths): for j in range(1, num_fwds): for k in range(0, num_fwds-j): g = np.random.normal() # ANTITHETICS - gMatrix[i_path, j, k] = g - gMatrix[i_path + halfNumPaths, j, k] = -g + g_matrix[i_path, j, k] = g + g_matrix[i_path + half_num_paths, j, k] = -g avgg = 0.0 stdg = 0.0 @@ -357,8 +357,8 @@ def lmm_simulate_fwds_nf(num_fwds, num_paths, fwd0, zetas, correl, taus, seed): for i_path in range(0, num_paths): # Initial value of forward curve at time 0 - for iFwd in range(0, num_fwds): - fwd[i_path, 0, iFwd] = fwd0[iFwd] + for i_fwd in range(0, num_fwds): + fwd[i_path, 0, i_fwd] = fwd0[i_fwd] for j in range(1, num_fwds): # TIME LOOP @@ -380,7 +380,7 @@ def lmm_simulate_fwds_nf(num_fwds, num_paths, fwd0, zetas, correl, taus, seed): w = 0.0 for k in range(0, num_fwds-j): f = factors[j][i-j, k] - w = w + f * gMatrix[i_path, j, k] + w = w + f * g_matrix[i_path, j, k] avgg += w stdg += w*w @@ -407,7 +407,7 @@ def lmm_simulate_fwds_nf(num_fwds, num_paths, fwd0, zetas, correl, taus, seed): @njit(float64[:, :, :](int64, int64, int64, float64[:], float64[:], float64[:], int64, int64), cache=True, fastmath=True) -def lmm_simulate_fwds_1f(num_fwds, num_paths, numeraireIndex, fwd0, gammas, +def lmm_simulate_fwds_1f(num_fwds, num_paths, numeraire_index, fwd0, gammas, taus, use_sobol, seed): """ One factor Arbitrage-free simulation of forward Ibor discount in the spot measure following Hull Page 768. Given an initial forward curve, @@ -432,49 +432,49 @@ def lmm_simulate_fwds_1f(num_fwds, num_paths, numeraireIndex, fwd0, gammas, raise FinError("Gamma vector does not have right number of forwards") if len(fwd0) != num_fwds: - raise FinError("The length of fwd0 is not equal to numForwards") + raise FinError("The length of fwd0 is not equal to num_fwds") if len(taus) != num_fwds: - raise FinError("The length of Taus is not equal to numForwards") + raise FinError("The length of Taus is not equal to num_fwds") np.random.seed(seed) # Even number of paths for antithetics num_paths = 2 * int(num_paths/2) - halfNumPaths = int(num_paths/2) + half_num_paths = int(num_paths/2) fwd = np.empty((num_paths, num_fwds, num_fwds)) fwdB = np.zeros(num_fwds) num_times = num_fwds if use_sobol == 1: - numDimensions = num_times - rands = get_uniform_sobol(halfNumPaths, numDimensions) - gMatrix = np.empty((num_paths, num_times)) - for i_path in range(0, halfNumPaths): + num_dimensions = num_times + rands = get_uniform_sobol(half_num_paths, num_dimensions) + g_matrix = np.empty((num_paths, num_times)) + for i_path in range(0, half_num_paths): for j in range(0, num_times): u = rands[i_path, j] g = norminvcdf(u) - gMatrix[i_path, j] = g - gMatrix[i_path + halfNumPaths, j] = -g + g_matrix[i_path, j] = g + g_matrix[i_path + half_num_paths, j] = -g elif use_sobol == 0: - gMatrix = np.empty((num_paths, num_times)) - for i_path in range(0, halfNumPaths): + g_matrix = np.empty((num_paths, num_times)) + for i_path in range(0, half_num_paths): for j in range(0, num_times): g = np.random.normal() - gMatrix[i_path, j] = g - gMatrix[i_path + halfNumPaths, j] = -g + g_matrix[i_path, j] = g + g_matrix[i_path + half_num_paths, j] = -g else: raise FinError("Use Sobol must be 0 or 1") for i_path in range(0, num_paths): # changed from prange # Initial value of forward curve at time 0 - for iFwd in range(0, num_fwds): - fwd[i_path, 0, iFwd] = fwd0[iFwd] + for i_fwd in range(0, num_fwds): + fwd[i_path, 0, i_fwd] = fwd0[i_fwd] for j in range(0, num_fwds-1): # TIME LOOP dtj = taus[j] sqrt_dtj = np.sqrt(dtj) - w = gMatrix[i_path, j] + w = g_matrix[i_path, j] for k in range(j, num_fwds): # FORWARDS LOOP zkj = gammas[k-j] @@ -509,7 +509,7 @@ def lmm_simulate_fwds_1f(num_fwds, num_paths, numeraireIndex, fwd0, gammas, @njit(float64[:, :, :](int64, int64, int64, int64, float64[:], float64[:, :], float64[:], int64, int64), cache=True, fastmath=True) -def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, +def lmm_simulate_fwds_mf(num_fwds, num_factors, num_paths, numeraire_index, fwd0, lambdas, taus, use_sobol, seed): """ Multi-Factor Arbitrage-free simulation of forward Ibor discount in the spot measure following Hull Page 768. Given an initial forward curve, @@ -518,7 +518,7 @@ def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, np.random.seed(seed) - if len(lambdas) != numFactors: + if len(lambdas) != num_factors: raise FinError("Lambda does not have the right number of factors") if len(lambdas[0]) != num_fwds: @@ -526,39 +526,39 @@ def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, # Even number of paths for antithetics num_paths = 2 * int(num_paths/2) - halfNumPaths = int(num_paths/2) + half_num_paths = int(num_paths/2) fwd = np.empty((num_paths, num_fwds, num_fwds)) fwdB = np.zeros(num_fwds) num_times = num_fwds if use_sobol == 1: - numDimensions = num_times * numFactors - rands = get_uniform_sobol(halfNumPaths, numDimensions) - gMatrix = np.empty((num_paths, num_times, numFactors)) - for i_path in range(0, halfNumPaths): + num_dimensions = num_times * num_factors + rands = get_uniform_sobol(half_num_paths, num_dimensions) + g_matrix = np.empty((num_paths, num_times, num_factors)) + for i_path in range(0, half_num_paths): for j in range(0, num_times): - for q in range(0, numFactors): - col = j*numFactors + q + for q in range(0, num_factors): + col = j*num_factors + q u = rands[i_path, col] g = norminvcdf(u) - gMatrix[i_path, j, q] = g - gMatrix[i_path + halfNumPaths, j, q] = -g + g_matrix[i_path, j, q] = g + g_matrix[i_path + half_num_paths, j, q] = -g elif use_sobol == 0: - gMatrix = np.empty((num_paths, num_times, numFactors)) - for i_path in range(0, halfNumPaths): + g_matrix = np.empty((num_paths, num_times, num_factors)) + for i_path in range(0, half_num_paths): for j in range(0, num_times): - for q in range(0, numFactors): + for q in range(0, num_factors): g = np.random.normal() - gMatrix[i_path, j, q] = g - gMatrix[i_path + halfNumPaths, j, q] = -g + g_matrix[i_path, j, q] = g + g_matrix[i_path + half_num_paths, j, q] = -g else: raise FinError("Use Sobol must be 0 or 1.") for i_path in range(0, num_paths): # Initial value of forward curve at time 0 - for iFwd in range(0, num_fwds): - fwd[i_path, 0, iFwd] = fwd0[iFwd] + for i_fwd in range(0, num_fwds): + fwd[i_path, 0, i_fwd] = fwd0[i_fwd] for j in range(0, num_fwds-1): # TIME LOOP dtj = taus[j] @@ -571,23 +571,23 @@ def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, fi = fwd[i_path, j, i] ti = taus[i] zz = 0.0 - for q in range(0, numFactors): + for q in range(0, num_factors): zij = lambdas[q][i-j] zkj = lambdas[q][k-j] zz += zij * zkj muA += fi * ti * zz / (1.0 + fi * ti) itoTerm = 0.0 - for q in range(0, numFactors): + for q in range(0, num_factors): itoTerm += lambdas[q][k-j] * lambdas[q][k-j] - randomTerm = 0.0 - for q in range(0, numFactors): - wq = gMatrix[i_path, j, q] - randomTerm += lambdas[q][k-j] * wq - randomTerm *= sqrt_dtj + random_term = 0.0 + for q in range(0, num_factors): + wq = g_matrix[i_path, j, q] + random_term += lambdas[q][k-j] * wq + random_term *= sqrt_dtj - x = np.exp(muA * dtj - 0.5 * itoTerm * dtj + randomTerm) + x = np.exp(muA * dtj - 0.5 * itoTerm * dtj + random_term) fwdB[k] = fwd[i_path, j, k] * x muB = 0.0 @@ -595,7 +595,7 @@ def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, fi = fwdB[k] ti = taus[i] zz = 0.0 - for q in range(0, numFactors): + for q in range(0, num_factors): zij = lambdas[q][i-j] zkj = lambdas[q][k-j] zz += zij * zkj @@ -603,7 +603,7 @@ def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, muC = 0.5 * (muA + muB) - x = np.exp(muC * dtj - 0.5 * itoTerm * dtj + randomTerm) + x = np.exp(muC * dtj - 0.5 * itoTerm * dtj + random_term) fwd[i_path, j+1, k] = fwd[i_path, j, k] * x return fwd @@ -614,7 +614,7 @@ def lmm_simulate_fwds_mf(num_fwds, numFactors, num_paths, numeraireIndex, @njit(float64[:](int64, int64, float64, float64[:], float64[:, :, :], float64[:], int64), cache=True, fastmath=True) -def lmm_cap_flr_pricer(num_fwds, num_paths, K, fwd0, fwds, taus, isCap): +def lmm_cap_flr_pricer(num_fwds, num_paths, K, fwd0, fwds, taus, is_cap): """ Function to price a strip of cap or floorlets in accordance with the simulated forward curve dynamics. """ @@ -622,19 +622,19 @@ def lmm_cap_flr_pricer(num_fwds, num_paths, K, fwd0, fwds, taus, isCap): max_fwds = len(fwds[0]) if num_fwds > max_fwds: - raise FinError("NumForwards > maxForwards") + raise FinError("num_fwds > max_fwds") if num_paths > max_paths: raise FinError("NumPaths > MaxPaths") - discFactor = np.zeros(num_fwds) + df = np.zeros(num_fwds) capFlrLets = np.zeros(num_fwds-1) capFlrLetValues = np.zeros(num_fwds-1) numeraire = np.zeros(num_fwds) for i_path in range(0, num_paths): - periodRoll = 1.0 + period_roll = 1.0 libor = fwds[i_path, 0, 0] capFlrLets[0] = max(K - libor, 0.0) * taus[0] @@ -644,29 +644,29 @@ def lmm_cap_flr_pricer(num_fwds, num_paths, K, fwd0, fwds, taus, isCap): libor = fwds[i_path, j, j] if j == 1: - if isCap == 0: + if is_cap == 0: capFlrLets[j] = max(K - libor, 0.0) * taus[j] else: capFlrLets[j] = max(libor - K, 0.0) * taus[j] - numeraire[0] = 1.0 / discFactor[0] + numeraire[0] = 1.0 / df[0] else: - if isCap == 1: + if is_cap == 1: capFlrLets[j] = max(libor - K, 0.0) * taus[j] - elif isCap == 0: + elif is_cap == 0: capFlrLets[j] = max(K - libor, 0.0) * taus[j] else: - raise FinError("isCap should be 0 or 1") + raise FinError("is_cap should be 0 or 1") - periodRoll = (1.0 + libor * taus[j]) - numeraire[j] = numeraire[j - 1] * periodRoll + period_roll = (1.0 + libor * taus[j]) + numeraire[j] = numeraire[j - 1] * period_roll - for iFwd in range(0, num_fwds): - denom = abs(numeraire[iFwd]) + 1e-12 - capFlrLetValues[iFwd] += capFlrLets[iFwd] / denom + for i_fwd in range(0, num_fwds): + denom = abs(numeraire[i_fwd]) + 1e-12 + capFlrLetValues[i_fwd] += capFlrLets[i_fwd] / denom - for iFwd in range(0, num_fwds): - capFlrLetValues[iFwd] /= num_paths + for i_fwd in range(0, num_fwds): + capFlrLetValues[i_fwd] /= num_paths return capFlrLetValues @@ -679,61 +679,62 @@ def lmm_swap_pricer(cpn, num_periods, num_paths, fwd0, fwds, taus): """ Function to reprice a basic swap using the simulated forward Ibors. """ - maxPaths = len(fwds) - maxForwards = len(fwds[0]) + max_paths = len(fwds) + max_fwds = len(fwds[0]) - if num_periods > maxForwards: - raise FinError("NumPeriods > numForwards") + if num_periods > max_fwds: + raise FinError("NumPeriods > num_fwds") - if num_paths > maxPaths: + if num_paths > max_paths: raise FinError("NumPaths > MaxPaths") - discFactor = np.zeros(maxForwards) - numeraire = np.zeros(maxForwards) - sumFixed = 0.0 - sumFloat = 0.0 - fixedFlows = np.zeros(maxForwards) - floatFlows = np.zeros(maxForwards) + df = np.zeros(max_fwds) + numeraire = np.zeros(max_fwds) + sum_fixed = 0.0 + sun_float = 0.0 + fixed_flows = np.zeros(max_fwds) + float_flows = np.zeros(max_fwds) # Set up initial term structure - discFactor[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) - for ix in range(1, maxForwards): - discFactor[ix] = discFactor[ix-1] / (1.0 + fwd0[ix] * taus[ix]) + df[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + for ix in range(1, max_fwds): + df[ix] = df[ix-1] / (1.0 + fwd0[ix] * taus[ix]) for i_path in range(0, num_paths): - periodRoll = 1.0 + period_roll = 1.0 libor = fwds[i_path, 0, 0] - floatFlows[0] = libor * taus[0] - fixedFlows[0] = cpn * taus[0] - numeraire[0] = 1.0 / discFactor[0] + float_flows[0] = libor * taus[0] + fixed_flows[0] = cpn * taus[0] + numeraire[0] = 1.0 / df[0] for j in range(1, num_periods): # TIME LOOP libor = fwds[i_path, j, j] if j == 1: - fixedFlows[j] = cpn * taus[j] - floatFlows[j] = libor * taus[j] + fixed_flows[j] = cpn * taus[j] + float_flows[j] = libor * taus[j] else: - fixedFlows[j] = fixedFlows[j-1] * periodRoll + cpn * taus[j] - floatFlows[j] = floatFlows[j-1] * periodRoll + libor * taus[j] + fixed_flows[j] = fixed_flows[j-1] * period_roll + cpn * taus[j] + float_flows[j] = float_flows[j-1] * \ + period_roll + libor * taus[j] - periodRoll = (1.0 + libor * taus[j]) - numeraire[j] = numeraire[j - 1] * periodRoll + period_roll = (1.0 + libor * taus[j]) + numeraire[j] = numeraire[j - 1] * period_roll - for iFwd in range(0, num_periods): - sumFloat += floatFlows[iFwd] / numeraire[iFwd] - sumFixed += fixedFlows[iFwd] / numeraire[iFwd] + for i_fwd in range(0, num_periods): + sun_float += float_flows[i_fwd] / numeraire[i_fwd] + sum_fixed += fixed_flows[i_fwd] / numeraire[i_fwd] - sumFloat /= num_paths - sumFixed /= num_paths - v = sumFixed - sumFloat - pv01 = sumFixed/cpn - swap_rate = sumFloat/pv01 + sun_float /= num_paths + sum_fixed /= num_paths + v = sum_fixed - sun_float + pv01 = sum_fixed/cpn + swap_rate = sun_float/pv01 - print("FLOAT LEG:", sumFloat) - print("FIXED LEG:", sumFixed) + print("FLOAT LEG:", sun_float) + print("FIXED LEG:", sum_fixed) print("SWAP RATE:", swap_rate) print("NET VALUE:", v) return v @@ -743,29 +744,29 @@ def lmm_swap_pricer(cpn, num_periods, num_paths, fwd0, fwds, taus): @njit(float64(float64, int64, int64, int64, float64[:], float64[:, :, :], float64[:], int64), cache=True, fastmath=True) -def lmm_swaption_pricer(strike, a, b, num_paths, fwd0, fwds, taus, isPayer): +def lmm_swaption_pricer(strike, a, b, num_paths, fwd0, fwds, taus, is_payer): """ Function to price a European swaption using the simulated forward discount. """ - maxPaths = len(fwds) - maxForwards = len(fwds[0]) + max_paths = len(fwds) + max_fwds = len(fwds[0]) - if a > maxForwards: - raise FinError("NumPeriods > numForwards") + if a > max_fwds: + raise FinError("NumPeriods > num_fwds") if a >= b: raise FinError("Swap maturity is before expiry date") - if num_paths > maxPaths: + if num_paths > max_paths: raise FinError("NumPaths > MaxPaths") - discFactor = np.zeros(maxForwards) -# pv01 = np.zeros(maxForwards) + df = np.zeros(max_fwds) +# pv01 = np.zeros(max_fwds) # Set up initial term structure - discFactor[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + df[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) for ix in range(1, b): - discFactor[ix] = discFactor[ix-1] / (1.0 + fwd0[ix] * taus[ix]) + df[ix] = df[ix-1] / (1.0 + fwd0[ix] * taus[ix]) sumPayRecSwaption = 0.0 @@ -785,12 +786,12 @@ def lmm_swaption_pricer(strike, a, b, num_paths, fwd0, fwds, taus, isPayer): df = df / (1.0 + tau * f) pv01 = pv01 + tau * df - fwdSwapRate = (1.0 - df) / pv01 + fwd_swap_rate = (1.0 - df) / pv01 - if isPayer == 1: - payRecSwaption = max(fwdSwapRate - strike, 0.0) * pv01 - elif isPayer == 0: - payRecSwaption = max(strike - fwdSwapRate, 0.0) * pv01 + if is_payer == 1: + payRecSwaption = max(fwd_swap_rate - strike, 0.0) * pv01 + elif is_payer == 0: + payRecSwaption = max(strike - fwd_swap_rate, 0.0) * pv01 else: raise FinError("Unknown payRecSwaption value - must be 0 or 1") @@ -807,30 +808,30 @@ def lmm_swaption_pricer(strike, a, b, num_paths, fwd0, fwds, taus, isPayer): def lmm_ratchet_caplet_pricer(spd, num_periods, num_paths, fwd0, fwds, taus): """ Price a ratchet using the simulated Ibor rates.""" - maxPaths = len(fwds) - maxForwards = len(fwds[0][0]) + max_paths = len(fwds) + max_fwds = len(fwds[0][0]) - if num_periods > maxForwards: - raise FinError("NumPeriods > numForwards") + if num_periods > max_fwds: + raise FinError("NumPeriods > num_fwds") - if num_paths > maxPaths: + if num_paths > max_paths: raise FinError("NumPaths > MaxPaths") - discFactor = np.zeros(maxForwards) - numeraire = np.zeros(maxForwards) - ratchetCaplets = np.zeros(maxForwards) - ratchetCapletValues = np.zeros(maxForwards) + df = np.zeros(max_fwds) + numeraire = np.zeros(max_fwds) + rachet_caplets = np.zeros(max_fwds) + rachet_caplet_values = np.zeros(max_fwds) # Set up initial term structure - discFactor[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) - for ix in range(1, maxForwards): - discFactor[ix] = discFactor[ix-1] / (1.0 + fwd0[ix] * taus[ix]) + df[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + for ix in range(1, max_fwds): + df[ix] = df[ix-1] / (1.0 + fwd0[ix] * taus[ix]) for i_path in range(0, num_paths): - periodRoll = 1.0 + period_roll = 1.0 libor = fwds[i_path, 0, 0] - ratchetCaplets[0] = 0.0 + rachet_caplets[0] = 0.0 for j in range(1, num_periods): # TIME LOOP @@ -839,21 +840,22 @@ def lmm_ratchet_caplet_pricer(spd, num_periods, num_paths, fwd0, fwds, taus): libor = fwds[i_path, j, j] if j == 1: - ratchetCaplets[j] = max(libor - K, 0.0) * taus[j] - numeraire[0] = 1.0 / discFactor[0] + rachet_caplets[j] = max(libor - K, 0.0) * taus[j] + numeraire[0] = 1.0 / df[0] else: - ratchetCaplets[j] = max(libor - K, 0.0) * taus[j] + rachet_caplets[j] = max(libor - K, 0.0) * taus[j] - periodRoll = (1.0 + libor * taus[j]) - numeraire[j] = numeraire[j - 1] * periodRoll + period_roll = (1.0 + libor * taus[j]) + numeraire[j] = numeraire[j - 1] * period_roll - for iFwd in range(0, num_periods): - ratchetCapletValues[iFwd] += ratchetCaplets[iFwd] / numeraire[iFwd] + for i_fwd in range(0, num_periods): + rachet_caplet_values[i_fwd] += rachet_caplets[i_fwd] / \ + numeraire[i_fwd] - for iFwd in range(0, num_periods): - ratchetCapletValues[iFwd] /= num_paths + for i_fwd in range(0, num_periods): + rachet_caplet_values[i_fwd] /= num_paths - return ratchetCapletValues + return rachet_caplet_values ############################################################################### @@ -864,61 +866,61 @@ def lmm_flexi_cap_pricer(maxCaplets, K, num_periods, num_paths, fwd0, fwds, taus): """ Price a flexicap using the simulated Ibor rates.""" - maxPaths = len(fwds) - maxForwards = len(fwds[0][0]) + max_paths = len(fwds) + max_fwds = len(fwds[0][0]) - if num_periods > maxForwards: - raise FinError("NumPeriods > numForwards") + if num_periods > max_fwds: + raise FinError("NumPeriods > num_fwds") - if num_paths > maxPaths: + if num_paths > max_paths: raise FinError("NumPaths > MaxPaths") - discFactor = np.zeros(maxForwards) - numeraire = np.zeros(maxForwards) - flexiCaplets = np.zeros(maxForwards) - flexiCapletValues = np.zeros(maxForwards) + df = np.zeros(max_fwds) + numeraire = np.zeros(max_fwds) + flexi_caplets = np.zeros(max_fwds) + flexi_caplet_values = np.zeros(max_fwds) # Set up initial term structure - discFactor[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) - for ix in range(1, maxForwards): - discFactor[ix] = discFactor[ix-1] / (1.0 + fwd0[ix] * taus[ix]) + df[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + for ix in range(1, max_fwds): + df[ix] = df[ix-1] / (1.0 + fwd0[ix] * taus[ix]) for i_path in range(0, num_paths): - periodRoll = 1.0 + period_roll = 1.0 libor = fwds[i_path, 0, 0] - flexiCaplets[0] = 0.0 + flexi_caplets[0] = 0.0 - numCapletsLeft = maxCaplets + num_caplets_left = maxCaplets for j in range(1, num_periods): # TIME LOOP libor = fwds[i_path, j, j] if j == 1: - if libor > K and numCapletsLeft > 0: - flexiCaplets[j] = max(libor - K, 0.0) * taus[j] - numCapletsLeft -= 1 - numeraire[0] = 1.0 / discFactor[0] + if libor > K and num_caplets_left > 0: + flexi_caplets[j] = max(libor - K, 0.0) * taus[j] + num_caplets_left -= 1 + numeraire[0] = 1.0 / df[0] else: - if libor > K and numCapletsLeft > 0: - flexiCaplets[j] = max(libor - K, 0.0) * taus[j] - numCapletsLeft -= 1 + if libor > K and num_caplets_left > 0: + flexi_caplets[j] = max(libor - K, 0.0) * taus[j] + num_caplets_left -= 1 - periodRoll = (1.0 + libor * taus[j]) - numeraire[j] = numeraire[j - 1] * periodRoll + period_roll = (1.0 + libor * taus[j]) + numeraire[j] = numeraire[j - 1] * period_roll - for iFwd in range(0, num_periods): - flexiCapletValues[iFwd] += flexiCaplets[iFwd] / numeraire[iFwd] + for i_fwd in range(0, num_periods): + flexi_caplet_values[i_fwd] += flexi_caplets[i_fwd] / numeraire[i_fwd] - for iFwd in range(0, num_periods): - flexiCapletValues[iFwd] /= num_paths + for i_fwd in range(0, num_periods): + flexi_caplet_values[i_fwd] /= num_paths - flexiCapValue = 0.0 - for iFwd in range(0, num_periods): - flexiCapValue += flexiCapletValues[iFwd] + flexi_cap_value = 0.0 + for i_fwd in range(0, num_periods): + flexi_cap_value += flexi_caplet_values[i_fwd] - return flexiCapValue + return flexi_cap_value ############################################################################### @@ -928,28 +930,28 @@ def lmm_flexi_cap_pricer(maxCaplets, K, num_periods, num_paths, def lmm_sticky_caplet_pricer(spread, num_periods, num_paths, fwd0, fwds, taus): """ Price a sticky cap using the simulated Ibor rates. """ - maxPaths = len(fwds) - maxForwards = len(fwds[0][0]) + max_paths = len(fwds) + max_fwds = len(fwds[0][0]) - if num_periods > maxForwards: - raise FinError("NumPeriods > numForwards") + if num_periods > max_fwds: + raise FinError("NumPeriods > num_fwds") - if num_paths > maxPaths: + if num_paths > max_paths: raise FinError("NumPaths > MaxPaths") - discFactor = np.zeros(maxForwards) - numeraire = np.zeros(maxForwards) - stickyCaplets = np.zeros(maxForwards) - stickyCapletValues = np.zeros(maxForwards) + df = np.zeros(max_fwds) + numeraire = np.zeros(max_fwds) + stickyCaplets = np.zeros(max_fwds) + stickyCapletValues = np.zeros(max_fwds) # Set up initial term structure - discFactor[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) - for ix in range(1, maxForwards): - discFactor[ix] = discFactor[ix-1] / (1.0 + fwd0[ix] * taus[ix]) + df[0] = 1.0 / (1.0 + fwd0[0] * taus[0]) + for ix in range(1, max_fwds): + df[ix] = df[ix-1] / (1.0 + fwd0[ix] * taus[ix]) for i_path in range(0, num_paths): - periodRoll = 1.0 + period_roll = 1.0 libor = fwds[i_path, 0, 0] stickyCaplets[0] = 0.0 K = libor @@ -962,18 +964,19 @@ def lmm_sticky_caplet_pricer(spread, num_periods, num_paths, fwd0, fwds, taus): if j == 1: stickyCaplets[j] = max(libor-K, 0.0) * taus[j] - numeraire[0] = 1.0 / discFactor[0] + numeraire[0] = 1.0 / df[0] else: stickyCaplets[j] = max(libor - K, 0.0) * taus[j] - periodRoll = (1.0 + libor * taus[j]) - numeraire[j] = numeraire[j - 1] * periodRoll + period_roll = (1.0 + libor * taus[j]) + numeraire[j] = numeraire[j - 1] * period_roll - for iFwd in range(0, num_periods): - stickyCapletValues[iFwd] += stickyCaplets[iFwd] / numeraire[iFwd] + for i_fwd in range(0, num_periods): + stickyCapletValues[i_fwd] += stickyCaplets[i_fwd] / \ + numeraire[i_fwd] - for iFwd in range(0, num_periods): - stickyCapletValues[iFwd] /= num_paths + for i_fwd in range(0, num_periods): + stickyCapletValues[i_fwd] /= num_paths return stickyCapletValues diff --git a/financepy/models/loss_dbn_builder.py b/financepy/models/loss_dbn_builder.py index d73a71ce..49195211 100644 --- a/financepy/models/loss_dbn_builder.py +++ b/financepy/models/loss_dbn_builder.py @@ -11,9 +11,9 @@ @njit(float64[:](int64, float64[:], float64[:]), fastmath=True, cache=True) -def indep_loss_dbn_heterogeneous_adj_binomial(num_credits, - cond_probs, - loss_ratio): +def indep_loss_dbn_hetero_adj_binomial(num_credits, + cond_probs, + loss_ratio): # Algorithm due to D. O'Kane. @@ -99,8 +99,8 @@ def portfolio_gcd(actual_losses): num2 = int(actual_losses[i_credit] * scaling) temp = pair_gcd(temp, num2) - portfolioGCD = float(temp / scaling) - return portfolioGCD + portfolio_gcd = float(temp / scaling) + return portfolio_gcd ############################################################################### diff --git a/financepy/models/merton_firm.py b/financepy/models/merton_firm.py index 0e358bf9..f0beb3c1 100644 --- a/financepy/models/merton_firm.py +++ b/financepy/models/merton_firm.py @@ -21,23 +21,23 @@ class MertonFirm(): rate, the asset growth rate and the asset value volatility. """ def __init__(self, - assetValue: (float, list, np.ndarray), - bondFace: (float, list, np.ndarray), - timeToMaturity: (float, list, np.ndarray), + asset_value: (float, list, np.ndarray), + bond_face: (float, list, np.ndarray), + years_to_maturity: (float, list, np.ndarray), risk_free_rate: (float, list, np.ndarray), - assetGrowthRate: (float, list, np.ndarray), - assetVolatility: (float, list, np.ndarray)): + asset_growth_rate: (float, list, np.ndarray), + asset_volatility: (float, list, np.ndarray)): """ Create an object that holds all of the model parameters. These parameters may be vectorised. """ check_argument_types(self.__init__, locals()) - self._A = np.array(assetValue) - self._L = np.array(bondFace) - self._t = np.array(timeToMaturity) + self._A = np.array(asset_value) + self._L = np.array(bond_face) + self._t = np.array(years_to_maturity) self._r = np.array(risk_free_rate) - self._mu = np.array(assetGrowthRate) - self._vA = np.array(assetVolatility) + self._mu = np.array(asset_growth_rate) + self._vA = np.array(asset_volatility) self._D = self.debt_value() self._E = self.equity_value() self._vE = self.equity_vol() @@ -72,10 +72,10 @@ def equity_vol(self): E = self.equity_value() lvg = self._A / self._L - sigmaRootT = self._vA * np.sqrt(self._t) + sigma_root_t = self._vA * np.sqrt(self._t) d1 = np.log(lvg) + (self._r + 0.5 * self._vA ** 2) * self._t - d1 = d1 / sigmaRootT + d1 = d1 / sigma_root_t evol = (self._A / E) * N(d1) * self._vA return evol @@ -85,10 +85,10 @@ def equity_value(self): """ Calculate the equity value. """ lvg = self._A / self._L - sigmaRootT = self._vA * np.sqrt(self._t) + sigma_root_t = self._vA * np.sqrt(self._t) d1 = np.log(lvg) + (self._r + 0.5 * self._vA ** 2) * self._t - d1 = d1 / sigmaRootT - d2 = d1 - sigmaRootT + d1 = d1 / sigma_root_t + d2 = d1 - sigma_root_t evalue = self._A * N(d1) - self._L * np.exp(-self._r * self._t) * N(d2) return evalue @@ -98,10 +98,10 @@ def debt_value(self): """ Calculate the debt value """ lvg = self._A / self._L - sigmaRootT = self._vA * np.sqrt(self._t) + sigma_root_t = self._vA * np.sqrt(self._t) d1 = np.log(lvg) + (self._r + 0.5 * self._vA ** 2) * self._t - d1 = d1 / sigmaRootT - d2 = d1 - sigmaRootT + d1 = d1 / sigma_root_t + d2 = d1 - sigma_root_t dvalue = self._A * N(-d1) + self._L * \ np.exp(-self._r * self._t) * N(d2) return dvalue diff --git a/financepy/models/merton_firm_mkt.py b/financepy/models/merton_firm_mkt.py index 8e11444c..5e766911 100644 --- a/financepy/models/merton_firm_mkt.py +++ b/financepy/models/merton_firm_mkt.py @@ -3,11 +3,9 @@ ############################################################################## import numpy as np - -from ..utils.math import N - from scipy import optimize +from ..utils.math import N from ..utils.helpers import label_to_string, check_argument_types from ..utils.error import FinError from .merton_firm import MertonFirm @@ -42,19 +40,21 @@ def _fobj(x, *args): class MertonFirmMkt(MertonFirm): - """ Market Extension of the Merton Firm Model according to the original + """ + Market Extension of the Merton Firm Model according to the original formulation by Merton with the inputs being the equity value of the firm, the liabilities (bond face), the time to maturity in years, the risk-free rate, the asset growth rate and the equity volatility. The asset value and asset volatility are computed internally by solving two non-linear - simultaneous equations. """ + simultaneous equations. + """ def __init__(self, equity_value: (float, list, np.ndarray), - bondFace: (float, list, np.ndarray), - timeToMaturity: (float, list, np.ndarray), + bond_face: (float, list, np.ndarray), + years_to_maturity: (float, list, np.ndarray), risk_free_rate: (float, list, np.ndarray), - assetGrowthRate: (float, list, np.ndarray), + asset_growth_rate: (float, list, np.ndarray), equity_volatility: (float, list, np.ndarray)): """ Create an object that holds all of the model parameters. These parameters may be vectorised. """ @@ -64,26 +64,26 @@ def __init__(self, if isinstance(equity_value, float): equity_value = [equity_value] - if isinstance(bondFace, float): - bondFace = [bondFace] + if isinstance(bond_face, float): + bond_face = [bond_face] - if isinstance(timeToMaturity, float): - timeToMaturity = [timeToMaturity] + if isinstance(years_to_maturity, float): + years_to_maturity = [years_to_maturity] if isinstance(risk_free_rate, float): risk_free_rate = [risk_free_rate] - if isinstance(assetGrowthRate, float): - assetGrowthRate = [assetGrowthRate] + if isinstance(asset_growth_rate, float): + asset_growth_rate = [asset_growth_rate] if isinstance(equity_volatility, float): equity_volatility = [equity_volatility] self._E = np.array(equity_value) - self._L = np.array(bondFace) - self._t = np.array(timeToMaturity) + self._L = np.array(bond_face) + self._t = np.array(years_to_maturity) self._r = np.array(risk_free_rate) - self._mu = np.array(assetGrowthRate) + self._mu = np.array(asset_growth_rate) self._vE = np.array(equity_volatility) nmax = max(len(self._E), diff --git a/financepy/models/process_simulator.py b/financepy/models/process_simulator.py index fdd7b674..3d0e7088 100644 --- a/financepy/models/process_simulator.py +++ b/financepy/models/process_simulator.py @@ -35,13 +35,13 @@ def get_process( process_type, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed): if process_type == ProcessTypes.GBM: (stock_price, drift, volatility, scheme) = model_params - paths = get_gbm_paths(num_paths, numAnnSteps, t, drift, + paths = get_gbm_paths(num_paths, num_annual_steps, t, drift, stock_price, volatility, scheme.value, seed) return paths @@ -49,7 +49,7 @@ def get_process( (stock_price, drift, v0, kappa, theta, sigma, rho, scheme) = model_params paths = get_heston_paths(num_paths, - numAnnSteps, + num_annual_steps, t, drift, stock_price, @@ -66,7 +66,7 @@ def get_process( (r0, kappa, theta, sigma, scheme) = model_params paths = get_vasicek_paths( num_paths, - numAnnSteps, + num_annual_steps, t, r0, kappa, @@ -78,7 +78,7 @@ def get_process( elif process_type == ProcessTypes.CIR: (r0, kappa, theta, sigma, scheme) = model_params - paths = get_cir_paths(num_paths, numAnnSteps, t, + paths = get_cir_paths(num_paths, num_annual_steps, t, r0, kappa, theta, sigma, scheme.value, seed) return paths @@ -100,7 +100,7 @@ class FinHestonNumericalScheme(Enum): float64, float64, float64, int64, int64), cache=True, fastmath=True) def get_heston_paths(num_paths, - numAnnSteps, + num_annual_steps, t, drift, s0, @@ -113,10 +113,10 @@ def get_heston_paths(num_paths, seed): np.random.seed(seed) - dt = 1.0 / numAnnSteps + dt = 1.0 / num_annual_steps num_steps = int(t / dt) - sPaths = np.empty(shape=(num_paths, num_steps + 1)) - sPaths[:, 0] = s0 + s_paths = np.empty(shape=(num_paths, num_steps + 1)) + s_paths[:, 0] = s0 sdt = sqrt(dt) rhohat = sqrt(1.0 - rho * rho) sigma2 = sigma * sigma @@ -131,13 +131,13 @@ def get_heston_paths(num_paths, z2 = np.random.normal(0.0, 1.0) * sdt zV = z1 zS = rho * z1 + rhohat * z2 - vplus = max(v, 0.0) - rtvplus = sqrt(vplus) - v += kappa * (theta - vplus) * dt + sigma * \ - rtvplus * zV + 0.25 * sigma2 * (zV * zV - dt) - s += drift * s * dt + rtvplus * s * \ - zS + 0.5 * s * vplus * (zV * zV - dt) - sPaths[i_path, i_step] = s + v_plus = max(v, 0.0) + rtv_plus = sqrt(v_plus) + v += kappa * (theta - v_plus) * dt + sigma * \ + rtv_plus * zV + 0.25 * sigma2 * (zV * zV - dt) + s += drift * s * dt + rtv_plus * s * \ + zS + 0.5 * s * v_plus * (zV * zV - dt) + s_paths[i_path, i_step] = s elif scheme == FinHestonNumericalScheme.EULERLOG.value: # Basic scheme to first order with truncation on variance @@ -147,12 +147,12 @@ def get_heston_paths(num_paths, for i_step in range(1, num_steps + 1): zV = np.random.normal(0.0, 1.0) * sdt zS = rho * zV + rhohat * np.random.normal(0.0, 1.0) * sdt - vplus = max(v, 0.0) - rtvplus = sqrt(vplus) - x += (drift - 0.5 * vplus) * dt + rtvplus * zS - v += kappa * (theta - vplus) * dt + sigma * \ - rtvplus * zV + sigma2 * (zV * zV - dt) / 4.0 - sPaths[i_path, i_step] = exp(x) + v_plus = max(v, 0.0) + rtv_plus = sqrt(v_plus) + x += (drift - 0.5 * v_plus) * dt + rtv_plus * zS + v += kappa * (theta - v_plus) * dt + sigma * \ + rtv_plus * zV + sigma2 * (zV * zV - dt) / 4.0 + s_paths[i_path, i_step] = exp(x) elif scheme == FinHestonNumericalScheme.QUADEXP.value: # Due to Leif Andersen(2006) @@ -206,12 +206,12 @@ def get_heston_paths(num_paths, x += mu * dt + K0 + (K1 * vn + K2 * vnp) + \ sqrt(K3 * vn + K4 * vnp) * zS - sPaths[i_path, i_step] = exp(x) + s_paths[i_path, i_step] = exp(x) vn = vnp else: raise FinError("Unknown FinHestonNumericalSchme") - return sPaths + return s_paths ############################################################################### @@ -225,10 +225,10 @@ class FinGBMNumericalScheme(Enum): @njit(float64[:, :](int64, int64, float64, float64, float64, float64, int64, int64), cache=True, fastmath=True) -def get_gbm_paths(num_paths, numAnnSteps, t, mu, stock_price, sigma, scheme, seed): +def get_gbm_paths(num_paths, num_annual_steps, t, mu, stock_price, sigma, scheme, seed): np.random.seed(seed) - dt = 1.0 / numAnnSteps + dt = 1.0 / num_annual_steps num_time_steps = int(t / dt + 0.50) vsqrt_dt = sigma * sqrt(dt) m = exp((mu - sigma * sigma / 2.0) * dt) @@ -252,7 +252,8 @@ def get_gbm_paths(num_paths, numAnnSteps, t, mu, stock_price, sigma, scheme, see for ip in range(0, num_paths): w = np.exp(g1D[ip] * vsqrt_dt) s_all[ip, it] = s_all[ip, it - 1] * m * w - s_all[ip + num_paths, it] = s_all[ip + num_paths, it - 1] * m / w + s_all[ip + num_paths, it] = s_all[ip + + num_paths, it - 1] * m / w else: @@ -260,7 +261,7 @@ def get_gbm_paths(num_paths, numAnnSteps, t, mu, stock_price, sigma, scheme, see # m = np.mean(s_all[:, -1]) # v = np.var(s_all[:, -1]/s_all[:, 0]) -# print("GBM", num_paths, numAnnSteps, t, mu, stock_price, sigma, scheme, m,v) +# print("GBM", num_paths, num_annual_steps, t, mu, stock_price, sigma, scheme, m,v) return s_all @@ -277,7 +278,7 @@ class FinVasicekNumericalScheme(Enum): @njit(float64[:, :](int64, int64, float64, float64, float64, float64, float64, int64, int64), cache=True, fastmath=True) def get_vasicek_paths(num_paths, - numAnnSteps, + num_annual_steps, t, r0, kappa, @@ -287,9 +288,9 @@ def get_vasicek_paths(num_paths, seed): np.random.seed(seed) - dt = 1.0 / numAnnSteps + dt = 1.0 / num_annual_steps num_steps = int(t / dt) - sigmasqrt_dt = sigma * sqrt(dt) + sigma_sqrt_dt = sigma * sqrt(dt) if scheme == FinVasicekNumericalScheme.NORMAL.value: rate_path = np.empty((num_paths, num_steps + 1)) @@ -298,7 +299,7 @@ def get_vasicek_paths(num_paths, r = r0 z = np.random.normal(0.0, 1.0, size=(num_steps)) for i_step in range(1, num_steps + 1): - r += kappa * (theta - r) * dt + z[i_step - 1] * sigmasqrt_dt + r += kappa * (theta - r) * dt + z[i_step - 1] * sigma_sqrt_dt rate_path[i_path, i_step] = r elif scheme == FinVasicekNumericalScheme.ANTITHETIC.value: rate_path = np.empty((2 * num_paths, num_steps + 1)) @@ -309,9 +310,9 @@ def get_vasicek_paths(num_paths, z = np.random.normal(0.0, 1.0, size=(num_steps)) for i_step in range(1, num_steps + 1): r1 = r1 + kappa * (theta - r1) * dt + \ - z[i_step - 1] * sigmasqrt_dt + z[i_step - 1] * sigma_sqrt_dt r2 = r2 + kappa * (theta - r2) * dt - \ - z[i_step - 1] * sigmasqrt_dt + z[i_step - 1] * sigma_sqrt_dt rate_path[i_path, i_step] = r1 rate_path[i_path + num_paths, i_step] = r2 return rate_path @@ -332,7 +333,7 @@ class CIRNumericalScheme(Enum): @njit(float64[:, :](int64, int64, float64, float64, float64, float64, float64, int64, int64), cache=True, fastmath=True) def get_cir_paths(num_paths, - numAnnSteps, + num_annual_steps, t, r0, kappa, @@ -342,21 +343,21 @@ def get_cir_paths(num_paths, seed): np.random.seed(seed) - dt = 1.0 / numAnnSteps + dt = 1.0 / num_annual_steps num_steps = int(t / dt) rate_path = np.empty(shape=(num_paths, num_steps + 1)) rate_path[:, 0] = r0 if scheme == CIRNumericalScheme.EULER.value: - sigmasqrt_dt = sigma * sqrt(dt) + sigma_sqrt_dt = sigma * sqrt(dt) for i_path in range(0, num_paths): r = r0 z = np.random.normal(0.0, 1.0, size=(num_steps)) for i_step in range(1, num_steps + 1): rplus = max(r, 0.0) - sqrtrplus = sqrt(rplus) + sqrt_rplus = sqrt(rplus) r = r + kappa * (theta - rplus) * dt + \ - sigmasqrt_dt * z[i_step - 1] * sqrtrplus + sigma_sqrt_dt * z[i_step - 1] * sqrt_rplus rate_path[i_path, i_step] = r elif scheme == CIRNumericalScheme.LOGNORMAL.value: @@ -373,15 +374,15 @@ def get_cir_paths(num_paths, rate_path[i_path, i_step] = r elif scheme == CIRNumericalScheme.MILSTEIN.value: - sigmasqrt_dt = sigma * sqrt(dt) + sigma_sqrt_dt = sigma * sqrt(dt) sigma2dt = sigma * sigma * dt / 4.0 for i_path in range(0, num_paths): r = r0 z = np.random.normal(0.0, 1.0, size=(num_steps)) for i_step in range(1, num_steps + 1): - sqrtrplus = sqrt(max(r, 0.0)) + sqrt_rplus = sqrt(max(r, 0.0)) r = r + kappa * (theta - r) * dt + \ - z[i_step - 1] * sigmasqrt_dt * sqrtrplus + z[i_step - 1] * sigma_sqrt_dt * sqrt_rplus r = r + sigma2dt * (z[i_step - 1]**2 - 1.0) rate_path[i_path, i_step] = r @@ -393,11 +394,11 @@ def get_cir_paths(num_paths, z = np.random.normal(0.0, 1.0, size=(num_steps)) for i_step in range(1, num_steps + 1): beta = z[i_step - 1] / sqrt_dt - sqrtrplus = sqrt(max(r, 0.0)) + sqrt_rplus = sqrt(max(r, 0.0)) c = 1.0 + (sigma * beta - 2.0 * kappa * - sqrtrplus) * dt / 4.0 / sqrtrplus + sqrt_rplus) * dt / 4.0 / sqrt_rplus r = r + (kappa * (bhat - r) + sigma * - beta * sqrtrplus) * c * dt + beta * sqrt_rplus) * c * dt rate_path[i_path, i_step] = r return rate_path diff --git a/financepy/models/sabr.py b/financepy/models/sabr.py index 94a4c5b6..162350d2 100644 --- a/financepy/models/sabr.py +++ b/financepy/models/sabr.py @@ -90,22 +90,22 @@ def vol_function_sabr_beta_one(params, f, k, t): if abs(m - 1.0) > 1e-6: sigma = 1.0 - numTerm1 = 0.0 - numTerm2 = rho * nu * alpha / 4.0 - numTerm3 = nu * nu * ((2.0 - 3.0 * (rho**2.0)) / 24.0) - num = alpha * (1.0 + (numTerm1 + numTerm2 + numTerm3) * t) - logM = np.log(m) - z = nu / alpha * logM + num_term1 = 0.0 + num_term2 = rho * nu * alpha / 4.0 + num_term3 = nu * nu * ((2.0 - 3.0 * (rho**2.0)) / 24.0) + num = alpha * (1.0 + (num_term1 + num_term2 + num_term3) * t) + log_m = np.log(m) + z = nu / alpha * log_m denom = 1.0 x = np.log((np.sqrt(1.0 - 2.0*rho*z + z**2.0) + z - rho)/(1.0 - rho)) sigma = num*z/(denom*x) else: # when the option is at the money - numTerm1 = 0.0 - numTerm2 = rho * nu * alpha / 4.0 - numTerm3 = nu * nu * ((2.0 - 3.0 * (rho**2.0)) / 24.0) - num = alpha * (1.0 + (numTerm1 + numTerm2 + numTerm3) * t) + num_term1 = 0.0 + num_term2 = rho * nu * alpha / 4.0 + num_term3 = nu * nu * ((2.0 - 3.0 * (rho**2.0)) / 24.0) + num = alpha * (1.0 + (num_term1 + num_term2 + num_term3) * t) denom = 1.0 sigma = num / denom @@ -213,8 +213,8 @@ def black_vol(self, f, k, t): def black_vol_with_alpha(self, alpha, f, k, t): self._alpha = alpha[0] - blackVol = self.black_vol(f, k, t) - return blackVol + black_vol = self.black_vol(f, k, t) + return black_vol ############################################################################### @@ -230,12 +230,12 @@ def value(self, f = forward_rate t = time_to_expiry k = strike_rate - sqrtT = np.sqrt(t) + sqrt_t = np.sqrt(t) vol = self.black_vol(f, k, t) d1 = np.log(f/k) + vol * vol * t / 2 - d1 = d1 / (vol * sqrtT) - d2 = d1 - vol * sqrtT + d1 = d1 / (vol * sqrt_t) + d2 = d1 - vol * sqrt_t if call_or_put == OptionTypes.EUROPEAN_CALL: return df * (f * N(d1) - k * N(d2)) @@ -247,53 +247,51 @@ def value(self, ############################################################################### def set_alpha_from_black_vol(self, - blackVol, + black_vol, forward, strike, time_to_expiry): """ Estimate the value of the alpha coefficient of the SABR model by solving for the value of alpha that makes the SABR black vol equal to the input black vol. This uses a numerical 1D solver. """ - t_exp = time_to_expiry f = forward - K = strike + k = strike # The starting point is based on assuming that the strike is ATM - self.set_alpha_from_atm_black_vol(blackVol, strike, time_to_expiry) + self.set_alpha_from_atm_black_vol(black_vol, strike, time_to_expiry) - initAlpha = self._alpha + init_alpha = self._alpha - if initAlpha != blackVol: + if init_alpha != black_vol: # Objective function def fn(x): return np.sqrt( - (blackVol - self.black_vol_with_alpha(x, f, K, t_exp)) ** 2) + (black_vol - self.black_vol_with_alpha(x, f, k, t_exp)) ** 2) bnds = ((0.0, None),) - x0 = initAlpha + x0 = init_alpha results = minimize(fn, x0, method="L-BFGS-B", bounds=bnds, tol=1e-8) alpha = results.x[0] else: - alpha = initAlpha + alpha = init_alpha self._alpha = alpha ############################################################################### - def set_alpha_from_atm_black_vol(self, blackVol, atmStrike, time_to_expiry): + def set_alpha_from_atm_black_vol(self, black_vol, atm_strike, time_to_expiry): """ We solve cubic equation for the unknown variable alpha for the special ATM case of the strike equalling the forward following Hagan and al. equation (3.3). We take the smallest real root as the preferred solution. This is useful for calibrating the model when beta has been chosen.""" - beta = self._beta rho = self._rho nu = self._nu t_exp = time_to_expiry - K = atmStrike + K = atm_strike - coeff0 = -blackVol * (K**(1.0 - self._beta)) + coeff0 = -black_vol * (K**(1.0 - self._beta)) coeff1 = 1.0 + ((2.0 - 3.0 * rho**2) / 24.0) * (nu**2) * t_exp coeff2 = (rho * beta * nu * t_exp) / (4.0 * (K**(1.0 - beta))) coeff3 = (((1.0 - beta)**2) * t_exp) / (24.0 * (K**(2.0 - 2.0 * beta))) @@ -308,7 +306,6 @@ def set_alpha_from_atm_black_vol(self, blackVol, atmStrike, time_to_expiry): def __repr__(self): """ Return string with class details. """ - s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("Alpha", self._alpha) s += label_to_string("Beta", self._beta) diff --git a/financepy/models/sabr_shifted.py b/financepy/models/sabr_shifted.py index c29b35ff..6f794f68 100644 --- a/financepy/models/sabr_shifted.py +++ b/financepy/models/sabr_shifted.py @@ -40,8 +40,7 @@ def vol_function_shifted_sabr(params, f, k, t): f = f + shift k = k + shift - if alpha < 1e-10: - alpha = 1e-10 + alpha = max(alpha, 1e-10) # Negative strikes or forwards if k <= 0: @@ -129,8 +128,8 @@ def black_vol(self, f, k, t): def black_vol_with_alpha(self, alpha, f, k, t): self._alpha = alpha[0] - blackVol = self.black_vol(f, k, t) - return blackVol + black_vol = self.black_vol(f, k, t) + return black_vol ############################################################################### @@ -146,11 +145,11 @@ def value(self, f = forward_rate t = time_to_expiry k = strike_rate - sqrtT = np.sqrt(t) + sqrt_t = np.sqrt(t) vol = self.black_vol(f, k, t) - d1 = (np.log((f)/(k)) + vol * vol * t / 2) / (vol * sqrtT) - d2 = d1 - vol*sqrtT + d1 = (np.log((f)/(k)) + vol * vol * t / 2) / (vol * sqrt_t) + d2 = d1 - vol*sqrt_t if call_or_put == OptionTypes.EUROPEAN_CALL: return df * (f * N(d1) - k * N(d2)) @@ -161,7 +160,7 @@ def value(self, ############################################################################### - def set_alpha_from_black_vol(self, blackVol, + def set_alpha_from_black_vol(self, black_vol, forward, strike, time_to_expiry): @@ -174,27 +173,27 @@ def set_alpha_from_black_vol(self, blackVol, K = strike # The starting point is based on assuming that the strike is ATM - self.set_alpha_from_atm_black_vol(blackVol, strike, time_to_expiry) + self.set_alpha_from_atm_black_vol(black_vol, strike, time_to_expiry) - initAlpha = self._alpha + init_alpha = self._alpha - if initAlpha != blackVol: + if init_alpha != black_vol: # Objective function def fn(x): return np.sqrt( - (blackVol - self.black_vol_with_alpha(x, f, K, t_exp)) ** 2) + (black_vol - self.black_vol_with_alpha(x, f, K, t_exp)) ** 2) bnds = ((0.0, None),) - x0 = initAlpha + x0 = init_alpha results = minimize(fn, x0, method="L-BFGS-B", bounds=bnds, tol=1e-8) alpha = results.x[0] else: - alpha = initAlpha + alpha = init_alpha self._alpha = alpha ############################################################################### - def set_alpha_from_atm_black_vol(self, blackVol, atmStrike, + def set_alpha_from_atm_black_vol(self, black_vol, atm_strike, time_to_expiry): """ We solve cubic equation for the unknown variable alpha for the special ATM case of the strike equalling the forward following Hagan @@ -203,15 +202,15 @@ def set_alpha_from_atm_black_vol(self, blackVol, atmStrike, chosen.""" # For shifted SABR - atmStrike = atmStrike + self._shift + atm_strike = atm_strike + self._shift beta = self._beta rho = self._rho nu = self._nu t_exp = time_to_expiry - K = atmStrike + K = atm_strike - coeff0 = -blackVol * (K**(1.0 - self._beta)) + coeff0 = -black_vol * (K**(1.0 - self._beta)) coeff1 = 1.0 + ((2.0 - 3.0 * rho**2) / 24.0) * (nu**2) * t_exp coeff2 = (rho * beta * nu * t_exp) / (4.0 * (K**(1.0 - beta))) coeff3 = (((1.0 - beta)**2) * t_exp) / (24.0 * (K**(2.0 - 2.0 * beta))) diff --git a/financepy/models/sobol.py b/financepy/models/sobol.py index 1df15843..825387b3 100644 --- a/financepy/models/sobol.py +++ b/financepy/models/sobol.py @@ -34,7 +34,7 @@ import numpy as np from numba import njit -from financepy.utils.math import norminvcdf +from ..utils.math import norminvcdf ############################################################################### # This code loads sobol coefficients from binary numpy file and allocates @@ -45,8 +45,8 @@ path = os.path.join(dirname, "sobolcoeff.npz") with np.load(path, mmap_mode='r') as f: - sArr = np.array(f['sa'][0]) - aArr = np.array(f['sa'][1]) + s_arr = np.array(f['sa'][0]) + a_arr = np.array(f['sa'][1]) m_i = f['c'] ############################################################################### @@ -75,8 +75,8 @@ def get_uniform_sobol(num_points, dimension): random draws. Each column of random numbers is ordered so as not to correlate, i.e be independent from any other column.""" - global sArr - global aArr + global s_arr + global a_arr global m_i # ll = number of bits needed @@ -111,8 +111,8 @@ def get_uniform_sobol(num_points, dimension): # ----- Compute the remaining dimensions ----- for j in range(1, dimension): # read parameters from file - s = sArr[j-1] - a = aArr[j-1] + s = s_arr[j-1] + a = a_arr[j-1] mm = m_i[j-1] m = np.concatenate((np.zeros(1), mm)) diff --git a/financepy/models/student_t_copula.py b/financepy/models/student_t_copula.py index 4b97d90a..602d6f87 100644 --- a/financepy/models/student_t_copula.py +++ b/financepy/models/student_t_copula.py @@ -15,26 +15,26 @@ class StudentTCopula(): def default_times(self, issuer_curves, - correlation_matrix, - degreesOfFreedom, + corr_matrix, + degrees_of_freedom, num_trials, seed): np.random.seed(seed) num_credits = len(issuer_curves) x = np.random.normal(0.0, 1.0, size=(num_credits, num_trials)) - c = np.linalg.cholesky(correlation_matrix) + c = np.linalg.cholesky(corr_matrix) y = np.dot(c, x) corr_times = np.empty(shape=(num_credits, 2 * num_trials)) for i_trial in range(0, num_trials): - chi2 = np.random.chisquare(degreesOfFreedom) - c = sqrt(chi2 / degreesOfFreedom) + chi2 = np.random.chisquare(degrees_of_freedom) + c = sqrt(chi2 / degrees_of_freedom) for iCredit in range(0, num_credits): issuer_curve = issuer_curves[iCredit] g = y[iCredit, i_trial] / c - u1 = student.cdf(g, degreesOfFreedom) + u1 = student.cdf(g, degrees_of_freedom) u2 = 1.0 - u1 times = issuer_curve._times values = issuer_curve._values diff --git a/financepy/products/bonds/bond.py b/financepy/products/bonds/bond.py index 787c58e4..27024b99 100644 --- a/financepy/products/bonds/bond.py +++ b/financepy/products/bonds/bond.py @@ -27,7 +27,7 @@ from ...utils.date import Date from ...utils.error import FinError from ...utils.frequency import annual_frequency, FrequencyTypes -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.day_count import DayCount, DayCountTypes from ...utils.schedule import Schedule from ...utils.calendar import Calendar @@ -51,10 +51,10 @@ class YTMCalcType(Enum): - ZERO = 0, - UK_DMO = 1, - US_STREET = 2, - US_TREASURY = 3, + ZERO = 0 + UK_DMO = 1 + US_STREET = 2 + US_TREASURY = 3 CFETS = 4 # China Foreign Exchange Trade System @@ -162,6 +162,9 @@ def __init__(self, self._calculate_cpn_dts() self._calculate_flows() + self._pcd = None + self._ncd = None + ########################################################################### def _calculate_cpn_dts(self): @@ -389,7 +392,7 @@ def modified_duration(self, ########################################################################### - def key_rate_durations(self, + def key_rate_durations(self, settle_dt: Date, ytm: float, key_rate_tenors: list = None, @@ -484,7 +487,7 @@ def key_rate_durations(self, mat = settle_dt.add_years(tenor) par_bond = Bond(settle_dt, mat, cpn, - self._freq_type, + self._freq_type, self._dc_type) par_bonds.append(par_bond) @@ -622,7 +625,7 @@ def dirty_price_from_discount_curve(self, px = 0.0 df = 1.0 - dfSettle = discount_curve.df(settle_dt) + df_settle_dt = discount_curve.df(settle_dt) dt = self._cpn_dts[1] if dt > settle_dt: @@ -641,7 +644,7 @@ def dirty_price_from_discount_curve(self, px += pv px += df - px = px / dfSettle + px = px / df_settle_dt return px * self._par @@ -663,14 +666,14 @@ def yield_to_maturity(self, """ Calculate the bond's yield to maturity by solving the price yield relationship using a one-dimensional root solver. """ - if type(clean_price) is float or type(clean_price) is np.float64: + if isinstance(clean_price, float) or isinstance(clean_price, np.float64): clean_prices = np.array([clean_price]) - elif type(clean_price) is list or type(clean_price) is np.ndarray: + elif isinstance(clean_price, list) or isinstance(clean_price, np.ndarray): clean_prices = np.array(clean_price) else: raise FinError("Unknown type for clean_price " + str(type(clean_price))) - + self.accrued_interest(settle_dt, 1.0) accrued_amount = self._accrued_interest * self._par @@ -830,7 +833,7 @@ def dirty_price_from_oas(self, if dt > settle_dt: t = (dt - settle_dt) / gDaysInYear - t = np.maximum(t, gSmall) + t = np.maximum(t, g_small) df = discount_curve.df(dt) @@ -854,9 +857,9 @@ def option_adjusted_spread(self, """ Return OAS for bullet bond given settlement date, clean bond price and the discount relative to which the spread is to be computed. """ - if type(clean_price) is float or type(clean_price) is np.float64: + if isinstance(clean_price, float) or isinstance(clean_price, np.float64): clean_prices = np.array([clean_price]) - elif type(clean_price) is list or type(clean_price) is np.ndarray: + elif isinstance(clean_price, list) or isinstance(clean_price, np.ndarray): clean_prices = np.array(clean_price) else: raise FinError("Unknown type for clean_price " diff --git a/financepy/products/bonds/bond_callable.py b/financepy/products/bonds/bond_callable.py index bec6716a..16b4cf74 100644 --- a/financepy/products/bonds/bond_callable.py +++ b/financepy/products/bonds/bond_callable.py @@ -68,14 +68,14 @@ def __init__(self, self._freq_type = freq_type self._dc_type = dc_type - ex_div_days = 0 + self._ex_div_days = 0 self._bond = Bond(issue_dt, maturity_dt, coupon, freq_type, dc_type, - ex_div_days) + self._ex_div_days) # Validate call and put schedules for dt in call_dts: diff --git a/financepy/products/bonds/bond_convertible.py b/financepy/products/bonds/bond_convertible.py index ba6db36a..36bb1ac0 100644 --- a/financepy/products/bonds/bond_convertible.py +++ b/financepy/products/bonds/bond_convertible.py @@ -105,10 +105,10 @@ def _value_convertible(t_mat, dt = t_mat / (num_times - 1) tree_times = np.linspace(0.0, t_mat, num_times) - treeDfs = np.zeros(num_times) + tree_dfs = np.zeros(num_times) for i in range(0, num_times): df = _uinterpolate(tree_times[i], df_times, df_values, interp) - treeDfs[i] = df + tree_dfs[i] = df h = credit_spread / (1.0 - recovery_rate) survival_prob = exp(-h * dt) @@ -119,11 +119,11 @@ def _value_convertible(t_mat, for i in range(0, num_cpns): flow_time = cpn_times[i] n = int(round(flow_time / dt, 0)) - treeTime = tree_times[n] + tree_time = tree_times[n] df_flow = _uinterpolate(flow_time, df_times, df_values, interp) df_flow *= exp(-h * flow_time) - df_tree = _uinterpolate(treeTime, df_times, df_values, interp) - df_tree *= exp(-h * treeTime) + df_tree = _uinterpolate(tree_time, df_times, df_values, interp) + df_tree *= exp(-h * tree_time) tree_flows[n] += cpn_flows[i] * 1.0 * df_flow / df_tree # map call onto tree - must have no calls at high value @@ -143,16 +143,16 @@ def _value_convertible(t_mat, tree_put_value[n] = put_prices[i] # map discrete dividend yields onto tree dates when they are made - treeDividendYield = np.zeros(num_times) + tree_dividend_yld = np.zeros(num_times) numDividends = len(dividend_times) for i in range(0, numDividends): dividend_time = dividend_times[i] n = int(round(dividend_time / dt, 0)) - treeDividendYield[n] = dividend_yields[i] + tree_dividend_yld[n] = dividend_yields[i] # Set up the tree of stock prices using a 2D matrix - half the matrix is # unused but this may be a cost worth bearing for simpler code. Review. - treeStockValue = np.zeros(shape=(num_times, num_levels)) + tree_stock_value = np.zeros(shape=(num_times, num_levels)) e = stock_volatility ** 2 - h if e < 0.0: raise FinError("Volatility squared minus the hazard rate is negative.") @@ -160,47 +160,47 @@ def _value_convertible(t_mat, u = exp(sqrt(e * dt)) d = 1.0 / u u2 = u * u - treeStockValue[0, 0] = stock_price + tree_stock_value[0, 0] = stock_price for i_time in range(1, num_times): - s = treeStockValue[i_time - 1, 0] * d - treeStockValue[i_time, 0] = s + s = tree_stock_value[i_time - 1, 0] * d + tree_stock_value[i_time, 0] = s for i_node in range(1, i_time + 1): s = s * u2 - treeStockValue[i_time, i_node] = s + tree_stock_value[i_time, i_node] = s # we now reduce all stocks by the same yield amount at the same date - y = treeDividendYield[i_time] + y = tree_dividend_yld[i_time] for i_node in range(0, i_time + 1): - treeStockValue[i_time, i_node] *= (1.0 - y) + tree_stock_value[i_time, i_node] *= (1.0 - y) # set up the tree of conversion values. Before allowed to convert the # conversion value must be set equal to zero - treeConvertValue = np.zeros(shape=(num_times, num_levels)) + tree_convert_value = np.zeros(shape=(num_times, num_levels)) for i_time in range(0, num_times): if tree_times[i_time] >= start_convert_time: for i_node in range(0, i_time + 1): - s = treeStockValue[i_time, i_node] - treeConvertValue[i_time, i_node] = s * conv_ratio * 1.0 + s = tree_stock_value[i_time, i_node] + tree_convert_value[i_time, i_node] = s * conv_ratio * 1.0 - # print_tree(treeConvertValue) + # print_tree(tree_convert_value) - treeConvBondValue = np.zeros(shape=(num_times, num_levels)) + tree_convert_bond_value = np.zeros(shape=(num_times, num_levels)) # store probability of up move as a function of time on the tree - treeProbsUp = np.zeros(num_times) - treeProbsDn = np.zeros(num_times) + tree_probs_up = np.zeros(num_times) + tree_probs_dn = np.zeros(num_times) q = 0.0 # we have discrete dividends paid as dividend yields only for i_time in range(1, num_times): - a = treeDfs[i_time - 1] / treeDfs[i_time] * exp(-q * dt) - treeProbsUp[i_time] = (a - d * survival_prob) / (u - d) - treeProbsDn[i_time] = (u * survival_prob - a) / (u - d) + a = tree_dfs[i_time - 1] / tree_dfs[i_time] * exp(-q * dt) + tree_probs_up[i_time] = (a - d * survival_prob) / (u - d) + tree_probs_dn[i_time] = (u * survival_prob - a) / (u - d) # r = log(a)/dt # n_min = r*r / stock_volatility / stock_volatility - if np.any(treeProbsUp > 1.0): - raise FinError("pUp > 1.0. Increase time steps.") + if np.any(tree_probs_up > 1.0): + raise FinError("p_up > 1.0. Increase time steps.") ########################################################################### # work backwards by first setting values at bond maturity date @@ -209,43 +209,46 @@ def _value_convertible(t_mat, flow = tree_flows[num_times - 1] bullet_pv = (1.0 + flow) * face_amount for i_node in range(0, num_levels): - convValue = treeConvertValue[num_times - 1, i_node] - treeConvBondValue[num_times - 1, i_node] = max(bullet_pv, convValue) + convValue = tree_convert_value[num_times - 1, i_node] + tree_convert_bond_value[num_times - 1, + i_node] = max(bullet_pv, convValue) # begin backward steps from expiry for i_time in range(num_times - 2, -1, -1): - pUp = treeProbsUp[i_time + 1] - pDn = treeProbsDn[i_time + 1] + p_up = tree_probs_up[i_time + 1] + p_dn = tree_probs_dn[i_time + 1] pDef = 1.0 - survival_prob - df = treeDfs[i_time + 1] / treeDfs[i_time] + df = tree_dfs[i_time + 1] / tree_dfs[i_time] call = tree_call_value[i_time] put = tree_put_value[i_time] flow = tree_flows[i_time] for i_node in range(0, i_time + 1): - futValueUp = treeConvBondValue[i_time + 1, i_node + 1] - futValueDn = treeConvBondValue[i_time + 1, i_node] - hold = pUp * futValueUp + pDn * futValueDn # pUp already embeds Q - holdPV = df * hold + pDef * df * recovery_rate * face_amount \ + fut_value_up = tree_convert_bond_value[i_time + 1, i_node + 1] + fut_value_dn = tree_convert_bond_value[i_time + 1, i_node] + hold = p_up * fut_value_up + p_dn * fut_value_dn # p_up already embeds Q + hold_pv = df * hold + pDef * df * recovery_rate * face_amount \ + flow * face_amount - conv = treeConvertValue[i_time, i_node] - value = min(max(holdPV, conv, put), call) - treeConvBondValue[i_time, i_node] = value + conv = tree_convert_value[i_time, i_node] + value = min(max(hold_pv, conv, put), call) + tree_convert_bond_value[i_time, i_node] = value bullet_pv = df * bullet_pv * survival_prob bullet_pv += pDef * df * recovery_rate * face_amount bullet_pv += flow * face_amount - price = treeConvBondValue[0, 0] - delta = (treeConvBondValue[1, 1] - treeConvBondValue[1, 0]) / \ - (treeStockValue[1, 1] - treeStockValue[1, 0]) - delta_up = (treeConvBondValue[2, 3] - treeConvBondValue[2, 2]) / \ - (treeStockValue[2, 3] - treeStockValue[2, 2]) - delta_dn = (treeConvBondValue[2, 2] - treeConvBondValue[2, 1]) / \ - (treeStockValue[2, 2] - treeStockValue[2, 1]) - gamma = (delta_up - delta_dn) / (treeStockValue[1, 1] - treeStockValue[1, 0]) - theta = (treeConvBondValue[2, 2] - treeConvBondValue[0, 0]) / (2.0 * dt) + price = tree_convert_bond_value[0, 0] + delta = (tree_convert_bond_value[1, 1] - tree_convert_bond_value[1, 0]) / \ + (tree_stock_value[1, 1] - tree_stock_value[1, 0]) + delta_up = (tree_convert_bond_value[2, 3] - tree_convert_bond_value[2, 2]) / \ + (tree_stock_value[2, 3] - tree_stock_value[2, 2]) + delta_dn = (tree_convert_bond_value[2, 2] - tree_convert_bond_value[2, 1]) / \ + (tree_stock_value[2, 2] - tree_stock_value[2, 1]) + gamma = (delta_up - delta_dn) / \ + (tree_stock_value[1, 1] - tree_stock_value[1, 0]) + theta = (tree_convert_bond_value[2, 2] - + tree_convert_bond_value[0, 0]) / (2.0 * dt) results = np.array([price, bullet_pv, delta, gamma, theta]) return results diff --git a/financepy/products/bonds/bond_future.py b/financepy/products/bonds/bond_future.py index 3312fbfd..ff73e5c9 100644 --- a/financepy/products/bonds/bond_future.py +++ b/financepy/products/bonds/bond_future.py @@ -53,14 +53,14 @@ def conversion_factor(self, issue_dt = Date(new_mat._d, new_mat._m, 2000) - newBond = Bond(issue_dt, + new_bond = Bond(issue_dt, new_mat, bond._cpn, bond._freq_type, bond._dc_type, ex_div_days) - p = newBond.clean_price_from_ytm(self._first_delivery_dt, + p = new_bond.clean_price_from_ytm(self._first_delivery_dt, self._cpn) # Convention is to round the conversion factor to 4dp @@ -105,17 +105,18 @@ def cheapest_to_deliver(self, futures_price: float): """ Determination of CTD as deliverable bond with the lowest cost to buy versus what is received when the bond is delivered. """ - ctdBond = None - ctdNet = -self._contract_size * 100 + ctd_bond = None + ctd_net = -self._contract_size * 100 for bondCleanPrice, bond in zip(bond_clean_prices, bonds): - receiveOnFuture = self.principal_invoice_price(bond, futures_price) - payForBond = self._contract_size * bondCleanPrice / 100.0 - net = receiveOnFuture - payForBond - if net > ctdNet: - ctdBond = bond - ctdNet = net + receive_on_future = self.principal_invoice_price( + bond, futures_price) + pay_for_bond = self._contract_size * bondCleanPrice / 100.0 + net = receive_on_future - pay_for_bond + if net > ctd_net: + ctd_bond = bond + ctd_net = net - return ctdBond + return ctd_bond ############################################################################### @@ -124,10 +125,10 @@ def delivery_gain_loss(self, bond_clean_price: float, futures_price: float): """ Determination of what is received when the bond is delivered. """ - receiveOnFuture = self.principal_invoice_price(bond, futures_price) - payForBond = self._contract_size * bond_clean_price / 100.0 - net = receiveOnFuture - payForBond - return net, payForBond, receiveOnFuture + receive_on_future = self.principal_invoice_price(bond, futures_price) + pay_for_bond = self._contract_size * bond_clean_price / 100.0 + net = receive_on_future - pay_for_bond + return net, pay_for_bond, receive_on_future ############################################################################### diff --git a/financepy/products/bonds/bond_yield_curve.py b/financepy/products/bonds/bond_yield_curve.py index 29013096..0129ad8e 100644 --- a/financepy/products/bonds/bond_yield_curve.py +++ b/financepy/products/bonds/bond_yield_curve.py @@ -48,13 +48,13 @@ def __init__(self, fit_type = type(self._curve_fit) - yearsToMaturities = [] + years_to_maturities = [] for bond in bonds: years_to_maturity = (bond._maturity_dt - settle_dt)/gDaysInYear - yearsToMaturities.append(years_to_maturity) + years_to_maturities.append(years_to_maturity) - self._yearsToMaturity = np.array(yearsToMaturities) + self._yearsToMaturity = np.array(years_to_maturities) if fit_type is CurveFitPolynomial: @@ -67,8 +67,10 @@ def __init__(self, xdata = self._yearsToMaturity ydata = self._ylds - popt, pcov = scipy.optimize.curve_fit(curve_fit._interpolated_yield, - xdata, ydata, bounds=curve_fit._bounds) + popt, pcov = scipy.optimize.curve_fit(curve_fit._interp_yield, + xdata, + ydata, + bounds=curve_fit._bounds) curve_fit._beta_1 = popt[0] curve_fit._beta_2 = popt[1] @@ -80,7 +82,7 @@ def __init__(self, xdata = self._yearsToMaturity ydata = self._ylds - popt, pcov = scipy.optimize.curve_fit(curve_fit._interpolated_yield, + popt, pcov = scipy.optimize.curve_fit(curve_fit._interp_yield, xdata, ydata, bounds=curve_fit._bounds) curve_fit._beta_1 = popt[0] @@ -104,7 +106,7 @@ def __init__(self, ############################################################################### - def interpolated_yield(self, + def interp_yield(self, maturity_dt: Date): if isinstance(maturity_dt, Date): @@ -113,7 +115,7 @@ def interpolated_yield(self, t = maturity_dt elif isinstance(maturity_dt, np.ndarray): t = maturity_dt - elif isinstance(maturity_dt, float) or type(maturity_dt) is np.float64: + elif isinstance(maturity_dt, float) or isinstance(maturity_dt, np.float64): t = maturity_dt else: raise FinError("Unknown date type.") @@ -121,16 +123,16 @@ def interpolated_yield(self, fit = self._curve_fit if isinstance(fit, CurveFitPolynomial): - yld = fit._interpolated_yield(t) + yld = fit._interp_yield(t) elif isinstance(fit, CurveFitNelsonSiegel): - yld = fit._interpolated_yield(t, + yld = fit._interp_yield(t, fit._beta_1, fit._beta_2, fit._beta_3, fit._tau) elif isinstance(fit, CurveFitNelsonSiegelSvensson): - yld = fit._interpolated_yield(t, + yld = fit._interp_yield(t, fit._beta_1, fit._beta_2, fit._beta_3, @@ -139,7 +141,7 @@ def interpolated_yield(self, fit._tau_2) elif isinstance(fit, CurveFitBSpline): - yld = fit._interpolated_yield(t) + yld = fit._interp_yield(t) return yld @@ -159,7 +161,7 @@ def plot(self, tmax = np.max(self._yearsToMaturity) t = np.linspace(0.0, int(tmax+0.5), 100) - yld = self.interpolated_yield(t) + yld = self.interp_yield(t) yld = scale(yld, 100.0) plt.plot(t, yld, label=str(self._curve_fit)) plt.legend(loc='lower right') diff --git a/financepy/products/bonds/bond_zero.py b/financepy/products/bonds/bond_zero.py index a98d4e29..f714230c 100644 --- a/financepy/products/bonds/bond_zero.py +++ b/financepy/products/bonds/bond_zero.py @@ -3,7 +3,7 @@ from ...utils.date import Date from ...utils.error import FinError -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.day_count import DayCount, DayCountTypes from ...utils.schedule import Schedule from ...utils.calendar import Calendar @@ -299,9 +299,9 @@ def yield_to_maturity(self, """ Calculate the bond's yield to maturity by solving the price yield relationship using a one-dimensional root solver. """ - if type(clean_price) is float or type(clean_price) is np.float64: + if isinstance(clean_price, float) or isinstance(clean_price, np.float64): clean_prices = np.array([clean_price]) - elif type(clean_price) is list or type(clean_price) is np.ndarray: + elif isinstance(clean_price, list) or isinstance(clean_price, np.ndarray): clean_prices = np.array(clean_price) else: raise FinError("Unknown type for clean_price " @@ -359,7 +359,7 @@ def accrued_interest(self, dc = DayCount(self._dc_type) cal = Calendar(self._cal_type) - exDividend_dt = cal.add_business_days( + ex_dividend_dt = cal.add_business_days( self._ncd, -self._ex_div_days) (acc_factor, num, _) = dc.year_frac(self._pcd, @@ -367,7 +367,7 @@ def accrued_interest(self, self._ncd, FrequencyTypes.ZERO) - if settle_dt > exDividend_dt: + if settle_dt > ex_dividend_dt: acc_factor = acc_factor - 1.0 self._alpha = 1.0 - acc_factor @@ -391,9 +391,9 @@ def asset_swap_spread( clean_price: float, discount_curve: DiscountCurve, swapFloatDayCountConventionType=DayCountTypes.ACT_360, - swapFloatFrequencyType=FrequencyTypes.SEMI_ANNUAL, - swapFloatCalendarType=CalendarTypes.WEEKEND, - swapFloatBusDayAdjustRuleType=BusDayAdjustTypes.FOLLOWING, + swap_float_freq_type=FrequencyTypes.SEMI_ANNUAL, + swap_float_cal_type=CalendarTypes.WEEKEND, + swap_float_bus_day_adjust_rule_type=BusDayAdjustTypes.FOLLOWING, swapFloatDateGenRuleType=DateGenRuleTypes.BACKWARD): """ Calculate the par asset swap spread of the bond. The discount curve is a Ibor curve that is passed in. This function is vectorised with @@ -404,7 +404,7 @@ def asset_swap_spread( accrued_amount = self._accrued_interest * self._par bond_price = clean_price + accrued_amount # Calculate the price of the bond discounted on the Ibor curve - pvIbor = 0.0 + pv_ibor = 0.0 prev_dt = self._pcd for dt in self._cpn_dts[1:]: @@ -412,18 +412,18 @@ def asset_swap_spread( # coupons paid on the settlement date are paid to the seller if dt > settle_dt: df = discount_curve.df(dt) - # pvIbor += df * self._cpn / self._freq + # pv_ibor += df * self._cpn / self._freq - pvIbor += df * self._par + pv_ibor += df * self._par # Calculate the PV01 of the floating leg of the asset swap # I assume here that the coupon starts accruing on the settlement date prev_dt = self._pcd schedule = Schedule(settle_dt, self._maturity_dt, - swapFloatFrequencyType, - swapFloatCalendarType, - swapFloatBusDayAdjustRuleType, + swap_float_freq_type, + swap_float_cal_type, + swap_float_bus_day_adjust_rule_type, swapFloatDateGenRuleType) day_count = DayCount(swapFloatDayCountConventionType) @@ -436,7 +436,7 @@ def asset_swap_spread( pv01 = pv01 + year_frac * df prev_dt = dt - asw = (pvIbor - bond_price / self._par) / pv01 + asw = (pv_ibor - bond_price / self._par) / pv01 return asw ########################################################################### @@ -457,7 +457,7 @@ def dirty_price_from_oas(self, if dt > settle_dt: t = (dt - settle_dt) / gDaysInYear - t = np.maximum(t, gSmall) + t = np.maximum(t, g_small) df = discount_curve.df(dt) # determine the Ibor implied zero rate @@ -550,11 +550,11 @@ def dirty_price_from_survival_curve(self, end payment present values. """ pv = 0.0 - prevQ = 1.0 - prevDf = 1.0 + prev_q = 1.0 + prev_df = 1.0 - defaultingPrincipalPVPayStart = 0.0 - defaultingPrincipalPVPayEnd = 0.0 + defaulting_principal_pv_pay_start = 0.0 + defaulting_principal_pv_pay_end = 0.0 for dt in self._cpn_dts[1:]: @@ -567,17 +567,17 @@ def dirty_price_from_survival_curve(self, # Any default results in all subsequent coupons being lost # with zero recovery - dq = q - prevQ + dq = q - prev_q - defaultingPrincipalPVPayStart += -dq * recovery_rate * prevDf - defaultingPrincipalPVPayStart += -dq * recovery_rate * df + defaulting_principal_pv_pay_start += -dq * recovery_rate * prev_df + defaulting_principal_pv_pay_start += -dq * recovery_rate * df # Add on PV of principal if default occurs in coupon period - prevQ = q - prevDf = df + prev_q = q + prev_df = df - pv = pv + 0.50 * defaultingPrincipalPVPayStart - pv = pv + 0.50 * defaultingPrincipalPVPayEnd + pv = pv + 0.50 * defaulting_principal_pv_pay_start + pv = pv + 0.50 * defaulting_principal_pv_pay_end pv = pv + df * q * self._par pv *= self._par return pv diff --git a/financepy/products/bonds/bond_zero_curve.py b/financepy/products/bonds/bond_zero_curve.py index 37949bb0..25ad2a78 100644 --- a/financepy/products/bonds/bond_zero_curve.py +++ b/financepy/products/bonds/bond_zero_curve.py @@ -26,12 +26,12 @@ def _f(df, *args): curve = args[0] value_dt = args[1] bond = args[2] - marketCleanPrice = args[3] + mkt_clean_price = args[3] num_points = len(curve._times) curve._values[num_points - 1] = df - bondDiscountPrice = bond.clean_price_from_discount_curve( + bond_discount_price = bond.clean_price_from_discount_curve( value_dt, curve) - obj_fn = bondDiscountPrice - marketCleanPrice + obj_fn = bond_discount_price - mkt_clean_price return obj_fn ############################################################################### @@ -186,9 +186,9 @@ def __repr__(self): # TODO header = "TIMES,DISCOUNT FACTORS" s = label_to_string("OBJECT TYPE", type(self).__name__) - valueTable = [self._times, self._values] + value_table = [self._times, self._values] precision = "10.7f" - s += table_to_string(header, valueTable, precision) + s += table_to_string(header, value_table, precision) return s ############################################################################### diff --git a/financepy/products/bonds/curve_fits.py b/financepy/products/bonds/curve_fits.py index a8be8654..e1688f61 100644 --- a/financepy/products/bonds/curve_fits.py +++ b/financepy/products/bonds/curve_fits.py @@ -23,7 +23,7 @@ def __init__(self, power=3): self._power = power self._coeffs = [] - def _interpolated_yield(self, t): + def _interp_yield(self, t): yld = np.polyval(self._coeffs, t) return yld @@ -54,7 +54,7 @@ def __init__(self, tau=None, bounds=[(-1, -1, -1, 0.5), (1, 1, 1, 100)]): """ Fairly permissive bounds. Only tau_1 is 1-100 """ self._bounds = bounds - def _interpolated_yield(self, t, beta_1=None, beta_2=None, + def _interp_yield(self, t, beta_1=None, beta_2=None, beta_3=None, tau=None): t = np.maximum(t, 1e-10) @@ -112,7 +112,7 @@ def __init__(self, tau_1=None, tau_2=None, the user does not provide any bounds. Especially for tau_2. """ self._bounds = bounds - def _interpolated_yield(self, t, beta_1=None, beta_2=None, beta_3=None, + def _interp_yield(self, t, beta_1=None, beta_2=None, beta_3=None, beta_4=None, tau_1=None, tau_2=None): # Careful if we get a time zero point @@ -171,7 +171,7 @@ def __init__(self, power=3, knots=[1, 3, 5, 10]): self._knots = knots self._spline = None - def _interpolated_yield(self, t): + def _interp_yield(self, t): t = np.maximum(t, 1e-10) yld = splev(t, self._spline) return yld diff --git a/financepy/products/credit/cds.py b/financepy/products/credit/cds.py index 84bb4f70..66c4e307 100644 --- a/financepy/products/credit/cds.py +++ b/financepy/products/credit/cds.py @@ -21,9 +21,9 @@ from ...utils.helpers import check_argument_types -use_flat_hazard_rate_integral = True -standard_recovery_rate = 0.40 -glob_num_steps_per_year = 25 +USE_FLAT_HAZARD_RATE_INTEGRAL = True +STANDARD_RECOVERY_RATE = 0.40 +GLOB_NUM_STEPS_PER_YEAR = 25 ############################################################################### # TODO: Perform protection leg pv analytically using fact that hazard rate and @@ -37,13 +37,13 @@ float64[:], float64[:], float64[:], int64), fastmath=True, cache=True) def _risky_pv01_numba(teff, - accrual_factorPCDToNow, + accrual_factor_pcd_to_now, payment_times, year_fracs, - npIborTimes, - npIborValues, - npSurvTimes, - npSurvValues, + np_ibor_times, + np_ibor_values, + np_surv_times, + np_surv_values, pv01_method): """ Fast calculation of the risky PV01 of a CDS using NUMBA. The output is a numpy array of the full and clean risky PV01.""" @@ -53,11 +53,11 @@ def _risky_pv01_numba(teff, if 1 == 0: print("===================") print("Teff", teff) - print("Acc", accrual_factorPCDToNow) + print("Acc", accrual_factor_pcd_to_now) print("Payments", payment_times) print("Alphas", year_fracs) - print("QTimes", npSurvTimes) - print("QValues", npSurvValues) + print("QTimes", np_surv_times) + print("QValues", np_surv_values) cpnAccruedIndicator = 1 @@ -69,12 +69,12 @@ def _risky_pv01_numba(teff, # The first cpn is a special case which needs to be handled carefully # taking into account what cpn has already accrued and what has not - qeff = _uinterpolate(teff, npSurvTimes, npSurvValues, method) - q1 = _uinterpolate(tncd, npSurvTimes, npSurvValues, method) - z1 = _uinterpolate(tncd, npIborTimes, npIborValues, method) + qeff = _uinterpolate(teff, np_surv_times, np_surv_values, method) + q1 = _uinterpolate(tncd, np_surv_times, np_surv_values, method) + z1 = _uinterpolate(tncd, np_ibor_times, np_ibor_values, method) # this is the part of the cpn accrued from previous cpn date to now - # accrual_factorPCDToNow = day_count.year_frac(pcd,teff) + # accrual_factor_pcd_to_now = day_count.year_frac(pcd,teff) # reference credit survives to the premium payment date full_rpv01 = q1 * z1 * year_fracs[1] @@ -82,20 +82,20 @@ def _risky_pv01_numba(teff, # cpn accrued from previous cpn to today paid in full at default # before cpn payment full_rpv01 = full_rpv01 + z1 * \ - (qeff - q1) * accrual_factorPCDToNow * cpnAccruedIndicator + (qeff - q1) * accrual_factor_pcd_to_now * cpnAccruedIndicator # future accrued from now to cpn payment date assuming default roughly # midway full_rpv01 += 0.5 * z1 * \ - (qeff - q1) * (year_fracs[1] - accrual_factorPCDToNow) \ + (qeff - q1) * (year_fracs[1] - accrual_factor_pcd_to_now) \ * cpnAccruedIndicator for it in range(1, len(payment_times)): t2 = payment_times[it] - q2 = _uinterpolate(t2, npSurvTimes, npSurvValues, method) - z2 = _uinterpolate(t2, npIborTimes, npIborValues, method) + q2 = _uinterpolate(t2, np_surv_times, np_surv_values, method) + z2 = _uinterpolate(t2, np_ibor_times, np_ibor_values, method) accrual_factor = year_fracs[it] @@ -107,16 +107,16 @@ def _risky_pv01_numba(teff, if cpnAccruedIndicator == 1: - if use_flat_hazard_rate_integral: + if USE_FLAT_HAZARD_RATE_INTEGRAL: # This needs to be updated to handle small h+r tau = accrual_factor h12 = -log(q2 / q1) / tau r12 = -log(z2 / z1) / tau alpha = h12 + r12 - expTerm = 1.0 - exp(-alpha * tau) - alpha * \ + exp_term = 1.0 - exp(-alpha * tau) - alpha * \ tau * exp(-alpha * tau) d_full_rpv01 = q1 * z1 * h12 * \ - expTerm / abs(alpha * alpha + 1e-20) + exp_term / abs(alpha * alpha + 1e-20) else: d_full_rpv01 = 0.50 * (q1 - q2) * z2 * accrual_factor @@ -124,7 +124,7 @@ def _risky_pv01_numba(teff, q1 = q2 - clean_rpv01 = full_rpv01 - accrual_factorPCDToNow + clean_rpv01 = full_rpv01 - accrual_factor_pcd_to_now return np.array([full_rpv01, clean_rpv01]) @@ -133,12 +133,12 @@ def _risky_pv01_numba(teff, @njit(float64(float64, float64, float64[:], float64[:], float64[:], float64[:], float64, int64, int64), fastmath=True, cache=True) -def _protection_leg_pv_numba(teff, +def _prot_leg_pv_numba(teff, t_mat, - npIborTimes, - npIborValues, - npSurvTimes, - npSurvValues, + np_ibor_times, + np_ibor_values, + np_surv_times, + np_surv_values, contract_recovery_rate, num_steps_per_year, prot_method): @@ -151,23 +151,23 @@ def _protection_leg_pv_numba(teff, dt = (t_mat - teff) / num_steps t = teff - z1 = _uinterpolate(t, npIborTimes, npIborValues, method) - q1 = _uinterpolate(t, npSurvTimes, npSurvValues, method) + z1 = _uinterpolate(t, np_ibor_times, np_ibor_values, method) + q1 = _uinterpolate(t, np_surv_times, np_surv_values, method) prot_pv = 0.0 small = 1e-8 - if use_flat_hazard_rate_integral: + if USE_FLAT_HAZARD_RATE_INTEGRAL: for _ in range(0, num_steps): t = t + dt - z2 = _uinterpolate(t, npIborTimes, npIborValues, method) - q2 = _uinterpolate(t, npSurvTimes, npSurvValues, method) + z2 = _uinterpolate(t, np_ibor_times, np_ibor_values, method) + q2 = _uinterpolate(t, np_surv_times, np_surv_values, method) # This needs to be updated to handle small h+r h12 = -log(q2 / q1) / dt r12 = -log(z2 / z1) / dt - expTerm = exp(-(r12 + h12) * dt) - dprot_pv = h12 * (1.0 - expTerm) * q1 * z1 / \ + exp_term = exp(-(r12 + h12) * dt) + dprot_pv = h12 * (1.0 - exp_term) * q1 * z1 / \ (abs(h12 + r12) + small) prot_pv += dprot_pv q1 = q2 @@ -177,8 +177,8 @@ def _protection_leg_pv_numba(teff, for _ in range(0, num_steps): t += dt - z2 = _uinterpolate(t, npIborTimes, npIborValues, method) - q2 = _uinterpolate(t, npSurvTimes, npSurvValues, method) + z2 = _uinterpolate(t, np_ibor_times, np_ibor_values, method) + q2 = _uinterpolate(t, np_surv_times, np_surv_values, method) dq = q1 - q2 dprot_pv = 0.5 * (z1 + z2) * dq prot_pv += dprot_pv @@ -202,7 +202,7 @@ def __init__(self, maturity_dt_or_tenor: (Date, str), # Date or tenor running_cpn: float, # Annualised cpn on premium fee leg notional: float = ONE_MILLION, - long_protection: bool = True, + long_protect: bool = True, freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, dc_type: DayCountTypes = DayCountTypes.ACT_360, cal_type: CalendarTypes = CalendarTypes.WEEKEND, @@ -228,7 +228,7 @@ def __init__(self, self._maturity_dt = maturity_dt self._running_cpn = running_cpn self._notional = notional - self._long_protection = long_protection + self._long_protect = long_protect self._dc_type = dc_type self._dg_type = dg_type self._cal_type = cal_type @@ -356,7 +356,7 @@ def value(self, contract_recovery_rate, pv01_method=0, prot_method=0, - num_steps_per_year=glob_num_steps_per_year): + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR): """ Valuation of a CDS contract on a specific valuation date given an issuer curve and a contract recovery rate.""" @@ -364,28 +364,28 @@ def value(self, issuer_curve, pv01_method) - dirtyRPV01 = rpv01['dirty_rpv01'] + dirty_rpv01 = rpv01['dirty_rpv01'] clean_rpv01 = rpv01['clean_rpv01'] - prot_pv = self.protection_leg_pv(value_dt, + prot_pv = self.prot_leg_pv(value_dt, issuer_curve, contract_recovery_rate, num_steps_per_year, prot_method) - fwdDf = 1.0 + fwd_df = 1.0 - if self._long_protection: - longProt = +1 + if self._long_protect: + long_prot = +1 else: - longProt = -1 + long_prot = -1 - dirtyPV = fwdDf * longProt * \ - (prot_pv - self._running_cpn * dirtyRPV01 * self._notional) - clean_pv = fwdDf * longProt * \ + dirty_pv = fwd_df * long_prot * \ + (prot_pv - self._running_cpn * dirty_rpv01 * self._notional) + clean_pv = fwd_df * long_prot * \ (prot_pv - self._running_cpn * clean_rpv01 * self._notional) - return {'dirty_pv': dirtyPV, 'clean_pv': clean_pv} + return {'dirty_pv': dirty_pv, 'clean_pv': clean_pv} ########################################################################### @@ -395,7 +395,7 @@ def credit_dv01(self, contract_recovery_rate, pv01_method=0, prot_method=0, - num_steps_per_year=glob_num_steps_per_year): + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR): """ Calculation of the change in the value of the CDS contract for a one basis point change in the level of the CDS curve.""" @@ -433,7 +433,7 @@ def interest_dv01(self, contract_recovery_rate, pv01_method: int = 0, prot_method: int = 0, - num_steps_per_year=glob_num_steps_per_year): + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR): """ Calculation of the interest DV01 based on a simple bump of the discount factors and reconstruction of the CDS curve. """ @@ -449,15 +449,15 @@ def interest_dv01(self, bump = 0.0001 # 1 basis point - for depo in new_issuer_curve._libor_curve._usedDeposits: + for depo in new_issuer_curve._libor_curve._used_deposits: depo._deposit_rate += bump - for fra in new_issuer_curve._libor_curve._usedFRAs: + for fra in new_issuer_curve._libor_curve._used_fras: - fra._fraRate += bump + fra._fra_rate += bump - for swap in new_issuer_curve._libor_curve._usedSwaps: + for swap in new_issuer_curve._libor_curve._used_swaps: cpn = swap._fixed_leg._cpn swap._fixed_leg._cpn = cpn + bump @@ -493,7 +493,7 @@ def cash_settlement_amount(self, contract_recovery_rate, pv01_method=0, prot_method=0, - num_steps_per_year=glob_num_steps_per_year): + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR): """ Value of the contract on the settlement date including accrued interest. """ @@ -517,23 +517,23 @@ def clean_price(self, contract_recovery_rate, pv01_method=0, prot_method=0, - num_steps_per_year=glob_num_steps_per_year): + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR): """ Value of the CDS contract excluding accrued interest. """ risky_pv01 = self.risky_pv01(value_dt, issuer_curve, pv01_method) clean_rpv01 = risky_pv01['clean_rpv01'] - prot_pv = self.protection_leg_pv(value_dt, + prot_pv = self.prot_leg_pv(value_dt, issuer_curve, contract_recovery_rate, num_steps_per_year, prot_method) - fwdDf = 1.0 + fwd_df = 1.0 - clean_pv = fwdDf * (prot_pv - self._running_cpn * clean_rpv01 - * self._notional) + clean_pv = fwd_df * (prot_pv - self._running_cpn * clean_rpv01 + * self._notional) clean_price = (self._notional - clean_pv) / self._notional * 100.0 @@ -562,18 +562,18 @@ def accrued_interest(self): accrued_interest = accrual_factor * self._notional \ * self._running_cpn - if self._long_protection: + if self._long_protect: accrued_interest *= -1.0 return accrued_interest ########################################################################### - def protection_leg_pv(self, + def prot_leg_pv(self, value_dt, issuer_curve, - contract_recovery_rate=standard_recovery_rate, - num_steps_per_year=glob_num_steps_per_year, + contract_recovery_rate=STANDARD_RECOVERY_RATE, + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR, prot_method=0): """ Calculates the protection leg PV of the CDS by calling into the fast NUMBA code that has been defined above. """ @@ -583,7 +583,7 @@ def protection_leg_pv(self, libor_curve = issuer_curve._libor_curve - v = _protection_leg_pv_numba(teff, + v = _prot_leg_pv_numba(teff, t_mat, libor_curve._times, libor_curve._dfs, @@ -619,13 +619,13 @@ def risky_pv01(self, eff = self._step_in_dt day_count = DayCount(self._dc_type) - accrual_factorPCDToNow = day_count.year_frac(pcd, eff)[0] + accrual_factor_pcd_to_now = day_count.year_frac(pcd, eff)[0] year_fracs = self._accrual_factors teff = (eff - value_dt) / gDaysInYear - valueRPV01 = _risky_pv01_numba(teff, - accrual_factorPCDToNow, + value_rpv01 = _risky_pv01_numba(teff, + accrual_factor_pcd_to_now, np.array(payment_times), np.array(year_fracs), libor_curve._times, @@ -634,8 +634,8 @@ def risky_pv01(self, issuer_curve._values, pv01_method) - full_rpv01 = valueRPV01[0] - clean_rpv01 = valueRPV01[1] + full_rpv01 = value_rpv01[0] + clean_rpv01 = value_rpv01[1] return {'dirty_rpv01': full_rpv01, 'clean_rpv01': clean_rpv01} @@ -648,8 +648,8 @@ def premium_leg_pv(self, """ Value of the premium leg of a CDS. """ full_rpv01 = self.risky_pv01(value_dt, - issuer_curve, - pv01_method)['dirty_rpv01'] + issuer_curve, + pv01_method)['dirty_rpv01'] v = full_rpv01 * self._notional * self._running_cpn return v @@ -659,18 +659,18 @@ def premium_leg_pv(self, def par_spread(self, value_dt, issuer_curve, - contract_recovery_rate=standard_recovery_rate, - num_steps_per_year=glob_num_steps_per_year, + contract_recovery_rate=STANDARD_RECOVERY_RATE, + num_steps_per_year=GLOB_NUM_STEPS_PER_YEAR, pv01_method=0, prot_method=0): """ Breakeven CDS cpn that would make the value of the CDS contract equal to zero. """ clean_rpv01 = self.risky_pv01(value_dt, - issuer_curve, - pv01_method)['clean_rpv01'] + issuer_curve, + pv01_method)['clean_rpv01'] - prot = self.protection_leg_pv(value_dt, + prot = self.prot_leg_pv(value_dt, issuer_curve, contract_recovery_rate, num_steps_per_year, @@ -686,8 +686,8 @@ def value_fast_approx(self, value_dt, flat_cont_interest_rate, flat_cds_curve_spread, - curve_recovery=standard_recovery_rate, - contract_recovery_rate=standard_recovery_rate): + curve_recovery=STANDARD_RECOVERY_RATE, + contract_recovery_rate=STANDARD_RECOVERY_RATE): """ Implementation of fast valuation of the CDS contract using an accurate approximation that avoids curve building. """ @@ -700,13 +700,13 @@ def value_fast_approx(self, h = flat_cds_curve_spread / (1.0 - curve_recovery) r = flat_cont_interest_rate - fwdDf = 1.0 + fwd_df = 1.0 bump_size = 0.0001 - if self._long_protection: - long_protection = +1 + if self._long_protect: + long_protect = +1 else: - long_protection = -1 + long_protect = -1 # The sign of he accrued has already been sign adjusted for direction accrued = self.accrued_interest() @@ -719,24 +719,25 @@ def value_fast_approx(self, z = np.exp(-w * t_eff) - np.exp(-w * t_mat) clean_rpv01 = (z / w) * 365.0 / 360.0 prot_pv = h * (1.0 - contract_recovery_rate) * (z / w) * self._notional - clean_pv = fwdDf * long_protection * \ + clean_pv = fwd_df * long_protect * \ (prot_pv - self._running_cpn * clean_rpv01 * self._notional) - full_pv = clean_pv + fwdDf * accrued + full_pv = clean_pv + fwd_df * accrued ####################################################################### # bump CDS spread and calculate ####################################################################### - h = (flat_cds_curve_spread + bump_size) / (1.0 - contract_recovery_rate) + h = (flat_cds_curve_spread + bump_size) / \ + (1.0 - contract_recovery_rate) r = flat_cont_interest_rate w = r + h z = np.exp(-w * t_eff) - np.exp(-w * t_mat) clean_rpv01 = (z / w) * 365.0 / 360.0 prot_pv = h * (1.0 - contract_recovery_rate) * (z / w) * self._notional - clean_pv_credit_bumped = fwdDf * long_protection * \ + clean_pv_credit_bumped = fwd_df * long_protect * \ (prot_pv - self._running_cpn * clean_rpv01 * self._notional) full_pv_credit_bumped = clean_pv_credit_bumped \ - + fwdDf * long_protection * accrued + + fwd_df * long_protect * accrued credit01 = full_pv_credit_bumped - full_pv ####################################################################### @@ -753,10 +754,10 @@ def value_fast_approx(self, prot_pv = h * (1.0 - contract_recovery_rate) * (z / w) * self._notional - clean_pv_ir_bumped = fwdDf * long_protection * \ + clean_pv_ir_bumped = fwd_df * long_protect * \ (prot_pv - self._running_cpn * clean_rpv01 * self._notional) - full_pv_ir_bumped = clean_pv_ir_bumped + fwdDf * long_protection * accrued + full_pv_ir_bumped = clean_pv_ir_bumped + fwd_df * long_protect * accrued ir01 = full_pv_ir_bumped - full_pv diff --git a/financepy/products/credit/cds_basket.py b/financepy/products/credit/cds_basket.py index ae79293d..d8b3c59d 100644 --- a/financepy/products/credit/cds_basket.py +++ b/financepy/products/credit/cds_basket.py @@ -41,7 +41,7 @@ def __init__(self, maturity_dt: Date, notional: float = ONE_MILLION, running_cpn: float = 0.0, - long_protection: bool = True, + long_protect: bool = True, freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, dc_type: DayCountTypes = DayCountTypes.ACT_360, cal_type: CalendarTypes = CalendarTypes.WEEKEND, @@ -54,7 +54,7 @@ def __init__(self, self._maturity_dt = maturity_dt self._notional = notional self._running_cpn = running_cpn / 10000.0 - self._long_protection = long_protection + self._long_protect = long_protect self._dc_type = dc_type self._dg_type = dg_type self._cal_type = cal_type @@ -65,7 +65,7 @@ def __init__(self, self._maturity_dt, self._running_cpn, 1.0, - self._long_protection, + self._long_protect, self._freq_type, self._dc_type, self._cal_type, @@ -92,7 +92,7 @@ def value_legs_mc(self, avg_acc_factor = 0.0 - rpv01ToTimes = np.zeros(num_payments) + rpv01_to_times = np.zeros(num_payments) for i_time in range(1, num_payments): @@ -101,7 +101,7 @@ def value_legs_mc(self, dt1 = payment_dts[i_time] accrual_factor = day_count.year_frac(dt0, dt1)[0] avg_acc_factor += accrual_factor - rpv01ToTimes[i_time] = rpv01ToTimes[i_time - 1] + \ + rpv01_to_times[i_time] = rpv01_to_times[i_time - 1] + \ accrual_factor * libor_curve._df(t) avg_acc_factor /= num_payments @@ -111,40 +111,40 @@ def value_legs_mc(self, rpv01 = 0.0 prot = 0.0 - assetTau = np.zeros(num_credits) + asset_tau = np.zeros(num_credits) for i_trial in range(0, num_trials): for i_credit in range(0, num_credits): - assetTau[i_credit] = default_times[i_credit, i_trial] + asset_tau[i_credit] = default_times[i_credit, i_trial] # ORDER THE DEFAULT TIMES - assetTau.sort() + asset_tau.sort() # GET THE Nth DEFAULT TIME - minTau = assetTau[n_to_default - 1] + min_tau = asset_tau[n_to_default - 1] - if minTau < t_mat: + if min_tau < t_mat: - num_pmnts_index = int(minTau / avg_acc_factor) - rpv01_trial = rpv01ToTimes[num_pmnts_index] - rpv01_trial += (minTau - num_pmnts_index * avg_acc_factor) + num_pmnts_index = int(min_tau / avg_acc_factor) + rpv01_trial = rpv01_to_times[num_pmnts_index] + rpv01_trial += (min_tau - num_pmnts_index * avg_acc_factor) # DETERMINE IDENTITY OF N-TO-DEFAULT CREDIT IF BASKET NOT HOMO - assetIndex = 0 + asset_index = 0 for i_credit in range(0, num_credits): - if minTau == default_times[i_credit, i_trial]: - assetIndex = i_credit + if min_tau == default_times[i_credit, i_trial]: + asset_index = i_credit break - prot_trial = (1.0 - issuer_curves[assetIndex]._recovery_rate) - prot_trial *= libor_curve._df(minTau) + prot_trial = (1.0 - issuer_curves[asset_index]._recovery_rate) + prot_trial *= libor_curve._df(min_tau) else: num_pmnts_index = int(t_mat / avg_acc_factor) - rpv01_trial = rpv01ToTimes[-1] + rpv01_trial = rpv01_to_times[-1] prot_trial = 0.0 rpv01 += rpv01_trial @@ -160,7 +160,7 @@ def value_gaussian_mc(self, value_dt, n_to_default, issuer_curves, - correlation_matrix, + corr_matrix, libor_curve, num_trials, seed): @@ -173,7 +173,7 @@ def value_gaussian_mc(self, raise FinError("n_to_default must be 1 to num_credits") default_times = default_times_gc(issuer_curves, - correlation_matrix, + corr_matrix, num_trials, seed) @@ -186,7 +186,7 @@ def value_gaussian_mc(self, spd = prot_pv / rpv01 value = self._notional * (prot_pv - self._running_cpn * rpv01) - if not self._long_protection: + if not self._long_protect: value = value * -1.0 return (value, rpv01, spd) @@ -197,7 +197,7 @@ def value_student_t_mc(self, value_dt, n_to_default, issuer_curves, - correlation_matrix, + corr_matrix, degrees_of_freedom, libor_curve, num_trials, @@ -212,7 +212,7 @@ def value_student_t_mc(self, model = StudentTCopula() default_times = model.default_times(issuer_curves, - correlation_matrix, + corr_matrix, degrees_of_freedom, num_trials, seed) @@ -226,7 +226,7 @@ def value_student_t_mc(self, spd = prot_pv / rpv01 value = self._notional * (prot_pv - self._running_cpn * rpv01) - if not self._long_protection: + if not self._long_protect: value = value * -1.0 return (value, rpv01, spd) @@ -279,13 +279,13 @@ def value_1f_gaussian_homo(self, InterpTypes.FLAT_FWD_RATES.value) loss_dbn = homog_basket_loss_dbn(issuer_surv_probs, - recovery_rates, - beta_vector, - num_points) + recovery_rates, + beta_vector, + num_points) basket_surv_curve[i_time] = 1.0 - for iToDefault in range(n_to_default, num_credits + 1): - basket_surv_curve[i_time] -= loss_dbn[iToDefault] + for i_to_default in range(n_to_default, num_credits + 1): + basket_surv_curve[i_time] -= loss_dbn[i_to_default] basket_times[i_time] = t @@ -295,7 +295,7 @@ def value_1f_gaussian_homo(self, basket_curve._times = basket_times basket_curve._values = basket_surv_curve - prot_leg_pv = self._cds_contract.protection_leg_pv( + prot_leg_pv = self._cds_contract.prot_leg_pv( value_dt, basket_curve, curve_recovery) risky_pv01 = self._cds_contract.risky_pv01( value_dt, basket_curve)['clean_rpv01'] @@ -303,16 +303,16 @@ def value_1f_gaussian_homo(self, # Long protection mtm = self._notional * (prot_leg_pv - risky_pv01 * self._running_cpn) - if not self._long_protection: + if not self._long_protect: mtm *= -1.0 - basketOutput = np.zeros(4) - basketOutput[0] = mtm - basketOutput[1] = risky_pv01 * self._notional * self._running_cpn - basketOutput[2] = prot_leg_pv * self._notional - basketOutput[3] = prot_leg_pv / risky_pv01 + basket_output = np.zeros(4) + basket_output[0] = mtm + basket_output[1] = risky_pv01 * self._notional * self._running_cpn + basket_output[2] = prot_leg_pv * self._notional + basket_output[3] = prot_leg_pv / risky_pv01 - return basketOutput + return basket_output ############################################################################### @@ -332,9 +332,9 @@ def __repr__(self): s += label_to_string("DATEGENRULE", self._dg_type) # header = "PAYMENT_dt, YEAR_FRAC, FLOW" -# valueTable = [self._payment_dts, self._accrual_factors, self._flows] +# value_table = [self._payment_dts, self._accrual_factors, self._flows] # precision = "12.6f" -# s += tableToString(header, valueTable, precision) +# s += tableToString(header, value_table, precision) return s diff --git a/financepy/products/credit/cds_index_option.py b/financepy/products/credit/cds_index_option.py index 7ce855f6..a416b7dd 100644 --- a/financepy/products/credit/cds_index_option.py +++ b/financepy/products/credit/cds_index_option.py @@ -11,7 +11,7 @@ from ...utils.day_count import DayCount, DayCountTypes from ...utils.frequency import FrequencyTypes from ...utils.global_vars import gDaysInYear -from ...utils.math import ONE_MILLION, INVROOT2PI, N +from ...utils.math import ONE_MILLION, inv_root_two_pi, N from ...utils.error import FinError from ...products.credit.cds_curve import CDSCurve from ...products.credit.cds import CDS @@ -25,7 +25,6 @@ class CDSIndexOption: - """ Class to manage the pricing and risk management of an option to enter into a CDS index. Different pricing algorithms are presented.""" @@ -35,14 +34,15 @@ def __init__(self, index_coupon: float, strike_coupon: float, notional: float = ONE_MILLION, - long_protection: bool = True, + long_protect: bool = True, freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, dc_type: DayCountTypes = DayCountTypes.ACT_360, cal_type: CalendarTypes = CalendarTypes.WEEKEND, bd_type: BusDayAdjustTypes = BusDayAdjustTypes.FOLLOWING, dg_type: DateGenRuleTypes = DateGenRuleTypes.BACKWARD): - """ Initialisation of the class object. Note that a large number of the - inputs are set to default values in line with the standard contract.""" + """ Initialisation of the class object. Note that a + large number of the inputs are set to default values in line with + the standard contract.""" check_argument_types(self.__init__, locals()) @@ -58,21 +58,21 @@ def __init__(self, self._expiry_dt = expiry_dt self._maturity_dt = maturity_dt self._index_coupon = index_coupon - self._strike_coupon = strike_coupon + self._strike_coupon = strike_coupon self._notional = notional - self._long_protection = long_protection + self._long_protect = long_protect self._dc_type = dc_type self._dg_type = dg_type self._cal_type = cal_type - self._freq_type = freq_type + self._freq_type = freq_type self._bd_type = bd_type self._cds_contract = CDS(self._expiry_dt, self._maturity_dt, self._index_coupon, 1.0, - self._long_protection, + self._long_protect, self._freq_type, self._dc_type, self._cal_type, @@ -82,19 +82,20 @@ def __init__(self, ############################################################################### def value_adjusted_black(self, - value_dt, - index_curve, - index_recovery, - libor_curve, - sigma): - """ This approach uses two adjustments to Black's option pricing + value_dt, + index_curve, + index_recovery, + libor_curve, + sigma): + """ This approach uses two adjustments to black's option pricing model to value an option on a CDS index. """ k = self._strike_coupon c = self._index_coupon time_to_expiry = (self._expiry_dt - value_dt) / gDaysInYear df = libor_curve.df(self._expiry_dt) - q_expiry_index = index_curve.survival_prob(time_to_expiry) + q_expiry_index = index_curve.survival_prob( + time_to_expiry) cds = CDS(value_dt, self._maturity_dt, k) strike_curve = CDSCurve( @@ -155,9 +156,10 @@ def value_anderson(self, 1.0) strike_curve = CDSCurve(value_dt, [strike_cds], libor_curve, - index_recovery) + index_recovery) strike_rpv01s = strike_cds.risky_pv01(value_dt, strike_curve) - q_to_expiry = strike_curve.survival_prob(time_to_expiry) + q_to_expiry = strike_curve.survival_prob( + time_to_expiry) strike_value = (k - c) * strike_rpv01s['clean_rpv01'] strike_value /= (df_to_expiry * q_to_expiry) @@ -221,10 +223,10 @@ def _solve_for_x(self, rtb = 999999 f = self._calc_obj_func(x1, value_dt, sigma, index_coupon, - index_recovery, libor_curve) - exp_h + index_recovery, libor_curve) - exp_h fmid = self._calc_obj_func(x2, value_dt, sigma, index_coupon, - index_recovery, libor_curve) - exp_h + index_recovery, libor_curve) - exp_h if f * fmid >= 0.0: raise FinError("Solution not bracketed.") @@ -240,8 +242,8 @@ def _solve_for_x(self, dx = dx * 0.5 xmid = rtb + dx fmid = self._calc_obj_func(xmid, value_dt, sigma, - index_coupon, - index_recovery, libor_curve) - exp_h + index_coupon, + index_recovery, libor_curve) - exp_h if fmid <= 0.0: rtb = xmid if abs(dx) < xacc or abs(fmid) < ftol: @@ -252,12 +254,12 @@ def _solve_for_x(self, ############################################################################### def _calc_obj_func(self, - x, - value_dt, - sigma, - index_coupon, # TODO - do I need this input ? - index_recovery, - libor_curve): + x, + value_dt, + sigma, + index_coupon, # TODO - do I need this input ? + index_recovery, + libor_curve): """ An internal function used in the Anderson valuation. """ # The strike value is not relevant here as we want the zeroth element @@ -302,8 +304,10 @@ def _calc_index_payer_option_price(self, expiry_to_flow_times = [1.0] * (num_flows) for i_flow in range(0, num_flows): - expiry_to_flow_times[i_flow] = (flow_dts[i_flow] - self._expiry_dt) / gDaysInYear - fwd_dfs[i_flow] = libor_curve.df(flow_dts[i_flow]) / df_to_expiry + expiry_to_flow_times[i_flow] = ( + flow_dts[i_flow] - self._expiry_dt) / gDaysInYear + fwd_dfs[i_flow] = libor_curve.df( + flow_dts[i_flow]) / df_to_expiry int_h = 0.0 int_max_h = 0.0 @@ -329,8 +333,10 @@ def _calc_index_payer_option_price(self, fwd_rpv01 = 0.0 for i_flow in range(1, num_flows): acc_factor = self._cds_contract._accrual_factors[i_flow] - surv_prob = exp(-s * expiry_to_flow_times[i_flow] / lgd) - fwd_rpv01 += acc_factor * surv_prob * fwd_dfs[i_flow] + surv_prob = exp(-s * + expiry_to_flow_times[i_flow] / lgd) + fwd_rpv01 += acc_factor * \ + surv_prob * fwd_dfs[i_flow] fwd_rpv01 += -accrual_factor_pcd_to_expiry h = (s - index_coupon) * fwd_rpv01 @@ -339,8 +345,8 @@ def _calc_index_payer_option_price(self, int_h += h * pdf int_max_h += maxh * pdf - int_h *= INVROOT2PI * dz - int_max_h *= INVROOT2PI * dz * df_to_expiry + int_h *= inv_root_two_pi * dz + int_max_h *= inv_root_two_pi * dz * df_to_expiry return int_h, int_max_h ############################################################################### @@ -353,7 +359,7 @@ def __repr__(self): s += label_to_string("MATURITY DATE", self._maturity_dt) s += label_to_string("INDEX COUPON", self._index_coupon*10000, "bp\n") s += label_to_string("NOTIONAL", self._notional) - s += label_to_string("LONG PROTECTION", self._long_protection) + s += label_to_string("LONG PROTECTION", self._long_protect) s += label_to_string("FREQUENCY", self._freq_type) s += label_to_string("DAYCOUNT", self._dc_type) s += label_to_string("CALENDAR", self._cal_type) diff --git a/financepy/products/credit/cds_index_portfolio.py b/financepy/products/credit/cds_index_portfolio.py index 8eee673f..0ab7a641 100644 --- a/financepy/products/credit/cds_index_portfolio.py +++ b/financepy/products/credit/cds_index_portfolio.py @@ -62,19 +62,19 @@ def intrinsic_rpv01(self, intrinsic_rpv01 = 0.0 for m in range(0, num_credits): - retValue = cds_contract.risky_pv01(value_dt, + ret_value = cds_contract.risky_pv01(value_dt, issuer_curves[m]) - cleanRPV01 = retValue['clean_rpv01'] + clean_rpv01 = ret_value['clean_rpv01'] - intrinsic_rpv01 += cleanRPV01 + intrinsic_rpv01 += clean_rpv01 intrinsic_rpv01 /= num_credits return (intrinsic_rpv01) ########################################################################### - def intrinsic_protection_leg_pv(self, + def intrinsic_prot_leg_pv(self, value_dt, step_in_dt, maturity_dt, @@ -93,10 +93,10 @@ def intrinsic_protection_leg_pv(self, 1.0) for m in range(0, num_credits): - protectionPV = cds_contract.protection_leg_pv(value_dt, + prot_pv = cds_contract.prot_leg_pv(value_dt, issuer_curves[m]) - intrinsic_prot_pv += protectionPV + intrinsic_prot_pv += prot_pv intrinsic_prot_pv /= num_credits return intrinsic_prot_pv @@ -112,7 +112,7 @@ def intrinsic_spread(self, which would make the value of the protection legs equal to the value of the premium legs if all premium legs paid the same spread. """ - intrinsic_prot_pv = self.intrinsic_protection_leg_pv(value_dt, + intrinsic_prot_pv = self.intrinsic_prot_leg_pv(value_dt, step_in_dt, maturity_dt, issuer_curves) @@ -166,13 +166,13 @@ def total_spread(self, maturity_dt, 0.0) - totalSpread = 0.0 + total_spd = 0.0 for m in range(0, num_credits): spread = cds_contract.par_spread(value_dt, issuer_curves[m]) - totalSpread += spread + total_spd += spread - return totalSpread + return total_spd ########################################################################### @@ -332,7 +332,7 @@ def spread_adjust_intrinsic(self, libor_curve, recovery_rate) - index_protection_pv = cds_index.protection_leg_pv(value_dt, + index_prot_pv = cds_index.prot_leg_pv(value_dt, adjusted_issuer_curve, index_recovery_rate) @@ -340,7 +340,7 @@ def spread_adjust_intrinsic(self, adjusted_issuer_curve)['clean_rpv01'] sum_rpv01 += clean_rpv01 - sum_prot += index_protection_pv + sum_prot += index_prot_pv sum_rpv01 /= num_credits sum_prot /= num_credits @@ -446,20 +446,20 @@ def hazard_rate_adjust_intrinsic(self, raise FinError("Max Iterations exceeded") sum_rpv01 = 0.0 - sumProt = 0.0 + sum_prot = 0.0 for i_credit in range(0, num_credits): q1 = adjusted_issuer_curves[i_credit]._values[i_maturity] q2 = adjusted_issuer_curves[i_credit]._values[i_maturity + 1] q12 = q2 / q1 - q12NEW = pow(q12, ratio) - q2NEW = q1 * q12NEW + q12_new = pow(q12, ratio) + q2_new = q1 * q12_new - adjusted_issuer_curves[i_credit]._values[i_maturity + 1] = q2NEW + adjusted_issuer_curves[i_credit]._values[i_maturity + 1] = q2_new # if i_maturity == 0 and index_cpns[0] == 0.006: - # print(i_credit, q1, q2NEW) + # print(i_credit, q1, q2_new) index_maturity_dt = index_maturity_dts[i_maturity] @@ -470,27 +470,27 @@ def hazard_rate_adjust_intrinsic(self, 0, 1.0) - indexProtPV = cds_index.protection_leg_pv(value_dt, + index_prot_pv = cds_index.prot_leg_pv(value_dt, adjusted_issuer_curves[i_credit], index_recovery_rate) - rpv01Ret = cds_index.risky_pv01(value_dt, + rpv01_ret = cds_index.risky_pv01(value_dt, adjusted_issuer_curves[i_credit]) - cleanRPV01 = rpv01Ret['clean_rpv01'] + clean_rpv01 = rpv01_ret['clean_rpv01'] - sum_rpv01 += cleanRPV01 - sumProt += indexProtPV + sum_rpv01 += clean_rpv01 + sum_prot += index_prot_pv sum_rpv01 /= num_credits - sumProt /= num_credits + sum_prot /= num_credits - spd = sumProt / sum_rpv01 + spd = sum_prot / sum_rpv01 - sumPrem = sum_rpv01 * index_cpns[i_maturity] + sum_prem = sum_rpv01 * index_cpns[i_maturity] - numerator = index_up_fronts[i_maturity] + sumPrem - denominator = sumProt + numerator = index_up_fronts[i_maturity] + sum_prem + denominator = sum_prot ratio = numerator / denominator alpha *= ratio diff --git a/financepy/products/credit/cds_option.py b/financepy/products/credit/cds_option.py index 3acbccc9..7bcd7940 100644 --- a/financepy/products/credit/cds_option.py +++ b/financepy/products/credit/cds_option.py @@ -118,13 +118,13 @@ def value(self, value_dt, issuer_curve)['dirty_rpv01'] time_to_expiry = (self._expiry_dt - value_dt) / gDaysInYear - logMoneyness = log(forward_spread / strike) + log_moneyness = log(forward_spread / strike) - halfVolSquaredT = 0.5 * volatility * volatility * time_to_expiry - volSqrtT = volatility * sqrt(time_to_expiry) + half_vol_squared_t = 0.5 * volatility * volatility * time_to_expiry + vol_sqrt_t = volatility * sqrt(time_to_expiry) - d1 = (logMoneyness + halfVolSquaredT) / volSqrtT - d2 = (logMoneyness - halfVolSquaredT) / volSqrtT + d1 = (log_moneyness + half_vol_squared_t) / vol_sqrt_t + d2 = (log_moneyness - half_vol_squared_t) / vol_sqrt_t if self._long_protection: option_value = forward_spread * N(d1) - strike * N(d2) @@ -140,8 +140,8 @@ def value(self, df = issuer_curve.getDF(time_to_expiry) q = issuer_curve.getSurvProb(time_to_expiry) recovery = issuer_curve._recovery_rate - frontEndProtection = df * (1.0 - q) * (1.0 - recovery) - option_value += frontEndProtection + front_end_protection = df * (1.0 - q) * (1.0 - recovery) + option_value += front_end_protection # we return the option price in dollars return option_value * self._notional diff --git a/financepy/products/credit/cds_tranche.py b/financepy/products/credit/cds_tranche.py index ad2de17b..2f399535 100644 --- a/financepy/products/credit/cds_tranche.py +++ b/financepy/products/credit/cds_tranche.py @@ -34,7 +34,6 @@ class FinLossDistributionBuilder(Enum): - ''' Method for constructing loss distributions numerically ''' RECURSION = 1 ADJUSTED_BINOMIAL = 2 GAUSSIAN = 3 @@ -53,7 +52,7 @@ def __init__(self, k2: float, notional: float = ONE_MILLION, running_cpn: float = 0.0, - long_protection: bool = True, + long_protect: bool = True, freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, dc_type: DayCountTypes = DayCountTypes.ACT_360, cal_type: CalendarTypes = CalendarTypes.WEEKEND, @@ -72,7 +71,7 @@ def __init__(self, self._maturity_dt = maturity_dt self._notional = notional self._running_cpn = running_cpn - self._long_protection = long_protection + self._long_protect = long_protect self._dc_type = dc_type self._dg_type = dg_type self._cal_type = cal_type @@ -85,7 +84,7 @@ def __init__(self, self._maturity_dt, self._running_cpn, notional, - self._long_protection, + self._long_protect, self._freq_type, self._dc_type, self._cal_type, @@ -160,11 +159,11 @@ def value_bc(self, for j in range(0, num_credits): issuer_curve = issuer_curves[j] - vTimes = issuer_curve._times - qRow = issuer_curve._values + v_times = issuer_curve._times + q_row = issuer_curve._values recovery_rates[j] = issuer_curve._recovery_rate q_vector[j] = interpolate( - t, vTimes, qRow, InterpTypes.FLAT_FWD_RATES.value) + t, v_times, q_row, InterpTypes.FLAT_FWD_RATES.value) if model == FinLossDistributionBuilder.RECURSION: @@ -198,10 +197,10 @@ def value_bc(self, elif model == FinLossDistributionBuilder.LHP: - qt1[i] = tr_surv_prob_lhp(0.0, k1, num_credits, + qt1[i] = tr_surv_prob_lhp(0.0, k1, num_credits, q_vector, recovery_rates, beta_1) - qt2[i] = tr_surv_prob_lhp(0.0, k2, num_credits, + qt2[i] = tr_surv_prob_lhp(0.0, k2, num_credits, q_vector, recovery_rates, beta_2) else: @@ -226,21 +225,22 @@ def value_bc(self, tranche_curve._times = tranche_times tranche_curve._values = tranche_surv_curve - protLegPV = self._cds_contract.protection_leg_pv( + prot_leg_pv = self._cds_contract.prot_leg_pv( value_dt, tranche_curve, curve_recovery) risky_pv01 = self._cds_contract.risky_pv01( value_dt, tranche_curve)['clean_rpv01'] - mtm = self._notional * (protLegPV - upfront - risky_pv01 * running_cpn) + mtm = self._notional * (prot_leg_pv - upfront - + risky_pv01 * running_cpn) - if not self._long_protection: + if not self._long_protect: mtm *= -1.0 tranche_output = np.zeros(4) tranche_output[0] = mtm tranche_output[1] = risky_pv01 * self._notional * running_cpn - tranche_output[2] = protLegPV * self._notional - tranche_output[3] = protLegPV / risky_pv01 + tranche_output[2] = prot_leg_pv * self._notional + tranche_output[3] = prot_leg_pv / risky_pv01 return tranche_output diff --git a/financepy/products/equity/equity_asian_option.py b/financepy/products/equity/equity_asian_option.py index 9b540f97..20e663a1 100644 --- a/financepy/products/equity/equity_asian_option.py +++ b/financepy/products/equity/equity_asian_option.py @@ -25,7 +25,6 @@ ############################################################################### class AsianOptionValuationMethods(Enum): - ''' Types of Asian Option valuation methods ''' GEOMETRIC = 1, TURNBULL_WAKEMAN = 2, CURRAN = 3 @@ -461,7 +460,7 @@ def _value_geometric(self, value_dt, stock_price, discount_curve, K = self._strike_price n = self._num_observations - S0 = stock_price + s0 = stock_price multiplier = 1.0 @@ -482,12 +481,12 @@ def _value_geometric(self, value_dt, stock_price, discount_curve, sigSq = volatility ** 2 meanGeo = (r - q - sigSq / 2.0) * (t0 + (t_exp - t0) / 2.0) varGeo = sigSq * (t0 + (t_exp - t0) * (2 * n - 1) / (6 * n)) - EG = S0 * np.exp(meanGeo + varGeo / 2.0) + EG = s0 * np.exp(meanGeo + varGeo / 2.0) if np.abs(varGeo) < 1e-10: raise FinError("Asian option geometric variance is zero.") - d1 = (meanGeo + np.log(S0 / K) + varGeo) / np.sqrt(varGeo) + d1 = (meanGeo + np.log(s0 / K) + varGeo) / np.sqrt(varGeo) d2 = d1 - np.sqrt(varGeo) # the Geometric price is the lower bound @@ -525,7 +524,7 @@ def _value_curran(self, value_dt, stock_price, discount_curve, volatility = model._volatility - S0 = stock_price + s0 = stock_price b = r - q sigma2 = volatility**2 K = self._strike_price @@ -551,8 +550,8 @@ def _value_curran(self, value_dt, stock_price, discount_curve, w = (1.0 - np.exp((2 * b + sigma2) * h * n)) / \ (1.0 - np.exp((2 * b + sigma2) * h)) - FA = (S0 / n) * np.exp(b * t0) * u - EA2 = (S0 * S0 / n / n) * np.exp((2.0 * b + sigma2) * t0) + FA = (s0 / n) * np.exp(b * t0) * u + EA2 = (s0 * s0 / n / n) * np.exp((2.0 * b + sigma2) * t0) EA2 = EA2 * (w + 2.0 / (1.0 - np.exp((b + sigma2) * h)) * (u - w)) sigmaA = np.sqrt((np.log(EA2) - 2.0 * np.log(FA)) / t_exp) @@ -613,7 +612,7 @@ def _value_turnbull_wakeman(self, value_dt, stock_price, discount_curve, sigma2 = volatility**2 a1 = b + sigma2 a2 = 2 * b + sigma2 - S0 = stock_price + s0 = stock_price dt = t_exp - t0 @@ -623,10 +622,10 @@ def _value_turnbull_wakeman(self, value_dt, stock_price, discount_curve, np.exp(sigma2 * t0) * (1.0 + sigma2 * dt) M2 = M2 / sigma2 / sigma2 / dt / dt else: - M1 = S0 * (np.exp(b * t_exp) - np.exp(b * t0)) / (b * dt) + M1 = s0 * (np.exp(b * t_exp) - np.exp(b * t0)) / (b * dt) M2 = np.exp(a2 * t_exp) / a1 / a2 / dt / dt + \ (np.exp(a2 * t0) / b / dt / dt) * (1.0/a2 - np.exp(b*dt) / a1) - M2 = 2.0 * M2 * S0 * S0 + M2 = 2.0 * M2 * s0 * s0 F0 = M1 sigma2 = (1.0 / t_exp) * np.log(M2 / M1 / M1) diff --git a/financepy/products/equity/equity_barrier_option.py b/financepy/products/equity/equity_barrier_option.py index 5e3169c8..2abcbb28 100644 --- a/financepy/products/equity/equity_barrier_option.py +++ b/financepy/products/equity/equity_barrier_option.py @@ -4,7 +4,7 @@ import numpy as np -from ...models.equity_barrier_models import value_bs +from ...models.equity_barrier_models import value_barrier from ...market.curves.discount_curve import DiscountCurve from ...products.equity.equity_option import EquityOption from ...models.process_simulator import FinProcessSimulator @@ -94,15 +94,15 @@ def value(self, if t_exp < 0: raise FinError("Option expires before value date.") - values = value_bs(t_exp, - self._strike_price, - self._barrier_level, - stock_prices, - discount_curve.cc_rate(self._expiry_dt), - dividend_curve.cc_rate(self._expiry_dt), - model._volatility, - self._option_type.value, - self._num_obs_per_year) + values = value_barrier(t_exp, + self._strike_price, + self._barrier_level, + stock_prices, + discount_curve.cc_rate(self._expiry_dt), + dividend_curve.cc_rate(self._expiry_dt), + model._volatility, + self._option_type.value, + self._num_obs_per_year) values = values * self._notional diff --git a/financepy/products/equity/equity_basket_option.py b/financepy/products/equity/equity_basket_option.py index 98dcfd63..43b5aae5 100644 --- a/financepy/products/equity/equity_basket_option.py +++ b/financepy/products/equity/equity_basket_option.py @@ -133,8 +133,8 @@ def value(self, for ia in range(0, self._num_assets): smean = smean + s[ia] * a[ia] - lnS0k = np.log(smean / self._strike_price) - sqrtT = np.sqrt(t_exp) + ln_s0_k = np.log(smean / self._strike_price) + sqrt_t = np.sqrt(t_exp) # Moment matching - starting with dividend qnum = 0.0 @@ -148,23 +148,23 @@ def value(self, vnum = 0.0 for ia in range(0, self._num_assets): for ja in range(0, ia): - rhoSigmaSigma = v[ia] * v[ja] * correlations[ia, ja] - expTerm = (qs[ia] + qs[ja] - rhoSigmaSigma) * t_exp - vnum = vnum + a[ia] * a[ja] * s[ia] * s[ja] * np.exp(-expTerm) + rho_sigma_sigma = v[ia] * v[ja] * correlations[ia, ja] + exp_term = (qs[ia] + qs[ja] - rho_sigma_sigma) * t_exp + vnum = vnum + a[ia] * a[ja] * s[ia] * s[ja] * np.exp(-exp_term) vnum *= 2.0 for ia in range(0, self._num_assets): - rhoSigmaSigma = v[ia] ** 2 - expTerm = (2.0 * qs[ia] - rhoSigmaSigma) * t_exp - vnum = vnum + ((a[ia] * s[ia]) ** 2) * np.exp(-expTerm) + rho_sigma_sigma = v[ia] ** 2 + exp_term = (2.0 * qs[ia] - rho_sigma_sigma) * t_exp + vnum = vnum + ((a[ia] * s[ia]) ** 2) * np.exp(-exp_term) vhat2 = np.log(vnum / qnum / qnum) / t_exp - den = np.sqrt(vhat2) * sqrtT + den = np.sqrt(vhat2) * sqrt_t mu = r - qhat - d1 = (lnS0k + (mu + vhat2 / 2.0) * t_exp) / den - d2 = (lnS0k + (mu - vhat2 / 2.0) * t_exp) / den + d1 = (ln_s0_k + (mu + vhat2 / 2.0) * t_exp) / den + d2 = (ln_s0_k + (mu - vhat2 / 2.0) * t_exp) / den if self._option_type == OptionTypes.EUROPEAN_CALL: v = smean * np.exp(-qhat * t_exp) * N(d1) diff --git a/financepy/products/equity/equity_binomial_tree.py b/financepy/products/equity/equity_binomial_tree.py index c5376697..9efc3d28 100644 --- a/financepy/products/equity/equity_binomial_tree.py +++ b/financepy/products/equity/equity_binomial_tree.py @@ -105,8 +105,7 @@ def _value_once(stock_price, exercise_type, payoff_params): - if num_steps < 3: - num_steps = 3 + num_steps = max(num_steps, 3) # validate_payoff(payoff_type.value,payoff_params) @@ -123,7 +122,7 @@ def _value_once(stock_price, option_values = np.zeros(num_nodes) u = exp(volatility * sqrt(dt)) d = 1.0 / u - sLow = stock_price + s_low = stock_price probs = np.zeros(num_steps) period_dfs = np.zeros(num_steps) @@ -135,8 +134,8 @@ def _value_once(stock_price, period_dfs[i_time] = exp(-r * dt) for i_time in range(1, num_steps + 1): - sLow *= d - s = sLow + s_low *= d + s = s_low for i_node in range(0, i_time + 1): index = 0.5 * i_time * (i_time + 1) stock_values[int(index + i_node)] = s @@ -160,10 +159,10 @@ def _value_once(stock_price, next_index = int(0.5 * (i_time + 1) * (i_time + 2)) next_node_dn = next_index + i_node next_node_up = next_node_dn + 1 - vUp = option_values[next_node_up] - vDn = option_values[next_node_dn] - future_expected_value = probs[i_time] * vUp - future_expected_value += (1.0 - probs[i_time]) * vDn + v_up = option_values[next_node_up] + v_dn = option_values[next_node_dn] + future_expected_value = probs[i_time] * v_up + future_expected_value += (1.0 - probs[i_time]) * v_dn hold_value = period_dfs[i_time] * future_expected_value if exercise_type == EquityTreeExerciseTypes.EUROPEAN: @@ -179,9 +178,9 @@ def _value_once(stock_price, (stock_values[2] - stock_values[1]) delta_up = (option_values[5] - option_values[4]) / \ (stock_values[5] - stock_values[4]) - deltaDn = (option_values[4] - option_values[3]) / \ + delta_dn = (option_values[4] - option_values[3]) / \ (stock_values[4] - stock_values[3]) - gamma = (delta_up - deltaDn) / (stock_values[2] - stock_values[1]) + gamma = (delta_up - delta_dn) / (stock_values[2] - stock_values[1]) theta = (option_values[4] - option_values[0]) / (2.0 * dt) results = np.array([price, delta, gamma, theta]) return results diff --git a/financepy/products/equity/equity_chooser_option.py b/financepy/products/equity/equity_chooser_option.py index c3573260..fe65b5d6 100644 --- a/financepy/products/equity/equity_chooser_option.py +++ b/financepy/products/equity/equity_chooser_option.py @@ -8,7 +8,7 @@ from ...utils.math import M from ...utils.global_vars import gDaysInYear -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small from ...utils.error import FinError from ...products.equity.equity_option import EquityOption @@ -130,12 +130,12 @@ def value(self, q = dividend_curve.cc_rate(self._chooseDate) - t = max(t, gSmall) - tc = max(tc, gSmall) - tp = max(tp, gSmall) + t = max(t, g_small) + tc = max(tc, g_small) + tp = max(tp, g_small) v = model._volatility - v = max(v, gSmall) + v = max(v, g_small) s0 = stock_price xc = self._call_strike diff --git a/financepy/products/equity/equity_cliquet_option.py b/financepy/products/equity/equity_cliquet_option.py index a88e605c..b907e370 100644 --- a/financepy/products/equity/equity_cliquet_option.py +++ b/financepy/products/equity/equity_cliquet_option.py @@ -102,10 +102,10 @@ def value(self, self._v_options = [] self._dfs = [] - self._actualDates = [] + self._actual_dts = [] - CALL = OptionTypes.EUROPEAN_CALL - PUT = OptionTypes.EUROPEAN_PUT + call_type = OptionTypes.EUROPEAN_CALL + put_type = OptionTypes.EUROPEAN_PUT if isinstance(model, BlackScholes): @@ -132,13 +132,13 @@ def value(self, q = -np.log(dqMat/dq)/tau - if self._option_type == CALL: + if self._option_type == call_type: v_fwd_opt = s * dq * \ - bs_value(1.0, tau, 1.0, r, q, v, CALL.value) + bs_value(1.0, tau, 1.0, r, q, v, call_type.value) v_cliquet += v_fwd_opt - elif self._option_type == PUT: + elif self._option_type == put_type: v_fwd_opt = s * dq * \ - bs_value(1.0, tau, 1.0, r, q, v, PUT.value) + bs_value(1.0, tau, 1.0, r, q, v, put_type.value) v_cliquet += v_fwd_opt else: raise FinError("Unknown option type") @@ -147,7 +147,7 @@ def value(self, self._dfs.append(df) self._v_options.append(v) - self._actualDates.append(dt) + self._actual_dts.append(dt) tprev = t_exp else: raise FinError("Unknown Model Type") @@ -159,7 +159,7 @@ def value(self, def print_payments(self): num_options = len(self._v_options) for i in range(0, num_options): - print(self._actualDates[i], self._dfs[i], self._v_options[i]) + print(self._actual_dts[i], self._dfs[i], self._v_options[i]) ############################################################################### diff --git a/financepy/products/equity/equity_compound_option.py b/financepy/products/equity/equity_compound_option.py index 2178a94f..a6e5b956 100644 --- a/financepy/products/equity/equity_compound_option.py +++ b/financepy/products/equity/equity_compound_option.py @@ -11,7 +11,7 @@ from ...utils.math import N, phi2 -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...utils.global_types import OptionTypes @@ -86,34 +86,34 @@ def _value_once(s, d2 = 1.0 / u2 probs = np.zeros(num_steps) - periodDiscountFactors = np.zeros(num_steps) + period_dfs = np.zeros(num_steps) # store time independent information for later use in tree for i_time in range(0, num_steps1): a1 = np.exp((r - q) * dt1) probs[i_time] = (a1 - d1) / (u1 - d1) - periodDiscountFactors[i_time] = np.exp(-r * dt1) + period_dfs[i_time] = np.exp(-r * dt1) for i_time in range(num_steps1, num_steps): a2 = np.exp((r - q) * dt2) probs[i_time] = (a2 - d2) / (u2 - d2) - periodDiscountFactors[i_time] = np.exp(-r * dt2) + period_dfs[i_time] = np.exp(-r * dt2) stock_values = np.zeros(num_nodes) stock_values[0] = s - sLow = s + s_low = s for i_time in range(1, num_steps1 + 1): - sLow *= d1 - s = sLow + s_low *= d1 + s = s_low for i_node in range(0, i_time + 1): index = int(0.5 * i_time * (i_time + 1)) stock_values[index + i_node] = s s = s * (u1 * u1) for i_time in range(num_steps1 + 1, num_steps + 1): - sLow *= d2 - s = sLow + s_low *= d2 + s = s_low for i_node in range(0, i_time + 1): index = int(0.5 * i_time * (i_time + 1)) stock_values[index + i_node] = s @@ -139,11 +139,11 @@ def _value_once(s, next_index = int(0.5 * (i_time + 1) * (i_time + 2)) next_node_dn = next_index + i_node next_node_up = next_index + i_node + 1 - vUp = option_values[next_node_up] - vDn = option_values[next_node_dn] - future_exp_val = probs[i_time] * vUp - future_exp_val += (1.0 - probs[i_time]) * vDn - hold_value = periodDiscountFactors[i_time] * future_exp_val + v_up = option_values[next_node_up] + v_dn = option_values[next_node_dn] + future_exp_val = probs[i_time] * v_up + future_exp_val += (1.0 - probs[i_time]) * v_dn + hold_value = period_dfs[i_time] * future_exp_val exercise_value = 0.0 # NUMBA NEEDS HELP TO DETERMINE THE TYPE @@ -163,11 +163,11 @@ def _value_once(s, next_index = int(0.5 * (i_time + 1) * (i_time + 2)) next_node_dn = next_index + i_node next_node_up = next_index + i_node + 1 - vUp = option_values[next_node_up] - vDn = option_values[next_node_dn] - future_exp_val = probs[i_time] * vUp - future_exp_val += (1.0 - probs[i_time]) * vDn - hold_value = periodDiscountFactors[i_time] * future_exp_val + v_up = option_values[next_node_up] + v_dn = option_values[next_node_dn] + future_exp_val = probs[i_time] * v_up + future_exp_val += (1.0 - probs[i_time]) * v_dn + hold_value = period_dfs[i_time] * future_exp_val if option_type1 == OptionTypes.EUROPEAN_CALL\ or option_type1 == OptionTypes.AMERICAN_CALL: @@ -187,11 +187,11 @@ def _value_once(s, next_index = int(0.5 * (i_time + 1) * (i_time + 2)) next_node_dn = next_index + i_node next_node_up = next_index + i_node + 1 - vUp = option_values[next_node_up] - vDn = option_values[next_node_dn] - future_exp_val = probs[i_time] * vUp - future_exp_val += (1.0 - probs[i_time]) * vDn - hold_value = periodDiscountFactors[i_time] * future_exp_val + v_up = option_values[next_node_up] + v_dn = option_values[next_node_dn] + future_exp_val = probs[i_time] * v_up + future_exp_val += (1.0 - probs[i_time]) * v_dn + hold_value = period_dfs[i_time] * future_exp_val exercise_value = 0.0 # NUMBA NEEDS HELP TO DETERMINE THE TYPE @@ -207,7 +207,7 @@ def _value_once(s, print("num_steps1:", num_steps1) print("num_steps2:", num_steps2) print("u1:", u1, "u2:", u2) - print("dfs", periodDiscountFactors) + print("dfs", period_dfs) print("probs:", probs) print("s:", stock_values) print("v4:", option_values) @@ -235,43 +235,43 @@ class EquityCompoundOption(EquityOption): initiation. """ def __init__(self, - cExpiryDate: Date, # Compound Option expiry date - cOptionType: OptionTypes, # Compound option type - cStrikePrice: float, # Compound option strike - uExpiryDate: Date, # Underlying option expiry date - uOptionType: OptionTypes, # Underlying option type - uStrikePrice: float): # Underlying option strike price + c_expiry_dt: Date, # Compound Option expiry date + c_option_type: OptionTypes, # Compound option type + c_strike_price: float, # Compound option strike + u_expiry_dt: Date, # Underlying option expiry date + u_option_type: OptionTypes, # Underlying option type + u_strike_price: float): # Underlying option strike price """ Create the EquityCompoundOption by passing in the first and second expiry dates as well as the corresponding strike prices and option types. """ check_argument_types(self.__init__, locals()) - if cExpiryDate > uExpiryDate: + if c_expiry_dt > u_expiry_dt: raise FinError( "Compound expiry date must precede underlying expiry date") - if cOptionType != OptionTypes.EUROPEAN_CALL and \ - cOptionType != OptionTypes.AMERICAN_CALL and \ - cOptionType != OptionTypes.EUROPEAN_PUT and \ - cOptionType != OptionTypes.AMERICAN_PUT: + if c_option_type != OptionTypes.EUROPEAN_CALL and \ + c_option_type != OptionTypes.AMERICAN_CALL and \ + c_option_type != OptionTypes.EUROPEAN_PUT and \ + c_option_type != OptionTypes.AMERICAN_PUT: raise FinError( "Compound option must be European or American call or put.") - if uOptionType != OptionTypes.EUROPEAN_CALL and \ - uOptionType != OptionTypes.AMERICAN_CALL and \ - uOptionType != OptionTypes.EUROPEAN_PUT and \ - uOptionType != OptionTypes.AMERICAN_PUT: + if u_option_type != OptionTypes.EUROPEAN_CALL and \ + u_option_type != OptionTypes.AMERICAN_CALL and \ + u_option_type != OptionTypes.EUROPEAN_PUT and \ + u_option_type != OptionTypes.AMERICAN_PUT: raise FinError( "Underlying Option must be European or American call or put.") - self._cExpiryDate = cExpiryDate - self._cStrikePrice = float(cStrikePrice) - self._cOptionType = cOptionType + self._c_expiry_dt = c_expiry_dt + self._c_strike_price = float(c_strike_price) + self._c_option_type = c_option_type - self._uExpiryDate = uExpiryDate - self._uStrikePrice = float(uStrikePrice) - self._uOptionType = uOptionType + self._u_expiry_dt = u_expiry_dt + self._u_strike_price = float(u_strike_price) + self._u_option_type = u_option_type ############################################################################### @@ -290,10 +290,10 @@ def value(self, if isinstance(value_dt, Date) is False: raise FinError("Valuation date is not a Date") - if value_dt > self._cExpiryDate: + if value_dt > self._c_expiry_dt: raise FinError("Valuation date after underlying expiry date.") - if value_dt > self._uExpiryDate: + if value_dt > self._u_expiry_dt: raise FinError("Valuation date after compound expiry date.") if discount_curve._value_dt != value_dt: @@ -305,10 +305,10 @@ def value(self, "Dividend Curve valuation date not same as option value date") # If the option has any American feature then use the tree - if self._cOptionType == OptionTypes.AMERICAN_CALL or\ - self._uOptionType == OptionTypes.AMERICAN_CALL or\ - self._cOptionType == OptionTypes.AMERICAN_PUT or\ - self._uOptionType == OptionTypes.AMERICAN_PUT: + if self._c_option_type == OptionTypes.AMERICAN_CALL or\ + self._u_option_type == OptionTypes.AMERICAN_CALL or\ + self._c_option_type == OptionTypes.AMERICAN_PUT or\ + self._u_option_type == OptionTypes.AMERICAN_PUT: v = self._value_tree(value_dt, stock_price, @@ -319,32 +319,32 @@ def value(self, return v[0] - tc = (self._cExpiryDate - value_dt) / gDaysInYear - tu = (self._uExpiryDate - value_dt) / gDaysInYear + tc = (self._c_expiry_dt - value_dt) / gDaysInYear + tu = (self._u_expiry_dt - value_dt) / gDaysInYear s0 = stock_price - df = discount_curve.df(self._uExpiryDate) + df = discount_curve.df(self._u_expiry_dt) ru = -np.log(df)/tu # CHECK INTEREST RATES AND IF THERE SHOULD BE TWO RU AND RC ????? - tc = np.maximum(tc, gSmall) + tc = np.maximum(tc, g_small) tu = np.maximum(tc, tu) - dq = dividend_curve.df(self._uExpiryDate) + dq = dividend_curve.df(self._u_expiry_dt) q = -np.log(dq)/tu - v = np.maximum(model._volatility, gSmall) + v = np.maximum(model._volatility, g_small) - kc = self._cStrikePrice - ku = self._uStrikePrice + kc = self._c_strike_price + ku = self._u_strike_price sstar = self._implied_stock_price(s0, - self._cExpiryDate, - self._uExpiryDate, + self._c_expiry_dt, + self._u_expiry_dt, kc, ku, - self._uOptionType, + self._u_option_type, ru, q, model) a1 = (log(s0 / sstar) + (ru - q + (v**2) / 2.0) * tc) / v / sqrt(tc) @@ -359,19 +359,19 @@ def value(self, # Taken from Hull Page 532 (6th edition) - CALL = OptionTypes.EUROPEAN_CALL - PUT = OptionTypes.EUROPEAN_PUT + call_type = OptionTypes.EUROPEAN_CALL + put_type = OptionTypes.EUROPEAN_PUT - if self._cOptionType == CALL and self._uOptionType == CALL: + if self._c_option_type == call_type and self._u_option_type == call_type: v = s0 * dqu * phi2(a1, b1, c) - ku * dfu * \ phi2(a2, b2, c) - dfc * kc * N(a2) - elif self._cOptionType == PUT and self._uOptionType == CALL: + elif self._c_option_type == put_type and self._u_option_type == call_type: v = ku * dfu * phi2(-a2, b2, -c) - s0 * dqu * \ phi2(-a1, b1, -c) + dfc * kc * N(-a2) - elif self._cOptionType == CALL and self._uOptionType == PUT: + elif self._c_option_type == call_type and self._u_option_type == put_type: v = ku * dfu * phi2(-a2, -b2, c) - s0 * dqu * \ phi2(-a1, -b1, c) - dfc * kc * N(-a2) - elif self._cOptionType == PUT and self._uOptionType == PUT: + elif self._c_option_type == put_type and self._u_option_type == put_type: v = s0 * dqu * phi2(a1, -b1, -c) - ku * dfu * \ phi2(a2, -b2, -c) + dfc * kc * N(a2) else: @@ -390,19 +390,19 @@ def _value_tree(self, num_steps=200): """ This function is called if the option has American features. """ - if value_dt > self._cExpiryDate: + if value_dt > self._c_expiry_dt: raise FinError("Value date is after expiry date.") - tc = (self._cExpiryDate - value_dt) / gDaysInYear - tu = (self._uExpiryDate - value_dt) / gDaysInYear + tc = (self._c_expiry_dt - value_dt) / gDaysInYear + tu = (self._u_expiry_dt - value_dt) / gDaysInYear - df = discount_curve.df(self._uExpiryDate) + df = discount_curve.df(self._u_expiry_dt) r = -np.log(df)/tu - dq = dividend_curve.df(self._uExpiryDate) + dq = dividend_curve.df(self._u_expiry_dt) q = -np.log(dq)/tu - r = discount_curve.zero_rate(self._uExpiryDate) + r = discount_curve.zero_rate(self._u_expiry_dt) volatility = model._volatility @@ -411,10 +411,10 @@ def _value_tree(self, q, volatility, tc, tu, - self._cOptionType, - self._uOptionType, - self._cStrikePrice, - self._uStrikePrice, + self._c_option_type, + self._u_option_type, + self._c_strike_price, + self._u_strike_price, num_steps) return v1 @@ -448,12 +448,12 @@ def _implied_stock_price(self, def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) - s += label_to_string("CPD EXPIRY DATE", self._cExpiryDate) - s += label_to_string("CPD STRIKE PRICE", self._cStrikePrice) - s += label_to_string("CPD OPTION TYPE", self._cOptionType) - s += label_to_string("UND EXPIRY DATE", self._uExpiryDate) - s += label_to_string("UND STRIKE PRICE", self._uStrikePrice) - s += label_to_string("UND OPTION TYPE", self._uOptionType) + s += label_to_string("CPD EXPIRY DATE", self._c_expiry_dt) + s += label_to_string("CPD STRIKE PRICE", self._c_strike_price) + s += label_to_string("CPD OPTION TYPE", self._c_option_type) + s += label_to_string("UND EXPIRY DATE", self._u_expiry_dt) + s += label_to_string("UND STRIKE PRICE", self._u_strike_price) + s += label_to_string("UND OPTION TYPE", self._u_option_type) return s ############################################################################### diff --git a/financepy/products/equity/equity_digital_option.py b/financepy/products/equity/equity_digital_option.py index c61eb15f..9e1230f8 100644 --- a/financepy/products/equity/equity_digital_option.py +++ b/financepy/products/equity/equity_digital_option.py @@ -3,11 +3,11 @@ ############################################################################## -import numpy as np from enum import Enum +import numpy as np -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...utils.global_types import OptionTypes from ...products.equity.equity_option import EquityOption @@ -87,8 +87,8 @@ def value(self, s0 = s X = self._barrier - lnS0k = np.log(s0 / X) - sqrtT = np.sqrt(t) + ln_s0_k = np.log(s0 / X) + sqrt_t = np.sqrt(t) df = discount_curve.df(self._expiry_dt) r = -np.log(df)/t @@ -98,12 +98,12 @@ def value(self, volatility = model._volatility - if abs(volatility) < gSmall: - volatility = gSmall + if abs(volatility) < g_small: + volatility = g_small - d1 = (lnS0k + (r - q + volatility*volatility / 2.0) * t) - d1 = d1 / volatility / sqrtT - d2 = d1 - volatility * sqrtT + d1 = (ln_s0_k + (r - q + volatility*volatility / 2.0) * t) + d1 = d1 / volatility / sqrt_t + d2 = d1 - volatility * sqrt_t if self._digital_type == FinDigitalOptionTypes.CASH_OR_NOTHING: diff --git a/financepy/products/equity/equity_fixed_lookback_option.py b/financepy/products/equity/equity_fixed_lookback_option.py index fc09986a..c60a7964 100644 --- a/financepy/products/equity/equity_fixed_lookback_option.py +++ b/financepy/products/equity/equity_fixed_lookback_option.py @@ -6,7 +6,7 @@ from ...utils.math import N -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...utils.date import Date @@ -104,8 +104,8 @@ def value(self, # There is a risk of an overflow in the limit of q=r which # we remove by adjusting the value of the dividend - if abs(r - q) < gSmall: - q = r + gSmall + if abs(r - q) < g_small: + q = r + g_small df = np.exp(-r * t) dq = np.exp(-q * t) @@ -113,38 +113,38 @@ def value(self, u = v * v / 2.0 / b w = 2.0 * b / (v * v) expbt = np.exp(b * t) - sqrtT = np.sqrt(t) + sqrt_t = np.sqrt(t) # Taken from Hull Page 536 (6th edition) and Haug Page 143 if self._option_type == OptionTypes.EUROPEAN_CALL: if k > s_max: - d1 = (np.log(s0 / k) + (b + v * v/2.0) * t) / v / sqrtT - d2 = d1 - v * sqrtT + d1 = (np.log(s0 / k) + (b + v * v/2.0) * t) / v / sqrt_t + d2 = d1 - v * sqrt_t if s0 == k: - term = -N(d1 - 2.0 * b * sqrtT / v) + expbt * N(d1) + term = -N(d1 - 2.0 * b * sqrt_t / v) + expbt * N(d1) elif s0 < k and w > 100.0: term = expbt * N(d1) else: - term = -np.power(s0 / k, -w) * N(d1 - 2 * b * sqrtT / v) \ + term = -np.power(s0 / k, -w) * N(d1 - 2 * b * sqrt_t / v) \ + expbt * N(d1) v = s0 * dq * N(d1) - k * df * N(d2) + s0 * df * u * term else: - e1 = (np.log(s0/s_max) + (r - q + v*v/2) * t) / v / sqrtT - e2 = e1 - v * sqrtT + e1 = (np.log(s0/s_max) + (r - q + v*v/2) * t) / v / sqrt_t + e2 = e1 - v * sqrt_t if s0 == s_max: - term = -N(e1 - 2.0 * b * sqrtT / v) + expbt * N(e1) + term = -N(e1 - 2.0 * b * sqrt_t / v) + expbt * N(e1) elif s0 < s_max and w > 100.0: term = expbt * N(e1) else: term = (-(s0 / s_max)**(-w)) * \ - N(e1 - 2.0 * b * sqrtT / v) + expbt * N(e1) + N(e1 - 2.0 * b * sqrt_t / v) + expbt * N(e1) v = df * (s_max - k) + s0 * dq * N(e1) - \ s_max * df * N(e2) + s0 * df * u * term @@ -153,15 +153,15 @@ def value(self, if k >= s_min: - f1 = (np.log(s0/s_min) + (b + v * v / 2.0) * t) / v / sqrtT - f2 = f1 - v * sqrtT + f1 = (np.log(s0/s_min) + (b + v * v / 2.0) * t) / v / sqrt_t + f2 = f1 - v * sqrt_t if s0 == s_min: - term = N(-f1 + 2.0 * b * sqrtT / v) - expbt * N(-f1) + term = N(-f1 + 2.0 * b * sqrt_t / v) - expbt * N(-f1) elif s0 > s_min and w < -100.0: term = -expbt * N(-f1) else: - term = ((s0 / s_min)**(-w)) * N(-f1 + 2.0 * b * sqrtT / v) \ + term = ((s0 / s_min)**(-w)) * N(-f1 + 2.0 * b * sqrt_t / v) \ - expbt * N(-f1) v = df * (k - s_min) - s0 * dq * N(-f1) + \ @@ -169,15 +169,15 @@ def value(self, else: - d1 = (np.log(s0 / k) + (b + v * v / 2) * t) / v / sqrtT - d2 = d1 - v * sqrtT + d1 = (np.log(s0 / k) + (b + v * v / 2) * t) / v / sqrt_t + d2 = d1 - v * sqrt_t if s0 == k: - term = N(-d1 + 2.0 * b * sqrtT / v) - expbt * N(-d1) + term = N(-d1 + 2.0 * b * sqrt_t / v) - expbt * N(-d1) elif s0 > k and w < -100.0: term = -expbt * N(-d1) else: - term = ((s0 / k)**(-w)) * N(-d1 + 2.0 * b * sqrtT / v) \ + term = ((s0 / k)**(-w)) * N(-d1 + 2.0 * b * sqrt_t / v) \ - expbt * N(-d1) v = k * df * N(-d2) - s0 * dq * N(-d1) + s0 * df * u * term @@ -204,7 +204,7 @@ def value_mc(self, Black-Scholes model that assumes the stock follows a GBM process. """ t = (self._expiry_dt - value_dt) / gDaysInYear - + df = discount_curve.df(self._expiry_dt) r = discount_curve.cc_rate(self._expiry_dt) q = dividend_curve.cc_rate(self._expiry_dt) diff --git a/financepy/products/equity/equity_float_lookback_option.py b/financepy/products/equity/equity_float_lookback_option.py index 3fce4c37..85881cf2 100644 --- a/financepy/products/equity/equity_float_lookback_option.py +++ b/financepy/products/equity/equity_float_lookback_option.py @@ -6,7 +6,7 @@ from ...utils.math import N -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...utils.date import Date @@ -102,8 +102,8 @@ def value(self, raise FinError( "Smax must be greater than or equal to the stock price.") - if abs(r - q) < gSmall: - q = r + gSmall + if abs(r - q) < g_small: + q = r + g_small dq = np.exp(-q * t) df = np.exp(-r * t) diff --git a/financepy/products/equity/equity_forward.py b/financepy/products/equity/equity_forward.py index b59a7c81..9c4bdad5 100644 --- a/financepy/products/equity/equity_forward.py +++ b/financepy/products/equity/equity_forward.py @@ -71,15 +71,15 @@ def value(self, t = np.maximum(t, 1e-10) - fwdStockPrice = self.forward(value_dt, + fwd_stock_price = self.forward(value_dt, stock_price, discount_curve, dividend_curve) - discountDF = discount_curve._df(t) + discount_df = discount_curve._df(t) - v = (fwdStockPrice - self._forward_price) - v = v * self._notional * discountDF + v = (fwd_stock_price - self._forward_price) + v = v * self._notional * discount_df if self._long_short == FinLongShort.SHORT: v = v * (-1.0) @@ -108,11 +108,11 @@ def forward(self, t = np.maximum(t, 1e-10) - discountDF = discount_curve._df(t) + discount_df = discount_curve._df(t) dividendDF = dividend_curve._df(t) - fwdStockPrice = stock_price * dividendDF / discountDF - return fwdStockPrice + fwd_stock_price = stock_price * dividendDF / discount_df + return fwd_stock_price ############################################################################### diff --git a/financepy/products/equity/equity_index_option.py b/financepy/products/equity/equity_index_option.py index c9b403a7..68aee892 100644 --- a/financepy/products/equity/equity_index_option.py +++ b/financepy/products/equity/equity_index_option.py @@ -63,8 +63,8 @@ def value(self, t_exp = (self._expiry_dt - value_dt) / gDaysInYear elif isinstance(self._expiry_dt, list): t_exp = [] - for expDate in self._expiry_dt: - t = (expDate - value_dt) / gDaysInYear + for exp_dt in self._expiry_dt: + t = (exp_dt - value_dt) / gDaysInYear t_exp.append(t) t_exp = np.array(t_exp) else: diff --git a/financepy/products/equity/equity_one_touch_option.py b/financepy/products/equity/equity_one_touch_option.py index bad3f3cf..965e8981 100644 --- a/financepy/products/equity/equity_one_touch_option.py +++ b/financepy/products/equity/equity_one_touch_option.py @@ -179,7 +179,7 @@ def value(self, H = self._barrier_price K = self._payment_size - sqrtT = np.sqrt(t) + sqrt_t = np.sqrt(t) df = discount_curve.df(self._expiry_dt) r = discount_curve.cc_rate(self._expiry_dt) @@ -209,10 +209,10 @@ def value(self, raise FinError("Stock price is currently below barrier.") eta = 1.0 - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta - * lam * v * sqrtT) + * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -223,10 +223,10 @@ def value(self, raise FinError("Stock price is currently above barrier.") eta = -1.0 - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta - * lam * v * sqrtT) + * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -238,10 +238,10 @@ def value(self, eta = 1.0 K = H - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta - * lam * v * sqrtT) + * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -253,10 +253,10 @@ def value(self, eta = -1.0 K = H - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta - * lam * v * sqrtT) + * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -268,11 +268,11 @@ def value(self, eta = +1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 + B4) return v @@ -285,11 +285,11 @@ def value(self, eta = -1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 + B4) return v @@ -301,8 +301,8 @@ def value(self, eta = +1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-q*t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -317,8 +317,8 @@ def value(self, eta = -1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-q*t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -334,11 +334,11 @@ def value(self, eta = +1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 - B4) return v @@ -351,11 +351,11 @@ def value(self, eta = -1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 - B4) return v @@ -368,8 +368,8 @@ def value(self, eta = +1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-q*t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -385,8 +385,8 @@ def value(self, eta = -1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-q*t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) diff --git a/financepy/products/equity/equity_option.py b/financepy/products/equity/equity_option.py index 2b7e380e..535d4fbe 100644 --- a/financepy/products/equity/equity_option.py +++ b/financepy/products/equity/equity_option.py @@ -25,8 +25,8 @@ class EquityOptionModelTypes(Enum): class EquityOption: - """ This class is a parent class for all option classes that require any - perturbatory risk. """ + """ This class is a parent class for all equitu option classes that + require any perturbatory risk. """ ############################################################################### @@ -53,12 +53,12 @@ def delta(self, v = self.value(value_dt, stock_price, discount_curve, dividend_curve, model) - vBumped = self.value(value_dt, stock_price + bump, - discount_curve, - dividend_curve, - model) + v_bumped = self.value(value_dt, stock_price + bump, + discount_curve, + dividend_curve, + model) - delta = (vBumped - v) / bump + delta = (v_bumped - v) / bump return delta ############################################################################### @@ -75,15 +75,15 @@ def gamma(self, v = self.value(value_dt, stock_price, discount_curve, dividend_curve, model) - vBumpedDn = self.value(value_dt, stock_price - bump, - discount_curve, - dividend_curve, model) + v_bumped_dn = self.value(value_dt, stock_price - bump, + discount_curve, + dividend_curve, model) - vBumpedUp = self.value(value_dt, stock_price + bump, - discount_curve, - dividend_curve, model) + v_bumped_up = self.value(value_dt, stock_price + bump, + discount_curve, + dividend_curve, model) - gamma = (vBumpedUp - 2.0 * v + vBumpedDn) / bump / bump + gamma = (v_bumped_up - 2.0 * v + v_bumped_dn) / bump / bump return gamma ############################################################################### @@ -103,10 +103,10 @@ def vega(self, model = BlackScholes(model._volatility + bump) - vBumped = self.value(value_dt, stock_price, discount_curve, - dividend_curve, model) + v_bumped = self.value(value_dt, stock_price, discount_curve, + dividend_curve, model) - vega = (vBumped - v) + vega = (v_bumped - v) return vega ############################################################################## @@ -160,15 +160,15 @@ def theta(self, dividend_curve._value_dt = next_dt bump = (next_dt - value_dt) / gDaysInYear - vBumped = self.value(next_dt, stock_price, - discount_curve, - dividend_curve, model) + v_bumped = self.value(next_dt, stock_price, + discount_curve, + dividend_curve, model) # restore valuation dates discount_curve._value_dt = value_dt dividend_curve._value_dt = value_dt - theta = (vBumped - v) / bump + theta = (v_bumped - v) / bump return theta ############################################################################### @@ -185,12 +185,12 @@ def rho(self, v = self.value(value_dt, stock_price, discount_curve, dividend_curve, model) - vBumped = self.value(value_dt, - stock_price, - discount_curve.bump(bump), - dividend_curve, model) + v_bumped = self.value(value_dt, + stock_price, + discount_curve.bump(bump), + dividend_curve, model) - rho = (vBumped - v) / bump + rho = (v_bumped - v) / bump return rho ############################################################################### diff --git a/financepy/products/equity/equity_swap.py b/financepy/products/equity/equity_swap.py index a17b0f6b..e9fd5cca 100644 --- a/financepy/products/equity/equity_swap.py +++ b/financepy/products/equity/equity_swap.py @@ -61,7 +61,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -120,7 +120,7 @@ def value(self, index_curve: DiscountCurve = None, dividend_curve: DiscountCurve = None, current_price: float = None, - firstFixingRate=None): + first_fixing_rate=None): """ Value the Equity swap on a valuation date. """ self._equity_leg_value = self._equity_leg.value(value_dt, @@ -133,7 +133,7 @@ def value(self, self._rate_leg_value = self._rate_leg.value(value_dt, discount_curve, index_curve, - firstFixingRate) + first_fixing_rate) return self._equity_leg_value + self._rate_leg_value @@ -154,15 +154,15 @@ def _fill_rate_notional_array(self): rate_freq = annual_frequency(self._rate_leg._freq_type) multiple = int(rate_freq // eq_freq) - isMultiple = int(rate_freq % eq_freq) == 0 + is_multiple = int(rate_freq % eq_freq) == 0 - if (eq_freq is None or rate_freq is None) or (not isMultiple): + if (eq_freq is None or rate_freq is None) or (not is_multiple): raise FinError("Invalid frequency type assigned!") self._rate_leg._notional_array = [] - for lastNotional in self._equity_leg._last_notionals: + for last_notional in self._equity_leg._last_notionals: for _ in range(multiple): - self._rate_leg._notional_array.append(lastNotional) + self._rate_leg._notional_array.append(last_notional) ########################################################################### diff --git a/financepy/products/equity/equity_swap_leg.py b/financepy/products/equity/equity_swap_leg.py index 22fb1ffd..352cc046 100644 --- a/financepy/products/equity/equity_swap_leg.py +++ b/financepy/products/equity/equity_swap_leg.py @@ -43,7 +43,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): termination_dt = term_dt_or_tenor else: termination_dt = effective_dt.add_tenor(term_dt_or_tenor) @@ -83,8 +83,8 @@ def __init__(self, self._dg_type = dg_type self._end_of_month = end_of_month - self._start_accd_dates = [] - self._end_accd_dates = [] + self._start_accd_dts = [] + self._end_accd_dts = [] self._payment_dts = [] self._pmnts = [] self._year_fracs = [] @@ -108,27 +108,27 @@ def generate_payment_dts(self): self._dg_type, end_of_month=self._end_of_month) - scheduleDates = schedule._adjusted_dts + schedule_dts = schedule._adjusted_dts - if len(scheduleDates) < 2: + if len(schedule_dts) < 2: raise FinError("Schedule has none or only one date") - self._start_accd_dates = [] - self._end_accd_dates = [] + self._start_accd_dts = [] + self._end_accd_dts = [] self._payment_dts = [] self._year_fracs = [] self._accrued_days = [] - prev_dt = scheduleDates[0] + prev_dt = schedule_dts[0] day_counter = DayCount(self._dc_type) calendar = Calendar(self._cal_type) # All of the lists end up with the same length - for next_dt in scheduleDates[1:]: + for next_dt in schedule_dts[1:]: - self._start_accd_dates.append(prev_dt) - self._end_accd_dates.append(next_dt) + self._start_accd_dts.append(prev_dt) + self._end_accd_dts.append(next_dt) if self._payment_lag == 0: payment_dt = next_dt @@ -188,31 +188,31 @@ def value(self, self._pmnt_pvs = [] self._cumulative_pvs = [] - dfValue = discount_curve.df(value_dt) + df_value = discount_curve.df(value_dt) leg_pv, eq_term_rate = 0.0, 0.0 last_notional = self._notional - numPayments = len(self._payment_dts) + num_payments = len(self._payment_dts) index_basis = index_curve._dc_type index_day_counter = DayCount(index_basis) - for iPmnt in range(0, numPayments): + for i_pmnt in range(0, num_payments): - pmntDate = self._payment_dts[iPmnt] + pmnt_dt = self._payment_dts[i_pmnt] - if pmntDate > value_dt: + if pmnt_dt > value_dt: - startAccruedDt = self._start_accd_dates[iPmnt] - endAccruedDt = self._end_accd_dates[iPmnt] - index_alpha = index_day_counter.year_frac(startAccruedDt, - endAccruedDt)[0] + start_accrued_dt = self._start_accd_dts[i_pmnt] + end_accrued_dt = self._end_accd_dts[i_pmnt] + index_alpha = index_day_counter.year_frac(start_accrued_dt, + end_accrued_dt)[0] - df_start = index_curve.df(startAccruedDt) - df_end = index_curve.df(endAccruedDt) + df_start = index_curve.df(start_accrued_dt) + df_end = index_curve.df(end_accrued_dt) fwd_rate = (df_start / df_end - 1.0) / index_alpha - div_start = dividend_curve.df(startAccruedDt) - div_end = dividend_curve.df(endAccruedDt) + div_start = dividend_curve.df(start_accrued_dt) + div_end = dividend_curve.df(end_accrued_dt) div_fwd_rate = (div_start / div_end - 1.0) / index_alpha # Equity discount derived from index and div curves @@ -223,13 +223,13 @@ def value(self, self._eq_fwd_rates.append(eq_fwd_rate) # Iterative update of the term rate - eq_term_rate = (1 + eq_fwd_rate * self._year_fracs[iPmnt]) * (1 + eq_term_rate) - 1 + eq_term_rate = (1 + eq_fwd_rate * self._year_fracs[i_pmnt]) * (1 + eq_term_rate) - 1 next_price = self._current_price * (1 + eq_term_rate) next_notional = next_price * self._quantity pmntAmount = next_notional - last_notional - df_pmnt = discount_curve.df(pmntDate) / dfValue + df_pmnt = discount_curve.df(pmnt_dt) / df_value pmnt_pv = pmntAmount * df_pmnt leg_pv += pmnt_pv @@ -282,8 +282,8 @@ def print_pmnts(self): rows.append([ i_flow + 1, self._payment_dts[i_flow], - self._start_accd_dates[i_flow], - self._end_accd_dates[i_flow], + self._start_accd_dts[i_flow], + self._end_accd_dts[i_flow], self._accrued_days[i_flow], round(self._year_fracs[i_flow], 4), ]) diff --git a/financepy/products/equity/equity_vanilla_option.py b/financepy/products/equity/equity_vanilla_option.py index 0882c034..ee97a7d0 100644 --- a/financepy/products/equity/equity_vanilla_option.py +++ b/financepy/products/equity/equity_vanilla_option.py @@ -113,8 +113,8 @@ def intrinsic(self, t_exp = (self._expiry_dt - value_dt) / gDaysInYear elif isinstance(self._expiry_dt, list): t_exp = [] - for expDate in self._expiry_dt: - t = (expDate - value_dt) / gDaysInYear + for exp_dt in self._expiry_dt: + t = (exp_dt - value_dt) / gDaysInYear t_exp.append(t) t_exp = np.array(t_exp) else: @@ -170,8 +170,8 @@ def value(self, t_exp = (self._expiry_dt - value_dt) / gDaysInYear elif isinstance(self._expiry_dt, list): t_exp = [] - for expDate in self._expiry_dt: - t = (expDate - value_dt) / gDaysInYear + for exp_dt in self._expiry_dt: + t = (exp_dt - value_dt) / gDaysInYear t_exp.append(t) t_exp = np.array(t_exp) else: diff --git a/financepy/products/equity/equity_variance_swap.py b/financepy/products/equity/equity_variance_swap.py index 7c92e4d8..7f15216d 100644 --- a/financepy/products/equity/equity_variance_swap.py +++ b/financepy/products/equity/equity_variance_swap.py @@ -31,7 +31,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(maturity_dt_or_tenor) == Date: + if isinstance(maturity_dt_or_tenor, Date): maturity_dt = maturity_dt_or_tenor else: maturity_dt = start_dt.add_tenor(maturity_dt_or_tenor) @@ -57,8 +57,8 @@ def __init__(self, def value(self, value_dt, - realisedVar, - fair_strikeVar, + realised_var, + fair_strike_var, libor_curve): """ Calculate the value of the variance swap based on the realised volatility to the valuation date, the forward looking implied @@ -67,10 +67,10 @@ def value(self, t1 = (value_dt - self._start_dt) / gDaysInYear t2 = (self._maturity_dt - self._start_dt) / gDaysInYear - expectedVariance = t1 * realisedVar/t2 - expectedVariance += (t2-t1) * fair_strikeVar / t2 + expected_variance = t1 * realised_var/t2 + expected_variance += (t2-t1) * fair_strike_var / t2 - payoff = expectedVariance - self._strike_variance + payoff = expected_variance - self._strike_variance df = libor_curve.df(self._maturity_dt) v = payoff * self._notional * df @@ -80,14 +80,14 @@ def value(self, def fair_strike_approx(self, value_dt, - fwdStockPrice, + fwd_stock_price, strikes, volatilities): """ This is an approximation of the fair strike variance by Demeterfi et al. (1999) which assumes that sigma(K) = sigma(F) - b(K-F)/F where F is the forward stock price and sigma(F) is the ATM forward vol. """ - f = fwdStockPrice + f = fwd_stock_price # TODO Linear interpolation - to be revisited atm_vol = np.interp(f, strikes, volatilities) @@ -147,7 +147,7 @@ def fair_strike(self, Goldman Sachs Research notes March 1999. See Appendix A. This aim is to use calls and puts to approximate the payoff of a log contract """ - minStrike = sstar - (num_put_options+1) * strike_spacing + min_strike = sstar - (num_put_options+1) * strike_spacing self._put_wts = [] self._put_strikes = [] @@ -155,7 +155,7 @@ def fair_strike(self, self._call_strikes = [] # if the lower strike is < 0 we go to as low as the strike spacing - if minStrike < strike_spacing: + if min_strike < strike_spacing: k = sstar klist = [sstar] while k >= strike_spacing: @@ -164,16 +164,16 @@ def fair_strike(self, put_k = np.array(klist) self._num_put_options = len(put_k) - 1 else: - put_k = np.linspace(sstar, minStrike, num_put_options+2) + put_k = np.linspace(sstar, min_strike, num_put_options+2) self._put_strikes = put_k max_strike = sstar + (num_call_options+1) * strike_spacing - callK = np.linspace(sstar, max_strike, num_call_options+2) + call_k = np.linspace(sstar, max_strike, num_call_options+2) - self._call_strikes = callK + self._call_strikes = call_k - optionTotal = 2.0*(r*t_mat - (s0*g/sstar-1.0) - np.log(sstar/s0))/t_mat + option_total = 2.0*(r*t_mat - (s0*g/sstar-1.0) - np.log(sstar/s0))/t_mat self._call_wts = np.zeros(num_call_options) self._put_wts = np.zeros(num_put_options) @@ -189,8 +189,8 @@ def f(x): return (2.0/t_mat)*((x-sstar)/sstar-np.log(x/sstar)) sum_wts = 0.0 for n in range(0, self._num_call_options): - kp = callK[n+1] - k = callK[n] + kp = call_k[n+1] + k = call_k[n] self._call_wts[n] = (f(kp)-f(k))/(kp-k) - sum_wts sum_wts += self._call_wts[n] @@ -206,7 +206,7 @@ def f(x): return (2.0/t_mat)*((x-sstar)/sstar-np.log(x/sstar)) pi_call = 0.0 for n in range(0, num_call_options): - k = callK[n] + k = call_k[n] vol = volatility_curve.volatility(k) opt = EquityVanillaOption(self._maturity_dt, k, call_type) model = BlackScholes(vol) @@ -215,8 +215,8 @@ def f(x): return (2.0/t_mat)*((x-sstar)/sstar-np.log(x/sstar)) pi_call += v * self._call_wts[n] pi = pi_call + pi_put - optionTotal += g * pi - var = optionTotal + option_total += g * pi + var = option_total return var @@ -232,18 +232,18 @@ def realised_variance(self, closePrices, use_logs=True): if closePrices[i] <= 0.0: raise FinError("Stock prices must be greater than zero") - cumX2 = 0.0 + cum_x2 = 0.0 if use_logs is True: for i in range(1, num_observations): x = np.log(closePrices[i]/closePrices[i-1]) - cumX2 += x*x + cum_x2 += x*x else: for i in range(1, num_observations): x = (closePrices[i]-closePrices[i-1])/closePrices[i-1] - cumX2 += x*x + cum_x2 += x*x - var = cumX2 * 252.0 / num_observations + var = cum_x2 * 252.0 / num_observations return var ############################################################################### diff --git a/financepy/products/fx/fx_barrier_option.py b/financepy/products/fx/fx_barrier_option.py index 749dfdaf..842b8b18 100644 --- a/financepy/products/fx/fx_barrier_option.py +++ b/financepy/products/fx/fx_barrier_option.py @@ -62,8 +62,8 @@ def __init__(self, def value(self, value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ Value FX Barrier Option using Black-Scholes model with closed-form analytical models. """ @@ -78,53 +78,53 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as option value date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as option value date") K = self._strike_fx_rate - S0 = spot_fx_rate + s0 = spot_fx_rate h = self._barrier_level t = (self._expiry_dt - value_dt) / gDaysInYear - lnS0k = log(float(S0) / K) - sqrtT = sqrt(t) + ln_s0_k = log(float(s0) / K) + sqrt_t = sqrt(t) - dq = for_discount_curve._df(t) - df = dom_discount_curve._df(t) + dq = foreign_curve._df(t) + df = domestic_curve._df(t) r_d = -log(df) / t rf = -log(dq) / t volatility = model._volatility - sigmaRootT = volatility * sqrtT + sigma_root_t = volatility * sqrt_t v2 = volatility * volatility mu = r_d - rf - d1 = (lnS0k + (mu + v2 / 2.0) * t) / sigmaRootT - d2 = (lnS0k + (mu - v2 / 2.0) * t) / sigmaRootT + d1 = (ln_s0_k + (mu + v2 / 2.0) * t) / sigma_root_t + d2 = (ln_s0_k + (mu - v2 / 2.0) * t) / sigma_root_t - c = S0 * dq * N(d1) - K * df * N(d2) - p = K * df * N(-d2) - S0 * dq * N(-d1) + c = s0 * dq * N(d1) - K * df * N(d2) + p = K * df * N(-d2) - s0 * dq * N(-d1) # print("CALL:",c,"PUT:",p) - if self._option_type == FinFXBarrierTypes.DOWN_AND_OUT_CALL and S0 <= h: + if self._option_type == FinFXBarrierTypes.DOWN_AND_OUT_CALL and s0 <= h: return 0.0 - elif self._option_type == FinFXBarrierTypes.UP_AND_OUT_CALL and S0 >= h: + elif self._option_type == FinFXBarrierTypes.UP_AND_OUT_CALL and s0 >= h: return 0.0 - elif self._option_type == FinFXBarrierTypes.UP_AND_OUT_PUT and S0 >= h: + elif self._option_type == FinFXBarrierTypes.UP_AND_OUT_PUT and s0 >= h: return 0.0 - elif self._option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT and S0 <= h: + elif self._option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT and s0 <= h: return 0.0 - elif self._option_type == FinFXBarrierTypes.DOWN_AND_IN_CALL and S0 <= h: + elif self._option_type == FinFXBarrierTypes.DOWN_AND_IN_CALL and s0 <= h: return c - elif self._option_type == FinFXBarrierTypes.UP_AND_IN_CALL and S0 >= h: + elif self._option_type == FinFXBarrierTypes.UP_AND_IN_CALL and s0 >= h: return c - elif self._option_type == FinFXBarrierTypes.UP_AND_IN_PUT and S0 >= h: + elif self._option_type == FinFXBarrierTypes.UP_AND_IN_PUT and s0 >= h: return p - elif self._option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT and S0 <= h: + elif self._option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT and s0 <= h: return p num_observations = t * self._num_obs_per_year @@ -158,93 +158,99 @@ def value(self, volatility = 1e-5 ll = (mu + v2 / 2.0) / v2 - y = log(h * h / (S0 * K)) / sigmaRootT + ll * sigmaRootT - x1 = log(S0 / h) / sigmaRootT + ll * sigmaRootT - y1 = log(h / S0) / sigmaRootT + ll * sigmaRootT - hOverS = h / S0 + y = log(h * h / (s0 * K)) / sigma_root_t + ll * sigma_root_t + x1 = log(s0 / h) / sigma_root_t + ll * sigma_root_t + y1 = log(h / s0) / sigma_root_t + ll * sigma_root_t + h_over_s = h / s0 if self._option_type == FinFXBarrierTypes.DOWN_AND_OUT_CALL: if h >= K: - c_do = S0 * dq * N(x1) - K * df * N(x1 - sigmaRootT) \ - - S0 * dq * pow(hOverS, 2.0 * ll) * N(y1) \ - + K * df * pow(hOverS, 2.0 * ll - 2.0) * N(y1 - sigmaRootT) + c_do = s0 * dq * N(x1) - K * df * N(x1 - sigma_root_t) \ + - s0 * dq * pow(h_over_s, 2.0 * ll) * N(y1) \ + + K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(y1 - sigma_root_t) price = c_do else: - c_di = S0 * dq * pow(hOverS, 2.0 * ll) * N(y) \ - - K * df * pow(hOverS, 2.0 * ll - 2.0) * N(y - sigmaRootT) + c_di = s0 * dq * pow(h_over_s, 2.0 * ll) * N(y) \ + - K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(y - sigma_root_t) price = c - c_di elif self._option_type == FinFXBarrierTypes.DOWN_AND_IN_CALL: if h <= K: - c_di = S0 * dq * pow(hOverS, 2.0 * ll) * N(y) \ - - K * df * pow(hOverS, 2.0 * ll - 2.0) * N(y - sigmaRootT) + c_di = s0 * dq * pow(h_over_s, 2.0 * ll) * N(y) \ + - K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(y - sigma_root_t) price = c_di else: - c_do = S0 * dq * N(x1) \ - - K * df * N(x1 - sigmaRootT) \ - - S0 * dq * pow(hOverS, 2.0 * ll) * N(y1) \ - + K * df * pow(hOverS, 2.0 * ll - 2.0) * N(y1 - sigmaRootT) + c_do = s0 * dq * N(x1) \ + - K * df * N(x1 - sigma_root_t) \ + - s0 * dq * pow(h_over_s, 2.0 * ll) * N(y1) \ + + K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(y1 - sigma_root_t) price = c - c_do elif self._option_type == FinFXBarrierTypes.UP_AND_IN_CALL: if h >= K: - c_ui = S0 * dq * N(x1) - K * df * N(x1 - sigmaRootT) \ - - S0 * dq * pow(hOverS, 2.0 * ll) * (N(-y) - N(-y1)) \ - + K * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(-y + sigmaRootT) - N(-y1 + sigmaRootT)) + c_ui = s0 * dq * N(x1) - K * df * N(x1 - sigma_root_t) \ + - s0 * dq * pow(h_over_s, 2.0 * ll) * (N(-y) - N(-y1)) \ + + K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(-y + sigma_root_t) - N(-y1 + sigma_root_t)) price = c_ui else: price = c elif self._option_type == FinFXBarrierTypes.UP_AND_OUT_CALL: if h > K: - c_ui = S0 * dq * N(x1) - K * df * N(x1 - sigmaRootT) \ - - S0 * dq * pow(hOverS, 2.0 * ll) * (N(-y) - N(-y1)) \ - + K * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(-y + sigmaRootT) - N(-y1 + sigmaRootT)) + c_ui = s0 * dq * N(x1) - K * df * N(x1 - sigma_root_t) \ + - s0 * dq * pow(h_over_s, 2.0 * ll) * (N(-y) - N(-y1)) \ + + K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(-y + sigma_root_t) - N(-y1 + sigma_root_t)) price = c - c_ui else: price = 0.0 elif self._option_type == FinFXBarrierTypes.UP_AND_IN_PUT: if h > K: - p_ui = -S0 * dq * pow(hOverS, 2.0 * ll) * N(-y) \ - + K * df * pow(hOverS, 2.0 * ll - 2.0) * N(-y + sigmaRootT) + p_ui = -s0 * dq * pow(h_over_s, 2.0 * ll) * N(-y) \ + + K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(-y + sigma_root_t) price = p_ui else: - p_uo = -S0 * dq * N(-x1) \ - + K * df * N(-x1 + sigmaRootT) \ - + S0 * dq * pow(hOverS, 2.0 * ll) * N(-y1) \ - - K * df * pow(hOverS, 2.0 * ll - 2.0) * \ - N(-y1 + sigmaRootT) + p_uo = -s0 * dq * N(-x1) \ + + K * df * N(-x1 + sigma_root_t) \ + + s0 * dq * pow(h_over_s, 2.0 * ll) * N(-y1) \ + - K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(-y1 + sigma_root_t) price = p - p_uo elif self._option_type == FinFXBarrierTypes.UP_AND_OUT_PUT: if h >= K: - p_ui = -S0 * dq * pow(hOverS, 2.0 * ll) * N(-y) \ - + K * df * pow(hOverS, 2.0 * ll - 2.0) * N(-y + sigmaRootT) + p_ui = -s0 * dq * pow(h_over_s, 2.0 * ll) * N(-y) \ + + K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(-y + sigma_root_t) price = p - p_ui else: - p_uo = -S0 * dq * N(-x1) \ - + K * df * N(-x1 + sigmaRootT) \ - + S0 * dq * pow(hOverS, 2.0 * ll) * N(-y1) \ - - K * df * pow(hOverS, 2.0 * ll - 2.0) * \ - N(-y1 + sigmaRootT) + p_uo = -s0 * dq * N(-x1) \ + + K * df * N(-x1 + sigma_root_t) \ + + s0 * dq * pow(h_over_s, 2.0 * ll) * N(-y1) \ + - K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + N(-y1 + sigma_root_t) price = p_uo elif self._option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT: if h >= K: price = 0.0 else: - p_di = -S0 * dq * N(-x1) \ - + K * df * N(-x1 + sigmaRootT) \ - + S0 * dq * pow(hOverS, 2.0 * ll) * (N(y) - N(y1)) \ - - K * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(y - sigmaRootT) - N(y1 - sigmaRootT)) + p_di = -s0 * dq * N(-x1) \ + + K * df * N(-x1 + sigma_root_t) \ + + s0 * dq * pow(h_over_s, 2.0 * ll) * (N(y) - N(y1)) \ + - K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(y - sigma_root_t) - N(y1 - sigma_root_t)) price = p - p_di elif self._option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT: if h >= K: price = p else: - p_di = -S0 * dq * N(-x1) \ - + K * df * N(-x1 + sigmaRootT) \ - + S0 * dq * pow(hOverS, 2.0 * ll) * (N(y) - N(y1)) \ - - K * df * pow(hOverS, 2.0 * ll - 2.0) * \ - (N(y - sigmaRootT) - N(y1 - sigmaRootT)) + p_di = -s0 * dq * N(-x1) \ + + K * df * N(-x1 + sigma_root_t) \ + + s0 * dq * pow(h_over_s, 2.0 * ll) * (N(y) - N(y1)) \ + - K * df * pow(h_over_s, 2.0 * ll - 2.0) * \ + (N(y - sigma_root_t) - N(y1 - sigma_root_t)) price = p_di else: raise FinError("Unknown barrier option type." + @@ -269,7 +275,7 @@ def value_mc(self, num_time_steps = int(t * num_ann_steps) K = self._strike_fx_rate B = self._barrier_level - S0 = spot_fx_rate + s0 = spot_fx_rate option_type = self._option_type process = FinProcessSimulator() @@ -278,13 +284,13 @@ def value_mc(self, ####################################################################### - if option_type == FinFXBarrierTypes.DOWN_AND_OUT_CALL and S0 <= B: + if option_type == FinFXBarrierTypes.DOWN_AND_OUT_CALL and s0 <= B: return 0.0 - elif option_type == FinFXBarrierTypes.UP_AND_OUT_CALL and S0 >= B: + elif option_type == FinFXBarrierTypes.UP_AND_OUT_CALL and s0 >= B: return 0.0 - elif option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT and S0 <= B: + elif option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT and s0 <= B: return 0.0 - elif option_type == FinFXBarrierTypes.UP_AND_OUT_PUT and S0 >= B: + elif option_type == FinFXBarrierTypes.UP_AND_OUT_PUT and s0 >= B: return 0.0 ####################################################################### @@ -292,13 +298,13 @@ def value_mc(self, simple_call = False simple_put = False - if option_type == FinFXBarrierTypes.DOWN_AND_IN_CALL and S0 <= B: + if option_type == FinFXBarrierTypes.DOWN_AND_IN_CALL and s0 <= B: simple_call = True - elif option_type == FinFXBarrierTypes.UP_AND_IN_CALL and S0 >= B: + elif option_type == FinFXBarrierTypes.UP_AND_IN_CALL and s0 >= B: simple_call = True - elif option_type == FinFXBarrierTypes.UP_AND_IN_PUT and S0 >= B: + elif option_type == FinFXBarrierTypes.UP_AND_IN_PUT and s0 >= B: simple_put = True - elif option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT and S0 <= B: + elif option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT and s0 <= B: simple_put = True if simple_put or simple_call: @@ -306,24 +312,24 @@ def value_mc(self, process_type, t, model_params, 1, num_paths, seed) if simple_call: - sT = s_all[:, -1] - c = (np.maximum(sT - K, 0.0)).mean() + s_t = s_all[:, -1] + c = (np.maximum(s_t - K, 0.0)).mean() c = c * exp(-r_d * t) return c if simple_put: - sT = s_all[:, -1] - p = (np.maximum(K - sT, 0.0)).mean() + s_t = s_all[:, -1] + p = (np.maximum(K - s_t, 0.0)).mean() p = p * exp(-r_d * t) return p # Get full set of paths s_all = process.get_process(process_type, - t, - model_params, - num_time_steps, - num_paths, - seed) + t, + model_params, + num_time_steps, + num_paths, + seed) (num_paths, num_time_steps) = s_all.shape @@ -332,43 +338,47 @@ def value_mc(self, option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT or \ option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT: - barrierCrossedFromAbove = [False] * num_paths + barrier_crossed_from_above = [False] * num_paths for p in range(0, num_paths): - barrierCrossedFromAbove[p] = np.any(s_all[p] <= B) + barrier_crossed_from_above[p] = np.any(s_all[p] <= B) if option_type == FinFXBarrierTypes.UP_AND_IN_CALL or \ option_type == FinFXBarrierTypes.UP_AND_OUT_CALL or \ option_type == FinFXBarrierTypes.UP_AND_IN_PUT or \ option_type == FinFXBarrierTypes.UP_AND_OUT_PUT: - barrierCrossedFromBelow = [False] * num_paths + barrier_crossed_from_below = [False] * num_paths for p in range(0, num_paths): - barrierCrossedFromBelow[p] = np.any(s_all[p] >= B) + barrier_crossed_from_below[p] = np.any(s_all[p] >= B) payoff = np.zeros(num_paths) ones = np.ones(num_paths) if option_type == FinFXBarrierTypes.DOWN_AND_OUT_CALL: payoff = np.maximum(s_all[:, -1] - K, 0.0) * \ - (ones - barrierCrossedFromAbove) + (ones - barrier_crossed_from_above) elif option_type == FinFXBarrierTypes.DOWN_AND_IN_CALL: - payoff = np.maximum(s_all[:, -1] - K, 0.0) * barrierCrossedFromAbove + payoff = np.maximum(s_all[:, -1] - K, 0.0) * \ + barrier_crossed_from_above elif option_type == FinFXBarrierTypes.UP_AND_IN_CALL: - payoff = np.maximum(s_all[:, -1] - K, 0.0) * barrierCrossedFromBelow + payoff = np.maximum(s_all[:, -1] - K, 0.0) * \ + barrier_crossed_from_below elif option_type == FinFXBarrierTypes.UP_AND_OUT_CALL: payoff = np.maximum(s_all[:, -1] - K, 0.0) * \ - (ones - barrierCrossedFromBelow) + (ones - barrier_crossed_from_below) elif option_type == FinFXBarrierTypes.UP_AND_IN_PUT: - payoff = np.maximum(K - s_all[:, -1], 0.0) * barrierCrossedFromBelow + payoff = np.maximum( + K - s_all[:, -1], 0.0) * barrier_crossed_from_below elif option_type == FinFXBarrierTypes.UP_AND_OUT_PUT: payoff = np.maximum(K - s_all[:, -1], 0.0) * \ - (ones - barrierCrossedFromBelow) + (ones - barrier_crossed_from_below) elif option_type == FinFXBarrierTypes.DOWN_AND_OUT_PUT: payoff = np.maximum(K - s_all[:, -1], 0.0) * \ - (ones - barrierCrossedFromAbove) + (ones - barrier_crossed_from_above) elif option_type == FinFXBarrierTypes.DOWN_AND_IN_PUT: - payoff = np.maximum(K - s_all[:, -1], 0.0) * barrierCrossedFromAbove + payoff = np.maximum( + K - s_all[:, -1], 0.0) * barrier_crossed_from_above else: raise FinError("Unknown barrier option type." + str(self._option_type)) @@ -395,7 +405,7 @@ def __repr__(self): ############################################################################### def _print(self): - """ Print a list of the unadjusted coupon payment dates used in + """ Print a lis_t of the unadjusted coupon payment dates used in analytic calculations for the bond. """ print(self) diff --git a/financepy/products/fx/fx_digital_option.py b/financepy/products/fx/fx_digital_option.py index c8f90a7d..abee9ec6 100644 --- a/financepy/products/fx/fx_digital_option.py +++ b/financepy/products/fx/fx_digital_option.py @@ -56,10 +56,10 @@ def __init__(self, self._strike_fx_rate = strike_fx_rate self._currency_pair = currency_pair - self._forName = self._currency_pair[0:3] - self._domName = self._currency_pair[3:6] + self._for_name = self._currency_pair[0:3] + self._dom_name = self._currency_pair[3:6] - if prem_currency != self._domName and prem_currency != self._forName: + if prem_currency != self._dom_name and prem_currency != self._for_name: raise FinError("Notional currency not in currency pair.") self._prem_currency = prem_currency @@ -78,8 +78,8 @@ def __init__(self, def value(self, value_dt, spot_fx_rate, # 1 unit of foreign in domestic - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ Valuation of a digital option using Black-Scholes model. This allows for 4 cases - first upper barriers that when crossed pay out @@ -93,11 +93,11 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as valuation date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as valuation date") @@ -118,35 +118,35 @@ def value(self, tdel = np.maximum(tdel, 1e-10) # TODO RESOLVE TDEL versus TEXP - dom_df = dom_discount_curve._df(tdel) - for_df = for_discount_curve._df(tdel) + dom_df = domestic_curve._df(tdel) + for_df = foreign_curve._df(tdel) r_d = -np.log(dom_df) / tdel rf = -np.log(for_df) / tdel - S0 = spot_fx_rate + s0 = spot_fx_rate K = self._strike_fx_rate if type(model) == BlackScholes: volatility = model._volatility - lnS0k = np.log(S0 / K) + ln_s0_k = np.log(s0 / K) den = volatility * np.sqrt(t_exp) v2 = volatility * volatility mu = r_d - rf - d2 = (lnS0k + (mu - v2 / 2.0) * tdel) / den + d2 = (ln_s0_k + (mu - v2 / 2.0) * tdel) / den if self._option_type == OptionTypes.DIGITAL_CALL and \ - self._forName == self._prem_currency: - v = S0 * np.exp(-rf * tdel) * n_vect(d2) + self._for_name == self._prem_currency: + v = s0 * np.exp(-rf * tdel) * n_vect(d2) elif self._option_type == OptionTypes.DIGITAL_PUT and \ - self._forName == self._prem_currency: - v = S0 * np.exp(-rf * tdel) * n_vect(-d2) + self._for_name == self._prem_currency: + v = s0 * np.exp(-rf * tdel) * n_vect(-d2) elif self._option_type == OptionTypes.DIGITAL_CALL and \ - self._domName == self._prem_currency: + self._dom_name == self._prem_currency: v = np.exp(-r_d * tdel) * n_vect(d2) elif self._option_type == OptionTypes.DIGITAL_PUT and \ - self._domName == self._prem_currency: + self._dom_name == self._prem_currency: v = np.exp(-r_d * tdel) * n_vect(-d2) else: raise FinError("Unknown option type") diff --git a/financepy/products/fx/fx_double_digital_option.py b/financepy/products/fx/fx_double_digital_option.py index 29836621..3533d173 100644 --- a/financepy/products/fx/fx_double_digital_option.py +++ b/financepy/products/fx/fx_double_digital_option.py @@ -59,10 +59,10 @@ def __init__(self, raise FinError("Currency pair must be 6 characters.") self._currency_pair = currency_pair - self._forName = self._currency_pair[0:3] - self._domName = self._currency_pair[3:6] + self._for_name = self._currency_pair[0:3] + self._dom_name = self._currency_pair[3:6] - if prem_currency != self._domName and prem_currency != self._forName: + if prem_currency != self._dom_name and prem_currency != self._for_name: raise FinError("Notional currency not in currency pair.") self._prem_currency = prem_currency @@ -76,8 +76,8 @@ def __init__(self, def value(self, value_dt, spot_fx_rate, # 1 unit of foreign in domestic - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ Valuation of a double digital option using Black-Scholes model. The option pays out the notional in the premium currency if the @@ -92,11 +92,11 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as valuation date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as valuation date") @@ -117,31 +117,31 @@ def value(self, tdel = np.maximum(tdel, 1e-10) # TODO RESOLVE TDEL versus TEXP - dom_df = dom_discount_curve._df(tdel) - for_df = for_discount_curve._df(tdel) + dom_df = domestic_curve._df(tdel) + for_df = foreign_curve._df(tdel) r_d = -np.log(dom_df) / tdel r_f = -np.log(for_df) / tdel - S0 = spot_fx_rate + s0 = spot_fx_rate K1 = self._lower_strike K2 = self._upper_strike - if type(model) == BlackScholes: + if isinstance(model, BlackScholes): volatility = model._volatility - lnS0k1 = np.log(S0 / K1) - lnS0k2 = np.log(S0 / K2) + ln_s0_k1 = np.log(s0 / K1) + ln_s0_k2 = np.log(s0 / K2) den = volatility * np.sqrt(t_exp) v2 = volatility * volatility mu = r_d - r_f - lower_d2 = (lnS0k1 + (mu - v2 / 2.0) * tdel) / den - upper_d2 = (lnS0k2 + (mu - v2 / 2.0) * tdel) / den + lower_d2 = (ln_s0_k1 + (mu - v2 / 2.0) * tdel) / den + upper_d2 = (ln_s0_k2 + (mu - v2 / 2.0) * tdel) / den - if self._prem_currency == self._forName: - lower_digital = S0 * np.exp(-r_f * tdel) * n_vect(-lower_d2) - upper_digital = S0 * np.exp(-r_f * tdel) * n_vect(-upper_d2) - elif self._prem_currency == self._domName: + if self._prem_currency == self._for_name: + lower_digital = s0 * np.exp(-r_f * tdel) * n_vect(-lower_d2) + upper_digital = s0 * np.exp(-r_f * tdel) * n_vect(-upper_d2) + elif self._prem_currency == self._dom_name: lower_digital = np.exp(-r_f * tdel) * n_vect(-lower_d2) upper_digital = np.exp(-r_f * tdel) * n_vect(-upper_d2) diff --git a/financepy/products/fx/fx_fixed_lookback_option.py b/financepy/products/fx/fx_fixed_lookback_option.py index 12b17ff0..77766b59 100644 --- a/financepy/products/fx/fx_fixed_lookback_option.py +++ b/financepy/products/fx/fx_fixed_lookback_option.py @@ -7,7 +7,7 @@ from ...utils.math import N -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...models.gbm_process_simulator import FinGBMProcess from ...utils.helpers import check_argument_types @@ -49,8 +49,8 @@ def __init__(self, def value(self, value_dt: Date, stock_price: float, - dom_discount_curve: DiscountCurve, - for_discount_curve: DiscountCurve, + domestic_curve: DiscountCurve, + foreign_curve: DiscountCurve, volatility: float, stock_min_max: float): """ Value FX Fixed Lookback Option using Black Scholes model and @@ -62,20 +62,20 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as option value date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as option value date") t = (self._expiry_dt - value_dt) / gDaysInYear - df = dom_discount_curve.df(self._expiry_dt) + df = domestic_curve.df(self._expiry_dt) r = -np.log(df)/t - dq = for_discount_curve.df(self._expiry_dt) + dq = foreign_curve.df(self._expiry_dt) q = -np.log(dq)/t v = volatility @@ -97,8 +97,8 @@ def value(self, # There is a risk of an overflow in the limit of q=r which # we remove by adjusting the value of the dividend - if abs(r - q) < gSmall: - q = r + gSmall + if abs(r - q) < g_small: + q = r + g_small df = exp(-r * t) dq = exp(-q * t) @@ -151,7 +151,7 @@ def value(self, term = -expbt * N(-f1) else: term = ((s0 / s_min)**(-w)) * N(-f1 + 2.0 * - b * sqrt(t) / v) - expbt * N(-f1) + b * sqrt(t) / v) - expbt * N(-f1) v = df * (k - s_min) - s0 * dq * N(-f1) + \ s_min * df * N(-f2) + s0 * df * u * term diff --git a/financepy/products/fx/fx_float_lookback_option.py b/financepy/products/fx/fx_float_lookback_option.py index dd538d52..0ff7308f 100644 --- a/financepy/products/fx/fx_float_lookback_option.py +++ b/financepy/products/fx/fx_float_lookback_option.py @@ -6,7 +6,7 @@ from enum import Enum from ...utils.math import N -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...models.gbm_process_simulator import FinGBMProcess from ...products.fx.fx_option import FXOption @@ -96,8 +96,8 @@ def value(self, raise FinError( "s_max must be greater than or equal to the stock price.") - if abs(r - q) < gSmall: - q = r + gSmall + if abs(r - q) < g_small: + q = r + g_small dq = np.exp(-q * t) df = np.exp(-r * t) diff --git a/financepy/products/fx/fx_forward.py b/financepy/products/fx/fx_forward.py index ad4454d0..11d6b98d 100644 --- a/financepy/products/fx/fx_forward.py +++ b/financepy/products/fx/fx_forward.py @@ -50,23 +50,27 @@ def __init__(self, self._strike_fx_rate = strike_fx_rate self._currency_pair = currency_pair - self._forName = self._currency_pair[0:3] - self._domName = self._currency_pair[3:6] + self._for_name = self._currency_pair[0:3] + self._dom_name = self._currency_pair[3:6] - if notional_currency != self._domName and notional_currency != self._forName: + if notional_currency != self._dom_name and notional_currency != self._for_name: raise FinError("Notional currency not in currency pair.") self._notional = notional self._notional_currency = notional_currency self._spot_days = spot_days + self._notional_dom = None + self._notional_for = None + self._cash_dom = None + self._cash_for = None ############################################################################### def value(self, value_dt, spot_fx_rate, # 1 unit of foreign in domestic - dom_discount_curve, - for_discount_curve): + domestic_curve, + foreign_curve): """ Calculate the value of an FX forward contract where the current FX rate is the spot_fx_rate. """ @@ -76,11 +80,11 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as option value date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as option value date") @@ -97,28 +101,28 @@ def value(self, t = np.maximum(t, 1e-10) - newFwdFXRate = self.forward(value_dt, - spot_fx_rate, - dom_discount_curve, - for_discount_curve) + newfwd_fx_rate = self.forward(value_dt, + spot_fx_rate, + domestic_curve, + foreign_curve) - dom_df = dom_discount_curve._df(t) + dom_df = domestic_curve._df(t) - if self._notional_currency == self._domName: + if self._notional_currency == self._dom_name: self._notional_dom = self._notional self._notional_for = self._notional / self._strike_fx_rate - elif self._notional_currency == self._forName: + elif self._notional_currency == self._for_name: self._notional_dom = self._notional * self._strike_fx_rate self._notional_for = self._notional else: raise FinError("Invalid notional currency.") - if self._notional_currency == self._forName: - v = (newFwdFXRate - self._strike_fx_rate) + if self._notional_currency == self._for_name: + v = (newfwd_fx_rate - self._strike_fx_rate) v = v * self._notional * dom_df - elif self._notional_currency == self._domName: - v = (newFwdFXRate - self._strike_fx_rate) - v = v * self._notional * dom_df * newFwdFXRate + elif self._notional_currency == self._dom_name: + v = (newfwd_fx_rate - self._strike_fx_rate) + v = v * self._notional * dom_df * newfwd_fx_rate self._cash_dom = v * self._notional_dom / self._strike_fx_rate self._cash_for = v * self._notional_for / spot_fx_rate @@ -128,16 +132,16 @@ def value(self, "cash_for": self._cash_for, "not_dom": self._notional_dom, "not_for": self._notional_for, - "ccy_dom": self._domName, - "ccy_for": self._forName} + "ccy_dom": self._dom_name, + "ccy_for": self._for_name} ############################################################################### def forward(self, value_dt, spot_fx_rate, # 1 unit of foreign in domestic - dom_discount_curve, - for_discount_curve): + domestic_curve, + foreign_curve): """ Calculate the FX Forward rate that makes the value of the FX contract equal to zero. """ @@ -154,11 +158,11 @@ def forward(self, t = np.maximum(t, 1e-10) - for_df = for_discount_curve._df(t) - dom_df = dom_discount_curve._df(t) + for_df = foreign_curve._df(t) + dom_df = domestic_curve._df(t) - fwdFXRate = spot_fx_rate * for_df / dom_df - return fwdFXRate + fwd_fx_rate = spot_fx_rate * for_df / dom_df + return fwd_fx_rate ############################################################################### diff --git a/financepy/products/fx/fx_mkt_conventions.py b/financepy/products/fx/fx_mkt_conventions.py index a12bee25..eaf9c923 100644 --- a/financepy/products/fx/fx_mkt_conventions.py +++ b/financepy/products/fx/fx_mkt_conventions.py @@ -130,6 +130,6 @@ def __init__(self, raise FinError("Unknown currency code ", ccy2) self._ccy2 = ccy2 - self._rate + self._rate = None ############################################################################### diff --git a/financepy/products/fx/fx_one_touch_option.py b/financepy/products/fx/fx_one_touch_option.py index bb566cce..bfeee4ae 100644 --- a/financepy/products/fx/fx_one_touch_option.py +++ b/financepy/products/fx/fx_one_touch_option.py @@ -151,8 +151,8 @@ def __init__(self, def value(self, value_dt: Date, spot_fx_rate: (float, np.ndarray), - dom_discount_curve: DiscountCurve, - for_discount_curve: DiscountCurve, + domestic_curve: DiscountCurve, + foreign_curve: DiscountCurve, model): """ FX One-Touch Option valuation using the Black-Scholes model assuming a continuous (American) barrier from value date to expiry. @@ -164,10 +164,10 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError("Domestic Curve date not same as valuation date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError("Foreign Curve date not same as valuation date") DEBUG_MODE = False @@ -184,11 +184,11 @@ def value(self, H = self._barrier_rate K = self._payment_size - sqrtT = np.sqrt(t) + sqrt_t = np.sqrt(t) - df = dom_discount_curve.df(self._expiry_dt) - r_d = dom_discount_curve.cc_rate(self._expiry_dt) - r_f = for_discount_curve.cc_rate(self._expiry_dt) + df = domestic_curve.df(self._expiry_dt) + r_d = domestic_curve.cc_rate(self._expiry_dt) + r_f = foreign_curve.cc_rate(self._expiry_dt) v = model._volatility v = max(v, 1e-6) @@ -212,9 +212,10 @@ def value(self, raise FinError("FX Rate is currently below barrier.") eta = 1.0 - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) - A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta * lam * v * sqrtT) + A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * + z - 2.0 * eta * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -225,9 +226,10 @@ def value(self, raise FinError("FX Rate is currently above barrier.") eta = -1.0 - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) - A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta * lam * v * sqrtT) + A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * + z - 2.0 * eta * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -239,9 +241,10 @@ def value(self, eta = 1.0 K = H - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) - A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta * lam * v * sqrtT) + A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * + z - 2.0 * eta * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -253,9 +256,10 @@ def value(self, eta = -1.0 K = H - z = np.log(H/s0) / v / sqrtT + lam * v * sqrtT + z = np.log(H/s0) / v / sqrt_t + lam * v * sqrt_t A5_1 = np.power(H/s0, mu + lam) * n_vect(eta * z) - A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * z - 2.0 * eta * lam * v * sqrtT) + A5_2 = np.power(H/s0, mu - lam) * n_vect(eta * + z - 2.0 * eta * lam * v * sqrt_t) v = (A5_1 + A5_2) * K return v @@ -267,11 +271,11 @@ def value(self, eta = +1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 + B4) return v @@ -284,10 +288,11 @@ def value(self, eta = -1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) - B4 = K * df * np.power(H/s0, 2.0 * mu) * n_vect(eta * y2 - eta * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) + B4 = K * df * np.power(H/s0, 2.0 * mu) * \ + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 + B4) return v @@ -299,8 +304,8 @@ def value(self, eta = +1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-r_f * t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -315,8 +320,8 @@ def value(self, eta = -1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-r_f * t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -332,11 +337,11 @@ def value(self, eta = +1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 - B4) return v @@ -349,11 +354,11 @@ def value(self, eta = -1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT - B2 = K * df * n_vect(phi * x2 - phi * v * sqrtT) + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + B2 = K * df * n_vect(phi * x2 - phi * v * sqrt_t) B4 = K * df * np.power(H/s0, 2.0 * mu) * \ - n_vect(eta * y2 - eta * v * sqrtT) + n_vect(eta * y2 - eta * v * sqrt_t) v = (B2 - B4) return v @@ -366,8 +371,8 @@ def value(self, eta = +1.0 phi = +1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-r_f*t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -383,8 +388,8 @@ def value(self, eta = -1.0 phi = -1.0 - x2 = np.log(s0/H) / v / sqrtT + (mu + 1.0) * v * sqrtT - y2 = np.log(H/s0) / v / sqrtT + (mu + 1.0) * v * sqrtT + x2 = np.log(s0/H) / v / sqrt_t + (mu + 1.0) * v * sqrt_t + y2 = np.log(H/s0) / v / sqrt_t + (mu + 1.0) * v * sqrt_t dq = np.exp(-r_f*t) A2 = s0 * dq * n_vect(phi * x2) A4 = s0 * dq * np.power(H/s0, 2.0*(mu+1.0)) * n_vect(eta * y2) @@ -417,8 +422,8 @@ def _print(self): def value_mc(self, value_dt: Date, stock_price: float, - domCurve: DiscountCurve, - forCurve: DiscountCurve, + dom_curve: DiscountCurve, + for_curve: DiscountCurve, model, num_paths: int = 10000, num_steps_per_year: int = 252, @@ -432,10 +437,10 @@ def value_mc(self, t = (self._expiry_dt - value_dt) / gDaysInYear - df_d = domCurve.df(self._expiry_dt) + df_d = dom_curve.df(self._expiry_dt) r_d = -np.log(df_d)/t - df_f = forCurve.df(self._expiry_dt) + df_f = for_curve.df(self._expiry_dt) r_f = -np.log(df_f)/t num_time_steps = int(t * num_steps_per_year) + 1 diff --git a/financepy/products/fx/fx_option.py b/financepy/products/fx/fx_option.py index c5d5c6ee..0ba21570 100644 --- a/financepy/products/fx/fx_option.py +++ b/financepy/products/fx/fx_option.py @@ -5,6 +5,7 @@ from ...models.black_scholes import BlackScholes from ...utils.global_vars import gDaysInYear +from ...utils.date import Date ########################################################################## @@ -14,132 +15,158 @@ class FXOption: - """ Class that is used to perform perturbation risk for FX options. """ + """ Class that is used to perform perturbation risk for FX options.""" + + def value(self, + value_dt: Date, + spot_fx_rate: float, + domestic_curve, + foreign_curve, + model): + + print("You should not be here!") + return 0.0 ############################################################################### def delta(self, value_dt, spot_fx_rate, - discount_curve, - dividend_curve, + domestic_curve, + foreign_curve, model): """ Calculate the option delta (FX rate sensitivity) by adding on a small bump and calculating the change in the option price. """ - v = self.value(value_dt, spot_fx_rate, - discount_curve, dividend_curve, + v = self.value(value_dt, + spot_fx_rate, + domestic_curve, + foreign_curve, model) - vBumped = self.value(value_dt, - spot_fx_rate + bump, - discount_curve, - dividend_curve, model) + v_bumped = self.value(value_dt, + spot_fx_rate + bump, + domestic_curve, + foreign_curve, model) - if type(vBumped) is dict: - delta = (vBumped['value'] - v['value']) / bump + if type(v_bumped) is dict: + delta = (v_bumped['value'] - v['value']) / bump else: - delta = (vBumped - v) / bump + delta = (v_bumped - v) / bump return delta ############################################################################### - def gamma(self, value_dt, spot_fx_rate, discount_curve, dividend_curve, + def gamma(self, value_dt, + spot_fx_rate, + domestic_curve, + foreign_curve, model): """ Calculate the option gamma (delta sensitivity) by adding on a small bump and calculating the change in the option delta. """ - v = self.delta(value_dt, spot_fx_rate, discount_curve, dividend_curve, + v = self.delta(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model) - vBumpedDn = self.delta(value_dt, spot_fx_rate + bump, discount_curve, - dividend_curve, model) + v_bumped_dn = self.delta(value_dt, spot_fx_rate + bump, domestic_curve, + foreign_curve, model) - vBumpedUp = self.delta(value_dt, spot_fx_rate + bump, discount_curve, - dividend_curve, model) + v_bumped_up = self.delta(value_dt, spot_fx_rate + bump, domestic_curve, + foreign_curve, model) - if type(v) is dict: - num = (vBumpedUp['value'] - 2.0 * v['value'] + vBumpedDn['value']) + if isinstance(v, dict): + num = (v_bumped_up['value'] - 2.0 * + v['value'] + v_bumped_dn['value']) gamma = num / bump / 2.0 else: - gamma = (vBumpedUp - 2.0 * v + vBumpedDn) / bump / 2.0 + gamma = (v_bumped_up - 2.0 * v + v_bumped_dn) / bump / 2.0 return gamma ############################################################################### - def vega(self, value_dt, spot_fx_rate, discount_curve, dividend_curve, model): + def vega(self, value_dt, + spot_fx_rate, + domestic_curve, + foreign_curve, model): """ Calculate the option vega (volatility sensitivity) by adding on a small bump and calculating the change in the option price. """ bump = 0.01 - v = self.value(value_dt, spot_fx_rate, discount_curve, dividend_curve, + v = self.value(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model) - vp = self.value(value_dt, spot_fx_rate, discount_curve, dividend_curve, + vp = self.value(value_dt, spot_fx_rate, domestic_curve, foreign_curve, BlackScholes(model._volatility + bump)) - if type(v) is dict: - vega = (vp['value'] - v['value'])# / bump + if isinstance(v, dict): + vega = (vp['value'] - v['value']) # / bump else: - vega = (vp - v)# / bump + vega = (vp - v) # / bump return vega ############################################################################### - def theta(self, value_dt, spot_fx_rate, discount_curve, dividend_curve, model): + def theta(self, value_dt, spot_fx_rate, domestic_curve, foreign_curve, model): """ Calculate the option theta (calendar time sensitivity) by moving forward one day and calculating the change in the option price. """ - v = self.value(value_dt, spot_fx_rate, discount_curve, - dividend_curve, model) + v = self.value(value_dt, + spot_fx_rate, + domestic_curve, + foreign_curve, + model) next_dt = value_dt.add_days(1) - discount_curve._value_dt = next_dt - dividend_curve._value_dt = next_dt + domestic_curve._value_dt = next_dt + foreign_curve._value_dt = next_dt - vBumped = self.value(next_dt, spot_fx_rate, discount_curve, - dividend_curve, model) + v_bumped = self.value(next_dt, spot_fx_rate, domestic_curve, + foreign_curve, model) bump = 1.0 / gDaysInYear - if type(v) is dict: - theta = (vBumped['value'] - v['value']) / bump + if isinstance(v, dict): + theta = (v_bumped['value'] - v['value']) / bump else: - theta = (vBumped - v) / bump + theta = (v_bumped - v) / bump - discount_curve._value_dt = value_dt - dividend_curve._value_dt = value_dt + domestic_curve._value_dt = value_dt + foreign_curve._value_dt = value_dt return theta ############################################################################## - def rho(self, value_dt, spot_fx_rate, discount_curve, dividend_curve, model): + def rho(self, value_dt, + spot_fx_rate, + domestic_curve, + foreign_curve, + model): """ Calculate the option rho (interest rate sensitivity) by perturbing the discount curve and revaluing. """ v = self.value( value_dt, spot_fx_rate, - discount_curve, - dividend_curve, + domestic_curve, + foreign_curve, model) - vBumped = self.value( + v_bumped = self.value( value_dt, spot_fx_rate, - discount_curve.bump(bump), - dividend_curve, + domestic_curve.bump(bump), + foreign_curve, model) - if type(v) is dict: - rho = (vBumped['value'] - v['value']) / bump + if isinstance(v, dict): + rho = (v_bumped['value'] - v['value']) / bump else: - rho = (vBumped - v) / bump + rho = (v_bumped - v) / bump return rho diff --git a/financepy/products/fx/fx_rainbow_option.py b/financepy/products/fx/fx_rainbow_option.py index e7284fec..e43d97ee 100644 --- a/financepy/products/fx/fx_rainbow_option.py +++ b/financepy/products/fx/fx_rainbow_option.py @@ -2,6 +2,8 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################## +from enum import Enum + import numpy as np from typing import List @@ -10,9 +12,7 @@ from ...utils.global_vars import gDaysInYear from ...utils.error import FinError from ...models.gbm_process_simulator import FinGBMProcess -from ...products.equity.equity_option import EquityOption - -from enum import Enum +from ...products.fx.fx_option import FXOption from ...utils.helpers import check_argument_types @@ -86,7 +86,7 @@ def value_mc_fast(t, num_time_steps = 2 s_all = model.get_paths_assets(num_assets, num_paths, num_time_steps, - t, mus, stock_prices, volatilities, betas, seed) + t, mus, stock_prices, volatilities, betas, seed) payoff = payoff_value(s_all, payoff_type.value, payoff_params) payoff = np.mean(payoff) @@ -96,7 +96,7 @@ def value_mc_fast(t, ############################################################################### -class FXRainbowOption(EquityOption): +class FXRainbowOption(FXOption): def __init__(self, expiry_dt: Date, @@ -180,8 +180,8 @@ def validate_payoff(self, payoff_type, payoff_params, num_assets): def value(self, value_dt, stock_prices, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, volatilities, betas): @@ -191,11 +191,11 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as option value date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as option value date") @@ -206,18 +206,18 @@ def value(self, raise FinError("Value date after expiry date.") self.validate(stock_prices, - for_discount_curve, + foreign_curve, volatilities, betas) # Use result by Stulz (1982) given by Haug Page 211 t = (self._expiry_dt - value_dt) / gDaysInYear - df = dom_discount_curve._df(t) + df = domestic_curve._df(t) r = -np.log(df) / t - q1 = for_discount_curve[0] - q2 = for_discount_curve[1] + q1 = foreign_curve[0] + q2 = foreign_curve[1] rho = betas[0] ** 2 s1 = stock_prices[0] s2 = stock_prices[1] diff --git a/financepy/products/fx/fx_vanilla_option.py b/financepy/products/fx/fx_vanilla_option.py index 0d8bd0b7..b2b16118 100644 --- a/financepy/products/fx/fx_vanilla_option.py +++ b/financepy/products/fx/fx_vanilla_option.py @@ -8,7 +8,7 @@ from ...utils.date import Date from ...utils.math import nprime -from ...utils.global_vars import gDaysInYear, gSmall +from ...utils.global_vars import gDaysInYear, g_small from ...utils.error import FinError from ...utils.global_types import OptionTypes #from ...products.fx.FinFXModelTypes import FinFXModel @@ -39,16 +39,16 @@ def f(volatility, *args): self = args[0] value_dt = args[1] spot_fx_rate = args[2] - dom_discount_curve = args[3] - for_discount_curve = args[4] + domestic_curve = args[3] + foreign_curve = args[4] price = args[5] model = BlackScholes(volatility) vdf = self.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] obj_fn = vdf - price @@ -66,15 +66,15 @@ def fvega(volatility, *args): self = args[0] value_dt = args[1] spot_fx_rate = args[2] - dom_discount_curve = args[3] - for_discount_curve = args[4] + domestic_curve = args[3] + foreign_curve = args[4] model = BlackScholes(volatility) fprime = self.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) return fprime @@ -115,8 +115,8 @@ def fast_delta(s, t, k, rd, rf, vol, deltaTypeValue, option_type_value): # self = args[0] # value_dt = args[1] # stock_price = args[2] -# dom_discount_curve = args[3] -# for_discount_curve = args[4] +# domestic_curve = args[3] +# foreign_curve = args[4] # delta = args[5] # deltaType = args[6] # volatility = args[7] @@ -127,8 +127,8 @@ def fast_delta(s, t, k, rd, rf, vol, deltaTypeValue, option_type_value): # deltaDict = self.delta(value_dt, # stock_price, -# dom_discount_curve, -# for_discount_curve, +# domestic_curve, +# foreign_curve, # model) # delta_out = deltaDict[deltaType] @@ -219,10 +219,10 @@ def __init__(self, self._strike_fx_rate = strike_fx_rate self._currency_pair = currency_pair - self._forName = self._currency_pair[0:3] - self._domName = self._currency_pair[3:6] + self._for_name = self._currency_pair[0:3] + self._dom_name = self._currency_pair[3:6] - if prem_currency != self._domName and prem_currency != self._forName: + if prem_currency != self._dom_name and prem_currency != self._for_name: raise FinError("Premium currency not in currency pair.") self._prem_currency = prem_currency @@ -243,8 +243,8 @@ def __init__(self, def value(self, value_dt, spot_fx_rate, # 1 unit of foreign in domestic - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ This function calculates the value of the option using a specified model with the resulting value being in domestic i.e. ccy2 terms. @@ -257,11 +257,11 @@ def value(self, if value_dt > self._expiry_dt: raise FinError("Valuation date after expiry date.") - if dom_discount_curve._value_dt != value_dt: + if domestic_curve._value_dt != value_dt: raise FinError( "Domestic Curve valuation date not same as valuation date") - if for_discount_curve._value_dt != value_dt: + if foreign_curve._value_dt != value_dt: raise FinError( "Foreign Curve valuation date not same as valuation date") @@ -282,8 +282,8 @@ def value(self, tdel = np.maximum(tdel, 1e-10) # TODO RESOLVE TDEL versus TEXP - dom_df = dom_discount_curve._df(tdel) - for_df = for_discount_curve._df(tdel) + dom_df = domestic_curve._df(tdel) + for_df = foreign_curve._df(tdel) r_d = -np.log(dom_df) / tdel r_f = -np.log(for_df) / tdel @@ -295,7 +295,7 @@ def value(self, if type(model) == BlackScholes or \ type(model) == SABR: - if type(model) == BlackScholes: + if isinstance(model, BlackScholes): volatility = model._volatility elif type(model) == SABR: @@ -345,10 +345,10 @@ def value(self, # the option may be quoted in either currency terms and so we calculate # these - if self._prem_currency == self._domName: + if self._prem_currency == self._dom_name: notional_dom = self._notional notional_for = self._notional / self._strike_fx_rate - elif self._prem_currency == self._forName: + elif self._prem_currency == self._for_name: notional_dom = self._notional * self._strike_fx_rate notional_for = self._notional else: @@ -373,8 +373,8 @@ def value(self, "pct_for": pct_for, "not_dom": notional_dom, "not_for": notional_for, - "ccy_dom": self._domName, - "ccy_for": self._forName} + "ccy_dom": self._dom_name, + "ccy_for": self._for_name} ############################################################################### @@ -397,17 +397,17 @@ def delta_bump(self, ccy2DiscountCurve, model) - vBumped = self.value( + v_bumped = self.value( value_dt, spot_fx_rate + bump, ccy1DiscountCurve, ccy2DiscountCurve, model) - if type(vBumped) is dict: - delta = (vBumped['value'] - v['value']) / bump + if type(v_bumped) is dict: + delta = (v_bumped['value'] - v['value']) / bump else: - delta = (vBumped - v) / bump + delta = (v_bumped - v) / bump return delta @@ -416,8 +416,8 @@ def delta_bump(self, def delta(self, value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ Calculation of the FX Option delta. There are several definitions of delta and so we are required to return a dictionary of values. The @@ -440,29 +440,29 @@ def delta(self, tdel = np.maximum(tdel, 1e-10) - dom_df = dom_discount_curve._df(tdel) + dom_df = domestic_curve._df(tdel) r_d = -np.log(dom_df)/tdel - for_df = for_discount_curve._df(tdel) + for_df = foreign_curve._df(tdel) r_f = -np.log(for_df)/tdel - S0 = spot_fx_rate + s0 = spot_fx_rate K = self._strike_fx_rate - if type(model) == BlackScholes: + if isinstance(model, BlackScholes): v = model._volatility if np.any(v < 0.0): raise FinError("Volatility should not be negative.") - v = np.maximum(v, gSmall) + v = np.maximum(v, g_small) pips_spot_delta = bs_delta( - S0, t_exp, K, r_d, r_f, v, self._option_type.value) + s0, t_exp, K, r_d, r_f, v, self._option_type.value) pips_fwd_delta = pips_spot_delta * np.exp(r_f*tdel) - vpctf = bs_value(S0, t_exp, K, r_d, r_f, v, - self._option_type.value) / S0 + vpctf = bs_value(s0, t_exp, K, r_d, r_f, v, + self._option_type.value) / s0 pct_spot_delta_prem_adj = pips_spot_delta - vpctf pct_fwd_delta_prem_adj = np.exp( r_f*tdel) * (pips_spot_delta - vpctf) @@ -486,7 +486,7 @@ def fast_delta(self, # spot_dt = value_dt.add_weekdays(self._spot_days) # tdel = (self._delivery_dt - value_dt) / gDaysInYear -# tdel = np.maximum(tdel, gSmall) +# tdel = np.maximum(tdel, g_small) # r_d = -np.log(dom_df)/tdel # r_f = -np.log(for_df)/tdel @@ -513,8 +513,8 @@ def fast_delta(self, def gamma(self, value_dt, spot_fx_rate, # value of a unit of foreign in domestic currency - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ This function calculates the FX Option Gamma using the spot delta. """ @@ -532,16 +532,16 @@ def gamma(self, t = np.maximum(t, 1e-10) - dom_df = dom_discount_curve.df(t) + dom_df = domestic_curve.df(t) r_d = -np.log(dom_df)/t - for_df = for_discount_curve.df(t) + for_df = foreign_curve.df(t) r_f = -np.log(for_df)/t K = self._strike_fx_rate - S0 = spot_fx_rate + s0 = spot_fx_rate - if type(model) == BlackScholes: + if isinstance(model, BlackScholes): volatility = model._volatility @@ -550,14 +550,14 @@ def gamma(self, volatility = np.maximum(volatility, 1e-10) - lnS0k = np.log(S0 / K) - sqrtT = np.sqrt(t) - den = volatility * sqrtT + ln_s0_k = np.log(s0 / K) + sqrt_t = np.sqrt(t) + den = volatility * sqrt_t mu = r_d - r_f v2 = volatility * volatility - d1 = (lnS0k + (mu + v2 / 2.0) * t) / den + d1 = (ln_s0_k + (mu + v2 / 2.0) * t) / den gamma = np.exp(-r_f * t) * nprime(d1) - gamma = gamma / S0 / den + gamma = gamma / s0 / den else: raise FinError("Unknown Model Type") @@ -568,8 +568,8 @@ def gamma(self, def vega(self, value_dt, spot_fx_rate, # value of a unit of foreign in domestic currency - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ This function calculates the FX Option Vega using the spot delta. """ @@ -587,16 +587,16 @@ def vega(self, t = np.maximum(t, 1e-10) - dom_df = dom_discount_curve._df(t) + dom_df = domestic_curve._df(t) r_d = -np.log(dom_df)/t - for_df = for_discount_curve._df(t) + for_df = foreign_curve._df(t) r_f = -np.log(for_df)/t K = self._strike_fx_rate - S0 = spot_fx_rate + s0 = spot_fx_rate - if type(model) == BlackScholes: + if isinstance(model, BlackScholes): volatility = model._volatility @@ -605,13 +605,13 @@ def vega(self, volatility = np.maximum(volatility, 1e-10) - lnS0k = np.log(S0/K) - sqrtT = np.sqrt(t) - den = volatility * sqrtT + ln_s0_k = np.log(s0/K) + sqrt_t = np.sqrt(t) + den = volatility * sqrt_t mu = r_d - r_f v2 = volatility * volatility - d1 = (lnS0k + (mu + v2 / 2.0) * t) / den - vega = S0 * sqrtT * np.exp(-r_f * t) * nprime(d1) + d1 = (ln_s0_k + (mu + v2 / 2.0) * t) / den + vega = s0 * sqrt_t * np.exp(-r_f * t) * nprime(d1) else: raise FinError("Unknown Model type") @@ -622,8 +622,8 @@ def vega(self, def theta(self, value_dt, spot_fx_rate, # value of a unit of foreign in domestic currency - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model): """ This function calculates the time decay of the FX option. """ @@ -640,16 +640,16 @@ def theta(self, t = np.maximum(t, 1e-10) - dom_df = dom_discount_curve._df(t) + dom_df = domestic_curve._df(t) r_d = -np.log(dom_df)/t - for_df = for_discount_curve._df(t) + for_df = foreign_curve._df(t) r_f = -np.log(for_df)/t K = self._strike_fx_rate - S0 = spot_fx_rate + s0 = spot_fx_rate - if type(model) == BlackScholes: + if isinstance(model, BlackScholes): vol = model._volatility @@ -658,22 +658,22 @@ def theta(self, vol = np.maximum(vol, 1e-10) - lnS0k = np.log(S0/K) - sqrtT = np.sqrt(t) - den = vol * sqrtT + ln_s0_k = np.log(s0/K) + sqrt_t = np.sqrt(t) + den = vol * sqrt_t mu = r_d - r_f v2 = vol * vol - d1 = (lnS0k + (mu + v2 / 2.0) * t) / den - d2 = (lnS0k + (mu - v2 / 2.0) * t) / den + d1 = (ln_s0_k + (mu + v2 / 2.0) * t) / den + d2 = (ln_s0_k + (mu - v2 / 2.0) * t) / den if self._option_type == OptionTypes.EUROPEAN_CALL: - v = - S0 * np.exp(-r_f * t) * nprime(d1) * vol / 2.0 / sqrtT - v = v + r_f * S0 * np.exp(-r_f * t) * N(d1) + v = - s0 * np.exp(-r_f * t) * nprime(d1) * vol / 2.0 / sqrt_t + v = v + r_f * s0 * np.exp(-r_f * t) * N(d1) v = v - r_d * K * np.exp(-r_d * t) * N(d2) elif self._option_type == OptionTypes.EUROPEAN_PUT: - v = - S0 * np.exp(-r_f * t) * nprime(d1) * vol / 2.0 / sqrtT + v = - s0 * np.exp(-r_f * t) * nprime(d1) * vol / 2.0 / sqrt_t v = v + r_d * K * np.exp(-r_d * t) * N(-d2) - v = v - r_f * S0 * np.exp(-r_f * t) * N(-d1) + v = v - r_f * s0 * np.exp(-r_f * t) * N(-d1) else: raise FinError("Unknown option type") @@ -706,8 +706,8 @@ def implied_volatility(self, def value_mc(self, value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model, num_paths=10000, seed=4242): @@ -725,8 +725,8 @@ def value_mc(self, np.random.seed(seed) t = (self._expiry_dt - value_dt) / gDaysInYear - dom_Df = dom_discount_curve.df(self._expiry_dt) - for_Df = for_discount_curve.df(self._expiry_dt) + dom_Df = domestic_curve.df(self._expiry_dt) + for_Df = foreign_curve.df(self._expiry_dt) r_d = -np.log(dom_Df)/t r_f = -np.log(for_Df)/t diff --git a/financepy/products/fx/fx_variance_swap.py b/financepy/products/fx/fx_variance_swap.py index 4845771f..ca56d20a 100644 --- a/financepy/products/fx/fx_variance_swap.py +++ b/financepy/products/fx/fx_variance_swap.py @@ -47,17 +47,17 @@ def __init__(self, # Replication portfolio is stored self._num_put_options = 0 self._num_call_options = 0 - self._putWts = [] + self._put_wts = [] self._put_strikes = [] - self._callWts = [] + self._call_wts = [] self._call_strikes = [] ############################################################################### def value(self, value_dt, - realisedVar, - fair_strikeVar, + realised_var, + fair_strike_var, libor_curve): """ Calculate the value of the variance swap based on the realised volatility to the valuation date, the forward looking implied @@ -66,8 +66,8 @@ def value(self, if isinstance(value_dt, Date) is False: raise FinError("Valuation date is not a Date") - if value_dt > self._expiry_dt: - raise FinError("Valuation date after expiry date.") + if value_dt > self._maturity_dt: + raise FinError("Valuation date after maturity date.") if libor_curve._value_dt != value_dt: raise FinError( @@ -76,10 +76,10 @@ def value(self, t1 = (value_dt - self._effective_dt) / gDaysInYear t2 = (self._maturity_dt - self._effective_dt) / gDaysInYear - expectedVariance = t1 * realisedVar/t2 - expectedVariance += (t2-t1) * fair_strikeVar / t2 + expected_var = t1 * realised_var/t2 + expected_var += (t2-t1) * fair_strike_var / t2 - payoff = expectedVariance - self._strike_variance + payoff = expected_var - self._strike_variance df = libor_curve.df(self._maturity_dt) v = payoff * self._notional * df @@ -89,14 +89,14 @@ def value(self, def fair_strike_approx(self, value_dt, - fwdStockPrice, + fwd_stock_price, strikes, volatilities): """ This is an approximation of the fair strike variance by Demeterfi et al. (1999) which assumes that sigma(K) = sigma(F) - b(K-F)/F where F is the forward stock price and sigma(F) is the ATM forward vol. """ - f = fwdStockPrice + f = fwd_stock_price # TODO Linear interpolation - to be revisited atm_vol = np.interp(f, strikes, volatilities) @@ -156,108 +156,110 @@ def fair_strike(self, Goldman Sachs Research notes March 1999. See Appendix A. This aim is to use calls and puts to approximate the payoff of a log contract """ - minStrike = sstar - (num_put_options+1) * strike_spacing + min_strike = sstar - (num_put_options+1) * strike_spacing - self._putWts = [] + self._put_wts = [] self._put_strikes = [] - self._callWts = [] + self._call_wts = [] self._call_strikes = [] # if the lower strike is < 0 we go to as low as the strike spacing - if minStrike < strike_spacing: + if min_strike < strike_spacing: k = sstar klist = [sstar] while k >= strike_spacing: k -= strike_spacing klist.append(k) - putK = np.array(klist) - self._num_put_options = len(putK) - 1 + put_k = np.array(klist) + self._num_put_options = len(put_k) - 1 else: - putK = np.linspace(sstar, minStrike, num_put_options+2) + put_k = np.linspace(sstar, min_strike, num_put_options+2) - self._put_strikes = putK + self._put_strikes = put_k - maxStrike = sstar + (num_call_options+1) * strike_spacing - callK = np.linspace(sstar, maxStrike, num_call_options+2) + max_strike = sstar + (num_call_options+1) * strike_spacing + call_k = np.linspace(sstar, max_strike, num_call_options+2) - self._call_strikes = callK + self._call_strikes = call_k - optionTotal = 2.0*(r*t_mat - (s0*g/sstar-1.0) - np.log(sstar/s0))/t_mat + option_total = 2.0*(r*t_mat - (s0*g/sstar-1.0) - + np.log(sstar/s0))/t_mat - self._callWts = np.zeros(num_call_options) - self._putWts = np.zeros(num_put_options) + self._call_wts = np.zeros(num_call_options) + self._put_wts = np.zeros(num_put_options) def f(x): return (2.0/t_mat)*((x-sstar)/sstar-np.log(x/sstar)) - sumWts = 0.0 + sum_wts = 0.0 for n in range(0, self._num_put_options): - kp = putK[n+1] - k = putK[n] - self._putWts[n] = (f(kp)-f(k))/(k-kp) - sumWts - sumWts += self._putWts[n] + kp = put_k[n+1] + k = put_k[n] + self._put_wts[n] = (f(kp)-f(k))/(k-kp) - sum_wts + sum_wts += self._put_wts[n] - sumWts = 0.0 + sum_wts = 0.0 for n in range(0, self._num_call_options): - kp = callK[n+1] - k = callK[n] - self._callWts[n] = (f(kp)-f(k))/(kp-k) - sumWts - sumWts += self._callWts[n] + kp = call_k[n+1] + k = call_k[n] + self._call_wts[n] = (f(kp)-f(k))/(kp-k) - sum_wts + sum_wts += self._call_wts[n] - piPut = 0.0 + pi_put = 0.0 for n in range(0, num_put_options): - k = putK[n] + k = put_k[n] vol = volatility_curve.volatility(k) opt = FXVanillaOption(self._maturity_dt, k, put_type) model = BlackScholes(vol) v = opt.value(value_dt, s0, discount_curve, dividend_curve, model) - piPut += v * self._putWts[n] + pi_put += v * self._put_wts[n] - piCall = 0.0 + pi_call = 0.0 for n in range(0, num_call_options): - k = callK[n] + k = call_k[n] vol = volatility_curve.volatility(k) opt = FXVanillaOption(self._maturity_dt, k, call_type) model = BlackScholes(vol) v = opt.value(value_dt, s0, discount_curve, dividend_curve, model) - piCall += v * self._callWts[n] + pi_call += v * self._call_wts[n] - pi = piCall + piPut - optionTotal += g * pi - var = optionTotal + pi = pi_call + pi_put + option_total += g * pi + var = option_total return var ############################################################################### - def realised_variance(self, closePrices, use_logs=True): + def realised_variance(self, close_prices, use_logs=True): """ Calculate the realised variance according to market standard calculations which can either use log or percentage returns.""" - num_observations = len(closePrices) + num_observations = len(close_prices) for i in range(0, num_observations): - if closePrices[i] <= 0.0: + if close_prices[i] <= 0.0: raise FinError("Stock prices must be greater than zero") - cumX2 = 0.0 + cum_x2 = 0.0 if use_logs is True: for i in range(1, num_observations): - x = np.log(closePrices[i]/closePrices[i-1]) - cumX2 += x*x + x = np.log(close_prices[i]/close_prices[i-1]) + cum_x2 += x*x else: for i in range(1, num_observations): - x = (closePrices[i]-closePrices[i-1])/closePrices[i-1] - cumX2 += x*x + x = (close_prices[i]-close_prices[i-1])/close_prices[i-1] + cum_x2 += x*x - var = cumX2 * 252.0 / num_observations + var = cum_x2 * 252.0 / num_observations return var ############################################################################### + def print_strikes(self): if self._num_put_options == 0 and self._num_call_options == 0: @@ -266,12 +268,12 @@ def print_strikes(self): print("TYPE", "STRIKE", "WEIGHT") for n in range(0, self._num_put_options): k = self._put_strikes[n] - wt = self._putWts[n]*self._notional + wt = self._put_wts[n]*self._notional print("PUT %7.2f %10.3f" % (k, wt)) for n in range(0, self._num_call_options): k = self._call_strikes[n] - wt = self._callWts[n]*self._notional + wt = self._call_wts[n]*self._notional print("CALL %7.2f %10.3f" % (k, wt)) ############################################################################### diff --git a/financepy/products/inflation/FinInflationIndexCurve.py b/financepy/products/inflation/FinInflationIndexCurve.py index bbae8279..91d6e1a1 100644 --- a/financepy/products/inflation/FinInflationIndexCurve.py +++ b/financepy/products/inflation/FinInflationIndexCurve.py @@ -28,30 +28,29 @@ class FinInflationIndexCurve(): ############################################################################### def __init__(self, - index_dates: list, + index_dts: list, index_values: (list, np.ndarray), lag_in_months: int = 3): check_argument_types(self.__init__, locals()) # Validate curve - if len(index_dates) == 0: + if len(index_dts) == 0: raise FinError("Dates has zero length") - if len(index_dates) != len(index_values): + if len(index_dts) != len(index_values): raise FinError("Dates and Values are not the same length") if lag_in_months < 0: raise FinError("Lag must be positive.") - self._index_dates = np.array(index_dates) + self._index_dts = np.array(index_dts) self._index_values = np.array(index_values) self._lag_in_months = lag_in_months - self._base_date = index_dates[0] + self._base_dt = index_dts[0] + self._index_times = times_from_dates(index_dts, self._base_dt) - self._indexTimes = times_from_dates(index_dates, self._base_date) - - if test_monotonicity(self._indexTimes) is False: + if test_monotonicity(self._index_times) is False: raise FinError("Times or dates are not sorted in increasing order") ############################################################################### @@ -61,26 +60,26 @@ def index_value(self, dt: Date): lagMonthsAgoDt = dt.add_months(-self._lag_in_months) - cpiFirstDate = Date(1, lagMonthsAgoDt._m, lagMonthsAgoDt._y) - cpiSecondDate = cpiFirstDate.add_months(1) + cpi_first_dt = Date(1, lagMonthsAgoDt._m, lagMonthsAgoDt._y) + cpi_second_dt = cpi_first_dt.add_months(1) - cpiFirstTime = (cpiFirstDate - self._base_date) / gDaysInYear - cpiSecondTime = (cpiSecondDate - self._base_date) / gDaysInYear + cpi_first_time = (cpi_first_dt - self._base_dt) / gDaysInYear + cpi_second_time = (cpi_second_dt - self._base_dt) / gDaysInYear - cpiFirstValue = np.interp(cpiFirstTime, - self._indexTimes, + cpi_first_value = np.interp(cpi_first_time, + self._index_times, self._index_values) - cpiSecondValue = np.interp(cpiSecondTime, - self._indexTimes, + cpi_second_value = np.interp(cpi_second_time, + self._index_times, self._index_values) d = dt._d m = dt._m y = dt._y - numDays = days_in_month(m, y) - v = cpiFirstValue + (d - 1) * (cpiSecondValue - - cpiFirstValue) / numDays + num_days = days_in_month(m, y) + v = cpi_first_value + (d - 1) * (cpi_second_value - + cpi_first_value) / num_days return v ############################################################################### @@ -89,7 +88,7 @@ def index_ratio(self, dt: Date): """ Calculate index value by interpolating the CPI curve """ vt = self.index_value(dt) - v0 = self.index_value(self._base_date) + v0 = self.index_value(self._base_dt) index_ratio = vt / v0 return index_ratio @@ -98,13 +97,13 @@ def index_ratio(self, dt: Date): def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) - s += label_to_string("BASE DATE", self._base_date) + s += label_to_string("BASE DATE", self._base_dt) s += label_to_string("INDEX LAG", self._lag_in_months) s += label_to_string("DATES", "ZERO RATES") num_points = len(self._index_values) for i in range(0, num_points): - s += label_to_string("%12s" % self._index_dates[i], + s += label_to_string("%12s" % self._index_dts[i], "%10.7f" % self._index_values[i]) return s diff --git a/financepy/products/inflation/FinInflationSwap.py b/financepy/products/inflation/FinInflationSwap.py index ddd70229..69e66d2f 100644 --- a/financepy/products/inflation/FinInflationSwap.py +++ b/financepy/products/inflation/FinInflationSwap.py @@ -43,10 +43,10 @@ def __init__(self, start_dt: Date, # The date the FRA starts to accrue # End of the Ibor rate period maturity_dt_or_tenor: (Date, str), - fraRate: float, # The fixed contractual FRA rate + fra_rate: float, # The fixed contractual FRA rate day_count_type: DayCountTypes, # For interest period notional: float = 100.0, - payFixedRate: bool = True, # True if the FRA rate is being paid + pay_fixed_rate: bool = True, # True if the FRA rate is being paid cal_type: CalendarTypes = CalendarTypes.WEEKEND, bd_type: BusDayAdjustTypes = BusDayAdjustTypes.MODIFIED_FOLLOWING): """ Create a Forward Rate Agreeement object. """ @@ -72,8 +72,8 @@ def __init__(self, self._start_dt = start_dt self._maturity_dt = maturity_dt - self._fraRate = fraRate - self._payFixedRate = payFixedRate + self._fra_rate = fra_rate + self._pay_fixed_rate = pay_fixed_rate self._dc_type = day_count_type self._notional = notional @@ -89,14 +89,14 @@ def value(self, value_dt, libor_curve): df1 = libor_curve.df(self._start_dt) df2 = libor_curve.df(self._maturity_dt) libor_fwd = (df1 / df2 - 1.0) / acc_factor - v = acc_factor * (libor_fwd - self._fraRate) * df2 + v = acc_factor * (libor_fwd - self._fra_rate) * df2 # print(df1, df2, acc_factor, libor_fwd, v) # Forward value the FRA to the value date df_to_value_dt = libor_curve.df(value_dt) v = v * self._notional / df_to_value_dt - if self._payFixedRate: + if self._pay_fixed_rate: v *= -1.0 return v @@ -109,7 +109,7 @@ def maturity_df(self, libor_curve): dc = DayCount(self._dc_type) df1 = libor_curve.df(self._start_dt) acc_factor = dc.year_frac(self._start_dt, self._maturity_dt)[0] - df2 = df1 / (1.0 + acc_factor * self._fraRate) + df2 = df1 / (1.0 + acc_factor * self._fra_rate) return df2 ########################################################################### @@ -120,9 +120,9 @@ def print_payments(self, value_dt): flow_settle = self._notional dc = DayCount(self._dc_type) acc_factor = dc.year_frac(self._start_dt, self._maturity_dt)[0] - flow_maturity = (1.0 + acc_factor * self._fraRate) * self._notional + flow_maturity = (1.0 + acc_factor * self._fra_rate) * self._notional - if self._payFixedRate is True: + if self._pay_fixed_rate is True: print(self._start_dt, -flow_settle) print(self._maturity_dt, flow_maturity) else: @@ -135,9 +135,9 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("START ACCD DATE", self._start_dt) s += label_to_string("MATURITY DATE", self._maturity_dt) - s += label_to_string("FRA RATE", self._fraRate) + s += label_to_string("FRA RATE", self._fra_rate) s += label_to_string("NOTIONAL", self._notional) - s += label_to_string("PAY FIXED RATE", self._payFixedRate) + s += label_to_string("PAY FIXED RATE", self._pay_fixed_rate) s += label_to_string("DAY COUNT TYPE", self._dc_type) s += label_to_string("BUS DAY ADJUST TYPE", self._bd_type) s += label_to_string("CALENDAR", self._cal_type) diff --git a/financepy/products/inflation/FinInflationSwapCurve.py b/financepy/products/inflation/FinInflationSwapCurve.py index a3c36d2e..b4615e24 100644 --- a/financepy/products/inflation/FinInflationSwapCurve.py +++ b/financepy/products/inflation/FinInflationSwapCurve.py @@ -13,7 +13,7 @@ from ...market.curves.interpolator import InterpTypes from ...market.curves.discount_curve import DiscountCurve -swaptol = 1e-8 +SWAP_TOL = 1e-10 ############################################################################## # TODO: CHANGE times to df_times @@ -127,14 +127,14 @@ def _validate_inputs(self, # Validation of the inputs. if num_depos > 0: for depo in ibor_deposits: - startDt = depo._start_dt - if startDt < self._value_dt: + start_dt = depo._start_dt + if start_dt < self._value_dt: raise FinError("First deposit starts before value date.") for depo in ibor_deposits: - startDt = depo._start_dt - endDt = depo._maturity_dt - if startDt >= endDt: + start_dt = depo._start_dt + end_dt = depo._maturity_dt + if start_dt >= end_dt: raise FinError("First deposit ends on or before it begins") # Ensure order of depos @@ -155,8 +155,8 @@ def _validate_inputs(self, if num_fras > 0: for fra in ibor_fras: - startDt = fra._start_dt - if startDt <= self._value_dt: + start_dt = fra._start_dt + if start_dt <= self._value_dt: raise FinError("FRAs starts before valuation date") if num_fras > 1: @@ -169,17 +169,17 @@ def _validate_inputs(self, if num_swaps > 0: for swap in ibor_swaps: - startDt = swap._start_dt - if startDt < self._value_dt: + start_dt = swap._start_dt + if start_dt < self._value_dt: raise FinError("Swaps starts before valuation date.") if num_swaps > 1: # Swaps must all start on the same date for the bootstrap - startDt = ibor_swaps[0]._start_dt + start_dt = ibor_swaps[0]._start_dt for swap in ibor_swaps[1:]: - nextStartDt = swap._start_dt - if nextStartDt != startDt: + next_start_dt = swap._start_dt + if next_start_dt != start_dt: raise FinError("Swaps must all have same start date.") # Swaps must be increasing in tenor/maturity @@ -191,13 +191,13 @@ def _validate_inputs(self, prev_dt = next_dt # Swaps must have same cash flows for bootstrap to work - longestSwap = ibor_swaps[-1] - longestSwapCpnDates = longestSwap._adjusted_fixed_dts + longest_swap = ibor_swaps[-1] + longest_swap_cpn_dts = longest_swap._adjusted_fixed_dts for swap in ibor_swaps[0:-1]: - swapCpnDates = swap._adjusted_fixed_dts - num_flows = len(swapCpnDates) + swap_cpn_dts = swap._adjusted_fixed_dts + num_flows = len(swap_cpn_dts) for i_flow in range(0, num_flows): - if swapCpnDates[i_flow] != longestSwapCpnDates[i_flow]: + if swap_cpn_dts[i_flow] != longest_swap_cpn_dts[i_flow]: raise FinError( "Swap coupons are not on the same date grid.") @@ -205,34 +205,34 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDeposit_maturityDate = Date(1, 1, 1900) - firstFRAMaturityDate = Date(1, 1, 1900) - lastFRAMaturityDate = Date(1, 1, 1900) + last_deposit_maturity_dt = Date(1, 1, 1900) + first_fra_maturity_dt = Date(1, 1, 1900) + last_fra_maturity_dt = Date(1, 1, 1900) if num_depos > 0: - lastDeposit_maturityDate = ibor_deposits[-1]._maturity_dt + last_deposit_maturity_dt = ibor_deposits[-1]._maturity_dt if num_fras > 0: - firstFRAMaturityDate = ibor_fras[0]._maturity_dt - lastFRAMaturityDate = ibor_fras[-1]._maturity_dt + first_fra_maturity_dt = ibor_fras[0]._maturity_dt + last_fra_maturity_dt = ibor_fras[-1]._maturity_dt if num_swaps > 0: first_swap_maturity_dt = ibor_swaps[0]._maturity_dt if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDeposit_maturityDate: - print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDeposit_maturityDate) + if first_fra_maturity_dt <= last_deposit_maturity_dt: + print("FRA Maturity Date:", first_fra_maturity_dt) + print("Last Deposit Date:", last_deposit_maturity_dt) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: - if first_swap_maturity_dt <= lastFRAMaturityDate: + if first_swap_maturity_dt <= last_fra_maturity_dt: raise FinError("First Swap must mature after last FRA") # Now determine which instruments are used - self._usedDeposits = ibor_deposits - self._usedFRAs = ibor_fras - self._usedSwaps = ibor_swaps + self._used_deposits = ibor_deposits + self._used_fras = ibor_fras + self._used_swaps = ibor_swaps self._dc_type = None ############################################################################### @@ -252,7 +252,7 @@ def _build_curve_using_solver(self): self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) - for depo in self._usedDeposits: + for depo in self._used_deposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear @@ -261,7 +261,7 @@ def _build_curve_using_solver(self): oldt_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -279,10 +279,10 @@ def _build_curve_using_solver(self): argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, - maxiter=50, fprime2=None) + args=argtuple, tol=SWAP_TOL, + maxiter=50, fprime2=None) - for swap in self._usedSwaps: + for swap in self._used_swaps: # I use the lastPaymentDate in case a date has been adjusted fwd # over a holiday as the maturity date is usually not adjusted CHECK maturity_dt = swap._lastPaymentDate @@ -294,11 +294,11 @@ def _build_curve_using_solver(self): argtuple = (self, self._value_dt, swap) df_mat = optimize.newton(_f, x0=df_mat, fprime=None, args=argtuple, - tol=swaptol, maxiter=50, fprime2=None, - full_output=False) + tol=SWAP_TOL, maxiter=50, fprime2=None, + full_output=False) if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### @@ -316,7 +316,7 @@ def _build_curve_linear_swap_rate_interpolation(self): self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) - for depo in self._usedDeposits: + for depo in self._used_deposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear @@ -325,7 +325,7 @@ def _build_curve_linear_swap_rate_interpolation(self): oldt_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -343,12 +343,12 @@ def _build_curve_linear_swap_rate_interpolation(self): argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, - maxiter=50, fprime2=None) + args=argtuple, tol=SWAP_TOL, + maxiter=50, fprime2=None) - if len(self._usedSwaps) == 0: + if len(self._used_swaps) == 0: if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) return # print("CURVE SO FAR") @@ -360,29 +360,29 @@ def _build_curve_linear_swap_rate_interpolation(self): ####################################################################### # Find where the FRAs and Depos go up to as this bit of curve is done - foundStart = False - lastDate = self._value_dt - if len(self._usedDeposits) != 0: - lastDate = self._usedDeposits[-1]._maturity_dt + found_start = False + last_dt = self._value_dt + if len(self._used_deposits) != 0: + last_dt = self._used_deposits[-1]._maturity_dt - if len(self._usedFRAs) != 0: - lastDate = self._usedFRAs[-1]._maturity_dt + if len(self._used_fras) != 0: + last_dt = self._used_fras[-1]._maturity_dt # We use the longest swap assuming it has a superset of ALL of the # swap flow dates used in the curve construction - longestSwap = self._usedSwaps[-1] - couponDates = longestSwap._adjusted_fixed_dts - num_flows = len(couponDates) + longest_swap = self._used_swaps[-1] + coupon_dts = longest_swap._adjusted_fixed_dts + num_flows = len(coupon_dts) # Find where first coupon without discount factor starts start_index = 0 for i in range(0, num_flows): - if couponDates[i] > lastDate: + if coupon_dts[i] > last_dt: start_index = i - foundStart = True + found_start = True break - if foundStart is False: + if found_start is False: raise FinError("Found start is false. Swaps payments inside FRAs") swap_rates = [] @@ -391,38 +391,38 @@ def _build_curve_linear_swap_rate_interpolation(self): # I use the last coupon date for the swap rate interpolation as this # may be different from the maturity date due to a holiday adjustment # and the swap rates need to align with the coupon payment dates - for swap in self._usedSwaps: + for swap in self._used_swaps: swap_rate = swap._fixed_coupon maturity_dt = swap._adjusted_fixed_dts[-1] tswap = (maturity_dt - self._value_dt) / gDaysInYear swap_times.append(tswap) swap_rates.append(swap_rate) - interpolatedSwapRates = [0.0] - interpolatedswap_times = [0.0] + interpolated_swap_rates = [0.0] + interpolated_swap_times = [0.0] - for dt in couponDates[1:]: - swapTime = (dt - self._value_dt) / gDaysInYear - swap_rate = np.interp(swapTime, swap_times, swap_rates) - interpolatedSwapRates.append(swap_rate) - interpolatedswap_times.append(swapTime) + for dt in coupon_dts[1:]: + swap_years = (dt - self._value_dt) / gDaysInYear + swap_rate = np.interp(swap_years, swap_times, swap_rates) + interpolated_swap_rates.append(swap_rate) + interpolated_swap_times.append(swap_years) # Do I need this line ? - interpolatedSwapRates[0] = interpolatedSwapRates[1] + interpolated_swap_rates[0] = interpolated_swap_rates[1] -# print("Interpolated swap times:", interpolatedswap_times) -# print("Interpolated swap rates:", interpolatedSwapRates) +# print("Interpolated swap times:", interpolated_swap_times) +# print("Interpolated swap rates:", interpolated_swap_rates) - accrual_factors = longestSwap._fixed_year_fracs + accrual_factors = longest_swap._fixed_year_fracs acc = 0.0 df = 1.0 pv01 = 0.0 - df_settle = self.df(longestSwap._start_dt) + df_settle = self.df(longest_swap._start_dt) # print("SETTLE", df_settle) for i in range(1, start_index): - dt = couponDates[i] + dt = coupon_dts[i] df = self.df(dt) acc = accrual_factors[i-1] pv01 += acc * df @@ -430,16 +430,16 @@ def _build_curve_linear_swap_rate_interpolation(self): for i in range(start_index, num_flows): - dt = couponDates[i] + dt = coupon_dts[i] t_mat = (dt - self._value_dt) / gDaysInYear - swap_rate = interpolatedSwapRates[i] + swap_rate = interpolated_swap_rates[i] acc = accrual_factors[i-1] - pv01End = (acc * swap_rate + 1.0) + pv01_end = (acc * swap_rate + 1.0) - df_mat = (df_settle - swap_rate * pv01) / pv01End + df_mat = (df_settle - swap_rate * pv01) / pv01_end # print("IN: %12s %12.10f %12.10f %12.10f %12.10f OUT: %14.12f" % -# (dt, swap_rate, acc, pv01, pv01End, df_mat)) +# (dt, swap_rate, acc, pv01, pv01_end, df_mat)) self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) @@ -450,30 +450,30 @@ def _build_curve_linear_swap_rate_interpolation(self): # print(self._dfs) if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### - def _check_refits(self, depoTol, fraTol, swapTol): + def _check_refits(self, depo_tol, fra_tol, swap_tol): """ Ensure that the Ibor curve refits the calibration instruments. """ - for depo in self._usedDeposits: + for depo in self._used_deposits: v = depo.value(self._value_dt, self) / depo._notional - if abs(v - 1.0) > depoTol: + if abs(v - 1.0) > depo_tol: print("Value", v) raise FinError("Deposit not repriced.") - for fra in self._usedFRAs: + for fra in self._used_fras: v = fra.value(self._value_dt, self) / fra._notional - if abs(v) > fraTol: + if abs(v) > fra_tol: print("Value", v) raise FinError("FRA not repriced.") - for swap in self._usedSwaps: + for swap in self._used_swaps: # We value it as of the start date of the swap v = swap.value(swap._start_dt, self, self, None, principal=0.0) v = v / swap._notional # print("REFIT SWAP VALUATION:", swap._adjustedMaturityDate, v) - if abs(v) > swapTol: + if abs(v) > swap_tol: print("Swap with maturity " + str(swap._maturity_dt) + " Not Repriced. Has Value", v) swap.print_fixed_leg_pv() @@ -488,15 +488,15 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VALUATION DATE", self._value_dt) - for depo in self._usedDeposits: + for depo in self._used_deposits: s += label_to_string("DEPOSIT", "") s += depo.__repr__() - for fra in self._usedFRAs: + for fra in self._used_fras: s += label_to_string("FRA", "") s += fra.__repr__() - for swap in self._usedSwaps: + for swap in self._used_swaps: s += label_to_string("SWAP", "") s += swap.__repr__() diff --git a/financepy/products/rates/callable_swap.py b/financepy/products/rates/callable_swap.py index 653b185a..c8bb98aa 100644 --- a/financepy/products/rates/callable_swap.py +++ b/financepy/products/rates/callable_swap.py @@ -139,7 +139,7 @@ # model and a discount curve. """ # float_spread = 0.0 -# payFixedFlag = True +# pay_fixedFlag = True # # The underlying is a swap in which we pay the fixed amount # swap = IborSwap(self._exercise_dt, @@ -151,7 +151,7 @@ # float_spread, # self._float_freq_type, # self._float_dc_type, -# payFixedFlag, +# pay_fixedFlag, # self._cal_type, # self._bd_type, # self._dg_type) @@ -163,7 +163,7 @@ # for i_flow in range(1, len(self._swap._adjusted_fixed_dts)): # flow_dt= swap._adjusted_fixed_dts[i_flow] # cpn_time = (flow_dt - settle_dt) / gDaysInYear -# cpn_flow = swap._fixedFlows[i_flow-1] / self._notional +# cpn_flow = swap._fixed_flows[i_flow-1] / self._notional # cpn_times.append(cpn_time) # cpn_amounts.append(cpn_flow) diff --git a/financepy/products/rates/dual_curve.py b/financepy/products/rates/dual_curve.py index 1f889581..a274e378 100644 --- a/financepy/products/rates/dual_curve.py +++ b/financepy/products/rates/dual_curve.py @@ -2,9 +2,10 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################## +import copy + import numpy as np from scipy import optimize -import copy from ...utils.error import FinError from ...utils.date import Date @@ -17,7 +18,7 @@ from ...products.rates.ibor_fra import IborFRA from ...products.rates.ibor_swap import IborSwap -swaptol = 1e-10 +SWAP_TOL = 1e-10 ############################################################################### # TODO: CHANGE times to df_times @@ -143,8 +144,8 @@ def _validate_inputs(self, for depo in ibor_deposits: start_dt = depo._start_dt - endDt = depo._maturity_dt - if start_dt >= endDt: + end_dt = depo._maturity_dt + if start_dt >= end_dt: raise FinError("First deposit ends on or before it begins") # Ensure order of depos @@ -215,13 +216,13 @@ def _validate_inputs(self, prev_dt = next_dt # Swaps must have same cash flows for bootstrap to work - longestSwap = ibor_swaps[-1] - longestSwapCpnDates = longestSwap._fixed_leg._payment_dts + longest_swap = ibor_swaps[-1] + longest_swap_cpn_dts = longest_swap._fixed_leg._payment_dts for swap in ibor_swaps[0:-1]: - swapCpnDates = swap._fixed_leg._payment_dts - num_flows = len(swapCpnDates) + swap_cpn_dts = swap._fixed_leg._payment_dts + num_flows = len(swap_cpn_dts) for i_flow in range(0, num_flows): - if swapCpnDates[i_flow] != longestSwapCpnDates[i_flow]: + if swap_cpn_dts[i_flow] != longest_swap_cpn_dts[i_flow]: raise FinError( "Swap coupons are not on the same date grid.") @@ -229,28 +230,28 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDeposit_maturityDate = Date(1, 1, 1900) - firstFRAMaturityDate = Date(1, 1, 1900) - lastFRAMaturityDate = Date(1, 1, 1900) + last_deposit_maturity_dt = Date(1, 1, 1900) + first_fra_maturity_dt = Date(1, 1, 1900) + last_fra_maturity_dt = Date(1, 1, 1900) if num_depos > 0: - lastDeposit_maturityDate = ibor_deposits[-1]._maturity_dt + last_deposit_maturity_dt = ibor_deposits[-1]._maturity_dt if num_fras > 0: - firstFRAMaturityDate = ibor_fras[0]._maturity_dt - lastFRAMaturityDate = ibor_fras[-1]._maturity_dt + first_fra_maturity_dt = ibor_fras[0]._maturity_dt + last_fra_maturity_dt = ibor_fras[-1]._maturity_dt if num_swaps > 0: first_swap_maturity_dt = ibor_swaps[0]._maturity_dt if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDeposit_maturityDate: - print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDeposit_maturityDate) + if first_fra_maturity_dt <= last_deposit_maturity_dt: + print("FRA Maturity Date:", first_fra_maturity_dt) + print("Last Deposit Date:", last_deposit_maturity_dt) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: - if first_swap_maturity_dt <= lastFRAMaturityDate: + if first_swap_maturity_dt <= last_fra_maturity_dt: raise FinError("First Swap must mature after last FRA") # If both depos and swaps start after T, we need a rate to get them to @@ -262,22 +263,22 @@ def _validate_inputs(self, raise FinError("Need a deposit rate to pin down short end.") if depo_start_dt > self._value_dt: - firstDepo = ibor_deposits[0] - if firstDepo._start_dt > self._value_dt: + first_depo = ibor_deposits[0] + if first_depo._start_dt > self._value_dt: print("Inserting synthetic deposit") - syntheticDeposit = copy.deepcopy(firstDepo) - syntheticDeposit._start_dt = self._value_dt - syntheticDeposit._maturity_dt = firstDepo._start_dt - ibor_deposits.insert(0, syntheticDeposit) + synthetic_deposit = copy.deepcopy(first_depo) + synthetic_deposit._start_dt = self._value_dt + synthetic_deposit._maturity_dt = first_depo._start_dt + ibor_deposits.insert(0, synthetic_deposit) num_depos += 1 # Now determine which instruments are used - self._usedDeposits = ibor_deposits - self._usedFRAs = ibor_fras - self._usedSwaps = ibor_swaps + self._used_deposits = ibor_deposits + self._used_fras = ibor_fras + self._used_swaps = ibor_swaps # Need the floating leg basis for the curve - if len(self._usedSwaps) > 0: + if len(self._used_swaps) > 0: self._dc_type = ibor_swaps[0]._float_leg._dc_type else: self._dc_type = None @@ -304,7 +305,7 @@ def _build_curve_using_1d_solver(self): # A deposit is not margined and not indexed to Libor so should # probably not be used to build an indexed Libor curve from - for depo in self._usedDeposits: + for depo in self._used_deposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle @@ -315,7 +316,7 @@ def _build_curve_using_1d_solver(self): oldt_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -333,10 +334,10 @@ def _build_curve_using_1d_solver(self): argtuple = (self._discount_curve, self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, - maxiter=50, fprime2=None) + args=argtuple, tol=SWAP_TOL, + maxiter=50, fprime2=None) - for swap in self._usedSwaps: + for swap in self._used_swaps: # I use the lastPaymentDate in case a date has been adjusted fwd # over a holiday as the maturity date is usually not adjusted CHECK maturity_dt = swap._fixed_leg._payment_dts[-1] @@ -348,11 +349,11 @@ def _build_curve_using_1d_solver(self): argtuple = (self._discount_curve, self, self._value_dt, swap) df_mat = optimize.newton(_f, x0=df_mat, fprime=None, args=argtuple, - tol=swaptol, maxiter=50, fprime2=None, - full_output=False) + tol=SWAP_TOL, maxiter=50, fprime2=None, + full_output=False) if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### @@ -373,7 +374,7 @@ def _build_curve_using_1d_solver(self): # self._dfs = np.append(self._dfs, df_mat) # self._interpolator.fit(self._times, self._dfs) - # for depo in self._usedDeposits: + # for depo in self._used_deposits: # df_settle = self.df(depo._effective_dt) # df_mat = depo._maturity_df() * df_settle # t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear @@ -383,7 +384,7 @@ def _build_curve_using_1d_solver(self): # oldt_mat = t_mat - # for fra in self._usedFRAs: + # for fra in self._used_fras: # t_set = (fra._start_dt - self._value_dt) / gDaysInYear # t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -403,12 +404,12 @@ def _build_curve_using_1d_solver(self): # argtuple = (self._discount_curve, self, self._value_dt, fra) # df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - # args=argtuple, tol=swaptol, + # args=argtuple, tol=swap_tol, # maxiter=50, fprime2=None) - # if len(self._usedSwaps) == 0: + # if len(self._used_swaps) == 0: # if self._check_refit is True: - # self._check_refits(1e-10, swaptol, 1e-5) + # self._check_refits(1e-10, swap_tol, 1e-5) # return # ####################################################################### @@ -416,29 +417,29 @@ def _build_curve_using_1d_solver(self): # ####################################################################### # # Find where the FRAs and Depos go up to as this bit of curve is done - # foundStart = False - # lastDate = self._value_dt - # if len(self._usedDeposits) != 0: - # lastDate = self._usedDeposits[-1]._maturity_dt + # found_start = False + # last_dt = self._value_dt + # if len(self._used_deposits) != 0: + # last_dt = self._used_deposits[-1]._maturity_dt - # if len(self._usedFRAs) != 0: - # lastDate = self._usedFRAs[-1]._maturity_dt + # if len(self._used_fras) != 0: + # last_dt = self._used_fras[-1]._maturity_dt # # We use the longest swap assuming it has a superset of ALL of the # # swap flow dates used in the curve construction - # longestSwap = self._usedSwaps[-1] - # cpn_dts = longestSwap._adjusted_fixed_dts + # longest_swap = self._used_swaps[-1] + # cpn_dts = longest_swap._adjusted_fixed_dts # num_flows = len(cpn_dts) # # Find where first coupon without discount factor starts # start_index = 0 # for i in range(0, num_flows): - # if cpn_dts[i] > lastDate: + # if cpn_dts[i] > last_dt: # start_index = i - # foundStart = True + # found_start = True # break - # if foundStart is False: + # if found_start is False: # raise FinError("Found start is false. Swaps payments inside FRAs") # swap_rates = [] @@ -447,7 +448,7 @@ def _build_curve_using_1d_solver(self): # # I use the last coupon date for the swap rate interpolation as this # # may be different from the maturity date due to a holiday adjustment # # and the swap rates need to align with the coupon payment dates - # for swap in self._usedSwaps: + # for swap in self._used_swaps: # swap_rate = swap._fixed_coupon # maturity_dt = swap._adjusted_fixed_dts[-1] # tswap = (maturity_dt - self._value_dt) / gDaysInYear @@ -458,20 +459,20 @@ def _build_curve_using_1d_solver(self): # interpolatedswap_times = [0.0] # for dt in cpn_dts[1:]: - # swapTime = (dt - self._value_dt) / gDaysInYear - # swap_rate = np.interp(swapTime, swap_times, swap_rates) + # swap_years = (dt - self._value_dt) / gDaysInYear + # swap_rate = np.interp(swap_years, swap_times, swap_rates) # interpolatedSwapRates.append(swap_rate) - # interpolatedswap_times.append(swapTime) + # interpolatedswap_times.append(swap_years) # # Do I need this line ? # interpolatedSwapRates[0] = interpolatedSwapRates[1] - # accrual_factors = longestSwap._fixedYearFracs + # accrual_factors = longest_swap._fixedYearFracs # acc = 0.0 # df = 1.0 # pv01 = 0.0 - # df_settle = self.df(longestSwap._effective_dt) + # df_settle = self.df(longest_swap._effective_dt) # for i in range(1, start_index): # dt = cpn_dts[i] @@ -485,8 +486,8 @@ def _build_curve_using_1d_solver(self): # t_mat = (dt - self._value_dt) / gDaysInYear # swap_rate = interpolatedSwapRates[i] # acc = accrual_factors[i-1] - # pv01End = (acc * swap_rate + 1.0) - # df_mat = (df_settle - swap_rate * pv01) / pv01End + # pv01_end = (acc * swap_rate + 1.0) + # df_mat = (df_settle - swap_rate * pv01) / pv01_end # self._times = np.append(self._times, t_mat) # self._dfs = np.append(self._dfs, df_mat) @@ -495,31 +496,31 @@ def _build_curve_using_1d_solver(self): # pv01 += acc * df_mat # if self._check_refit is True: - # self._check_refits(1e-10, swaptol, 1e-5) + # self._check_refits(1e-10, swap_tol, 1e-5) ############################################################################### - def _check_refits(self, depoTol, fraTol, swapTol): + def _check_refits(self, depo_tol, fra_tol, swap_tol): """ Ensure that the Ibor curve refits the calibration instruments. """ - for depo in self._usedDeposits: + for depo in self._used_deposits: v = depo.value(self._value_dt, self) / depo._notional - if abs(v - 1.0) > depoTol: + if abs(v - 1.0) > depo_tol: print("Value", v) raise FinError("Deposit not repriced.") - for fra in self._usedFRAs: + for fra in self._used_fras: v = fra.value(self._value_dt, self._discount_curve, self) / fra._notional - if abs(v) > fraTol: + if abs(v) > fra_tol: print("Value", v) raise FinError("FRA not repriced.") - for swap in self._usedSwaps: + for swap in self._used_swaps: # We value it as of the start date of the swap v = swap.value(swap._effective_dt, self._discount_curve, self, None) v = v / swap._fixed_leg._notional - if abs(v) > swapTol: + if abs(v) > swap_tol: print("Swap with maturity " + str(swap._maturity_dt) + " Not Repriced. Has Value", v) swap.print_fixed_leg_pv() @@ -534,15 +535,15 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VALUATION DATE", self._value_dt) - for depo in self._usedDeposits: + for depo in self._used_deposits: s += label_to_string("DEPOSIT", "") s += depo.__repr__() - for fra in self._usedFRAs: + for fra in self._used_fras: s += label_to_string("FRA", "") s += fra.__repr__() - for swap in self._usedSwaps: + for swap in self._used_swaps: s += label_to_string("SWAP", "") s += swap.__repr__() diff --git a/financepy/products/rates/ibor_basis_swap.py b/financepy/products/rates/ibor_basis_swap.py index 9e070b9f..d28eaad7 100644 --- a/financepy/products/rates/ibor_basis_swap.py +++ b/financepy/products/rates/ibor_basis_swap.py @@ -32,10 +32,10 @@ class IborBasisSwap: def __init__(self, effective_dt: Date, # Date interest starts to accrue term_dt_or_tenor: (Date, str), # Date contract ends - leg1Type: SwapTypes, - leg1FreqType: FrequencyTypes = FrequencyTypes.QUARTERLY, - leg1DayCountType: DayCountTypes = DayCountTypes.THIRTY_E_360, - leg1Spread: float = 0.0, + leg_1_type: SwapTypes, + leg_1_freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, + leg_1_day_count_type: DayCountTypes = DayCountTypes.THIRTY_E_360, + leg_1_spread: float = 0.0, leg2FreqType: FrequencyTypes = FrequencyTypes.QUARTERLY, leg2DayCountType: DayCountTypes = DayCountTypes.THIRTY_E_360, leg2Spread: float = 0.0, @@ -54,7 +54,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -68,18 +68,18 @@ def __init__(self, raise FinError("Start date after maturity date") leg2Type = SwapTypes.PAY - if leg1Type == SwapTypes.PAY: + if leg_1_type == SwapTypes.PAY: leg2Type = SwapTypes.RECEIVE payment_lag = 0 principal = 0.0 - self._floatLeg1 = SwapFloatLeg(effective_dt, + self._float_leg_1 = SwapFloatLeg(effective_dt, self._termination_dt, - leg1Type, - leg1Spread, - leg1FreqType, - leg1DayCountType, + leg_1_type, + leg_1_spread, + leg_1_freq_type, + leg_1_day_count_type, notional, principal, payment_lag, @@ -87,7 +87,7 @@ def __init__(self, bd_type, dg_type) - self._floatLeg2 = SwapFloatLeg(effective_dt, + self._float_leg_2 = SwapFloatLeg(effective_dt, self._termination_dt, leg2Type, leg2Spread, @@ -105,30 +105,30 @@ def __init__(self, def value(self, value_dt: Date, discount_curve: DiscountCurve, - index_curveLeg1: DiscountCurve = None, - index_curveLeg2: DiscountCurve = None, - firstFixingRateLeg1=None, - firstFixingRateLeg2=None): + index_curve_leg_1: DiscountCurve = None, + index_curve_leg_2: DiscountCurve = None, + first_fixing_rate_leg_1=None, + first_fixing_rate_leg_2=None): """ Value the interest rate swap on a value date given a single Ibor discount curve and an index curve for the Ibors on each swap leg. """ - if index_curveLeg1 is None: - index_curveLeg1 = discount_curve + if index_curve_leg_1 is None: + index_curve_leg_1 = discount_curve - if index_curveLeg2 is None: - index_curveLeg2 = discount_curve + if index_curve_leg_2 is None: + index_curve_leg_2 = discount_curve - floatLeg1Value = self._floatLeg1.value(value_dt, + float_leg_1Value = self._float_leg_1.value(value_dt, discount_curve, - index_curveLeg1, - firstFixingRateLeg1) + index_curve_leg_1, + first_fixing_rate_leg_1) - floatLeg2Value = self._floatLeg2.value(value_dt, + float_leg_2Value = self._float_leg_2.value(value_dt, discount_curve, - index_curveLeg2, - firstFixingRateLeg2) + index_curve_leg_2, + first_fixing_rate_leg_2) - value = floatLeg1Value + floatLeg2Value + value = float_leg_1Value + float_leg_2Value return value ############################################################################### @@ -137,7 +137,7 @@ def print_float_leg_1_pv(self): """ Prints the fixed leg amounts without any valuation details. Shows the dates and sizes of the promised fixed leg flows. """ - self._floatLeg1.print_valuation() + self._float_leg_1.print_valuation() ############################################################################### @@ -145,7 +145,7 @@ def print_float_leg_2_pv(self): """ Prints the fixed leg amounts without any valuation details. Shows the dates and sizes of the promised fixed leg flows. """ - self._floatLeg2.print_valuation() + self._float_leg_2.print_valuation() ############################################################################### @@ -153,16 +153,16 @@ def print_payments(self): """ Prints the fixed leg amounts without any valuation details. Shows the dates and sizes of the promised fixed leg flows. """ - self._floatLeg1.print_payments() - self._floatLeg2.print_payments() + self._float_leg_1.print_payments() + self._float_leg_2.print_payments() ########################################################################## def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) - s += self._floatLeg1.__repr__() + s += self._float_leg_1.__repr__() s += "\n" - s += self._floatLeg2.__repr__() + s += self._float_leg_2.__repr__() return s ############################################################################### diff --git a/financepy/products/rates/ibor_conventions.py b/financepy/products/rates/ibor_conventions.py index e401b363..3e0f4b07 100644 --- a/financepy/products/rates/ibor_conventions.py +++ b/financepy/products/rates/ibor_conventions.py @@ -15,15 +15,15 @@ class IborConventions(): def __init__(self, - currencyName: str, - indexName: str = "LIBOR"): + currency_name: str, + index_name: str = "LIBOR"): - if currencyName == "USD" and indexName == "LIBOR": - self._spotLag = 2 + if currency_name == "USD" and index_name == "LIBOR": + self._spot_lag = 2 self._dc_type = DayCountTypes.THIRTY_E_360_ISDA self._cal_type = CalendarTypes.TARGET - elif currencyName == "EUR" and indexName == "EURIBOR": - self._spotLag = 2 + elif currency_name == "EUR" and index_name == "EURIBOR": + self._spot_lag = 2 self._dc_type = DayCountTypes.THIRTY_E_360_ISDA self._cal_type = CalendarTypes.TARGET else: diff --git a/financepy/products/rates/ibor_fra.py b/financepy/products/rates/ibor_fra.py index 6f366147..3262a421 100644 --- a/financepy/products/rates/ibor_fra.py +++ b/financepy/products/rates/ibor_fra.py @@ -47,10 +47,10 @@ def __init__(self, start_dt: Date, # The date the FRA starts to accrue # End of the Ibor rate period maturity_dt_or_tenor: (Date, str), - fraRate: float, # The fixed contractual FRA rate + fra_rate: float, # The fixed contractual FRA rate dc_type: DayCountTypes, # For interest period notional: float = 100.0, - payFixedRate: bool = True, # True if the FRA rate is being paid + pay_fixed_rate: bool = True, # True if the FRA rate is being paid cal_type: CalendarTypes = CalendarTypes.WEEKEND, bd_type: BusDayAdjustTypes = BusDayAdjustTypes.MODIFIED_FOLLOWING): """ Create a Forward Rate Agreement object. """ @@ -73,8 +73,8 @@ def __init__(self, self._start_dt = start_dt self._maturity_dt = maturity_dt - self._fra_rate = fraRate - self._pay_fixed_rate = payFixedRate + self._fra_rate = fra_rate + self._pay_fixed_rate = pay_fixed_rate self._dc_type = dc_type self._notional = notional @@ -94,14 +94,14 @@ def value(self, # Get the Libor index from the index curve dc = DayCount(self._dc_type) acc_factor = dc.year_frac(self._start_dt, self._maturity_dt)[0] - dfIndex1 = index_curve.df(self._start_dt) - dfIndex2 = index_curve.df(self._maturity_dt) - liborFwd = (dfIndex1 / dfIndex2 - 1.0) / acc_factor + df_index1 = index_curve.df(self._start_dt) + df_index2 = index_curve.df(self._maturity_dt) + libor_fwd = (df_index1 / df_index2 - 1.0) / acc_factor # Get the discount factor from a discount curve - dfDiscount2 = discount_curve.df(self._maturity_dt) + df_discount2 = discount_curve.df(self._maturity_dt) - v = acc_factor * (liborFwd - self._fra_rate) * dfDiscount2 + v = acc_factor * (libor_fwd - self._fra_rate) * df_discount2 # Forward value the FRA to the value date df_to_value_dt = discount_curve.df(value_dt) diff --git a/financepy/products/rates/ibor_future.py b/financepy/products/rates/ibor_future.py index 30b03687..5b92d679 100644 --- a/financepy/products/rates/ibor_future.py +++ b/financepy/products/rates/ibor_future.py @@ -70,7 +70,7 @@ def to_fra(self, futures_price, convexity): fra_rate, self._dc_type, notional=self._contract_size, - payFixedRate=False) + pay_fixed_rate=False) return fra @@ -78,8 +78,8 @@ def to_fra(self, futures_price, convexity): def futures_rate(self, futures_price): """ Calculate implied futures rate from the futures price.""" - futuresRate = (100.0 - futures_price) / 100.0 - return futuresRate + futures_rate = (100.0 - futures_price) / 100.0 + return futures_rate ############################################################################### diff --git a/financepy/products/rates/ibor_lmm_products.py b/financepy/products/rates/ibor_lmm_products.py index 4a9733e1..6cdc4e21 100644 --- a/financepy/products/rates/ibor_lmm_products.py +++ b/financepy/products/rates/ibor_lmm_products.py @@ -68,7 +68,7 @@ def __init__(self, be priced. """ self._start_dt = settle_dt - self._grid_dates = Schedule(settle_dt, + self._grid_dts = Schedule(settle_dt, maturity_dt, float_freq_type, cal_type, @@ -79,13 +79,13 @@ def __init__(self, self._float_dc_type = float_dc_type basis = DayCount(self._float_dc_type) - prev_dt = self._grid_dates[0] + prev_dt = self._grid_dts[0] self._grid_times = [0.0] - for next_dt in self._grid_dates[1:]: + for next_dt in self._grid_dts[1:]: tau = basis.year_frac(prev_dt, next_dt)[0] - t = (next_dt - self._grid_dates[0]) / gDaysInYear + t = (next_dt - self._grid_dts[0]) / gDaysInYear self._accrual_factors.append(tau) self._grid_times.append(t) prev_dt = next_dt @@ -94,7 +94,14 @@ def __init__(self, self._accrual_factors = np.array(self._accrual_factors) self._num_fwds = len(self._accrual_factors) self._fwds = None - + self._use_sobol = None + self._num_paths = None + self._numeraire_index = None + self._fwd_curve = None + self._vol_curves = None + self._corr_matrix = None + self._model_type = None + # print("Num FORWARDS", self._num_fwds) ############################################################################### @@ -103,7 +110,7 @@ def simulate_1f(self, discount_curve, vol_curve: IborCapVolCurve, num_paths: int = 1000, - numeraireIndex: int = 0, + numeraire_index: int = 0, use_sobol: bool = True, seed: int = 42): """ Run the one-factor simulation of the evolution of the forward @@ -116,17 +123,17 @@ def simulate_1f(self, raise FinError("Curve anchor date not the same as LMM start date.") self._num_paths = num_paths - self._numeraire_index = numeraireIndex + self._numeraire_index = numeraire_index self._use_sobol = use_sobol - num_grid_points = len(self._grid_dates) + num_grid_points = len(self._grid_dts) self._num_fwds = num_grid_points self._fwd_curve = [] for i in range(1, num_grid_points): - start_dt = self._grid_dates[i-1] - end_dt = self._grid_dates[i] + start_dt = self._grid_dts[i-1] + end_dt = self._grid_dts[i] fwd_rate = discount_curve.fwd_rate(start_dt, end_dt, self._float_dc_type) @@ -136,12 +143,12 @@ def simulate_1f(self, gammas = np.zeros(num_grid_points) for ix in range(1, num_grid_points): - dt = self._grid_dates[ix] + dt = self._grid_dts[ix] gammas[ix] = vol_curve.caplet_vol(dt) self._fwds = lmm_simulate_fwds_1f(self._num_fwds, num_paths, - numeraireIndex, + numeraire_index, self._fwd_curve, gammas, self._accrual_factors, @@ -152,10 +159,10 @@ def simulate_1f(self, def simulate_mf(self, discount_curve, - numFactors: int, + num_factors: int, lambdas: np.ndarray, num_paths: int = 10000, - numeraireIndex: int = 0, + numeraire_index: int = 0, use_sobol: bool = True, seed: int = 42): """ Run the simulation to generate and store all of the Ibor forward @@ -175,7 +182,7 @@ def simulate_mf(self, print("LEN LAMBDAS", len(lambdas)) print("LEN", len(lambdas[0])) # We pass a vector of vol discount, one for each factor - if numFactors != len(lambdas): + if num_factors != len(lambdas): raise FinError("Lambda doesn't have specified number of factors.") num_rows = len(lambdas[0]) @@ -183,15 +190,15 @@ def simulate_mf(self, raise FinError("Vol Components needs same number of rows as grid") self._num_paths = num_paths - self._numeraire_index = numeraireIndex + self._numeraire_index = numeraire_index self._use_sobol = use_sobol - self._num_fwds = len(self._grid_dates) - 1 + self._num_fwds = len(self._grid_dts) - 1 self._fwd_curve = [] for i in range(1, self._num_fwds): - start_dt = self._grid_dates[i-1] - end_dt = self._grid_dates[i] + start_dt = self._grid_dts[i-1] + end_dt = self._grid_dts[i] fwd_rate = discount_curve.fwd_rate(start_dt, end_dt, self._float_dc_type) self._fwd_curve.append(fwd_rate) @@ -199,9 +206,9 @@ def simulate_mf(self, self._fwd_curve = np.array(self._fwd_curve) self._fwds = lmm_simulate_fwds_mf(self._num_fwds, - numFactors, + num_factors, num_paths, - numeraireIndex, + numeraire_index, self._fwd_curve, lambdas, self._accrual_factors, @@ -237,7 +244,7 @@ def simulate_nf(self, self._num_paths = num_paths self._vol_curves = vol_curve self._corr_matrix = corr_matrix - self._modelType = model_type + self._model_type = model_type self._numeraire_index = numeraire_index self._use_sobol = use_sobol @@ -247,8 +254,8 @@ def simulate_nf(self, self._fwd_curve = [] for i in range(1, num_grid_points): - start_dt = self._grid_dates[i-1] - end_dt = self._grid_dates[i] + start_dt = self._grid_dts[i-1] + end_dt = self._grid_dts[i] fwd_rate = discount_curve.forward_rate(start_dt, end_dt, self._float_dc_type) @@ -258,7 +265,7 @@ def simulate_nf(self, zetas = np.zeros(num_grid_points) for ix in range(1, num_grid_points): - dt = self._grid_dates[ix] + dt = self._grid_dts[ix] zetas[ix] = vol_curve.caplet_vol(dt) # This function does not use Sobol - TODO @@ -308,23 +315,23 @@ def value_swaption(self, for swaption_dt in swaption_float_dts: found_dt = False - for grid_dt in self._grid_dates: + for grid_dt in self._grid_dts: if swaption_dt == grid_dt: found_dt = True break if found_dt is False: raise FinError("Swaption float leg not on grid.") - swaption_fixed_dates = Schedule(settle_dt, + swaption_fixed_dts = Schedule(settle_dt, maturity_dt, fixed_freq_type, cal_type, bd_type, dg_type).generate() - for swaption_dt in swaption_fixed_dates: + for swaption_dt in swaption_fixed_dts: found_dt = False - for grid_dt in self._grid_dates: + for grid_dt in self._grid_dts: if swaption_dt == grid_dt: found_dt = True break @@ -334,13 +341,13 @@ def value_swaption(self, a = 0 b = 0 - for grid_dt in self._grid_dates: + for grid_dt in self._grid_dts: if grid_dt == exercise_dt: break else: a += 1 - for grid_dt in self._grid_dates: + for grid_dt in self._grid_dts: if grid_dt == maturity_dt: break else: @@ -351,7 +358,7 @@ def value_swaption(self, # num_paths = 1000 # v = LMMSwaptionPricer(fixed_coupon, a, b, num_paths, -# fwd0, fwds, taus, isPayer) +# fwd0, fwds, taus, is_payer) v = 0.0 return v @@ -379,7 +386,7 @@ def value_cap_floor(self, for cap_floorlet_dt in cap_floor_dts: found_dt = False - for grid_dt in self._grid_dates: + for grid_dt in self._grid_dts: if cap_floorlet_dt == grid_dt: found_dt = True break @@ -402,11 +409,11 @@ def value_cap_floor(self, fwd0, fwds, taus, is_cap) # Sum the cap/floorlets to get cap/floor value - v_capFloor = 0.0 - for v_capFloorLet in v: - v_capFloor += v_capFloorLet * notional + v_cap_floor = 0.0 + for v_cap_floor_let in v: + v_cap_floor += v_cap_floor_let * notional - return v_capFloor + return v_cap_floor ############################################################################### diff --git a/financepy/products/rates/ibor_single_curve.py b/financepy/products/rates/ibor_single_curve.py index b770adc2..c84a9dbb 100644 --- a/financepy/products/rates/ibor_single_curve.py +++ b/financepy/products/rates/ibor_single_curve.py @@ -21,7 +21,7 @@ from ...products.rates.ibor_fra import IborFRA from ...products.rates.ibor_swap import IborSwap -swaptol = 1e-10 +SWAP_TOL = 1e-10 ############################################################################## # TODO: CHANGE times to df_times @@ -79,23 +79,23 @@ def _cost_function(dfs, *args): # For discount that need a fit function, we fit it now libor_curve._interpolator.fit(libor_curve._times, libor_curve._dfs) - if libor_curve._interp_type == InterpTypes.CUBIC_SPLINE_log_dfs: + if libor_curve._interp_type == InterpTypes.CUBIC_SPLINE_LOG_DFS: libor_curve._splineFunction = CubicSpline(times, values) elif libor_curve._interp_type == InterpTypes.PCHIP_CUBIC_SPLINE: libor_curve._splineFunction = PchipInterpolator(times, values) cost = 0.0 - for depo in libor_curve._usedDeposits: + for depo in libor_curve._used_deposits: v = depo.value(value_dt, libor_curve) / depo._notional # print("DEPO:", depo._maturity_dt, v) cost += (v-1.0)**2 - for fra in libor_curve._usedFRAs: + for fra in libor_curve._used_fras: v = fra.value(value_dt, libor_curve) / fra._notional # print("FRA:", fra._maturity_dt, v) cost += v*v - for swap in libor_curve._usedSwaps: + for swap in libor_curve._used_swaps: v = swap.value(value_dt, libor_curve) / swap._notional # print("SWAP:", swap._maturity_dt, v) cost += v*v @@ -214,9 +214,9 @@ def _validate_inputs(self, depo_start_dt = start_dt for depo in ibor_deposits: - startDt = depo._start_dt - endDt = depo._maturity_dt - if startDt >= endDt: + start_dt = depo._start_dt + end_dt = depo._maturity_dt + if start_dt >= end_dt: raise FinError("First deposit ends on or before it begins") # Ensure order of depos @@ -241,8 +241,8 @@ def _validate_inputs(self, if isinstance(fra, IborFRA) is False: raise FinError("FRA is not of type IborFRA") - startDt = fra._start_dt - if startDt < self._value_dt: + start_dt = fra._start_dt + if start_dt < self._value_dt: raise FinError("FRAs starts before valuation date") if num_fras > 1: @@ -263,8 +263,8 @@ def _validate_inputs(self, if isinstance(swap, IborSwap) is False: raise FinError("Swap is not of type IborSwap") - startDt = swap._effective_dt - if startDt < self._value_dt: + start_dt = swap._effective_dt + if start_dt < self._value_dt: raise FinError("Swaps starts before valuation date.") if swap._effective_dt < swap_start_dt: @@ -273,10 +273,10 @@ def _validate_inputs(self, if num_swaps > 1: # Swaps must all start on the same date for the bootstrap - startDt = ibor_swaps[0]._effective_dt + start_dt = ibor_swaps[0]._effective_dt for swap in ibor_swaps[1:]: - nextStartDt = swap._effective_dt - if nextStartDt != startDt: + next_start_dt = swap._effective_dt + if next_start_dt != start_dt: raise FinError("Swaps must all have same start date.") # Swaps must be increasing in tenor/maturity @@ -288,9 +288,9 @@ def _validate_inputs(self, prev_dt = next_dt # Swaps must have same cash flows for bootstrap to work - longestSwap = ibor_swaps[-1] + longest_swap = ibor_swaps[-1] - longestSwapCpnDates = longestSwap._fixed_leg._payment_dts + longest_swapCpnDates = longest_swap._fixed_leg._payment_dts for swap in ibor_swaps[0:-1]: @@ -298,7 +298,7 @@ def _validate_inputs(self, num_flows = len(swapCpnDates) for i_flow in range(0, num_flows): - if swapCpnDates[i_flow] != longestSwapCpnDates[i_flow]: + if swapCpnDates[i_flow] != longest_swapCpnDates[i_flow]: raise FinError( "Swap coupons are not on the same date grid.") @@ -306,28 +306,28 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDeposit_maturityDate = Date(1, 1, 1900) - firstFRAMaturityDate = Date(1, 1, 1900) - lastFRAMaturityDate = Date(1, 1, 1900) + last_deposit_maturity_dt = Date(1, 1, 1900) + first_fra_maturity_dt = Date(1, 1, 1900) + last_fra_maturity_dt = Date(1, 1, 1900) if num_depos > 0: - lastDeposit_maturityDate = ibor_deposits[-1]._maturity_dt + last_deposit_maturity_dt = ibor_deposits[-1]._maturity_dt if num_fras > 0: - firstFRAMaturityDate = ibor_fras[0]._maturity_dt - lastFRAMaturityDate = ibor_fras[-1]._maturity_dt + first_fra_maturity_dt = ibor_fras[0]._maturity_dt + last_fra_maturity_dt = ibor_fras[-1]._maturity_dt if num_swaps > 0: first_swap_maturity_dt = ibor_swaps[0]._maturity_dt if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDeposit_maturityDate: - print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDeposit_maturityDate) + if first_fra_maturity_dt <= last_deposit_maturity_dt: + print("FRA Maturity Date:", first_fra_maturity_dt) + print("Last Deposit Date:", last_deposit_maturity_dt) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: - if first_swap_maturity_dt <= lastFRAMaturityDate: + if first_swap_maturity_dt <= last_fra_maturity_dt: raise FinError("First Swap must mature after last FRA ends") # If both depos and swaps start after T, we need a rate to get them to @@ -339,21 +339,21 @@ def _validate_inputs(self, raise FinError("Need a deposit rate to pin down short end.") if depo_start_dt > self._value_dt: - firstDepo = ibor_deposits[0] - if firstDepo._start_dt > self._value_dt: - syntheticDeposit = copy.deepcopy(firstDepo) - syntheticDeposit._start_dt = self._value_dt - syntheticDeposit._maturity_dt = firstDepo._start_dt - ibor_deposits.insert(0, syntheticDeposit) + first_depo = ibor_deposits[0] + if first_depo._start_dt > self._value_dt: + synthetic_deposit = copy.deepcopy(first_depo) + synthetic_deposit._start_dt = self._value_dt + synthetic_deposit._maturity_dt = first_depo._start_dt + ibor_deposits.insert(0, synthetic_deposit) num_depos += 1 # Now determine which instruments are used - self._usedDeposits = ibor_deposits - self._usedFRAs = ibor_fras - self._usedSwaps = ibor_swaps + self._used_deposits = ibor_deposits + self._used_fras = ibor_fras + self._used_swaps = ibor_swaps # Need the floating leg basis for the curve - if len(self._usedSwaps) > 0: + if len(self._used_swaps) > 0: self._dc_type = ibor_swaps[0]._float_leg._dc_type else: self._dc_type = None @@ -377,9 +377,9 @@ def _build_curve_using_1d_solver(self): self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) - for depo in self._usedDeposits: - dfSettle = self.df(depo._start_dt) - df_mat = depo._maturity_df() * dfSettle + for depo in self._used_deposits: + df_settle_dt = self.df(depo._start_dt) + df_mat = depo._maturity_df() * df_settle_dt t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) @@ -387,7 +387,7 @@ def _build_curve_using_1d_solver(self): oldt_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -404,10 +404,10 @@ def _build_curve_using_1d_solver(self): self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, + args=argtuple, tol=SWAP_TOL, maxiter=50, fprime2=None) - for swap in self._usedSwaps: + for swap in self._used_swaps: # I use the lastPaymentDate in case a date has been adjusted fwd # over a holiday as the maturity date is usually not adjusted CHECK maturity_dt = swap._fixed_leg._payment_dts[-1] @@ -419,11 +419,11 @@ def _build_curve_using_1d_solver(self): argtuple = (self, self._value_dt, swap) df_mat = optimize.newton(_f, x0=df_mat, fprime=None, args=argtuple, - tol=swaptol, maxiter=50, fprime2=None, + tol=SWAP_TOL, maxiter=50, fprime2=None, full_output=False) if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### @@ -435,18 +435,18 @@ def _build_curve_using_quadratic_minimiser(self): df_mat = 1.0 grid_times = [t_mat] - gridDfs = [df_mat] + grid_dfs = [df_mat] - for depo in self._usedDeposits: + for depo in self._used_deposits: t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear grid_times.append(t_mat) - for fra in self._usedFRAs: + for fra in self._used_fras: t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear grid_times.append(t_mat) - gridDfs.append(df_mat) + grid_dfs.append(df_mat) - for swap in self._usedSwaps: + for swap in self._used_swaps: t_mat = (swap._maturity_dt - self._value_dt) / gDaysInYear grid_times.append(t_mat) @@ -461,7 +461,7 @@ def _build_curve_using_quadratic_minimiser(self): self._dfs = np.array(res.x) if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### @@ -482,9 +482,9 @@ def _build_curve_linear_swap_rate_interpolation(self): self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) - for depo in self._usedDeposits: - dfSettle = self.df(depo._start_dt) - df_mat = depo._maturity_df() * dfSettle + for depo in self._used_deposits: + df_settle_dt = self.df(depo._start_dt) + df_mat = depo._maturity_df() * df_settle_dt t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) @@ -492,7 +492,7 @@ def _build_curve_linear_swap_rate_interpolation(self): oldt_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -517,12 +517,12 @@ def _build_curve_linear_swap_rate_interpolation(self): argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, + args=argtuple, tol=SWAP_TOL, maxiter=50, fprime2=None) - if len(self._usedSwaps) == 0: + if len(self._used_swaps) == 0: if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) return ####################################################################### @@ -530,29 +530,29 @@ def _build_curve_linear_swap_rate_interpolation(self): ####################################################################### # Find where the FRAs and Depos go up to as this bit of curve is done - foundStart = False - lastDate = self._value_dt - if len(self._usedDeposits) != 0: - lastDate = self._usedDeposits[-1]._maturity_dt + found_start = False + last_dt = self._value_dt + if len(self._used_deposits) != 0: + last_dt = self._used_deposits[-1]._maturity_dt - if len(self._usedFRAs) != 0: - lastDate = self._usedFRAs[-1]._maturity_dt + if len(self._used_fras) != 0: + last_dt = self._used_fras[-1]._maturity_dt # We use the longest swap assuming it has a superset of ALL of the # swap flow dates used in the curve construction - longestSwap = self._usedSwaps[-1] - cpn_dts = longestSwap._adjusted_fixed_dts + longest_swap = self._used_swaps[-1] + cpn_dts = longest_swap._adjusted_fixed_dts num_flows = len(cpn_dts) # Find where first coupon without discount factor starts start_index = 0 for i in range(0, num_flows): - if cpn_dts[i] > lastDate: + if cpn_dts[i] > last_dt: start_index = i - foundStart = True + found_start = True break - if foundStart is False: + if found_start is False: raise FinError("Found start is false. Swaps payments inside FRAs") swap_rates = [] @@ -561,7 +561,7 @@ def _build_curve_linear_swap_rate_interpolation(self): # I use the last coupon date for the swap rate interpolation as this # may be different from the maturity date due to a holiday adjustment # and the swap rates need to align with the coupon payment dates - for swap in self._usedSwaps: + for swap in self._used_swaps: swap_rate = swap._fixed_leg._coupon maturity_dt = swap._adjusted_fixed_dts[-1] tswap = (maturity_dt - self._value_dt) / gDaysInYear @@ -572,20 +572,20 @@ def _build_curve_linear_swap_rate_interpolation(self): interpolated_swap_times = [0.0] for dt in cpn_dts[1:]: - swapTime = (dt - self._value_dt) / gDaysInYear - swap_rate = np.interp(swapTime, swap_times, swap_rates) + swap_years = (dt - self._value_dt) / gDaysInYear + swap_rate = np.interp(swap_years, swap_times, swap_rates) interpolated_swap_rates.append(swap_rate) - interpolated_swap_times.append(swapTime) + interpolated_swap_times.append(swap_years) # Do I need this line ? interpolated_swap_rates[0] = interpolated_swap_rates[1] - accrual_factors = longestSwap._fixed_year_fracs + accrual_factors = longest_swap._fixed_year_fracs acc = 0.0 df = 1.0 pv01 = 0.0 - dfSettle = self.df(longestSwap._effective_dt) + df_settle_dt = self.df(longest_swap._effective_dt) for i in range(1, start_index): dt = cpn_dts[i] @@ -599,9 +599,9 @@ def _build_curve_linear_swap_rate_interpolation(self): t_mat = (dt - self._value_dt) / gDaysInYear swap_rate = interpolated_swap_rates[i] acc = accrual_factors[i-1] - pv01End = (acc * swap_rate + 1.0) + pv01_end = (acc * swap_rate + 1.0) - df_mat = (dfSettle - swap_rate * pv01) / pv01End + df_mat = (df_settle_dt - swap_rate * pv01) / pv01_end self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) @@ -610,30 +610,30 @@ def _build_curve_linear_swap_rate_interpolation(self): pv01 += acc * df_mat if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### - def _check_refits(self, depoTol, fraTol, swapTol): + def _check_refits(self, depo_tol, fra_tol, swap_tol): """ Ensure that the Ibor curve refits the calibration instruments. """ - for depo in self._usedDeposits: + for depo in self._used_deposits: v = depo.value(self._value_dt, self) / depo._notional - if abs(v - 1.0) > depoTol: + if abs(v - 1.0) > depo_tol: print("Value", v) raise FinError("Deposit not repriced.") - for fra in self._usedFRAs: + for fra in self._used_fras: v = fra.value(self._value_dt, self, self) / fra._notional - if abs(v) > fraTol: + if abs(v) > fra_tol: print("Value", v) raise FinError("FRA not repriced.") - for swap in self._usedSwaps: + for swap in self._used_swaps: # We value it as of the start date of the swap v = swap.value(swap._effective_dt, self, self, None) v = v / swap._fixed_leg._notional # print("REFIT SWAP VALUATION:", swap._adjustedMaturityDate, v) - if abs(v) > swapTol: + if abs(v) > swap_tol: print("Swap with maturity " + str(swap._maturity_dt) + " Not Repriced. Has Value", v) swap.print_fixed_leg_pv() @@ -648,15 +648,15 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VALUATION DATE", self._value_dt) - for depo in self._usedDeposits: + for depo in self._used_deposits: s += label_to_string("DEPOSIT", "") s += depo.__repr__() - for fra in self._usedFRAs: + for fra in self._used_fras: s += label_to_string("FRA", "") s += fra.__repr__() - for swap in self._usedSwaps: + for swap in self._used_swaps: s += label_to_string("SWAP", "") s += swap.__repr__() diff --git a/financepy/products/rates/ibor_swap.py b/financepy/products/rates/ibor_swap.py index 87ca6799..0b992169 100644 --- a/financepy/products/rates/ibor_swap.py +++ b/financepy/products/rates/ibor_swap.py @@ -6,7 +6,7 @@ from ...utils.error import FinError from ...utils.date import Date -from ...utils.global_vars import gSmall +from ...utils.global_vars import g_small from ...utils.day_count import DayCountTypes from ...utils.frequency import FrequencyTypes, annual_frequency from ...utils.calendar import CalendarTypes, DateGenRuleTypes @@ -62,7 +62,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -116,7 +116,7 @@ def value(self, value_dt: Date, discount_curve: DiscountCurve, index_curve: DiscountCurve = None, - firstFixingRate=None): + first_fixing_rate=None): """ Value the interest rate swap on a value date given a single Ibor discount curve. """ @@ -129,7 +129,7 @@ def value(self, float_leg_value = self._float_leg.value(value_dt, discount_curve, index_curve, - firstFixingRate) + first_fixing_rate) value = fixed_leg_value + float_leg_value return value @@ -163,7 +163,7 @@ def swap_rate(self, pv01 = self.pv01(value_dt, discount_curve) - if abs(pv01) < gSmall: + if abs(pv01) < g_small: raise FinError("PV01 is zero. Cannot compute swap rate.") if value_dt < self._effective_dt: @@ -215,15 +215,15 @@ def cash_settled_pv01(self, start_index = 1 """ Now PV fixed leg flows. """ - flatPV01 = 0.0 + flat_pv01 = 0.0 df = 1.0 alpha = 1.0 / m for _ in self._fixed_leg._payment_dts[start_index:]: df = df / (1.0 + alpha * flat_swap_rate) - flatPV01 += df * alpha + flat_pv01 += df * alpha - return flatPV01 + return flat_pv01 ########################################################################### diff --git a/financepy/products/rates/ibor_swaption.py b/financepy/products/rates/ibor_swaption.py index 8cf94a30..5c3b6eea 100644 --- a/financepy/products/rates/ibor_swaption.py +++ b/financepy/products/rates/ibor_swaption.py @@ -94,6 +94,7 @@ def __init__(self, self._fwd_swap_rate = None self._forward_df = None self._underlying_swap = None + self._swap_type = None ############################################################################### @@ -214,21 +215,21 @@ def value(self, elif isinstance(model, HWTree): - swaptionPx = model.european_bond_option_jamshidian(t_exp, - strike_price, - face_amount, - cpn_times, - cpn_flows, - df_times, - df_values) + swaption_px = model.european_bond_option_jamshidian(t_exp, + strike_price, + face_amount, + cpn_times, + cpn_flows, + df_times, + df_values) if self._fixed_leg_type == SwapTypes.PAY: - swaption_price = swaptionPx['put'] + swaption_price = swaption_px['put'] elif self._fixed_leg_type == SwapTypes.RECEIVE: - swaption_price = swaptionPx['call'] + swaption_price = swaption_px['call'] else: raise FinError("Unknown swaption option type" + - str(self._swapType)) + str(self._swap_type)) # Cancel the multiplication at the end below swaption_price /= pv01 @@ -236,36 +237,36 @@ def value(self, elif isinstance(model, BKTree): model.build_tree(t_mat, df_times, df_values) - swaptionPx = model.bermudan_swaption(t_exp, - t_mat, - strike_price, - face_amount, - cpn_times, - cpn_flows, - FinExerciseTypes.EUROPEAN) + swaption_px = model.bermudan_swaption(t_exp, + t_mat, + strike_price, + face_amount, + cpn_times, + cpn_flows, + FinExerciseTypes.EUROPEAN) if self._fixed_leg_type == SwapTypes.PAY: - swaption_price = swaptionPx['pay'] + swaption_price = swaption_px['pay'] elif self._fixed_leg_type == SwapTypes.RECEIVE: - swaption_price = swaptionPx['rec'] + swaption_price = swaption_px['rec'] swaption_price /= pv01 elif isinstance(model, BDTTree): model.build_tree(t_mat, df_times, df_values) - swaptionPx = model.bermudan_swaption(t_exp, - t_mat, - strike_price, - face_amount, - cpn_times, - cpn_flows, - FinExerciseTypes.EUROPEAN) + swaption_px = model.bermudan_swaption(t_exp, + t_mat, + strike_price, + face_amount, + cpn_times, + cpn_flows, + FinExerciseTypes.EUROPEAN) if self._fixed_leg_type == SwapTypes.PAY: - swaption_price = swaptionPx['pay'] + swaption_price = swaption_px['pay'] elif self._fixed_leg_type == SwapTypes.RECEIVE: - swaption_price = swaptionPx['rec'] + swaption_price = swaption_px['rec'] swaption_price /= pv01 else: @@ -345,8 +346,8 @@ def cash_settled_value(self, # The exchange of cash occurs on the settlement date but we need to # value the swaption on the provided valuation date - which could be # the settlement date or may be a different date. - dfValuation = discount_curve.df(value_dt) - swaption_price = swaption_price * self._pv01 * self._notional / dfValuation + df_value_dt = discount_curve.df(value_dt) + swaption_price = swaption_price * self._pv01 * self._notional / df_value_dt return swaption_price ############################################################################### diff --git a/financepy/products/rates/ois.py b/financepy/products/rates/ois.py index a09d06c6..e2627403 100644 --- a/financepy/products/rates/ois.py +++ b/financepy/products/rates/ois.py @@ -87,7 +87,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -95,7 +95,7 @@ def __init__(self, calendar = Calendar(cal_type) self._maturity_dt = calendar.adjust(self._termination_dt, - bd_type) + bd_type) if effective_dt > self._maturity_dt: raise FinError("Start date after maturity date") @@ -160,7 +160,7 @@ def pv01(self, value_dt, discount_curve): """ Calculate the value of 1 basis point coupon on the fixed leg. """ pv = self._fixed_leg.value(value_dt, discount_curve) - pv01 = pv / self._fixed_leg._coupon / self._fixed_leg._notional + pv01 = pv / self._fixed_leg._cpn / self._fixed_leg._notional # Needs to be positive even if it is a payer leg and/or coupon < 0 pv01 = np.abs(pv01) diff --git a/financepy/products/rates/ois_basis_swap.py b/financepy/products/rates/ois_basis_swap.py index 27c1a90d..18397573 100644 --- a/financepy/products/rates/ois_basis_swap.py +++ b/financepy/products/rates/ois_basis_swap.py @@ -32,14 +32,14 @@ class OISBasisSwap: def __init__(self, effective_dt: Date, # Date interest starts to accrue term_dt_or_tenor: (Date, str), # Date contract ends - iborType: SwapTypes, - iborFreqType: FrequencyTypes = FrequencyTypes.QUARTERLY, - iborDayCountType: DayCountTypes = DayCountTypes.THIRTY_E_360, - iborSpread: float = 0.0, - oisFreqType: FrequencyTypes = FrequencyTypes.QUARTERLY, - oisDayCountType: DayCountTypes = DayCountTypes.THIRTY_E_360, - oisSpread: float = 0.0, - oisPaymentLag: int = 0, + ibor_type: SwapTypes, + ibor_freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, + ibor_day_count_type: DayCountTypes = DayCountTypes.THIRTY_E_360, + ibor_spread: float = 0.0, + ois_freq_type: FrequencyTypes = FrequencyTypes.QUARTERLY, + ois_day_count_type: DayCountTypes = DayCountTypes.THIRTY_E_360, + ois_spread: float = 0.0, + ois_payment_lag: int = 0, notional: float = ONE_MILLION, cal_type: CalendarTypes = CalendarTypes.WEEKEND, bd_type: BusDayAdjustTypes = BusDayAdjustTypes.FOLLOWING, @@ -55,7 +55,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -63,23 +63,23 @@ def __init__(self, calendar = Calendar(cal_type) self._maturity_dt = calendar.adjust(self._termination_dt, - bd_type) + bd_type) if effective_dt > self._maturity_dt: raise FinError("Start date after maturity date") - oisType = SwapTypes.PAY - if iborType == SwapTypes.PAY: - oisType = SwapTypes.RECEIVE + ois_type = SwapTypes.PAY + if ibor_type == SwapTypes.PAY: + ois_type = SwapTypes.RECEIVE principal = 0.0 - self._floatIborLeg = SwapFloatLeg(effective_dt, + self._float_ibor_leg = SwapFloatLeg(effective_dt, self._termination_dt, - iborType, - iborSpread, - iborFreqType, - iborDayCountType, + ibor_type, + ibor_spread, + ibor_freq_type, + ibor_day_count_type, notional, principal, 0, @@ -87,15 +87,15 @@ def __init__(self, bd_type, dg_type) - self._floatOISLeg = SwapFloatLeg(effective_dt, + self._float_ois_leg = SwapFloatLeg(effective_dt, self._termination_dt, - oisType, - oisSpread, - oisFreqType, - oisDayCountType, + ois_type, + ois_spread, + ois_freq_type, + ois_day_count_type, notional, principal, - oisPaymentLag, + ois_payment_lag, cal_type, bd_type, dg_type) @@ -105,30 +105,30 @@ def __init__(self, def value(self, value_dt: Date, discount_curve: DiscountCurve, - indexIborCurve: DiscountCurve = None, - indexOISCurve: DiscountCurve = None, - firstFixingRateLeg1=None, - firstFixingRateLeg2=None): + index_ibor_curve: DiscountCurve = None, + index_ois_curve: DiscountCurve = None, + first_fixing_rate_leg_1=None, + first_fixing_rate_leg_2=None): """ Value the interest rate swap on a value date given a single Ibor discount curve and an index curve for the Ibors on each swap leg. """ - if indexIborCurve is None: - indexIborCurve = discount_curve + if index_ibor_curve is None: + index_ibor_curve = discount_curve - if indexOISCurve is None: - indexOISCurve = discount_curve + if index_ois_curve is None: + index_ois_curve = discount_curve - floatIborLegValue = self._floatIborLeg.value(value_dt, + float_ibor_leg_value = self._float_ibor_leg.value(value_dt, discount_curve, - indexIborCurve, - firstFixingRateLeg1) + index_ibor_curve, + first_fixing_rate_leg_1) - floatOISLegValue = self._floatOISLeg.value(value_dt, + float_ois_leg_value = self._float_ois_leg.value(value_dt, discount_curve, - indexOISCurve, - firstFixingRateLeg2) + index_ois_curve, + first_fixing_rate_leg_2) - value = floatIborLegValue + floatOISLegValue + value = float_ibor_leg_value + float_ois_leg_value return value ############################################################################### @@ -137,16 +137,16 @@ def print_payments(self): """ Prints the fixed leg amounts without any valuation details. Shows the dates and sizes of the promised fixed leg flows. """ - self._floatIborLeg.print_payments() - self._floatOISLeg.print_payments() + self._float_ibor_leg.print_payments() + self._float_ois_leg.print_payments() ########################################################################## def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) - s += self._floatIborLeg.__repr__() + s += self._float_ibor_leg.__repr__() s += "\n" - s += self._floatOISLeg.__repr__() + s += self._float_ois_leg.__repr__() return s ############################################################################### diff --git a/financepy/products/rates/ois_curve.py b/financepy/products/rates/ois_curve.py index 24bead92..45616b83 100644 --- a/financepy/products/rates/ois_curve.py +++ b/financepy/products/rates/ois_curve.py @@ -17,7 +17,7 @@ from ...products.rates.ibor_deposit import IborDeposit from ...products.rates.ois import OIS -swaptol = 1e-10 +SWAP_TOL = 1e-10 ############################################################################## # TODO: CHANGE times to df_times @@ -137,14 +137,14 @@ def _build_curve(self): ############################################################################### def _validate_inputs(self, - oisDeposits, - oisFRAs, - oisSwaps): + ois_deposits, + ois_fras, + ois_swaps): """ Validate the inputs for each of the Libor products. """ - num_depos = len(oisDeposits) - num_fras = len(oisFRAs) - num_swaps = len(oisSwaps) + num_depos = len(ois_deposits) + num_fras = len(ois_fras) + num_swaps = len(ois_swaps) depo_start_dt = self._value_dt swap_start_dt = self._value_dt @@ -155,9 +155,9 @@ def _validate_inputs(self, # Validation of the inputs. if num_depos > 0: - depo_start_dt = oisDeposits[0]._start_dt + depo_start_dt = ois_deposits[0]._start_dt - for depo in oisDeposits: + for depo in ois_deposits: if isinstance(depo, IborDeposit) is False: raise FinError("Deposit is not of type IborDeposit") @@ -170,17 +170,17 @@ def _validate_inputs(self, if start_dt < depo_start_dt: depo_start_dt = start_dt - for depo in oisDeposits: - startDt = depo._start_dt - endDt = depo._maturity_dt - if startDt >= endDt: + for depo in ois_deposits: + start_dt = depo._start_dt + end_dt = depo._maturity_dt + if start_dt >= end_dt: raise FinError("First deposit ends on or before it begins") # Ensure order of depos if num_depos > 1: - prev_dt = oisDeposits[0]._maturity_dt - for depo in oisDeposits[1:]: + prev_dt = ois_deposits[0]._maturity_dt + for depo in ois_deposits[1:]: next_dt = depo._maturity_dt if next_dt <= prev_dt: raise FinError("Deposits must be in increasing maturity") @@ -191,23 +191,23 @@ def _validate_inputs(self, # Ensure that valuation date is on or after first deposit start date # Ensure that valuation date is on or after first deposit start date # if num_depos > 1: - # if oisDeposits[0]._start_dt > self._value_dt: + # if ois_deposits[0]._start_dt > self._value_dt: # raise FinError("Valuation date must not be before first deposit settles.") # Validation of the inputs. if num_fras > 0: - for fra in oisFRAs: - startDt = fra._start_dt - if startDt <= self._value_dt: + for fra in ois_fras: + start_dt = fra._start_dt + if start_dt <= self._value_dt: raise FinError("FRAs starts before valuation date") - startDt = fra._start_dt - if startDt < self._value_dt: + start_dt = fra._start_dt + if start_dt < self._value_dt: raise FinError("FRAs starts before valuation date") if num_fras > 1: - prev_dt = oisFRAs[0]._maturity_dt - for fra in oisFRAs[1:]: + prev_dt = ois_fras[0]._maturity_dt + for fra in ois_fras[1:]: next_dt = fra._maturity_dt if next_dt <= prev_dt: raise FinError("FRAs must be in increasing maturity") @@ -215,15 +215,15 @@ def _validate_inputs(self, if num_swaps > 0: - swap_start_dt = oisSwaps[0]._effective_dt + swap_start_dt = ois_swaps[0]._effective_dt - for swap in oisSwaps: + for swap in ois_swaps: if isinstance(swap, OIS) is False: raise FinError("Swap is not of type FinOIS") - startDt = swap._effective_dt - if startDt < self._value_dt: + start_dt = swap._effective_dt + if start_dt < self._value_dt: raise FinError("Swaps starts before valuation date.") if swap._effective_dt < swap_start_dt: @@ -232,8 +232,8 @@ def _validate_inputs(self, if num_swaps > 1: # Swaps must be increasing in tenor/maturity - prev_dt = oisSwaps[0]._maturity_dt - for swap in oisSwaps[1:]: + prev_dt = ois_swaps[0]._maturity_dt + for swap in ois_swaps[1:]: next_dt = swap._maturity_dt if next_dt <= prev_dt: raise FinError("Swaps must be in increasing maturity") @@ -241,45 +241,45 @@ def _validate_inputs(self, # TODO: REINSTATE THESE CHECKS ? # Swaps must have same cash flows for linear swap bootstrap to work -# longestSwap = oisSwaps[-1] -# longestSwapCpnDates = longestSwap._adjusted_fixed_dts -# for swap in oisSwaps[0:-1]: +# longest_swap = ois_swaps[-1] +# longest_swapCpnDates = longest_swap._adjusted_fixed_dts +# for swap in ois_swaps[0:-1]: # swapCpnDates = swap._adjusted_fixed_dts # num_flows = len(swapCpnDates) # for i_flow in range(0, num_flows): -# if swapCpnDates[i_flow] != longestSwapCpnDates[i_flow]: +# if swapCpnDates[i_flow] != longest_swapCpnDates[i_flow]: # raise FinError("Swap coupons are not on the same date grid.") ####################################################################### # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDeposit_maturityDate = Date(1, 1, 1900) - firstFRAMaturityDate = Date(1, 1, 1900) - lastFRAMaturityDate = Date(1, 1, 1900) + last_deposit_maturity_dt = Date(1, 1, 1900) + first_fra_maturity_dt = Date(1, 1, 1900) + last_fra_maturity_dt = Date(1, 1, 1900) if num_depos > 0: - lastDeposit_maturityDate = oisDeposits[-1]._maturity_dt + last_deposit_maturity_dt = ois_deposits[-1]._maturity_dt if num_fras > 0: - firstFRAMaturityDate = oisFRAs[0]._maturity_dt - lastFRAMaturityDate = oisFRAs[-1]._maturity_dt + first_fra_maturity_dt = ois_fras[0]._maturity_dt + last_fra_maturity_dt = ois_fras[-1]._maturity_dt if num_swaps > 0: - first_swap_maturity_dt = oisSwaps[0]._maturity_dt + first_swap_maturity_dt = ois_swaps[0]._maturity_dt if num_fras > 0 and num_swaps > 0: - if first_swap_maturity_dt <= lastFRAMaturityDate: + if first_swap_maturity_dt <= last_fra_maturity_dt: raise FinError("First Swap must mature after last FRA ends") if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDeposit_maturityDate: - print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDeposit_maturityDate) + if first_fra_maturity_dt <= last_deposit_maturity_dt: + print("FRA Maturity Date:", first_fra_maturity_dt) + print("Last Deposit Date:", last_deposit_maturity_dt) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: - if first_swap_maturity_dt <= lastFRAMaturityDate: + if first_swap_maturity_dt <= last_fra_maturity_dt: raise FinError("First Swap must mature after last FRA") if swap_start_dt > self._value_dt: @@ -288,23 +288,23 @@ def _validate_inputs(self, raise FinError("Need a deposit rate to pin down short end.") if depo_start_dt > self._value_dt: - firstDepo = oisDeposits[0] - if firstDepo._start_dt > self._value_dt: + first_depo = ois_deposits[0] + if first_depo._start_dt > self._value_dt: print("Inserting synthetic deposit") - syntheticDeposit = copy.deepcopy(firstDepo) - syntheticDeposit._start_dt = self._value_dt - syntheticDeposit._maturity_dt = firstDepo._start_dt - oisDeposits.insert(0, syntheticDeposit) + synthetic_deposit = copy.deepcopy(first_depo) + synthetic_deposit._start_dt = self._value_dt + synthetic_deposit._maturity_dt = first_depo._start_dt + ois_deposits.insert(0, synthetic_deposit) num_depos += 1 # Now determine which instruments are used - self._usedDeposits = oisDeposits - self._usedFRAs = oisFRAs - self._usedSwaps = oisSwaps + self._used_deposits = ois_deposits + self._used_fras = ois_fras + self._used_swaps = ois_swaps # Need the floating leg basis for the curve - if len(self._usedSwaps) > 0: - self._dc_type = oisSwaps[0]._float_leg._dc_type + if len(self._used_swaps) > 0: + self._dc_type = ois_swaps[0]._float_leg._dc_type else: self._dc_type = None @@ -327,7 +327,7 @@ def _build_curve_using_1d_solver(self): self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) - for depo in self._usedDeposits: + for depo in self._used_deposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear @@ -337,7 +337,7 @@ def _build_curve_using_1d_solver(self): old_t_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -354,10 +354,10 @@ def _build_curve_using_1d_solver(self): self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, - maxiter=50, fprime2=None) + args=argtuple, tol=SWAP_TOL, + maxiter=50, fprime2=None) - for swap in self._usedSwaps: + for swap in self._used_swaps: # I use the lastPaymentDate in case a date has been adjusted fwd # over a holiday as the maturity date is usually not adjusted CHECK maturity_dt = swap._fixed_leg._payment_dts[-1] @@ -369,11 +369,11 @@ def _build_curve_using_1d_solver(self): argtuple = (self, self._value_dt, swap) df_mat = optimize.newton(_f, x0=df_mat, fprime=None, args=argtuple, - tol=swaptol, maxiter=50, fprime2=None, - full_output=False) + tol=SWAP_TOL, maxiter=50, fprime2=None, + full_output=False) if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### @@ -392,7 +392,7 @@ def _build_curve_linear_swap_rate_interpolation(self): self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) - for depo in self._usedDeposits: + for depo in self._used_deposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear @@ -402,7 +402,7 @@ def _build_curve_linear_swap_rate_interpolation(self): old_t_mat = t_mat - for fra in self._usedFRAs: + for fra in self._used_fras: t_set = (fra._start_dt - self._value_dt) / gDaysInYear t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear @@ -422,12 +422,12 @@ def _build_curve_linear_swap_rate_interpolation(self): argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, - args=argtuple, tol=swaptol, + args=argtuple, tol=SWAP_TOL, maxiter=50, fprime2=None) - if len(self._usedSwaps) == 0: + if len(self._used_swaps) == 0: if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) return ####################################################################### @@ -437,16 +437,16 @@ def _build_curve_linear_swap_rate_interpolation(self): # Find where the FRAs and Depos go up to as this bit of curve is done found_start = False last_dt = self._value_dt - if len(self._usedDeposits) != 0: - last_dt = self._usedDeposits[-1]._maturity_dt + if len(self._used_deposits) != 0: + last_dt = self._used_deposits[-1]._maturity_dt - if len(self._usedFRAs) != 0: - last_dt = self._usedFRAs[-1]._maturity_dt + if len(self._used_fras) != 0: + last_dt = self._used_fras[-1]._maturity_dt # We use the longest swap assuming it has a superset of ALL of the # swap flow dates used in the curve construction - longestSwap = self._usedSwaps[-1] - cpn_dts = longestSwap._adjusted_fixed_dts + longest_swap = self._used_swaps[-1] + cpn_dts = longest_swap._adjusted_fixed_dts num_flows = len(cpn_dts) # Find where first coupon without discount factor starts @@ -466,7 +466,7 @@ def _build_curve_linear_swap_rate_interpolation(self): # I use the last coupon date for the swap rate interpolation as this # may be different from the maturity date due to a holiday adjustment # and the swap rates need to align with the coupon payment dates - for swap in self._usedSwaps: + for swap in self._used_swaps: swap_rate = swap._fixed_coupon maturity_dt = swap._adjusted_fixed_dts[-1] tswap = (maturity_dt - self._value_dt) / gDaysInYear @@ -484,12 +484,12 @@ def _build_curve_linear_swap_rate_interpolation(self): # Do I need this line ? interpolated_swap_rates[0] = interpolated_swap_rates[1] - accrual_factors = longestSwap._fixed_year_fracs + accrual_factors = longest_swap._fixed_year_fracs acc = 0.0 df = 1.0 pv01 = 0.0 - df_settle = self.df(longestSwap._start_dt) + df_settle = self.df(longest_swap._start_dt) for i in range(1, start_index): dt = cpn_dts[i] @@ -503,9 +503,9 @@ def _build_curve_linear_swap_rate_interpolation(self): t_mat = (dt - self._value_dt) / gDaysInYear swap_rate = interpolated_swap_rates[i] acc = accrual_factors[i-1] - pv01End = (acc * swap_rate + 1.0) + pv01_end = (acc * swap_rate + 1.0) - df_mat = (df_settle - swap_rate * pv01) / pv01End + df_mat = (df_settle - swap_rate * pv01) / pv01_end self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) @@ -514,25 +514,25 @@ def _build_curve_linear_swap_rate_interpolation(self): pv01 += acc * df_mat if self._check_refit is True: - self._check_refits(1e-10, swaptol, 1e-5) + self._check_refits(1e-10, SWAP_TOL, 1e-5) ############################################################################### - def _check_refits(self, depoTol, fraTol, swapTol): + def _check_refits(self, depo_tol, fra_tol, swap_tol): """ Ensure that the Libor curve refits the calibration instruments. """ - for fra in self._usedFRAs: + for fra in self._used_fras: v = fra.value(self._value_dt, self) / fra._notional - if abs(v) > fraTol: + if abs(v) > fra_tol: print("Value", v) raise FinError("FRA not repriced.") - for swap in self._usedSwaps: + for swap in self._used_swaps: # We value it as of the start date of the swap v = swap.value(swap._effective_dt, self, self, None, principal=0.0) v = v / swap._notional - if abs(v) > swapTol: + if abs(v) > swap_tol: print("Swap with maturity " + str(swap._maturity_dt) + " Not Repriced. Has Value", v) swap.print_fixed_leg_pv() @@ -560,7 +560,7 @@ def _check_refits(self, depoTol, fraTol, swapTol): # overnightRates = [] - # dfValuationDate = self.df(settle_dt) + # df_value_dt = self.df(settle_dt) # for maturity_dt in maturity_dts: @@ -578,13 +578,13 @@ def _check_refits(self, depoTol, fraTol, swapTol): # for next_dt in flow_dts[1:]: # if next_dt > settle_dt: - # df = self.df(next_dt) / dfValuationDate + # df = self.df(next_dt) / df_value_dt # alpha = day_counter.year_frac(prev_dt, next_dt)[0] # pv01 += alpha * df # prev_dt = next_dt - # if abs(pv01) < gSmall: + # if abs(pv01) < g_small: # par_rate = None # else: # df_start = self.df(start_dt) @@ -605,15 +605,15 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("VALUATION DATE", self._value_dt) - for depo in self._usedDeposits: + for depo in self._used_deposits: s += label_to_string("DEPOSIT", "") s += depo.__repr__() - for fra in self._usedFRAs: + for fra in self._used_fras: s += label_to_string("FRA", "") s += fra.__repr__() - for swap in self._usedSwaps: + for swap in self._used_swaps: s += label_to_string("SWAP", "") s += swap.__repr__() diff --git a/financepy/products/rates/swap_fixed_leg.py b/financepy/products/rates/swap_fixed_leg.py index f74d6b4a..29ea8865 100644 --- a/financepy/products/rates/swap_fixed_leg.py +++ b/financepy/products/rates/swap_fixed_leg.py @@ -98,9 +98,9 @@ def generate_payments(self): self._dg_type, end_of_month=self._end_of_month) - scheduleDates = schedule._adjusted_dts + schedule_dts = schedule._adjusted_dts - if len(scheduleDates) < 2: + if len(schedule_dts) < 2: raise FinError("Schedule has none or only one date") self._start_accrued_dts = [] @@ -111,12 +111,12 @@ def generate_payments(self): self._accrued_days = [] self._rates = [] - prev_dt = scheduleDates[0] + prev_dt = schedule_dts[0] day_counter = DayCount(self._dc_type) calendar = Calendar(self._cal_type) - for next_dt in scheduleDates[1:]: + for next_dt in schedule_dts[1:]: self._start_accrued_dts.append(prev_dt) self._end_accrued_dts.append(next_dt) @@ -148,43 +148,43 @@ def value(self, value_dt: Date, discount_curve: DiscountCurve): - self._paymentDfs = [] + self._payment_dfs = [] self._payment_pvs = [] - self._cumulativePVs = [] + self._cumulative_pvs = [] notional = self._notional - dfValue = discount_curve.df(value_dt) + df_value = discount_curve.df(value_dt) leg_pv = 0.0 - numPayments = len(self._payment_dts) + num_payments = len(self._payment_dts) - dfPmnt = 0.0 + df_pmnt = 0.0 - for iPmnt in range(0, numPayments): + for i_pmnt in range(0, num_payments): - pmntDate = self._payment_dts[iPmnt] - pmntAmount = self._payments[iPmnt] + pmnt_dt = self._payment_dts[i_pmnt] + pmnt_amount = self._payments[i_pmnt] - if pmntDate > value_dt: + if pmnt_dt > value_dt: - dfPmnt = discount_curve.df(pmntDate) / dfValue - pmntPV = pmntAmount * dfPmnt - leg_pv += pmntPV + df_pmnt = discount_curve.df(pmnt_dt) / df_value + pmnt_pv = pmnt_amount * df_pmnt + leg_pv += pmnt_pv - self._paymentDfs.append(dfPmnt) - self._payment_pvs.append(pmntAmount*dfPmnt) - self._cumulativePVs.append(leg_pv) + self._payment_dfs.append(df_pmnt) + self._payment_pvs.append(pmnt_amount*df_pmnt) + self._cumulative_pvs.append(leg_pv) else: - self._paymentDfs.append(0.0) + self._payment_dfs.append(0.0) self._payment_pvs.append(0.0) - self._cumulativePVs.append(0.0) + self._cumulative_pvs.append(0.0) - if pmntDate > value_dt: - payment_pv = self._principal * dfPmnt * notional + if pmnt_dt > value_dt: + payment_pv = self._principal * df_pmnt * notional self._payment_pvs[-1] += payment_pv leg_pv += payment_pv - self._cumulativePVs[-1] = leg_pv + self._cumulative_pvs[-1] = leg_pv if self._leg_type == SwapTypes.PAY: leg_pv = leg_pv * (-1.0) @@ -258,9 +258,9 @@ def print_valuation(self): round(self._notional, 0), round(self._rates[i_flow] * 100.0, 4), round(self._payments[i_flow], 2), - round(self._paymentDfs[i_flow], 4), + round(self._payment_dfs[i_flow], 4), round(self._payment_pvs[i_flow], 2), - round(self._cumulativePVs[i_flow], 2), + round(self._cumulative_pvs[i_flow], 2), ]) table = format_table(header, rows) diff --git a/financepy/products/rates/swap_float_leg.py b/financepy/products/rates/swap_float_leg.py index 8bacd991..64707fbf 100644 --- a/financepy/products/rates/swap_float_leg.py +++ b/financepy/products/rates/swap_float_leg.py @@ -50,7 +50,7 @@ def __init__(self, calendar = Calendar(cal_type) self._maturity_dt = calendar.adjust(self._termination_dt, - bd_type) + bd_type) if effective_dt > self._maturity_dt: raise FinError("Start date after maturity date") @@ -71,8 +71,8 @@ def __init__(self, self._dg_type = dg_type self._end_of_month = end_of_month - self._startAccruedDates = [] - self._endAccruedDates = [] + self._start_accrued_dts = [] + self._end_accrued_dts = [] self._payment_dts = [] self._payments = [] self._year_fracs = [] @@ -94,33 +94,33 @@ def generate_payment_dts(self): self._dg_type, end_of_month=self._end_of_month) - scheduleDates = schedule._adjusted_dts + schedule_dts = schedule._adjusted_dts - if len(scheduleDates) < 2: + if len(schedule_dts) < 2: raise FinError("Schedule has none or only one date") - self._startAccruedDates = [] - self._endAccruedDates = [] + self._start_accrued_dts = [] + self._end_accrued_dts = [] self._payment_dts = [] self._year_fracs = [] self._accrued_days = [] - prev_dt = scheduleDates[0] + prev_dt = schedule_dts[0] day_counter = DayCount(self._dc_type) calendar = Calendar(self._cal_type) # All of the lists end up with the same length - for next_dt in scheduleDates[1:]: + for next_dt in schedule_dts[1:]: - self._startAccruedDates.append(prev_dt) - self._endAccruedDates.append(next_dt) + self._start_accrued_dts.append(prev_dt) + self._end_accrued_dts.append(next_dt) if self._payment_lag == 0: payment_dt = next_dt else: payment_dt = calendar.add_business_days(next_dt, - self._payment_lag) + self._payment_lag) self._payment_dts.append(payment_dt) @@ -138,7 +138,7 @@ def value(self, value_dt: Date, # This should be the settlement date discount_curve: DiscountCurve, index_curve: DiscountCurve, - firstFixingRate: float = None): + first_fixing_rate: float = None): """ Value the floating leg with payments from an index curve and discounting based on a supplied discount curve as of the valuation date supplied. For an existing swap, the user must enter the next fixing @@ -152,70 +152,71 @@ def value(self, self._rates = [] self._payments = [] - self._paymentDfs = [] - self._paymentPVs = [] - self._cumulativePVs = [] + self._payment_dfs = [] + self._payment_pvs = [] + self._cumulative_pvs = [] - dfValue = discount_curve.df(value_dt) + df_value = discount_curve.df(value_dt) leg_pv = 0.0 - numPayments = len(self._payment_dts) - firstPayment = False + num_payments = len(self._payment_dts) + first_payment = False if not len(self._notional_array): - self._notional_array = [self._notional] * numPayments + self._notional_array = [self._notional] * num_payments index_basis = index_curve._dc_type index_day_counter = DayCount(index_basis) - for iPmnt in range(0, numPayments): + for i_pmnt in range(0, num_payments): - pmntDate = self._payment_dts[iPmnt] + pmnt_dt = self._payment_dts[i_pmnt] - if pmntDate > value_dt: + if pmnt_dt > value_dt: - startAccruedDt = self._startAccruedDates[iPmnt] - endAccruedDt = self._endAccruedDates[iPmnt] - pay_alpha = self._year_fracs[iPmnt] + start_accrued_dt = self._start_accrued_dts[i_pmnt] + end_accrued_dt = self._end_accrued_dts[i_pmnt] + pay_alpha = self._year_fracs[i_pmnt] - (index_alpha, num, _) = index_day_counter.year_frac(startAccruedDt, - endAccruedDt) + (index_alpha, num, _) = index_day_counter.year_frac(start_accrued_dt, + end_accrued_dt) - if firstPayment is False and firstFixingRate is not None: + if first_payment is False and first_fixing_rate is not None: - fwd_rate = firstFixingRate - firstPayment = True + fwd_rate = first_fixing_rate + first_payment = True else: - df_start = index_curve.df(startAccruedDt) - dfEnd = index_curve.df(endAccruedDt) - fwd_rate = (df_start / dfEnd - 1.0) / index_alpha + df_start = index_curve.df(start_accrued_dt) + df_end = index_curve.df(end_accrued_dt) + fwd_rate = (df_start / df_end - 1.0) / index_alpha - pmntAmount = (fwd_rate + self._spread) * pay_alpha * self._notional_array[iPmnt] + pmntAmount = (fwd_rate + self._spread) * \ + pay_alpha * self._notional_array[i_pmnt] - dfPmnt = discount_curve.df(pmntDate) / dfValue - pmntPV = pmntAmount * dfPmnt - leg_pv += pmntPV + df_pmnt = discount_curve.df(pmnt_dt) / df_value + pmnt_pv = pmntAmount * df_pmnt + leg_pv += pmnt_pv self._rates.append(fwd_rate) self._payments.append(pmntAmount) - self._paymentDfs.append(dfPmnt) - self._paymentPVs.append(pmntPV) - self._cumulativePVs.append(leg_pv) + self._payment_dfs.append(df_pmnt) + self._payment_pvs.append(pmnt_pv) + self._cumulative_pvs.append(leg_pv) else: self._rates.append(0.0) self._payments.append(0.0) - self._paymentDfs.append(0.0) - self._paymentPVs.append(0.0) - self._cumulativePVs.append(leg_pv) + self._payment_dfs.append(0.0) + self._payment_pvs.append(0.0) + self._cumulative_pvs.append(leg_pv) - if pmntDate > value_dt: - paymentPV = self._principal * dfPmnt * self._notional_array[-1] - self._paymentPVs[-1] += paymentPV - leg_pv += paymentPV - self._cumulativePVs[-1] = leg_pv + if pmnt_dt > value_dt: + payment_pv = self._principal * df_pmnt * self._notional_array[-1] + self._payment_pvs[-1] += payment_pv + leg_pv += payment_pv + self._cumulative_pvs[-1] = leg_pv if self._leg_type == SwapTypes.PAY: leg_pv = leg_pv * (-1.0) @@ -239,7 +240,8 @@ def print_payments(self): print("Payments Dates not calculated.") return - header = [ "PAY_NUM", "PAY_dt", "ACCR_START", "ACCR_END", "DAYS", "YEARFRAC"] + header = ["PAY_NUM", "PAY_dt", "ACCR_START", + "ACCR_END", "DAYS", "YEARFRAC"] rows = [] num_flows = len(self._payment_dts) @@ -247,10 +249,10 @@ def print_payments(self): rows.append([ i_flow + 1, self._payment_dts[i_flow], - self._startAccruedDates[i_flow], - self._endAccruedDates[i_flow], + self._start_accrued_dts[i_flow], + self._end_accrued_dts[i_flow], self._accrued_days[i_flow], - round(self._year_fracs[i_flow],4), + round(self._year_fracs[i_flow], 4), ]) table = format_table(header, rows) @@ -274,7 +276,7 @@ def print_valuation(self): print("Payments not calculated.") return - header = [ "PAY_NUM", "PAY_dt", "NOTIONAL", + header = ["PAY_NUM", "PAY_dt", "NOTIONAL", "IBOR", "PMNT", "DF", "PV", "CUM_PV"] rows = [] @@ -286,9 +288,9 @@ def print_valuation(self): round(self._notional_array[i_flow], 0), round(self._rates[i_flow] * 100.0, 4), round(self._payments[i_flow], 2), - round(self._paymentDfs[i_flow], 4), - round(self._paymentPVs[i_flow], 2), - round(self._cumulativePVs[i_flow], 2), + round(self._payment_dfs[i_flow], 4), + round(self._payment_pvs[i_flow], 2), + round(self._cumulative_pvs[i_flow], 2), ]) table = format_table(header, rows) diff --git a/financepy/products/rates/swaps/FinFixedFixedXCcySwap.py b/financepy/products/rates/swaps/FinFixedFixedXCcySwap.py index 9d8e7372..8ea55cb0 100644 --- a/financepy/products/rates/swaps/FinFixedFixedXCcySwap.py +++ b/financepy/products/rates/swaps/FinFixedFixedXCcySwap.py @@ -4,7 +4,7 @@ from ...utils.FinError import FinError from ...utils.Date import Date -from ...utils.FinGlobalVariables import gSmall +from ...utils.FinGlobalVariables import g_small from ...utils.FinDayCount import FinDayCount, DayCountTypes from ...utils.FinFrequency import FrequencyTypes, FinFrequency from ...utils.FinCalendar import CalendarTypes, DateGenRuleTypes @@ -95,7 +95,7 @@ def __init__(self, # Need to know latest payment date for bootstrap - DO I NEED THIS ??! self._last_payment_dt = self._maturity_dt if self._adjusted_fixed_dts[-1] > self._last_payment_dt: - self._last_payment_date = self._adjusted_fixed_dts[-1] + self._last_payment_dt = self._adjusted_fixed_dts[-1] if self._adjusted_float_dts[-1] > self._last_payment_dt: self._last_payment_dt = self._adjusted_float_dts[-1] @@ -217,7 +217,7 @@ def swap_rate(self, value_dt, discount_curve): df_T = discount_curve.df(self._maturity_dt) - if abs(pv01) < gSmall: + if abs(pv01) < g_small: raise FinError("PV01 is zero. Cannot compute swap rate.") cpn = (df_0 - df_T) / pv01 diff --git a/financepy/products/rates/swaps/FinFixedIborXCcySwap.py b/financepy/products/rates/swaps/FinFixedIborXCcySwap.py index 41646690..10950084 100644 --- a/financepy/products/rates/swaps/FinFixedIborXCcySwap.py +++ b/financepy/products/rates/swaps/FinFixedIborXCcySwap.py @@ -4,7 +4,7 @@ from ...utils.FinError import FinError from ...utils.Date import Date -from ...utils.FinGlobalVariables import gSmall +from ...utils.FinGlobalVariables import g_small from ...utils.FinDayCount import FinDayCount, DayCountTypes from ...utils.FinFrequency import FrequencyTypes, FinFrequency from ...utils.FinCalendar import CalendarTypes, DateGenRuleTypes @@ -12,7 +12,7 @@ from ...utils.FinSchedule import FinSchedule from ...utils.FinHelperFunctions import label_to_string, check_argument_types from ...utils.FinMath import ONE_MILLION -from ...utils.FinGlobalTypes import SwapTypes +from ...utils.FinGlobalTypes import swap_types ########################################################################## @@ -31,7 +31,7 @@ class FinFixedIborXCcySwap: def __init__(self, effective_dt: Date, # Date interest starts to accrue term_dt_or_tenor: (Date, str), # Date contract ends - fixed_leg_type: SwapTypes, + fixed_leg_type: swap_types, fixed_coupon: float, # Fixed coupon (annualised) fixed_freq_type: FrequencyTypes, fixed_dc_type: DayCountTypes, @@ -53,7 +53,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -61,7 +61,7 @@ def __init__(self, calendar = Calendar(cal_type) self._maturity_dt = calendar.adjust(self._termination_dt, - bd_type) + bd_type) if effective_dt > self._maturity_dt: raise FinError("Start date after maturity date") @@ -102,16 +102,16 @@ def __init__(self, # NOT TO BE PRINTED self._floatYearFracs = [] - self._floatFlows = [] - self._floatFlowPVs = [] - self._floatDfs = [] + self._float_flows = [] + self._float_flow_pvs = [] + self._float_dfs = [] self._fixedYearFracs = [] - self._fixedFlows = [] + self._fixed_flows = [] self._fixedDfs = [] self._fixedFlowPVs = [] - self._firstFixingRate = None + self._first_fixing_rate = None self._value_dt = None self._fixedStartIndex = None @@ -140,7 +140,7 @@ def value(self, value = fixed_leg_value - float_leg_value - if self._fixed_leg_type == SwapTypes.PAY: + if self._fixed_leg_type == swap_types.PAY: value = value * (-1.0) return value @@ -217,7 +217,7 @@ def swap_rate(self, value_dt, discount_curve): dfT = discount_curve.df(self._maturity_dt) - if abs(pv01) < gSmall: + if abs(pv01) < g_small: raise FinError("PV01 is zero. Cannot compute swap rate.") cpn = (df0 - dfT) / pv01 @@ -230,7 +230,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): self._value_dt = value_dt self._fixedYearFracs = [] - self._fixedFlows = [] + self._fixed_flows = [] self._fixedDfs = [] self._fixedFlowPVs = [] self._fixed_total_pv = [] @@ -251,7 +251,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): self._fixedStartIndex = start_index """ Now PV fixed leg flows. """ - self._dfValuationDate = discount_curve.df(value_dt) + self._df_value_dt = discount_curve.df(value_dt) pv = 0.0 prev_dt = self._adjusted_fixed_dts[start_index - 1] @@ -261,14 +261,14 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): for next_dt in self._adjusted_fixed_dts[start_index:]: alpha = day_counter.year_frac(prev_dt, next_dt)[0] - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt flow = self._fixed_coupon * alpha * self._notional flowPV = flow * df_discount pv += flowPV prev_dt = next_dt self._fixedYearFracs.append(alpha) - self._fixedFlows.append(flow) + self._fixed_flows.append(flow) self._fixedDfs.append(df_discount) self._fixedFlowPVs.append(flow * df_discount) self._fixed_total_pv.append(pv) @@ -276,7 +276,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): flow = principal * self._notional pv = pv + flow * df_discount self._fixedFlowPVs[-1] += flow * df_discount - self._fixedFlows[-1] += flow + self._fixed_flows[-1] += flow self._fixed_total_pv[-1] = pv return pv @@ -285,7 +285,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): def _calc_fixed_leg_flows(self): self._fixedYearFracs = [] - self._fixedFlows = [] + self._fixed_flows = [] day_counter = FinDayCount(self._fixed_dc_type) @@ -297,7 +297,7 @@ def _calc_fixed_leg_flows(self): flow = self._fixed_coupon * alpha * self._notional prev_dt = next_dt self._fixedYearFracs.append(alpha) - self._fixedFlows.append(flow) + self._fixed_flows.append(flow) ########################################################################## @@ -327,15 +327,15 @@ def cash_settled_pv01(self, start_index = 1 """ Now PV fixed leg flows. """ - flatPV01 = 0.0 + flat_pv01 = 0.0 df = 1.0 alpha = 1.0 / m for _ in self._adjusted_fixed_dts[start_index:]: df = df / (1.0 + alpha * flatSwapRate) - flatPV01 += df * alpha + flat_pv01 += df * alpha - return flatPV01 + return flat_pv01 ########################################################################## @@ -343,7 +343,7 @@ def float_leg_value(self, value_dt, # This should be the settlement date discount_curve, index_curve, - firstFixingRate=None, + first_fixing_rate=None, principal=0.0): """ Value the floating leg with payments from an index curve and discounting based on a supplied discount curve. The valuation date can @@ -354,12 +354,12 @@ def float_leg_value(self, self._value_dt = value_dt self._floatYearFracs = [] - self._floatFlows = [] + self._float_flows = [] self._floatRates = [] - self._floatDfs = [] - self._floatFlowPVs = [] + self._float_dfs = [] + self._float_flow_pvs = [] self._floatTotalPV = [] - self._firstFixingRate = firstFixingRate + self._first_fixing_rate = first_fixing_rate basis = FinDayCount(self._float_dc_type) @@ -377,7 +377,7 @@ def float_leg_value(self, self._floatStartIndex = start_index # Forward price to settlement date (if valuation is settlement date) - self._dfValuationDate = discount_curve.df(value_dt) + self._df_value_dt = discount_curve.df(value_dt) """ The first floating payment is usually already fixed so is not implied by the index curve. """ @@ -390,24 +390,24 @@ def float_leg_value(self, floatRate = 0.0 - if self._firstFixingRate is None: + if self._first_fixing_rate is None: fwd_rate = (df1_index / df2_index - 1.0) / alpha flow = (fwd_rate + self._float_spread) * alpha * self._notional floatRate = fwd_rate else: - flow = self._firstFixingRate * alpha * self._notional - floatRate = self._firstFixingRate + flow = self._first_fixing_rate * alpha * self._notional + floatRate = self._first_fixing_rate # All discounting is done forward to the valuation date - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt pv = flow * df_discount self._floatYearFracs.append(alpha) - self._floatFlows.append(flow) + self._float_flows.append(flow) self._floatRates.append(floatRate) - self._floatDfs.append(df_discount) - self._floatFlowPVs.append(flow * df_discount) + self._float_dfs.append(df_discount) + self._float_flow_pvs.append(flow * df_discount) self._floatTotalPV.append(pv) prev_dt = next_dt @@ -421,23 +421,23 @@ def float_leg_value(self, flow = (fwd_rate + self._float_spread) * alpha * self._notional # All discounting is done forward to the valuation date - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt pv += flow * df_discount df1_index = df2_index prev_dt = next_dt - self._floatFlows.append(flow) + self._float_flows.append(flow) self._floatYearFracs.append(alpha) self._floatRates.append(fwd_rate) - self._floatDfs.append(df_discount) - self._floatFlowPVs.append(flow * df_discount) + self._float_dfs.append(df_discount) + self._float_flow_pvs.append(flow * df_discount) self._floatTotalPV.append(pv) flow = principal * self._notional pv = pv + flow * df_discount - self._floatFlows[-1] += flow - self._floatFlowPVs[-1] += flow * df_discount + self._float_flows[-1] += flow + self._float_flow_pvs[-1] += flow * df_discount self._floatTotalPV[-1] = pv return pv @@ -456,7 +456,7 @@ def print_fixed_leg_pv(self): print("FIXED LEG DAY COUNT:", str(self._fixed_dc_type)) print("VALUATION DATE", self._value_dt) - if len(self._fixedFlows) == 0: + if len(self._fixed_flows) == 0: print("Fixed Flows not calculated.") return @@ -483,7 +483,7 @@ def print_fixed_leg_pv(self): print("%15s %10.7f %12.2f %12.8f %12.2f %12.2f" % (payment_dt, self._fixedYearFracs[i_flow], - self._fixedFlows[i_flow], + self._fixed_flows[i_flow], self._fixedDfs[i_flow], self._fixedFlowPVs[i_flow], self._fixed_total_pv[i_flow])) @@ -502,7 +502,7 @@ def print_fixed_leg_flows(self): print("FIXED LEG FREQUENCY:", str(self._fixed_freq_type)) print("FIXED LEG DAY COUNT:", str(self._fixed_dc_type)) - if len(self._fixedFlows) == 0: + if len(self._fixed_flows) == 0: print("Fixed Flows not calculated.") return @@ -516,7 +516,7 @@ def print_fixed_leg_flows(self): print("%15s %12.8f %12.2f" % (payment_dt, self._fixedYearFracs[i_flow], - self._fixedFlows[i_flow])) + self._fixed_flows[i_flow])) i_flow += 1 @@ -534,11 +534,11 @@ def print_float_leg_pv(self): print("FLOAT LEG DAY COUNT:", str(self._float_dc_type)) print("VALUATION DATE", self._value_dt) - if len(self._floatFlows) == 0: + if len(self._float_flows) == 0: print("Floating Flows not calculated.") return - if self._firstFixingRate is None: + if self._first_fixing_rate is None: print(" *** FIRST FLOATING RATE PAYMENT IS IMPLIED ***") header = "PAYMENT_dt YEAR_FRAC RATE(%) FLOW DF" @@ -564,9 +564,9 @@ def print_float_leg_pv(self): (payment_dt, self._floatYearFracs[i_flow], self._floatRates[i_flow]*100.0, - self._floatFlows[i_flow], - self._floatDfs[i_flow], - self._floatFlowPVs[i_flow], + self._float_flows[i_flow], + self._float_dfs[i_flow], + self._float_flow_pvs[i_flow], self._floatTotalPV[i_flow])) i_flow += 1 @@ -579,7 +579,7 @@ def __repr__(self): s += label_to_string("TERMINATION DATE", self._termination_dt) s += label_to_string("MATURITY DATE", self._maturity_dt) s += label_to_string("NOTIONAL", self._notional) - s += label_to_string("SWAP TYPE", self._swapType) + s += label_to_string("SWAP TYPE", self._swap_type) s += label_to_string("FIXED COUPON", self._fixed_coupon) s += label_to_string("FLOAT SPREAD", self._float_spread) s += label_to_string("FIXED FREQUENCY", self._fixed_freq_type) diff --git a/financepy/products/rates/swaps/FinIborIborSwap.py b/financepy/products/rates/swaps/FinIborIborSwap.py index 4eb58a06..f38d8030 100644 --- a/financepy/products/rates/swaps/FinIborIborSwap.py +++ b/financepy/products/rates/swaps/FinIborIborSwap.py @@ -49,7 +49,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -57,7 +57,7 @@ def __init__(self, calendar = CalendarTypes(cal_type) self._maturity_dt = calendar.adjust(self._termination_dt, - bd_type) + bd_type) if effective_dt > self._maturity_dt: raise FinError("Start date after maturity date") @@ -81,14 +81,14 @@ def __init__(self, self._payFloatYearFracs = [] self._recFloatYearFracs = [] - self._payFloatFlows = [] - self._recFloatFlows = [] + self._payfloat_flows = [] + self._recfloat_flows = [] - self._payFloatFlowPVs = [] - self._recFloatFlowPVs = [] + self._pay_float_flow_pvs = [] + self._recfloat_flow_pvs = [] - self._payFirstFixingRate = None - self._recFirstFixingRate = None + self._payfirst_fixing_rate = None + self._recfirst_fixing_rate = None self._value_dt = None @@ -114,8 +114,8 @@ def value(self, discount_curve, payIndexCurve, recIndexCurve, - payFirstFixingRate=None, - recFirstFixingRate=None, + payfirst_fixing_rate=None, + recfirst_fixing_rate=None, principal=0.0): """ Value the LIBOR basis swap on a value date given a single Ibor discount curve and each of the index discount for the two floating legs @@ -124,13 +124,13 @@ def value(self, payFloatLegValue = self.float_leg_value(value_dt, discount_curve, payIndexCurve, - payFirstFixingRate, + payfirst_fixing_rate, principal) recFloatLegValue = self.float_leg_value(value_dt, discount_curve, recIndexCurve, - recFirstFixingRate, + recfirst_fixing_rate, principal) value = recFloatLegValue - payFloatLegValue @@ -142,7 +142,7 @@ def float_leg_value(self, value_dt, # This should be the settlement date discount_curve, index_curve, - firstFixingRate=None, + first_fixing_rate=None, principal=0.0): """ Value the floating leg with payments from an index curve and discounting based on a supplied discount curve. The valuation date can @@ -153,12 +153,12 @@ def float_leg_value(self, self._value_dt = value_dt self._floatYearFracs = [] - self._floatFlows = [] + self._float_flows = [] self._floatRates = [] self._floatDfs = [] - self._floatFlowPVs = [] + self._float_flow_pvs = [] self._floatTotalPV = [] - self._firstFixingRate = firstFixingRate + self._first_fixing_rate = first_fixing_rate basis = FinDayCount(self._float_dc_type) @@ -176,7 +176,7 @@ def float_leg_value(self, self._floatStartIndex = start_index # Forward price to settlement date (if valuation is settlement date) - self._dfValuationDate = discount_curve.df(value_dt) + self._df_value_dt = discount_curve.df(value_dt) """ The first floating payment is usually already fixed so is not implied by the index curve. """ @@ -189,24 +189,24 @@ def float_leg_value(self, floatRate = 0.0 - if self._firstFixingRate is None: + if self._first_fixing_rate is None: fwd_rate = (df1_index / df2_index - 1.0) / alpha flow = (fwd_rate + self._float_spread) * alpha * self._notional floatRate = fwd_rate else: - flow = self._firstFixingRate * alpha * self._notional - floatRate = self._firstFixingRate + flow = self._first_fixing_rate * alpha * self._notional + floatRate = self._first_fixing_rate # All discounting is done forward to the valuation date - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt pv = flow * df_discount self._floatYearFracs.append(alpha) - self._floatFlows.append(flow) + self._float_flows.append(flow) self._floatRates.append(floatRate) self._floatDfs.append(df_discount) - self._floatFlowPVs.append(flow * df_discount) + self._float_flow_pvs.append(flow * df_discount) self._floatTotalPV.append(pv) prev_dt = next_dt @@ -220,23 +220,23 @@ def float_leg_value(self, flow = (fwd_rate + self._float_spread) * alpha * self._notional # All discounting is done forward to the valuation date - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt pv += flow * df_discount df1_index = df2_index prev_dt = next_dt - self._floatFlows.append(flow) + self._float_flows.append(flow) self._floatYearFracs.append(alpha) self._floatRates.append(fwd_rate) self._floatDfs.append(df_discount) - self._floatFlowPVs.append(flow * df_discount) + self._float_flow_pvs.append(flow * df_discount) self._floatTotalPV.append(pv) flow = principal * self._notional pv = pv + flow * df_discount - self._floatFlows[-1] += flow - self._floatFlowPVs[-1] += flow * df_discount + self._float_flows[-1] += flow + self._float_flow_pvs[-1] += flow * df_discount self._floatTotalPV[-1] = pv return pv @@ -255,11 +255,11 @@ def print_float_leg_pv(self): print("FLOAT LEG DAY COUNT:", str(self._float_dc_type)) print("VALUATION DATE", self._value_dt) - if len(self._floatFlows) == 0: + if len(self._float_flows) == 0: print("Floating Flows not calculated.") return - if self._firstFixingRate is None: + if self._first_fixing_rate is None: print(" *** FIRST FLOATING RATE PAYMENT IS IMPLIED ***") header = "PAYMENT_dt YEAR_FRAC RATE(%) FLOW DF" @@ -285,9 +285,9 @@ def print_float_leg_pv(self): (payment_dt, self._floatYearFracs[i_flow], self._floatRates[i_flow]*100.0, - self._floatFlows[i_flow], + self._float_flows[i_flow], self._floatDfs[i_flow], - self._floatFlowPVs[i_flow], + self._float_flow_pvs[i_flow], self._floatTotalPV[i_flow])) i_flow += 1 @@ -300,7 +300,7 @@ def __repr__(self): s += label_to_string("TERMINATION DATE", self._termination_dt) s += label_to_string("MATURITY DATE", self._maturity_dt) s += label_to_string("NOTIONAL", self._notional) - s += label_to_string("SWAP TYPE", self._swapType) + s += label_to_string("SWAP TYPE", self._swap_type) s += label_to_string("FIXED COUPON", self._fixed_coupon) s += label_to_string("FLOAT SPREAD", self._float_spread) s += label_to_string("FIXED FREQUENCY", self._fixed_freq_type) diff --git a/financepy/products/rates/swaps/FinIborIborXCcySwap.py b/financepy/products/rates/swaps/FinIborIborXCcySwap.py index 4435de8c..1a77dcb3 100644 --- a/financepy/products/rates/swaps/FinIborIborXCcySwap.py +++ b/financepy/products/rates/swaps/FinIborIborXCcySwap.py @@ -4,7 +4,7 @@ from ...utils.FinError import FinError from ...utils.Date import Date -from ...utils.GlobalVariables import gSmall +from ...utils.GlobalVariables import g_small from ...utils.DayCount import FinDayCount, DayCountTypes from ...utils.Frequency import FrequencyTypes, FinFrequency from ...utils.Calendar import CalendarTypes, DateGenRuleTypes @@ -12,7 +12,7 @@ from ...utils.Schedule import Schedule from ...utils.HelperFunctions import label_to_string, check_argument_types from ...utils.Math import ONE_MILLION -from ...utils.GlobalTypes import SwapTypes +from ...utils.GlobalTypes import swap_types ########################################################################## @@ -31,7 +31,7 @@ class FinIborIborXCcySwap: def __init__(self, effective_dt: Date, # Date interest starts to accrue term_dt_or_tenor: (Date, str), # Date contract ends - fixed_leg_type: SwapTypes, + fixed_leg_type: swap_types, fixed_coupon: float, # Fixed coupon (annualised) fixed_freq_type: FrequencyTypes, fixed_dc_type: DayCountTypes, @@ -53,7 +53,7 @@ def __init__(self, check_argument_types(self.__init__, locals()) - if type(term_dt_or_tenor) == Date: + if isinstance(term_dt_or_tenor, Date): self._termination_dt = term_dt_or_tenor else: self._termination_dt = effective_dt.add_tenor( @@ -61,7 +61,7 @@ def __init__(self, calendar = Calendar(cal_type) self._maturity_dt = calendar.adjust(self._termination_dt, - bd_type) + bd_type) if effective_dt > self._maturity_dt: raise FinError("Start date after maturity date") @@ -102,16 +102,16 @@ def __init__(self, # NOT TO BE PRINTED self._float_year_fracs = [] - self._floatFlows = [] - self._floatFlowPVs = [] - self._floatDfs = [] + self._float_flows = [] + self._float_flow_pvs = [] + self._float_dfs = [] self._fixed_year_fracs = [] - self._fixedFlows = [] + self._fixed_flows = [] self._fixedDfs = [] self._fixedFlowPVs = [] - self._firstFixingRate = None + self._first_fixing_rate = None self._value_dt = None self._fixedStartIndex = None @@ -123,7 +123,7 @@ def value(self, value_dt, discount_curve, index_curve, - firstFixingRate=None, + first_fixing_rate=None, principal=0.0): """ Value the interest rate swap on a value date given a single Ibor discount curve. """ @@ -135,12 +135,12 @@ def value(self, float_leg_value = self.float_leg_value(value_dt, discount_curve, index_curve, - firstFixingRate, + first_fixing_rate, principal) value = fixed_leg_value - float_leg_value - if self._fixed_leg_type == SwapTypes.PAY: + if self._fixed_leg_type == swap_types.PAY: value = value * (-1.0) return value @@ -217,7 +217,7 @@ def swap_rate(self, value_dt, discount_curve): dfT = discount_curve.df(self._maturity_dt) - if abs(pv01) < gSmall: + if abs(pv01) < g_small: raise FinError("PV01 is zero. Cannot compute swap rate.") cpn = (df0 - dfT) / pv01 @@ -230,7 +230,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): self._value_dt = value_dt self._fixed_year_fracs = [] - self._fixedFlows = [] + self._fixed_flows = [] self._fixedDfs = [] self._fixedFlowPVs = [] self._fixed_total_pv = [] @@ -251,7 +251,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): self._fixedStartIndex = start_index """ Now PV fixed leg flows. """ - self._dfValuationDate = discount_curve.df(value_dt) + self._df_value_dt = discount_curve.df(value_dt) pv = 0.0 prev_dt = self._adjusted_fixed_dts[start_index - 1] @@ -261,14 +261,14 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): for next_dt in self._adjusted_fixed_dts[start_index:]: alpha = day_counter.year_frac(prev_dt, next_dt)[0] - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt flow = self._fixed_coupon * alpha * self._notional flowPV = flow * df_discount pv += flowPV prev_dt = next_dt self._fixed_year_fracs.append(alpha) - self._fixedFlows.append(flow) + self._fixed_flows.append(flow) self._fixedDfs.append(df_discount) self._fixedFlowPVs.append(flow * df_discount) self._fixed_total_pv.append(pv) @@ -276,7 +276,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): flow = principal * self._notional pv = pv + flow * df_discount self._fixedFlowPVs[-1] += flow * df_discount - self._fixedFlows[-1] += flow + self._fixed_flows[-1] += flow self._fixed_total_pv[-1] = pv return pv @@ -285,7 +285,7 @@ def fixed_leg_value(self, value_dt, discount_curve, principal=0.0): def _calc_fixed_leg_flows(self): self._fixed_year_fracs = [] - self._fixedFlows = [] + self._fixed_flows = [] day_counter = FinDayCount(self._fixed_dc_type) @@ -297,7 +297,7 @@ def _calc_fixed_leg_flows(self): flow = self._fixed_coupon * alpha * self._notional prev_dt = next_dt self._fixed_year_fracs.append(alpha) - self._fixedFlows.append(flow) + self._fixed_flows.append(flow) ########################################################################## @@ -327,15 +327,15 @@ def cash_settled_pv01(self, start_index = 1 """ Now PV fixed leg flows. """ - flatPV01 = 0.0 + flat_pv01 = 0.0 df = 1.0 alpha = 1.0 / m for _ in self._adjusted_fixed_dts[start_index:]: df = df / (1.0 + alpha * flatSwapRate) - flatPV01 += df * alpha + flat_pv01 += df * alpha - return flatPV01 + return flat_pv01 ########################################################################## @@ -343,7 +343,7 @@ def float_leg_value(self, value_dt, # This should be the settlement date discount_curve, index_curve, - firstFixingRate=None, + first_fixing_rate=None, principal=0.0): """ Value the floating leg with payments from an index curve and discounting based on a supplied discount curve. The valuation date can @@ -354,12 +354,12 @@ def float_leg_value(self, self._value_dt = value_dt self._float_year_fracs = [] - self._floatFlows = [] + self._float_flows = [] self._floatRates = [] - self._floatDfs = [] - self._floatFlowPVs = [] + self._float_dfs = [] + self.float_flow_pvs = [] self._floatTotalPV = [] - self._firstFixingRate = firstFixingRate + self._first_fixing_rate = first_fixing_rate basis = FinDayCount(self._float_dc_type) @@ -377,7 +377,7 @@ def float_leg_value(self, self._floatStartIndex = start_index # Forward price to settlement date (if valuation is settlement date) - self._dfValuationDate = discount_curve.df(value_dt) + self._df_value_dt = discount_curve.df(value_dt) """ The first floating payment is usually already fixed so is not implied by the index curve. """ @@ -390,24 +390,24 @@ def float_leg_value(self, floatRate = 0.0 - if self._firstFixingRate is None: + if self._first_fixing_rate is None: fwd_rate = (df1_index / df2_index - 1.0) / alpha flow = (fwd_rate + self._float_spread) * alpha * self._notional floatRate = fwd_rate else: - flow = self._firstFixingRate * alpha * self._notional - floatRate = self._firstFixingRate + flow = self._first_fixing_rate * alpha * self._notional + floatRate = self._first_fixing_rate # All discounting is done forward to the valuation date - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt pv = flow * df_discount self._float_year_fracs.append(alpha) - self._floatFlows.append(flow) + self._float_flows.append(flow) self._floatRates.append(floatRate) - self._floatDfs.append(df_discount) - self._floatFlowPVs.append(flow * df_discount) + self._float_dfs.append(df_discount) + self._float_flow_pvs.append(flow * df_discount) self._floatTotalPV.append(pv) prev_dt = next_dt @@ -421,23 +421,23 @@ def float_leg_value(self, flow = (fwd_rate + self._float_spread) * alpha * self._notional # All discounting is done forward to the valuation date - df_discount = discount_curve.df(next_dt) / self._dfValuationDate + df_discount = discount_curve.df(next_dt) / self._df_value_dt pv += flow * df_discount df1_index = df2_index prev_dt = next_dt - self._floatFlows.append(flow) + self._float_flows.append(flow) self._float_year_fracs.append(alpha) self._floatRates.append(fwd_rate) - self._floatDfs.append(df_discount) - self._floatFlowPVs.append(flow * df_discount) + self._float_dfs.append(df_discount) + self.float_flow_pvs.append(flow * df_discount) self._floatTotalPV.append(pv) flow = principal * self._notional pv = pv + flow * df_discount - self._floatFlows[-1] += flow - self._floatFlowPVs[-1] += flow * df_discount + self._float_flows[-1] += flow + self.float_flow_pvs[-1] += flow * df_discount self._floatTotalPV[-1] = pv return pv @@ -456,7 +456,7 @@ def print_fixed_leg_pv(self): print("FIXED LEG DAY COUNT:", str(self._fixed_dc_type)) print("VALUATION DATE", self._value_dt) - if len(self._fixedFlows) == 0: + if len(self._fixed_flows) == 0: print("Fixed Flows not calculated.") return @@ -483,7 +483,7 @@ def print_fixed_leg_pv(self): print("%15s %10.7f %12.2f %12.8f %12.2f %12.2f" % (payment_dt, self._fixed_year_fracs[i_flow], - self._fixedFlows[i_flow], + self._fixed_flows[i_flow], self._fixedDfs[i_flow], self._fixedFlowPVs[i_flow], self._fixed_total_pv[i_flow])) @@ -502,7 +502,7 @@ def print_fixed_leg_flows(self): print("FIXED LEG FREQUENCY:", str(self._fixed_freq_type)) print("FIXED LEG DAY COUNT:", str(self._fixed_dc_type)) - if len(self._fixedFlows) == 0: + if len(self._fixed_flows) == 0: print("Fixed Flows not calculated.") return @@ -516,7 +516,7 @@ def print_fixed_leg_flows(self): print("%15s %12.8f %12.2f" % (payment_dt, self._fixed_year_fracs[i_flow], - self._fixedFlows[i_flow])) + self._fixed_flows[i_flow])) i_flow += 1 @@ -534,11 +534,11 @@ def print_float_leg_pv(self): print("FLOAT LEG DAY COUNT:", str(self._float_dc_type)) print("VALUATION DATE", self._value_dt) - if len(self._floatFlows) == 0: + if len(self._float_flows) == 0: print("Floating Flows not calculated.") return - if self._firstFixingRate is None: + if self._first_fixing_rate is None: print(" *** FIRST FLOATING RATE PAYMENT IS IMPLIED ***") header = "PAYMENT_dt YEAR_FRAC RATE(%) FLOW DF" @@ -564,9 +564,9 @@ def print_float_leg_pv(self): (payment_dt, self._float_year_fracs[i_flow], self._floatRates[i_flow]*100.0, - self._floatFlows[i_flow], - self._floatDfs[i_flow], - self._floatFlowPVs[i_flow], + self._float_flows[i_flow], + self._float_dfs[i_flow], + self.float_flow_pvs[i_flow], self._floatTotalPV[i_flow])) i_flow += 1 @@ -579,7 +579,7 @@ def __repr__(self): s += label_to_string("TERMINATION DATE", self._termination_dt) s += label_to_string("MATURITY DATE", self._maturity_dt) s += label_to_string("NOTIONAL", self._notional) - s += label_to_string("SWAP TYPE", self._swapType) + s += label_to_string("SWAP TYPE", self._swap_type) s += label_to_string("FIXED COUPON", self._fixed_coupon) s += label_to_string("FLOAT SPREAD", self._float_spread) s += label_to_string("FIXED FREQUENCY", self._fixed_freq_type) diff --git a/financepy/utils/calendar.py b/financepy/utils/calendar.py index 2ad09685..624b4b86 100644 --- a/financepy/utils/calendar.py +++ b/financepy/utils/calendar.py @@ -183,37 +183,37 @@ def adjust(self, def add_business_days(self, start_dt: Date, - numDays: int): - """ Returns a new date that is numDays business days after Date. + num_days: int): + """ Returns a new date that is num_days business days after Date. All holidays in the chosen calendar are assumed not business days. """ # TODO: REMOVE DATETIME DEPENDENCE HERE ??? - if isinstance(numDays, int) is False: + if isinstance(num_days, int) is False: raise FinError("Num days must be an integer") dt = datetime.date(start_dt._y, start_dt._m, start_dt._d) d = dt.day m = dt.month y = dt.year - newDt = Date(d, m, y) + new_dt = Date(d, m, y) s = +1 - if numDays < 0: - numDays = -1 * numDays + if num_days < 0: + num_days = -1 * num_days s = -1 - while numDays > 0: + while num_days > 0: dt = dt + s * datetime.timedelta(days=1) d = dt.day m = dt.month y = dt.year - newDt = Date(d, m, y) + new_dt = Date(d, m, y) - if self.is_business_day(newDt) is True: - numDays -= 1 + if self.is_business_day(new_dt) is True: + num_days -= 1 - return newDt + return new_dt ############################################################################### @@ -1064,15 +1064,15 @@ def get_holiday_list(self, year: float): calendar. Useful for diagnostics. """ start_dt = Date(1, 1, year) end_dt = Date(1, 1, year + 1) - holidayList = [] + holiday_list = [] while start_dt < end_dt: if self.is_business_day(start_dt) is False and \ start_dt.is_weekend() is False: - holidayList.append(start_dt.__str__()) + holiday_list.append(start_dt.__str__()) start_dt = start_dt.add_days(1) - return holidayList + return holiday_list ############################################################################### @@ -1085,9 +1085,9 @@ def easter_monday(self, raise FinError( "Unable to determine Easter monday in year " + str(year)) - emDays = easterMondayDay[year - 1901] + em_days = easterMondayDay[year - 1901] start_dt = Date(1, 1, year) - em = start_dt.add_days(emDays-1) + em = start_dt.add_days(em_days-1) return em ############################################################################### diff --git a/financepy/utils/date.py b/financepy/utils/date.py index 6eff38d4..f0b00b49 100644 --- a/financepy/utils/date.py +++ b/financepy/utils/date.py @@ -4,6 +4,7 @@ from collections.abc import Iterable from functools import partial +from enum import Enum from numba import njit import numpy as np @@ -15,8 +16,6 @@ ############################################################################### -from enum import Enum - class DateFormatTypes(Enum): BLOOMBERG = 1 @@ -105,7 +104,7 @@ def parse_dt(date_str, date_format): ############################################################################### -g_date_counter_list = None +g_dt_counter_list = None g_start_year = 1900 g_end_year = 2100 @@ -121,11 +120,11 @@ def calculate_list(): day_counter = 0 max_days = 0 - global g_date_counter_list + global g_dt_counter_list global g_start_year global g_end_year - g_date_counter_list = [] + g_dt_counter_list = [] idx = -1 # the first element will be idx=0 @@ -149,12 +148,12 @@ def calculate_list(): idx += 1 day_counter += 1 if yy >= g_start_year: - g_date_counter_list.append(day_counter) + g_dt_counter_list.append(day_counter) for _ in range(max_days, 31): idx += 1 if yy >= g_start_year: - g_date_counter_list.append(-999) + g_dt_counter_list.append(-999) ############################################################################### # The index in these functions is not the Excel date index used as the @@ -240,7 +239,7 @@ def __init__(self, d, m, y, hh=0, mm=0, ss=0): raise FinError( "Date arguments must now be in the order Date(dd, mm, yyyy)") - if g_date_counter_list is None: + if g_dt_counter_list is None: calculate_list() if y < 1900: @@ -362,7 +361,7 @@ def _refresh(self): """ Update internal representation of date as number of days since the 1st Jan 1900. This is same as Excel convention. """ idx = date_index(self._d, self._m, self._y) - days_since_first_jan_1900 = g_date_counter_list[idx] + days_since_first_jan_1900 = g_dt_counter_list[idx] wd = weekday(days_since_first_jan_1900) self._excel_dt = days_since_first_jan_1900 self._weekday = wd @@ -493,7 +492,7 @@ def add_days(self, while num_days != 0: idx += step - if g_date_counter_list[idx] > 0: + if g_dt_counter_list[idx] > 0: num_days -= step (d, m, y) = date_from_index(idx) @@ -704,8 +703,8 @@ def next_cds_date(self, elif m == 1 or m == 2 or m == 3: m_cds = 3 - cds_date = Date(d_cds, m_cds, y_cds) - return cds_date + cds_dt = Date(d_cds, m_cds, y_cds) + return cds_dt ########################################################################## @@ -723,8 +722,8 @@ def third_wednesday_of_month(self, d_end = 21 for d in range(d_start, d_end+1): - imm_date = Date(d, m, y) - if imm_date.weekday() == self.WED: + imm_dt = Date(d, m, y) + if imm_dt.weekday() == self.WED: return d # Should never reach this line but just to be defensive @@ -764,8 +763,8 @@ def next_imm_date(self): d_imm = self.third_wednesday_of_month(m_imm, y_imm) - imm_date = Date(d_imm, m_imm, y_imm) - return imm_date + imm_dt = Date(d_imm, m_imm, y_imm) + return imm_dt ########################################################################### @@ -791,7 +790,7 @@ def add_tenor(self, else: raise FinError("Tenor must be a string e.g. '5Y'") - new_dates = [] + new_dts = [] for tenor_str in tenor: @@ -825,34 +824,34 @@ def add_tenor(self, else: raise FinError("Unknown tenor type in " + tenor) - new_date = Date(self._d, self._m, self._y) + new_dt = Date(self._d, self._m, self._y) if period_type == DAYS: for _ in range(0, abs(num_periods)): - new_date = new_date.add_days(math.copysign(1, num_periods)) + new_dt = new_dt.add_days(math.copysign(1, num_periods)) elif period_type == WEEKS: for _ in range(0, abs(num_periods)): - new_date = new_date.add_days(math.copysign(7, num_periods)) + new_dt = new_dt.add_days(math.copysign(7, num_periods)) elif period_type == MONTHS: for _ in range(0, abs(num_periods)): - new_date = new_date.add_months(math.copysign(1, num_periods)) + new_dt = new_dt.add_months(math.copysign(1, num_periods)) # in case we landed on a 28th Feb and lost the month day we add this logic - y = new_date.y() - m = new_date.m() - d = min(self.d(), new_date.eom()._d) - new_date = Date(d, m, y) + y = new_dt.y() + m = new_dt.m() + d = min(self.d(), new_dt.eom()._d) + new_dt = Date(d, m, y) elif period_type == YEARS: for _ in range(0, abs(num_periods)): - new_date = new_date.add_months(math.copysign(12, num_periods)) + new_dt = new_dt.add_months(math.copysign(12, num_periods)) - new_dates.append(new_date) + new_dts.append(new_dt) if list_flag is True: - return new_dates + return new_dts else: - return new_dates[0] + return new_dts[0] ########################################################################### @@ -1028,8 +1027,8 @@ def from_datetime(dt: Date): """ Construct a Date from a datetime as this is often needed if we receive inputs from other Python objects such as Pandas dataframes. """ - fin_date = Date(dt.day, dt.month, dt.year) - return fin_date + fin_dt = Date(dt.day, dt.month, dt.year) + return fin_dt ############################################################################### diff --git a/financepy/utils/global_types.py b/financepy/utils/global_types.py index 5a771764..8d4720e7 100644 --- a/financepy/utils/global_types.py +++ b/financepy/utils/global_types.py @@ -82,15 +82,15 @@ class FinSolverTypes(Enum): ############################################################################### class TouchOptionTypes(Enum): - DOWN_AND_IN_CASH_AT_HIT = 1 # S0>H pays $1 at hit time from above - UP_AND_IN_CASH_AT_HIT = 2 # S0H pays $1 at T if hit from below - UP_AND_IN_CASH_AT_EXPIRY = 4 # S0H pays $1 at T if S>H for all tH pays H at hit time from above - UP_AND_IN_ASSET_AT_HIT = 8 # S0>H pays H at hit time from below - DOWN_AND_IN_ASSET_AT_EXPIRY = 9 # S0>H pays S(T) at T if SH for t < T - DOWN_AND_OUT_ASSET_OR_NOTHING = 11 # S0>H pays S(T) at T if S>H for t < T - UP_AND_OUT_ASSET_OR_NOTHING = 12 # S0H pays $1 at hit time from above + UP_AND_IN_CASH_AT_HIT = 2 # s0H pays $1 at T if hit from below + UP_AND_IN_CASH_AT_EXPIRY = 4 # s0H pays $1 at T if S>H for all tH pays H at hit time from above + UP_AND_IN_ASSET_AT_HIT = 8 # s0>H pays H at hit time from below + DOWN_AND_IN_ASSET_AT_EXPIRY = 9 # s0>H pays S(T) at T if SH for t < T + DOWN_AND_OUT_ASSET_OR_NOTHING = 11 # s0>H pays S(T) at T if S>H for t < T + UP_AND_OUT_ASSET_OR_NOTHING = 12 # s0 gSmall: + if grid_flows[i_grid] > g_small: cpn_times = np.append(cpn_times, cpn_time) cpn_flows = np.append(cpn_flows, cpn_flow) diff --git a/financepy/utils/math.py b/financepy/utils/math.py index 2975976d..bd694f70 100644 --- a/financepy/utils/math.py +++ b/financepy/utils/math.py @@ -9,7 +9,7 @@ from .error import FinError PI = 3.14159265358979323846 -INVROOT2PI = 0.3989422804014327 +inv_root_two_pi = 0.3989422804014327 ONE_MILLION = 1000000 TEN_MILLION = 10000000 @@ -24,9 +24,8 @@ def accrued_interpolator(t_set: float, # Settlement time in years cpn_times: np.ndarray, cpn_amounts: np.ndarray): - """ Fast calculation of accrued interest using an Actual/Actual type of - convention. This does not calculate according to other conventions. """ - + """Fast calculation of accrued interest using an Actual/Actual type of + convention. This does not calculate according to other conventions.""" num_cpns = len(cpn_times) for i in range(1, num_cpns): @@ -125,7 +124,7 @@ def maxaxis(s: np.ndarray): shp = s.shape - maxVector = np.empty(shp[0]) + max_vector = np.empty(shp[0]) for i in range(0, shp[0]): xmax = s[i, 0] @@ -134,9 +133,9 @@ def maxaxis(s: np.ndarray): if x > xmax: xmax = x - maxVector[i] = xmax + max_vector[i] = xmax - return maxVector + return max_vector ############################################################################### @@ -147,7 +146,7 @@ def minaxis(s: np.ndarray): 2D Numpy Array """ shp = s.shape - minVector = np.empty(shp[0]) + min_vector = np.empty(shp[0]) for i in range(0, shp[0]): xmin = s[i, 0] @@ -156,9 +155,9 @@ def minaxis(s: np.ndarray): if x < xmin: xmin = x - minVector[i] = xmin + min_vector[i] = xmin - return minVector + return min_vector ############################################################################### @@ -220,8 +219,8 @@ def pair_gcd(v1: float, v2 = v1 - factor * v2 v1 = temp - pairGCD = abs(v1) - return pairGCD + pair_gcd = abs(v1) + return pair_gcd ############################################################################### @@ -231,8 +230,8 @@ def nprime(x: float): """Calculate the first derivative of the Cumulative Normal CDF which is simply the PDF of the Normal Distribution """ - InvRoot2Pi = 0.3989422804014327 - return np.exp(-x * x / 2.0) * InvRoot2Pi + inv_root_two_pi = 0.3989422804014327 + return np.exp(-x * x / 2.0) * inv_root_two_pi ############################################################################### @@ -267,7 +266,7 @@ def frange(start: int, def normpdf(x: float): """ Calculate the probability density function for a Gaussian (Normal) function at value x""" - return np.exp(-x * x / 2.0) * INVROOT2PI + return np.exp(-x * x / 2.0) * inv_root_two_pi ############################################################################### @@ -292,7 +291,7 @@ def N(x): if x >= 0.0: c = (a1 * k + a2 * k2 + a3 * k3 + a4 * k4 + a5 * k5) - phi = 1.0 - c * np.exp(-x*x/2.0) * INVROOT2PI + phi = 1.0 - c * np.exp(-x*x/2.0) * inv_root_two_pi else: phi = 1.0 - N(-x) @@ -338,7 +337,7 @@ def normcdf_integrate(x: float): x = x + dx fx = np.exp(-x * x / 2.0) integral += fx / 2.0 - integral *= INVROOT2PI * dx + integral *= inv_root_two_pi * dx return integral ############################################################################### @@ -527,7 +526,7 @@ def norminvcdf(p): q = np.sqrt(-2.0 * np.log(p)) inverse_cdf = (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q - + 1.0) + + 1.0) elif p <= p_high: # Rational approximation for lower region q = p - 0.5 @@ -538,7 +537,7 @@ def norminvcdf(p): # Rational approximation for upper region q = np.sqrt(-2.0 * np.log(1 - p)) inverse_cdf = -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) - * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1.0) + * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1.0) return inverse_cdf diff --git a/financepy/utils/solver_1d.py b/financepy/utils/solver_1d.py index 3b2125e2..36011e3f 100644 --- a/financepy/utils/solver_1d.py +++ b/financepy/utils/solver_1d.py @@ -28,8 +28,8 @@ @njit(cache=True, fastmath=True) def _results(r): r"""Select from a tuple of(root, funccalls, iterations, flag)""" - x, funcalls, iterations, flag = r - return x # results(x, funcalls, iterations, flag == 0) + x, fun_calls, iterations, flag = r + return x # results(x, fun_calls, iterations, flag == 0) ############################################################################### # DO NOT TOUCH THIS FUNCTION AS IT IS USED IN FX VOL CALIBRATION !!!!!!!!! @@ -86,7 +86,7 @@ def newton_secant(func, x0, args=(), tol=1.48e-8, maxiter=50, disp=True): # Convert to float (don't use float(x0); this works also for complex x0) eps = 1e-4 p0 = 1.0 * x0 - funcalls = 0 + fun_calls = 0 status = _ECONVERR p1 = x0 * (1.0 + eps) @@ -97,9 +97,9 @@ def newton_secant(func, x0, args=(), tol=1.48e-8, maxiter=50, disp=True): p1 = p1 - eps q0 = func(p0, *args) - funcalls += 1 + fun_calls += 1 q1 = func(p1, *args) - funcalls += 1 + fun_calls += 1 if np.abs(q1) < np.abs(q0): p0, p1, q0, q1 = p1, p0, q1, q0 @@ -126,7 +126,7 @@ def newton_secant(func, x0, args=(), tol=1.48e-8, maxiter=50, disp=True): p0, q0 = p1, q1 p1 = p q1 = func(p1, *args) - funcalls += 1 + fun_calls += 1 if disp and status == _ECONVERR: msg = "Failed to converge" @@ -298,18 +298,18 @@ class of similar problems can be solved together. # Convert to float (don't use float(x0); this works also for complex x0) p0 = 1.0 * x0 - funcalls = 0 + fun_calls = 0 if fprime is not None: # Newton-Raphson method for itr in range(maxiter): # first evaluate fval fval = func(p0, args) - funcalls += 1 + fun_calls += 1 # If fval is 0, a root has been found, then terminate if fval == 0: return p0 fder = fprime(p0, args) - funcalls += 1 + fun_calls += 1 # print("==>", itr, p0, fval, fder) @@ -322,7 +322,7 @@ class of similar problems can be solved together. newton_step = fval / fder if fprime2: fder2 = fprime2(p0, args) - funcalls += 1 + fun_calls += 1 # Halley's method: # newton_step /= (1.0 - 0.5 * newton_step * fder2 / fder) # Only do it if denominator stays close enough to 1 @@ -347,9 +347,9 @@ class of similar problems can be solved together. p1 = x0 * (1 + eps) p1 += (eps if p1 >= 0 else -eps) q0 = func(p0, args) - funcalls += 1 + fun_calls += 1 q1 = func(p1, args) - funcalls += 1 + fun_calls += 1 if abs(q1) < abs(q0): p0, p1, q0, q1 = p1, p0, q1, q0 for itr in range(maxiter): @@ -371,7 +371,7 @@ class of similar problems can be solved together. p0, q0 = p1, q1 p1 = p q1 = func(p1, *args) - funcalls += 1 + fun_calls += 1 if disp: print("Failed to converge after ", str(itr+1), @@ -534,7 +534,7 @@ def brent_max(func, a, b, args, xtol=1e-5, maxiter=500): # @jit(fastmath=True, cache=True) -def bisection(func, x1, x2, args, xtol=1e-6, maxIter=100): +def bisection(func, x1, x2, args, xtol=1e-6, maxiter=100): """ Bisection algorithm. You need to supply root brackets x1 and x2. """ if np.abs(x1-x2) < 1e-10: @@ -555,7 +555,7 @@ def bisection(func, x1, x2, args, xtol=1e-6, maxIter=100): print("Root not bracketed") return None - for i in range(0, maxIter): + for i in range(0, maxiter): xmid = (x1 + x2)/2.0 fmid = func(xmid, args) @@ -568,7 +568,7 @@ def bisection(func, x1, x2, args, xtol=1e-6, maxIter=100): if np.abs(fmid) < xtol: return xmid - print("Bisection exceeded number of iterations", maxIter) + print("Bisection exceeded number of iterations", maxiter) return None ############################################################################### diff --git a/financepy/utils/solver_nm.py b/financepy/utils/solver_nm.py index 5a61afcd..194610a8 100644 --- a/financepy/utils/solver_nm.py +++ b/financepy/utils/solver_nm.py @@ -12,9 +12,9 @@ _ECONVERGED = 0 _ECONVERR = -1 -_iter = 100 -_xtol = 2e-12 -_rtol = 4*np.finfo(float).eps +_ITER = 100 +_XTOL = 2e-12 +_RTOL = 4*np.finfo(float).eps results = namedtuple('results', 'root function_calls iterations converged') diff --git a/notebooks/finutils/FINDAYCOUNT_Introduction.ipynb b/notebooks/finutils/FINDAYCOUNT_Introduction.ipynb index ef9060bb..39121f8c 100644 --- a/notebooks/finutils/FINDAYCOUNT_Introduction.ipynb +++ b/notebooks/finutils/FINDAYCOUNT_Introduction.ipynb @@ -67,7 +67,7 @@ } ], "source": [ - "numDays = 1\n", + "num_days = 1\n", "settle_dt = Date(15, 2, 2019)\n", "freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", @@ -118,7 +118,7 @@ } ], "source": [ - "numDays = 1\n", + "num_days = 1\n", "settle_dt = Date(15, 2, 2019)\n", "freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", diff --git a/notebooks/market/curves/FINDISCOUNTCURVEZERO_ConvertZeroCurveToDiscountCurve.ipynb b/notebooks/market/curves/FINDISCOUNTCURVEZERO_ConvertZeroCurveToDiscountCurve.ipynb index 6e3821dc..26414ff3 100644 --- a/notebooks/market/curves/FINDISCOUNTCURVEZERO_ConvertZeroCurveToDiscountCurve.ipynb +++ b/notebooks/market/curves/FINDISCOUNTCURVEZERO_ConvertZeroCurveToDiscountCurve.ipynb @@ -96,9 +96,9 @@ "metadata": {}, "outputs": [], "source": [ - "spot_dates = [Date(1, 1, 2015), Date(1, 6, 2015), Date(1, 12, 2015), Date(1, 4, 2016), Date(1, 8, 2016)]\n", + "spot_dts = [Date(1, 1, 2015), Date(1, 6, 2015), Date(1, 12, 2015), Date(1, 4, 2016), Date(1, 8, 2016)]\n", "spot_rates = [0, 0.02, 0.04, 0.06, 0.08]\n", - "zero_curve = DiscountCurveZeros(value_dt, spot_dates, spot_rates, \n", + "zero_curve = DiscountCurveZeros(value_dt, spot_dts, spot_rates, \n", " frequencyType, day_count_type, InterpTypes.LINEAR_ZERO_RATES)" ] }, @@ -152,7 +152,7 @@ } ], "source": [ - "for dt in spot_dates:\n", + "for dt in spot_dts:\n", " df = zero_curve.df(dt)\n", " print(dt, df)" ] diff --git a/notebooks/market/volatility/EquityVolSurfaceConstructionSVI.ipynb b/notebooks/market/volatility/EquityVolSurfaceConstructionSVI.ipynb index 7d7c3be4..faebf675 100644 --- a/notebooks/market/volatility/EquityVolSurfaceConstructionSVI.ipynb +++ b/notebooks/market/volatility/EquityVolSurfaceConstructionSVI.ipynb @@ -80,7 +80,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_dates = [Date(11, 2, 2021), Date(11, 3, 2021), Date(11, 4, 2021), \n", + "expiry_dts = [Date(11, 2, 2021), Date(11, 3, 2021), Date(11, 4, 2021), \n", " Date(11, 7, 2021), Date(11,10, 2021), Date(11, 1, 2022), \n", " Date(11, 1, 2023)]" ] @@ -167,7 +167,7 @@ " stock_price,\n", " discount_curve,\n", " dividend_curve,\n", - " expiry_dates,\n", + " expiry_dts,\n", " strikes,\n", " volSurface,\n", " vol_functionType)" diff --git a/notebooks/market/volatility/FXVolSurfaceConstructionPartOne.ipynb b/notebooks/market/volatility/FXVolSurfaceConstructionPartOne.ipynb index 858fe30d..4f1318e6 100644 --- a/notebooks/market/volatility/FXVolSurfaceConstructionPartOne.ipynb +++ b/notebooks/market/volatility/FXVolSurfaceConstructionPartOne.ipynb @@ -101,8 +101,8 @@ "metadata": {}, "outputs": [], "source": [ - "dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate)\n", - "for_discount_curve = DiscountCurveFlat(value_dt, forCCRate)" + "domestic_curve = DiscountCurveFlat(value_dt, domCCRate)\n", + "foreign_curve = DiscountCurveFlat(value_dt, forCCRate)" ] }, { @@ -148,7 +148,7 @@ "outputs": [], "source": [ "notional_currency = forName\n", - "atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", + "atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", "delta_method = FinFXDeltaMethod.SPOT_DELTA" ] }, @@ -159,9 +159,9 @@ "outputs": [], "source": [ "fxVolSurfaceClark = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, ms25DeltaVols, rr25DeltaVols,\n", - " atmMethod, delta_method, VolFuncTypes.CLARK5)" + " atm_method, delta_method, VolFuncTypes.CLARK5)" ] }, { @@ -171,9 +171,9 @@ "outputs": [], "source": [ "fxVolSurfaceSABR = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, ms25DeltaVols, rr25DeltaVols,\n", - " atmMethod, delta_method, VolFuncTypes.SABR)" + " atm_method, delta_method, VolFuncTypes.SABR)" ] }, { @@ -183,9 +183,9 @@ "outputs": [], "source": [ "fxVolSurfaceBBG = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, ms25DeltaVols, rr25DeltaVols,\n", - " atmMethod, delta_method, VolFuncTypes.BBG)" + " atm_method, delta_method, VolFuncTypes.BBG)" ] }, { @@ -374,7 +374,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = value_dt.add_tenor(\"1Y\")" + "expiry_dt = value_dt.add_tenor(\"1Y\")" ] }, { @@ -388,9 +388,9 @@ "volsBBG = []\n", "\n", "for k in strikes:\n", - " volClark = fxVolSurfaceClark.volatility(k, expiry_date)\n", - " volSABR = fxVolSurfaceSABR.volatility(k, expiry_date)\n", - " volBBG = fxVolSurfaceBBG.volatility(k, expiry_date)\n", + " volClark = fxVolSurfaceClark.volatility(k, expiry_dt)\n", + " volSABR = fxVolSurfaceSABR.volatility(k, expiry_dt)\n", + " volBBG = fxVolSurfaceBBG.volatility(k, expiry_dt)\n", " volsClark.append(volClark*100.0) \n", " volsSABR.append(volSABR*100.0) \n", " volsBBG.append(volBBG*100.0) " @@ -506,7 +506,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_dates = value_dt.add_years(years)" + "expiry_dts = value_dt.add_years(years)" ] }, { @@ -519,11 +519,11 @@ "volsSABR = []\n", "volsBBG = []\n", "\n", - "for expiry_date in expiry_dates:\n", + "for expiry_dt in expiry_dts:\n", " \n", - " volClark = fxVolSurfaceClark.volatility(k, expiry_date)\n", - " volSABR = fxVolSurfaceSABR.volatility(k, expiry_date)\n", - " volBBG = fxVolSurfaceBBG.volatility(k, expiry_date)\n", + " volClark = fxVolSurfaceClark.volatility(k, expiry_dt)\n", + " volSABR = fxVolSurfaceSABR.volatility(k, expiry_dt)\n", + " volBBG = fxVolSurfaceBBG.volatility(k, expiry_dt)\n", "\n", " volsClark.append(volClark*100.0) \n", " volsSABR.append(volSABR*100.0) \n", diff --git a/notebooks/market/volatility/FXVolSurfaceConstructionPartThree.ipynb b/notebooks/market/volatility/FXVolSurfaceConstructionPartThree.ipynb index 2731cf9b..f220aab1 100644 --- a/notebooks/market/volatility/FXVolSurfaceConstructionPartThree.ipynb +++ b/notebooks/market/volatility/FXVolSurfaceConstructionPartThree.ipynb @@ -80,8 +80,8 @@ "metadata": {}, "outputs": [], "source": [ - "dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate)\n", - "for_discount_curve = DiscountCurveFlat(value_dt, forCCRate)" + "domestic_curve = DiscountCurveFlat(value_dt, domCCRate)\n", + "foreign_curve = DiscountCurveFlat(value_dt, forCCRate)" ] }, { @@ -129,7 +129,7 @@ "outputs": [], "source": [ "notional_currency = forName\n", - "atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", + "atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", "delta_method = FinFXDeltaMethod.SPOT_DELTA\n", "alpha = 0.5" ] @@ -141,12 +141,12 @@ "outputs": [], "source": [ "fxVolSurfaceClark = FXVolSurfacePlus(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, \n", " ms25DeltaVols, rr25DeltaVols, \n", " ms10DeltaVols, rr25DeltaVols,\n", " alpha,\n", - " atmMethod, delta_method, \n", + " atm_method, delta_method, \n", " VolFuncTypes.CLARK5)" ] }, @@ -157,12 +157,12 @@ "outputs": [], "source": [ "fxVolSurfaceSABR = FXVolSurfacePlus(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, \n", " ms25DeltaVols, rr25DeltaVols, \n", " ms10DeltaVols, rr25DeltaVols,\n", " alpha,\n", - " atmMethod, delta_method,\n", + " atm_method, delta_method,\n", " VolFuncTypes.SABR)" ] }, @@ -173,12 +173,12 @@ "outputs": [], "source": [ "fxVolSurfaceBBG = FXVolSurfacePlus(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, \n", " ms25DeltaVols, rr25DeltaVols, \n", " ms10DeltaVols, rr25DeltaVols,\n", " alpha,\n", - " atmMethod, delta_method,\n", + " atm_method, delta_method,\n", " VolFuncTypes.BBG)" ] }, diff --git a/notebooks/market/volatility/FXVolSurfaceConstructionPartTwo.ipynb b/notebooks/market/volatility/FXVolSurfaceConstructionPartTwo.ipynb index 668f72be..cd5a33c2 100644 --- a/notebooks/market/volatility/FXVolSurfaceConstructionPartTwo.ipynb +++ b/notebooks/market/volatility/FXVolSurfaceConstructionPartTwo.ipynb @@ -91,8 +91,8 @@ "metadata": {}, "outputs": [], "source": [ - "dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate)\n", - "for_discount_curve = DiscountCurveFlat(value_dt, forCCRate)" + "domestic_curve = DiscountCurveFlat(value_dt, domCCRate)\n", + "foreign_curve = DiscountCurveFlat(value_dt, forCCRate)" ] }, { @@ -140,7 +140,7 @@ "outputs": [], "source": [ "notional_currency = forName\n", - "atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", + "atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", "delta_method = FinFXDeltaMethod.SPOT_DELTA\n", "alpha = 0.50" ] @@ -152,12 +152,12 @@ "outputs": [], "source": [ "fxVolSurfaceClark = FXVolSurfacePlus(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, \n", " ms25DeltaVols, rr25DeltaVols, \n", " ms10DeltaVols, rr10DeltaVols,\n", " alpha,\n", - " atmMethod, delta_method, \n", + " atm_method, delta_method, \n", " VolFuncTypes.CLARK)" ] }, @@ -168,12 +168,12 @@ "outputs": [], "source": [ "fxVolSurfaceSABR = FXVolSurfacePlus(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols,\n", " ms25DeltaVols, rr25DeltaVols, \n", " ms10DeltaVols, rr10DeltaVols,\n", " alpha,\n", - " atmMethod, delta_method, \n", + " atm_method, delta_method, \n", " VolFuncTypes.SABR)" ] }, @@ -184,12 +184,12 @@ "outputs": [], "source": [ "fxVolSurfaceBBG = FXVolSurfacePlus(value_dt, spot_fx_rate, currency_pair, notional_currency,\n", - " dom_discount_curve, for_discount_curve,\n", + " domestic_curve, foreign_curve,\n", " tenors, atm_vols, \n", " ms25DeltaVols, rr25DeltaVols, \n", " ms10DeltaVols, rr25DeltaVols,\n", " alpha,\n", - " atmMethod, delta_method, \n", + " atm_method, delta_method, \n", " VolFuncTypes.BBG)" ] }, diff --git a/notebooks/market/volatility/SimpleBuildFXVolatilitySurface25Delta.ipynb b/notebooks/market/volatility/SimpleBuildFXVolatilitySurface25Delta.ipynb index cfe1de9a..b170fbc3 100644 --- a/notebooks/market/volatility/SimpleBuildFXVolatilitySurface25Delta.ipynb +++ b/notebooks/market/volatility/SimpleBuildFXVolatilitySurface25Delta.ipynb @@ -77,8 +77,8 @@ "metadata": {}, "outputs": [], "source": [ - "dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate)\n", - "for_discount_curve = DiscountCurveFlat(value_dt, forCCRate)" + "domestic_curve = DiscountCurveFlat(value_dt, domCCRate)\n", + "foreign_curve = DiscountCurveFlat(value_dt, forCCRate)" ] }, { @@ -108,7 +108,7 @@ "metadata": {}, "outputs": [], "source": [ - "atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", + "atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL\n", "delta_method = FinFXDeltaMethod.SPOT_DELTA" ] }, @@ -122,13 +122,13 @@ " spot_fx_rate,\n", " currency_pair,\n", " notional_currency,\n", - " dom_discount_curve,\n", - " for_discount_curve,\n", + " domestic_curve,\n", + " foreign_curve,\n", " tenors,\n", " atm_vols,\n", " marketStrangle25DeltaVols,\n", " riskReversal25DeltaVols,\n", - " atmMethod,\n", + " atm_method,\n", " delta_method)" ] }, @@ -422,7 +422,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_dates = value_dt.add_tenor(tenors)" + "expiry_dts = value_dt.add_tenor(tenors)" ] }, { @@ -458,7 +458,7 @@ } ], "source": [ - "K, fxMarket.volatility(K, expiry_dates[0])" + "K, fxMarket.volatility(K, expiry_dts[0])" ] }, { @@ -494,7 +494,7 @@ } ], "source": [ - "K, fxMarket.volatility(K,expiry_dates[-1])" + "K, fxMarket.volatility(K,expiry_dts[-1])" ] }, { diff --git a/notebooks/models/FINITE_DIFFERENCE_PSOR.ipynb b/notebooks/models/FINITE_DIFFERENCE_PSOR.ipynb index 3fe75fb5..4f280033 100644 --- a/notebooks/models/FINITE_DIFFERENCE_PSOR.ipynb +++ b/notebooks/models/FINITE_DIFFERENCE_PSOR.ipynb @@ -38,7 +38,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 7, 2015)\n", + "expiry_dt = Date(1, 7, 2015)\n", "strike_price = 100.0\n", "option_type = OptionTypes.EUROPEAN_CALL\n", "\n", @@ -51,7 +51,7 @@ "num_samples = 2000\n", "\n", "# Time to contract expiry in years\n", - "time_to_expiry = (expiry_date - value_dt) / gDaysInYear\n" + "time_to_expiry = (expiry_dt - value_dt) / gDaysInYear\n" ] }, { diff --git a/notebooks/models/FINMODEL_SABR_InterestRates.ipynb b/notebooks/models/FINMODEL_SABR_InterestRates.ipynb index d4a0bfda..9794db12 100644 --- a/notebooks/models/FINMODEL_SABR_InterestRates.ipynb +++ b/notebooks/models/FINMODEL_SABR_InterestRates.ipynb @@ -176,7 +176,7 @@ "metadata": {}, "outputs": [], "source": [ - "blackVol = 0.22" + "black_vol = 0.22" ] }, { @@ -203,7 +203,7 @@ "metadata": {}, "outputs": [], "source": [ - "model.set_alpha_from_atm_black_vol(blackVol, k, t_exp)" + "model.set_alpha_from_atm_black_vol(black_vol, k, t_exp)" ] }, { @@ -298,7 +298,7 @@ "plt.title(\"SABR\")\n", "plt.xlabel(\"Strike\")\n", "plt.ylabel(\"Black Volatility\")\n", - "plt.plot(k, blackVol*100, 'o', label=\"ATM\")\n", + "plt.plot(k, black_vol*100, 'o', label=\"ATM\")\n", "plt.legend()" ] }, @@ -315,7 +315,7 @@ "metadata": {}, "outputs": [], "source": [ - "blackVol = 0.26" + "black_vol = 0.26" ] }, { @@ -342,7 +342,7 @@ "metadata": {}, "outputs": [], "source": [ - "model.set_alpha_from_black_vol(blackVol, f, k, t_exp)" + "model.set_alpha_from_black_vol(black_vol, f, k, t_exp)" ] }, { @@ -402,7 +402,7 @@ "plt.title(\"SABR\")\n", "plt.xlabel(\"Strike\")\n", "plt.ylabel(\"Black Volatility\")\n", - "plt.plot(k, blackVol*100, 'o', label=\"ATM\")\n", + "plt.plot(k, black_vol*100, 'o', label=\"ATM\")\n", "plt.legend();" ] }, diff --git a/notebooks/models/FINVOLFUNCTIONS_SSVI_MODEL.ipynb b/notebooks/models/FINVOLFUNCTIONS_SSVI_MODEL.ipynb index 7605071c..538186ae 100644 --- a/notebooks/models/FINVOLFUNCTIONS_SSVI_MODEL.ipynb +++ b/notebooks/models/FINVOLFUNCTIONS_SSVI_MODEL.ipynb @@ -93,7 +93,7 @@ "metadata": {}, "outputs": [], "source": [ - "logMoneyness = np.log(f/strikes)" + "log_moneyness = np.log(f/strikes)" ] }, { @@ -182,8 +182,8 @@ ], "source": [ "plt.figure(figsize=(8,5))\n", - "plt.plot(logMoneyness, volSSI_1, label=\"Initial\")\n", - "plt.plot(logMoneyness, volSSI_2, label=\"Bumped\")\n", + "plt.plot(log_moneyness, volSSI_1, label=\"Initial\")\n", + "plt.plot(log_moneyness, volSSI_2, label=\"Bumped\")\n", "plt.title(\"Gatheral's SSI\")\n", "plt.xlabel(\"Log Moneyness\")\n", "plt.ylabel(\"Black Volatility\")\n", diff --git a/notebooks/models/MERTON_CREDIT_MODEL.ipynb b/notebooks/models/MERTON_CREDIT_MODEL.ipynb index ef8e6fb1..16882887 100644 --- a/notebooks/models/MERTON_CREDIT_MODEL.ipynb +++ b/notebooks/models/MERTON_CREDIT_MODEL.ipynb @@ -76,10 +76,10 @@ "source": [ "equity_value = [2.6406, 2.6817, 3.977, 2.947, 2.528]\n", "equity_vol = [0.7103, 0.3929, 0.3121, 0.4595, 0.6181]\n", - "bondFace = [4.0, 3.5, 3.5, 3.2, 4.0]\n", + "bond_face = [4.0, 3.5, 3.5, 3.2, 4.0]\n", "risk_free_rate = [0.05, 0.05, 0.05, 0.05, 0.05]\n", - "assetGrowthRate = [0.0306, 0.03, 0.031, 0.0302, 0.0305]\n", - "timeToMaturity = 1.0 #np.linspace(0.1, 10, 100)" + "asset_growth_rate = [0.0306, 0.03, 0.031, 0.0302, 0.0305]\n", + "years_to_maturity = 1.0 #np.linspace(0.1, 10, 100)" ] }, { @@ -88,7 +88,7 @@ "metadata": {}, "outputs": [], "source": [ - "model = MertonFirmMkt(equity_value, bondFace, timeToMaturity, risk_free_rate, assetGrowthRate, equity_vol)" + "model = MertonFirmMkt(equity_value, bond_face, years_to_maturity, risk_free_rate, asset_growth_rate, equity_vol)" ] }, { @@ -257,10 +257,10 @@ "outputs": [], "source": [ "assetVol = 0.20\n", - "bondFace = 100.0\n", + "bond_face = 100.0\n", "risk_free_rate = 0.05\n", - "assetGrowthRate = 0.05\n", - "timeToMaturity = np.linspace(0.01,10.,1000)" + "asset_growth_rate = 0.05\n", + "years_to_maturity = np.linspace(0.01,10.,1000)" ] }, { @@ -269,9 +269,9 @@ "metadata": {}, "outputs": [], "source": [ - "model1 = MertonFirm(140.0, bondFace, timeToMaturity, risk_free_rate, assetGrowthRate, assetVol)\n", - "model2 = MertonFirm(115.0, bondFace, timeToMaturity, risk_free_rate, assetGrowthRate, assetVol)\n", - "model3 = MertonFirm(105.0, bondFace, timeToMaturity, risk_free_rate, assetGrowthRate, assetVol)" + "model1 = MertonFirm(140.0, bond_face, years_to_maturity, risk_free_rate, asset_growth_rate, assetVol)\n", + "model2 = MertonFirm(115.0, bond_face, years_to_maturity, risk_free_rate, asset_growth_rate, assetVol)\n", + "model3 = MertonFirm(105.0, bond_face, years_to_maturity, risk_free_rate, asset_growth_rate, assetVol)" ] }, { @@ -303,9 +303,9 @@ ], "source": [ "plt.figure(figsize=(10,6))\n", - "plt.plot(timeToMaturity, spd1, label=\"Low Leverage\")\n", - "plt.plot(timeToMaturity, spd2, label=\"Medium\")\n", - "plt.plot(timeToMaturity, spd3, label=\"Highly Leverage\")\n", + "plt.plot(years_to_maturity, spd1, label=\"Low Leverage\")\n", + "plt.plot(years_to_maturity, spd2, label=\"Medium\")\n", + "plt.plot(years_to_maturity, spd3, label=\"Highly Leverage\")\n", "plt.xlabel(\"Maturity (yrs)\")\n", "plt.ylabel(\"Credit Spread (bp)\")\n", "plt.legend();" diff --git a/notebooks/products/bonds/FINANNUITY_Valuation.ipynb b/notebooks/products/bonds/FINANNUITY_Valuation.ipynb index e34addfd..f40a903b 100644 --- a/notebooks/products/bonds/FINANNUITY_Valuation.ipynb +++ b/notebooks/products/bonds/FINANNUITY_Valuation.ipynb @@ -188,12 +188,12 @@ "depos = []\n", "dcType = DayCountTypes.ACT_360\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"2Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"3Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"4Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"5Y\",swapType,0.0500,fixedFreq,dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"2Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"3Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"4Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"5Y\",swap_type,0.0500,fixedFreq,dcType)\n", "swaps = [swap1, swap2, swap3, swap4, swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" diff --git a/notebooks/products/bonds/FINBONDEMBEDDEDOPTION_Valuation.ipynb b/notebooks/products/bonds/FINBONDEMBEDDEDOPTION_Valuation.ipynb index 99872f3f..4a5fbc85 100644 --- a/notebooks/products/bonds/FINBONDEMBEDDEDOPTION_Valuation.ipynb +++ b/notebooks/products/bonds/FINBONDEMBEDDEDOPTION_Valuation.ipynb @@ -91,10 +91,10 @@ "source": [ "dcType = DayCountTypes.ACT_360\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt, Date(1,1,2008), swapType, 0.05, fixedFreq, dcType)\n", - "swap2 = IborSwap(settle_dt, Date(1,1,2009), swapType, 0.05, fixedFreq, dcType)\n", - "swap3 = IborSwap(settle_dt, Date(1,1,2010), swapType, 0.05, fixedFreq, dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt, Date(1,1,2008), swap_type, 0.05, fixedFreq, dcType)\n", + "swap2 = IborSwap(settle_dt, Date(1,1,2009), swap_type, 0.05, fixedFreq, dcType)\n", + "swap3 = IborSwap(settle_dt, Date(1,1,2010), swap_type, 0.05, fixedFreq, dcType)\n", "swaps = [swap1, swap2, swap3]\n", "discount_curve = IborSingleCurve(value_dt, [], [], swaps)" ] @@ -174,9 +174,9 @@ "metadata": {}, "outputs": [], "source": [ - "call_dates = []\n", + "call_dts = []\n", "call_prices = []\n", - "put_dates = [Date(1, 1, 2008), Date(1, 1, 2009), Date(1, 1, 2010)]\n", + "put_dts = [Date(1, 1, 2008), Date(1, 1, 2009), Date(1, 1, 2010)]\n", "put_prices = [100.0, 100.0, 100.0]" ] }, @@ -194,7 +194,7 @@ "outputs": [], "source": [ "puttable_bond = BondEmbeddedOption(issue_dt, maturity_dt, coupon, frequencyType, dc_type,\n", - " call_dates, call_prices, put_dates, put_prices)" + " call_dts, call_prices, put_dts, put_prices)" ] }, { diff --git a/notebooks/products/bonds/FINBONDMARKET_DatabaseOfConventions.ipynb b/notebooks/products/bonds/FINBONDMARKET_DatabaseOfConventions.ipynb index 4ab0d048..618a214c 100644 --- a/notebooks/products/bonds/FINBONDMARKET_DatabaseOfConventions.ipynb +++ b/notebooks/products/bonds/FINBONDMARKET_DatabaseOfConventions.ipynb @@ -166,11 +166,11 @@ "print(\"%20s %17s %15s %11s %10s %10s\" % (\"COUNTRY\",\"ACCRUED\",\"FREQ\",\"SET_DAYS\",\"EX_DIV_DAYS\",\"CALENDAR\"))\n", "for country in BondMarkets:\n", "\n", - " (dc_type, frequencyType, settlementDays, exDiv, cal) = get_bond_market_conventions(country)\n", + " (dc_type, frequencyType, settle_days, exDiv, cal) = get_bond_market_conventions(country)\n", " \n", " if dc_type is not None:\n", " print(\"%20s %17s %15s %11d %10d %10s\" %(country.name, dc_type.name, frequencyType.name, \n", - " settlementDays, exDiv, cal))" + " settle_days, exDiv, cal))" ] }, { diff --git a/notebooks/products/bonds/FINBONDOPTION_BK_ModelValuationAnalysis.ipynb b/notebooks/products/bonds/FINBONDOPTION_BK_ModelValuationAnalysis.ipynb index 1d6cd4ad..d508e2e1 100644 --- a/notebooks/products/bonds/FINBONDOPTION_BK_ModelValuationAnalysis.ipynb +++ b/notebooks/products/bonds/FINBONDOPTION_BK_ModelValuationAnalysis.ipynb @@ -83,12 +83,12 @@ "source": [ "dcType = DayCountTypes.THIRTY_360_BOND\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"5Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"7Y\",swapType,0.0500,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"10Y\",swapType,0.0500,fixedFreq,dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"5Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"7Y\",swap_type,0.0500,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"10Y\",swap_type,0.0500,fixedFreq,dcType)\n", "swaps = [swap1, swap2, swap3, swap4, swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, [], [], swaps)" diff --git a/notebooks/products/bonds/FINBONDOPTION_HW_Model_Jamshidian.ipynb b/notebooks/products/bonds/FINBONDOPTION_HW_Model_Jamshidian.ipynb index 2a531ace..b491d97b 100644 --- a/notebooks/products/bonds/FINBONDOPTION_HW_Model_Jamshidian.ipynb +++ b/notebooks/products/bonds/FINBONDOPTION_HW_Model_Jamshidian.ipynb @@ -203,7 +203,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = settle_dt.add_tenor(\"18m\")\n", + "expiry_dt = settle_dt.add_tenor(\"18m\")\n", "strike_price = 105.0\n", "face_amount = 100.0" ] @@ -214,7 +214,7 @@ "metadata": {}, "outputs": [], "source": [ - "europeanCallBondOption = BondOption(bond, expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "europeanCallBondOption = BondOption(bond, expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -223,7 +223,7 @@ "metadata": {}, "outputs": [], "source": [ - "europeanPutBondOption = BondOption(bond, expiry_date, strike_price, OptionTypes.EUROPEAN_PUT)" + "europeanPutBondOption = BondOption(bond, expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT)" ] }, { @@ -248,8 +248,8 @@ } ], "source": [ - "cp = bond.clean_price_from_discount_curve(expiry_date, discount_curve)\n", - "dp = bond.dirty_price_from_discount_curve(expiry_date, discount_curve)\n", + "cp = bond.clean_price_from_discount_curve(expiry_dt, discount_curve)\n", + "dp = bond.dirty_price_from_discount_curve(expiry_dt, discount_curve)\n", "print(\"Fixed Income Clean Price: %9.3f\"% cp)\n", "print(\"Fixed Income Dirty Price: %9.3f\"% dp)" ] @@ -260,7 +260,7 @@ "metadata": {}, "outputs": [], "source": [ - "df = discount_curve.df(expiry_date)" + "df = discount_curve.df(expiry_dt)" ] }, { @@ -507,7 +507,7 @@ ], "source": [ "for K in strikes:\n", - " europeanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_CALL)\n", + " europeanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_CALL)\n", " ec1 = europeanCallBondOption.value(settle_dt, discount_curve, modelJamshidian)\n", " ec2 = europeanCallBondOption.value(settle_dt, discount_curve, modelExpiryOnly)\n", " ec3 = europeanCallBondOption.value(settle_dt, discount_curve, modelExpiryTree) \n", diff --git a/notebooks/products/bonds/FINBONDOPTION_Tree_Convergence_Zero_Vol.ipynb b/notebooks/products/bonds/FINBONDOPTION_Tree_Convergence_Zero_Vol.ipynb index 265c39c9..dd8cece7 100644 --- a/notebooks/products/bonds/FINBONDOPTION_Tree_Convergence_Zero_Vol.ipynb +++ b/notebooks/products/bonds/FINBONDOPTION_Tree_Convergence_Zero_Vol.ipynb @@ -128,8 +128,8 @@ } ], "source": [ - "expiry_date = settle_dt.add_tenor(\"18m\")\n", - "print(expiry_date)" + "expiry_dt = settle_dt.add_tenor(\"18m\")\n", + "print(expiry_dt)" ] }, { @@ -154,7 +154,7 @@ "metadata": {}, "outputs": [], "source": [ - "df = discount_curve.df(expiry_date)" + "df = discount_curve.df(expiry_dt)" ] }, { @@ -178,7 +178,7 @@ "outputs": [], "source": [ "sp = bond.clean_price_from_discount_curve(settle_dt, discount_curve)\n", - "fp = bond.clean_price_from_discount_curve(expiry_date, discount_curve)" + "fp = bond.clean_price_from_discount_curve(expiry_dt, discount_curve)" ] }, { @@ -338,16 +338,16 @@ " \n", " hwModel = HWTree(sigma, a, num_steps)\n", " \n", - " europeanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_CALL)\n", + " europeanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_CALL)\n", " v_ec = europeanCallBondOption.value(settle_dt, discount_curve, hwModel)\n", "\n", - " americanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.AMERICAN_CALL)\n", + " americanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.AMERICAN_CALL)\n", " v_ac = americanCallBondOption.value(settle_dt, discount_curve, hwModel)\n", " \n", - " europeanPutBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_PUT)\n", + " europeanPutBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_PUT)\n", " v_ep = europeanPutBondOption.value(settle_dt, discount_curve, hwModel)\n", " \n", - " americanPutBondOption = BondOption(bond, expiry_date, K, OptionTypes.AMERICAN_PUT)\n", + " americanPutBondOption = BondOption(bond, expiry_dt, K, OptionTypes.AMERICAN_PUT)\n", " v_ap = americanPutBondOption.value(settle_dt, discount_curve, hwModel)\n", " \n", " vec_ec.append(v_ec)\n", @@ -424,16 +424,16 @@ " \n", " bkModel = BKTree(sigma, a, num_steps)\n", " \n", - " europeanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_CALL)\n", + " europeanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_CALL)\n", " v_ec = europeanCallBondOption.value(settle_dt, discount_curve, bkModel)\n", "\n", - " americanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.AMERICAN_CALL)\n", + " americanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.AMERICAN_CALL)\n", " v_ac = americanCallBondOption.value(settle_dt, discount_curve, bkModel)\n", " \n", - " europeanPutBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_PUT)\n", + " europeanPutBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_PUT)\n", " v_ep = europeanPutBondOption.value(settle_dt, discount_curve, bkModel)\n", " \n", - " americanPutBondOption = BondOption(bond, expiry_date, K, OptionTypes.AMERICAN_PUT)\n", + " americanPutBondOption = BondOption(bond, expiry_dt, K, OptionTypes.AMERICAN_PUT)\n", " v_ap = americanPutBondOption.value(settle_dt, discount_curve, bkModel)\n", " \n", " vec_ec.append(v_ec)\n", @@ -502,16 +502,16 @@ " \n", " bdtModel = BDTTree(sigma, num_steps)\n", " \n", - " europeanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_CALL)\n", + " europeanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_CALL)\n", " v_ec = europeanCallBondOption.value(settle_dt, discount_curve, bdtModel)\n", "\n", - " americanCallBondOption = BondOption(bond, expiry_date, K, OptionTypes.AMERICAN_CALL)\n", + " americanCallBondOption = BondOption(bond, expiry_dt, K, OptionTypes.AMERICAN_CALL)\n", " v_ac = americanCallBondOption.value(settle_dt, discount_curve, bdtModel)\n", " \n", - " europeanPutBondOption = BondOption(bond, expiry_date, K, OptionTypes.EUROPEAN_PUT)\n", + " europeanPutBondOption = BondOption(bond, expiry_dt, K, OptionTypes.EUROPEAN_PUT)\n", " v_ep = europeanPutBondOption.value(settle_dt, discount_curve, bdtModel)\n", " \n", - " americanPutBondOption = BondOption(bond, expiry_date, K, OptionTypes.AMERICAN_PUT)\n", + " americanPutBondOption = BondOption(bond, expiry_dt, K, OptionTypes.AMERICAN_PUT)\n", " v_ap = americanPutBondOption.value(settle_dt, discount_curve, bdtModel)\n", " \n", " vec_ec.append(v_ec)\n", diff --git a/notebooks/products/bonds/FINBONDYIELDCURVES_FittingExample.ipynb b/notebooks/products/bonds/FINBONDYIELDCURVES_FittingExample.ipynb index b1a09571..ab682401 100644 --- a/notebooks/products/bonds/FINBONDYIELDCURVES_FittingExample.ipynb +++ b/notebooks/products/bonds/FINBONDYIELDCURVES_FittingExample.ipynb @@ -100,7 +100,7 @@ "metadata": {}, "outputs": [], "source": [ - "dc_type, frequencyType, settlementDays, exDiv, calendar = get_bond_market_conventions(BondMarkets.UNITED_KINGDOM)" + "dc_type, frequencyType, settle_days, exDiv, calendar = get_bond_market_conventions(BondMarkets.UNITED_KINGDOM)" ] }, { @@ -118,7 +118,7 @@ ], "source": [ "today = Date(18,9,2012)\n", - "settle_dt = today.add_weekdays(settlementDays)\n", + "settle_dt = today.add_weekdays(settle_days)\n", "print(\"Settles:\", settle_dt)" ] }, @@ -249,7 +249,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To get a specific yield we can call the function interpolated_yield" + "To get a specific yield we can call the function interp_yield" ] }, { @@ -269,7 +269,7 @@ } ], "source": [ - "fitted_curve.interpolated_yield(20.0)*100" + "fitted_curve.interp_yield(20.0)*100" ] }, { @@ -299,7 +299,7 @@ } ], "source": [ - "fitted_curve.interpolated_yield(times)*100" + "fitted_curve.interp_yield(times)*100" ] }, { @@ -408,7 +408,7 @@ } ], "source": [ - "fitted_curve.interpolated_yield(times)*100" + "fitted_curve.interp_yield(times)*100" ] }, { @@ -518,7 +518,7 @@ } ], "source": [ - "fitted_curve.interpolated_yield(times)*100" + "fitted_curve.interp_yield(times)*100" ] }, { @@ -736,7 +736,7 @@ } ], "source": [ - "fitted_curve.interpolated_yield(times)*100" + "fitted_curve.interp_yield(times)*100" ] }, { @@ -843,7 +843,7 @@ } ], "source": [ - "fitted_curve.interpolated_yield(times)*100" + "fitted_curve.interp_yield(times)*100" ] }, { diff --git a/notebooks/products/bonds/FINBONDYIELDCURVE_FittingToBondMarketPrices.ipynb b/notebooks/products/bonds/FINBONDYIELDCURVE_FittingToBondMarketPrices.ipynb index 77bc7529..5b8b5418 100644 --- a/notebooks/products/bonds/FINBONDYIELDCURVE_FittingToBondMarketPrices.ipynb +++ b/notebooks/products/bonds/FINBONDYIELDCURVE_FittingToBondMarketPrices.ipynb @@ -100,8 +100,8 @@ "for index, bondData in bondDataFrame.iterrows():\n", "\n", " date_string = bondData['maturity']\n", - " mat_date_time = dt.datetime.strptime(date_string, '%d-%b-%y')\n", - " maturity_dt = from_datetime(mat_date_time)\n", + " mat_dt_time = dt.datetime.strptime(date_string, '%d-%b-%y')\n", + " maturity_dt = from_dttime(mat_dt_time)\n", " coupon = bondData['coupon']/100.0\n", " clean_price = bondData['mid']\n", " issue_dt = Date(maturity_dt._d, maturity_dt._m, 2000)\n", @@ -433,8 +433,8 @@ "source": [ "# EXTRACT A YIELD FROM A FITTED YIELD CURVE\n", "maturity_dt = Date(19, 9, 2030)\n", - "interpolated_yield = fitted_curve5.interpolated_yield(maturity_dt)\n", - "print(maturity_dt, interpolated_yield*100)" + "interp_yield = fitted_curve5.interp_yield(maturity_dt)\n", + "print(maturity_dt, interp_yield*100)" ] }, { @@ -466,7 +466,7 @@ "metadata": {}, "outputs": [], "source": [ - "interpolated_yields = fitted_curve5.interpolated_yield(times)" + "interp_yields = fitted_curve5.interp_yield(times)" ] }, { @@ -505,7 +505,7 @@ } ], "source": [ - "interpolated_yields*100" + "interp_yields*100" ] }, { diff --git a/notebooks/products/bonds/FINBONDZEROCURVE_BootstrapOutstandingBonds.ipynb b/notebooks/products/bonds/FINBONDZEROCURVE_BootstrapOutstandingBonds.ipynb index 7e981081..be2e1271 100644 --- a/notebooks/products/bonds/FINBONDZEROCURVE_BootstrapOutstandingBonds.ipynb +++ b/notebooks/products/bonds/FINBONDZEROCURVE_BootstrapOutstandingBonds.ipynb @@ -100,7 +100,7 @@ "metadata": {}, "outputs": [], "source": [ - "dc_type, frequencyType, settlementDays, spot_days, cal = \\\n", + "dc_type, frequencyType, settle_days, spot_days, cal = \\\n", "get_bond_market_conventions(BondMarkets.UNITED_KINGDOM)" ] }, @@ -139,7 +139,7 @@ ], "source": [ "today = Date(18,9,2012)\n", - "settle_dt = today.add_weekdays(settlementDays)\n", + "settle_dt = today.add_weekdays(settle_days)\n", "print(\"Settles:\", settle_dt)" ] }, @@ -162,8 +162,8 @@ "for index, bondRow in bondDataFrame.iterrows():\n", "\n", " date_string = bondRow['maturity']\n", - " mat_date_time = dt.datetime.strptime(date_string, '%d-%b-%y')\n", - " maturity_dt = from_datetime(mat_date_time)\n", + " mat_dt_time = dt.datetime.strptime(date_string, '%d-%b-%y')\n", + " maturity_dt = from_dttime(mat_dt_time)\n", " issue_dt = Date(maturity_dt._d, maturity_dt._m, 2000)\n", " coupon = bondRow['coupon']/100.0\n", " bond = Bond(issue_dt, maturity_dt, coupon, frequencyType, dc_type)\n", diff --git a/notebooks/products/bonds/FINBOND_ComparisonWithQLExample.ipynb b/notebooks/products/bonds/FINBOND_ComparisonWithQLExample.ipynb index a92152b7..c9177b89 100644 --- a/notebooks/products/bonds/FINBOND_ComparisonWithQLExample.ipynb +++ b/notebooks/products/bonds/FINBOND_ComparisonWithQLExample.ipynb @@ -143,7 +143,7 @@ "metadata": {}, "outputs": [], "source": [ - "zero_dates = [Date(15,1,2015), Date(15,7,2015), Date(15,1,2016)]\n", + "zero_dts = [Date(15,1,2015), Date(15,7,2015), Date(15,1,2016)]\n", "zero_rates = [0.00, 0.005, 0.007]" ] }, @@ -153,7 +153,7 @@ "metadata": {}, "outputs": [], "source": [ - "discount_curve = DiscountCurveZeros(settle_dt, zero_dates, zero_rates, \n", + "discount_curve = DiscountCurveZeros(settle_dt, zero_dts, zero_rates, \n", " FrequencyTypes.ANNUAL,\n", " DayCountTypes.THIRTY_360_BOND)" ] diff --git a/notebooks/products/bonds/FINBOND_Key_Rate_Durations_Example.ipynb b/notebooks/products/bonds/FINBOND_Key_Rate_Durations_Example.ipynb index 8b9f886e..e56ab394 100644 --- a/notebooks/products/bonds/FINBOND_Key_Rate_Durations_Example.ipynb +++ b/notebooks/products/bonds/FINBOND_Key_Rate_Durations_Example.ipynb @@ -67,7 +67,7 @@ "source": [ "# First, let's create a bond object.\n", "\n", - "dc_type, frequencyType, settlementDays, exDiv, calendar = get_bond_market_conventions(\n", + "dc_type, frequencyType, settle_days, exDiv, calendar = get_bond_market_conventions(\n", " BondMarkets.UNITED_STATES)\n", "\n", "# interest accrues on this date. Original issue date is 01/08/2022\n", diff --git a/notebooks/products/bonds/FINBOND_QuantStackExchangeQuestion.ipynb b/notebooks/products/bonds/FINBOND_QuantStackExchangeQuestion.ipynb index e221a7d8..94190278 100644 --- a/notebooks/products/bonds/FINBOND_QuantStackExchangeQuestion.ipynb +++ b/notebooks/products/bonds/FINBOND_QuantStackExchangeQuestion.ipynb @@ -174,7 +174,7 @@ "metadata": {}, "outputs": [], "source": [ - "spot_dates = [Date(31, 7, 2020), Date(1, 1, 2027)]\n", + "spot_dts = [Date(31, 7, 2020), Date(1, 1, 2027)]\n", "spot_rates = [0.01, 0.02]" ] }, @@ -185,7 +185,7 @@ "outputs": [], "source": [ "zero_curve = DiscountCurveZeros(value_dt, \n", - " spot_dates, \n", + " spot_dts, \n", " spot_rates, \n", " freq_type, \n", " day_count_type, \n", diff --git a/notebooks/products/credit/FINCDSBASKET_ValuationModelComparison_REPAIR.ipynb b/notebooks/products/credit/FINCDSBASKET_ValuationModelComparison_REPAIR.ipynb index 504a039c..38742b44 100644 --- a/notebooks/products/credit/FINCDSBASKET_ValuationModelComparison_REPAIR.ipynb +++ b/notebooks/products/credit/FINCDSBASKET_ValuationModelComparison_REPAIR.ipynb @@ -80,14 +80,14 @@ "source": [ "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "depo = IborDeposit(settle_dt, \"1D\", 0.0502, dcType)\n", "depos = [depo]\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"2Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"3Y\",swapType,0.0501,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"4Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"5Y\",swapType,0.0501,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"2Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"3Y\",swap_type,0.0501,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"4Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"5Y\",swap_type,0.0501,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -113,8 +113,8 @@ "metadata": {}, "outputs": [], "source": [ - "step_in_date = value_dt.add_weekdays(0)\n", - "value_dt = step_in_date" + "step_in_dt = value_dt.add_weekdays(0)\n", + "value_dt = step_in_dt" ] }, { @@ -123,10 +123,10 @@ "metadata": {}, "outputs": [], "source": [ - "maturity3Y = value_dt.next_cds_date(36)\n", - "maturity5Y = value_dt.next_cds_date(60)\n", - "maturity7Y = value_dt.next_cds_date(84)\n", - "maturity10Y = value_dt.next_cds_date(120)" + "maturity3Y = value_dt.next_cds_dt(36)\n", + "maturity5Y = value_dt.next_cds_dt(60)\n", + "maturity7Y = value_dt.next_cds_dt(84)\n", + "maturity10Y = value_dt.next_cds_dt(120)" ] }, { @@ -155,10 +155,10 @@ " spd7Y = float(splitRow[3]) / 10000.0\n", " spd10Y = float(splitRow[4]) / 10000.0\n", " recovery_rate = float(splitRow[5])\n", - " cds3Y = CDS(step_in_date, maturity3Y, spd3Y)\n", - " cds5Y = CDS(step_in_date, maturity5Y, spd5Y)\n", - " cds7Y = CDS(step_in_date, maturity7Y, spd7Y)\n", - " cds10Y = CDS(step_in_date, maturity10Y, spd10Y)\n", + " cds3Y = CDS(step_in_dt, maturity3Y, spd3Y)\n", + " cds5Y = CDS(step_in_dt, maturity5Y, spd5Y)\n", + " cds7Y = CDS(step_in_dt, maturity7Y, spd7Y)\n", + " cds10Y = CDS(step_in_dt, maturity10Y, spd10Y)\n", " cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n", " issuer_curve = CDSCurve(value_dt, cds_contracts, libor_curve, recovery_rate)\n", " heteroIssuerCurves.append(issuer_curve)" @@ -204,10 +204,10 @@ "metadata": {}, "outputs": [], "source": [ - "spd3Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity3Y, heteroIssuerCurves)\n", - "spd5Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity5Y, heteroIssuerCurves)\n", - "spd7Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity7Y, heteroIssuerCurves)\n", - "spd10Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity10Y, heteroIssuerCurves)" + "spd3Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity3Y, heteroIssuerCurves)\n", + "spd5Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity5Y, heteroIssuerCurves)\n", + "spd7Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity7Y, heteroIssuerCurves)\n", + "spd10Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity10Y, heteroIssuerCurves)" ] }, { @@ -240,10 +240,10 @@ "outputs": [], "source": [ "for row in range(0,num_credits):\n", - " cds3Y = CDS(step_in_date, maturity3Y, spd3Y)\n", - " cds5Y = CDS(step_in_date, maturity5Y, spd5Y)\n", - " cds7Y = CDS(step_in_date, maturity7Y, spd7Y)\n", - " cds10Y = CDS(step_in_date, maturity10Y, spd10Y)\n", + " cds3Y = CDS(step_in_dt, maturity3Y, spd3Y)\n", + " cds5Y = CDS(step_in_dt, maturity5Y, spd5Y)\n", + " cds7Y = CDS(step_in_dt, maturity7Y, spd7Y)\n", + " cds10Y = CDS(step_in_dt, maturity10Y, spd10Y)\n", " cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n", " issuer_curve = CDSCurve(value_dt, cds_contracts, libor_curve, recovery_rate)\n", " homoIssuerCurves.append(issuer_curve)" @@ -301,19 +301,19 @@ } ], "source": [ - "intrinsicSpd = cdsIndex.intrinsic_spread(value_dt, step_in_date, basketMaturity, issuer_curves) * 10000.0\n", + "intrinsicSpd = cdsIndex.intrinsic_spread(value_dt, step_in_dt, basketMaturity, issuer_curves) * 10000.0\n", "\n", "print(\"INTRINSIC SPD BASKET MATURITY\", intrinsicSpd)\n", "\n", - "totalSpd = cdsIndex.total_spread(value_dt, step_in_date, basketMaturity, issuer_curves) * 10000.0\n", + "totalSpd = cdsIndex.total_spread(value_dt, step_in_dt, basketMaturity, issuer_curves) * 10000.0\n", "\n", "print(\"SUMMED UP SPD BASKET MATURITY\", totalSpd)\n", "\n", - "minSpd = cdsIndex.min_spread(value_dt, step_in_date, basketMaturity, issuer_curves) * 10000.0\n", + "minSpd = cdsIndex.min_spread(value_dt, step_in_dt, basketMaturity, issuer_curves) * 10000.0\n", "\n", "print(\"MINIMUM SPD BASKET MATURITY\", minSpd)\n", "\n", - "maxSpd = cdsIndex.max_spread(value_dt, step_in_date, basketMaturity, issuer_curves) * 10000.0\n", + "maxSpd = cdsIndex.max_spread(value_dt, step_in_dt, basketMaturity, issuer_curves) * 10000.0\n", "\n", "print(\"MAXIMUM SPD BASKET MATURITY\", maxSpd)" ] @@ -362,7 +362,7 @@ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mIndexError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[20], line 14\u001b[0m\n\u001b[0;32m 12\u001b[0m corr_matrix \u001b[38;5;241m=\u001b[39m corr_matrix_generator(rho, num_credits)\n\u001b[0;32m 13\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m num_trials \u001b[38;5;129;01min\u001b[39;00m [\u001b[38;5;241m5000\u001b[39m]:\n\u001b[1;32m---> 14\u001b[0m v1 \u001b[38;5;241m=\u001b[39m basket\u001b[38;5;241m.\u001b[39mvalue_gaussian_mc(value_dt,ntd,issuer_curves,corr_matrix,libor_curve,num_trials,seed)\n\u001b[0;32m 15\u001b[0m v2 \u001b[38;5;241m=\u001b[39m basket\u001b[38;5;241m.\u001b[39mvalue_1f_gaussian_homo(value_dt,ntd,issuer_curves,beta_vector,libor_curve)\n\u001b[0;32m 16\u001b[0m v3 \u001b[38;5;241m=\u001b[39m basket\u001b[38;5;241m.\u001b[39mvalue_student_t_mc(value_dt, ntd, issuer_curves, corr_matrix, doF, libor_curve, num_trials,seed)\n", - "File \u001b[1;32mc:\\Users\\Dominic\\anaconda3\\Lib\\site-packages\\financepy\\products\\credit\\cds_basket.py:183\u001b[0m, in \u001b[0;36mCDSBasket.value_gaussian_mc\u001b[1;34m(self, value_dt, n_to_default, issuer_curves, correlation_matrix, libor_curve, num_trials, seed)\u001b[0m\n\u001b[0;32m 176\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m FinError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mn_to_default must be 1 to num_credits\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 178\u001b[0m default_times \u001b[38;5;241m=\u001b[39m default_times_gc(issuer_curves,\n\u001b[0;32m 179\u001b[0m correlation_matrix,\n\u001b[0;32m 180\u001b[0m num_trials,\n\u001b[0;32m 181\u001b[0m seed)\n\u001b[1;32m--> 183\u001b[0m rpv01, prot_pv \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mvalue_legs_mc(value_dt,\n\u001b[0;32m 184\u001b[0m n_to_default,\n\u001b[0;32m 185\u001b[0m default_times,\n\u001b[0;32m 186\u001b[0m issuer_curves,\n\u001b[0;32m 187\u001b[0m libor_curve)\n\u001b[0;32m 189\u001b[0m spd \u001b[38;5;241m=\u001b[39m prot_pv \u001b[38;5;241m/\u001b[39m rpv01\n\u001b[0;32m 190\u001b[0m value \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_notional \u001b[38;5;241m*\u001b[39m (prot_pv \u001b[38;5;241m-\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_running_cpn \u001b[38;5;241m*\u001b[39m rpv01)\n", + "File \u001b[1;32mc:\\Users\\Dominic\\anaconda3\\Lib\\site-packages\\financepy\\products\\credit\\cds_basket.py:183\u001b[0m, in \u001b[0;36mCDSBasket.value_gaussian_mc\u001b[1;34m(self, value_dt, n_to_default, issuer_curves, corr_matrix, libor_curve, num_trials, seed)\u001b[0m\n\u001b[0;32m 176\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m FinError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mn_to_default must be 1 to num_credits\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 178\u001b[0m default_times \u001b[38;5;241m=\u001b[39m default_times_gc(issuer_curves,\n\u001b[0;32m 179\u001b[0m corr_matrix,\n\u001b[0;32m 180\u001b[0m num_trials,\n\u001b[0;32m 181\u001b[0m seed)\n\u001b[1;32m--> 183\u001b[0m rpv01, prot_pv \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mvalue_legs_mc(value_dt,\n\u001b[0;32m 184\u001b[0m n_to_default,\n\u001b[0;32m 185\u001b[0m default_times,\n\u001b[0;32m 186\u001b[0m issuer_curves,\n\u001b[0;32m 187\u001b[0m libor_curve)\n\u001b[0;32m 189\u001b[0m spd \u001b[38;5;241m=\u001b[39m prot_pv \u001b[38;5;241m/\u001b[39m rpv01\n\u001b[0;32m 190\u001b[0m value \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_notional \u001b[38;5;241m*\u001b[39m (prot_pv \u001b[38;5;241m-\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_running_cpn \u001b[38;5;241m*\u001b[39m rpv01)\n", "File \u001b[1;32mc:\\Users\\Dominic\\anaconda3\\Lib\\site-packages\\financepy\\products\\credit\\cds_basket.py:134\u001b[0m, in \u001b[0;36mCDSBasket.value_legs_mc\u001b[1;34m(self, value_dt, n_to_default, default_times, issuer_curves, libor_curve)\u001b[0m\n\u001b[0;32m 131\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m minTau \u001b[38;5;241m<\u001b[39m t_mat:\n\u001b[0;32m 133\u001b[0m num_pmnts_index \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mint\u001b[39m(minTau \u001b[38;5;241m/\u001b[39m avg_acc_factor)\n\u001b[1;32m--> 134\u001b[0m rpv01_trial \u001b[38;5;241m=\u001b[39m rpv01ToTimes[num_pmnts_index]\n\u001b[0;32m 135\u001b[0m rpv01_trial \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m (minTau \u001b[38;5;241m-\u001b[39m num_pmnts_index \u001b[38;5;241m*\u001b[39m avg_acc_factor)\n\u001b[0;32m 137\u001b[0m \u001b[38;5;66;03m# DETERMINE IDENTITY OF N-TO-DEFAULT CREDIT IF BASKET NOT HOMO\u001b[39;00m\n", "\u001b[1;31mIndexError\u001b[0m: index 18 is out of bounds for axis 0 with size 18" ] diff --git a/notebooks/products/credit/FINCDSCURVE_BuildingASurvivalCurve.ipynb b/notebooks/products/credit/FINCDSCURVE_BuildingASurvivalCurve.ipynb index 239eefa3..04d57e89 100644 --- a/notebooks/products/credit/FINCDSCURVE_BuildingASurvivalCurve.ipynb +++ b/notebooks/products/credit/FINCDSCURVE_BuildingASurvivalCurve.ipynb @@ -79,19 +79,19 @@ "depo5 = IborDeposit(settle_dt, \"12M\", 0.019930, dcType)\n", "depos = [depo1,depo2,depo3,depo4,depo5]\n", "\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swap1 = IborSwap(settle_dt,\"2Y\",swapType,0.015910,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\",swapType,0.014990,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\",swapType,0.014725,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\",swapType,0.014640,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\",swapType,0.014800,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\",swapType,0.014995,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\",swapType,0.015180,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\",swapType,0.015610,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\",swapType,0.0159880,fixedFreq,dcType)\n", - "swap10 = IborSwap(settle_dt,\"12Y\",swapType,0.016430,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"2Y\",swap_type,0.015910,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\",swap_type,0.014990,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\",swap_type,0.014725,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\",swap_type,0.014640,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\",swap_type,0.014800,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\",swap_type,0.014995,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\",swap_type,0.015180,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\",swap_type,0.015610,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\",swap_type,0.0159880,fixedFreq,dcType)\n", + "swap10 = IborSwap(settle_dt,\"12Y\",swap_type,0.016430,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9,swap10]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" diff --git a/notebooks/products/credit/FINCDSINDEXOPTION_CompareValuationApproaches.ipynb b/notebooks/products/credit/FINCDSINDEXOPTION_CompareValuationApproaches.ipynb index 3237dba3..f3186932 100644 --- a/notebooks/products/credit/FINCDSINDEXOPTION_CompareValuationApproaches.ipynb +++ b/notebooks/products/credit/FINCDSINDEXOPTION_CompareValuationApproaches.ipynb @@ -55,9 +55,9 @@ "outputs": [], "source": [ "value_dt = Date(1, 8, 2007)\n", - "step_in_date = value_dt.add_weekdays(0)\n", - "value_dt = step_in_date\n", - "settle_dt = step_in_date" + "step_in_dt = value_dt.add_weekdays(0)\n", + "value_dt = step_in_dt\n", + "settle_dt = step_in_dt" ] }, { @@ -78,12 +78,12 @@ "depo = IborDeposit(settle_dt, \"1D\", 0.0500, dcType); depos.append(depo)\n", "\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"2Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"3Y\",swapType,0.0501,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"4Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"5Y\",swapType,0.0501,fixedFreq,dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"2Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"3Y\",swap_type,0.0501,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"4Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"5Y\",swap_type,0.0501,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -95,10 +95,10 @@ "metadata": {}, "outputs": [], "source": [ - "cdsMaturity3Y = value_dt.next_cds_date(36)\n", - "cdsMaturity5Y = value_dt.next_cds_date(60)\n", - "cdsMaturity7Y = value_dt.next_cds_date(84)\n", - "cdsMaturity10Y = value_dt.next_cds_date(120)" + "cdsMaturity3Y = value_dt.next_cds_dt(36)\n", + "cdsMaturity5Y = value_dt.next_cds_dt(60)\n", + "cdsMaturity7Y = value_dt.next_cds_dt(84)\n", + "cdsMaturity10Y = value_dt.next_cds_dt(120)" ] }, { @@ -129,10 +129,10 @@ " spd10Y = float(splitRow[4]) / 10000.0\n", " recovery_rate = float(splitRow[5])\n", "\n", - " cds3Y = CDS(step_in_date, cdsMaturity3Y, spd3Y)\n", - " cds5Y = CDS(step_in_date, cdsMaturity5Y, spd5Y)\n", - " cds7Y = CDS(step_in_date, cdsMaturity7Y, spd7Y)\n", - " cds10Y = CDS(step_in_date, cdsMaturity10Y, spd10Y)\n", + " cds3Y = CDS(step_in_dt, cdsMaturity3Y, spd3Y)\n", + " cds5Y = CDS(step_in_dt, cdsMaturity5Y, spd5Y)\n", + " cds7Y = CDS(step_in_dt, cdsMaturity7Y, spd7Y)\n", + " cds10Y = CDS(step_in_dt, cdsMaturity10Y, spd10Y)\n", " cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n", "\n", " issuer_curve = CDSCurve(value_dt, cds_contracts, libor_curve, recovery_rate)\n", @@ -196,7 +196,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1,2,2008)\n", + "expiry_dt = Date(1,2,2008)\n", "maturity_dt = Date(20,12,2011)\n", "notional = 10000\n", "volatility = 0.50\n", @@ -250,7 +250,7 @@ "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mFinError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32mc:\\Users\\Dominic\\Dropbox\\Desktop\\RESEARCH_DB\\FinancePy\\Code\\financepy-git\\notebooks\\products\\credit\\FINCDSINDEXOPTION_CompareValuationApproaches.ipynb Cell 19\u001b[0m line \u001b[0;36m1\n\u001b[0;32m 15\u001b[0m indexSpreads \u001b[39m=\u001b[39m [index \u001b[39m/\u001b[39m \u001b[39m10000.0\u001b[39m] \u001b[39m*\u001b[39m \u001b[39m4\u001b[39m\n\u001b[0;32m 17\u001b[0m indexPortfolio \u001b[39m=\u001b[39m CDSIndexPortfolio()\n\u001b[1;32m---> 18\u001b[0m adjustedIssuerCurves \u001b[39m=\u001b[39m indexPortfolio\u001b[39m.\u001b[39;49mhazard_rate_adjust_intrinsic(value_dt, \n\u001b[0;32m 19\u001b[0m issuer_curves, \n\u001b[0;32m 20\u001b[0m indexSpreads, \n\u001b[0;32m 21\u001b[0m index_upfronts,\n\u001b[0;32m 22\u001b[0m index_maturity_dts, \n\u001b[0;32m 23\u001b[0m index_recovery, \n\u001b[0;32m 24\u001b[0m tolerance) \n\u001b[0;32m 26\u001b[0m \u001b[39mfor\u001b[39;00m strike \u001b[39min\u001b[39;00m np\u001b[39m.\u001b[39mlinspace(\u001b[39m20\u001b[39m, \u001b[39m60\u001b[39m, \u001b[39m5\u001b[39m): \n\u001b[0;32m 28\u001b[0m option \u001b[39m=\u001b[39m CDSIndexOption(expiry_date,\n\u001b[0;32m 29\u001b[0m maturity_dt, \n\u001b[0;32m 30\u001b[0m index_coupon, \n\u001b[0;32m 31\u001b[0m strike \u001b[39m/\u001b[39m \u001b[39m10000.0\u001b[39m, \n\u001b[0;32m 32\u001b[0m notional)\n", + "\u001b[1;32mc:\\Users\\Dominic\\Dropbox\\Desktop\\RESEARCH_DB\\FinancePy\\Code\\financepy-git\\notebooks\\products\\credit\\FINCDSINDEXOPTION_CompareValuationApproaches.ipynb Cell 19\u001b[0m line \u001b[0;36m1\n\u001b[0;32m 15\u001b[0m indexSpreads \u001b[39m=\u001b[39m [index \u001b[39m/\u001b[39m \u001b[39m10000.0\u001b[39m] \u001b[39m*\u001b[39m \u001b[39m4\u001b[39m\n\u001b[0;32m 17\u001b[0m indexPortfolio \u001b[39m=\u001b[39m CDSIndexPortfolio()\n\u001b[1;32m---> 18\u001b[0m adjustedIssuerCurves \u001b[39m=\u001b[39m indexPortfolio\u001b[39m.\u001b[39;49mhazard_rate_adjust_intrinsic(value_dt, \n\u001b[0;32m 19\u001b[0m issuer_curves, \n\u001b[0;32m 20\u001b[0m indexSpreads, \n\u001b[0;32m 21\u001b[0m index_upfronts,\n\u001b[0;32m 22\u001b[0m index_maturity_dts, \n\u001b[0;32m 23\u001b[0m index_recovery, \n\u001b[0;32m 24\u001b[0m tolerance) \n\u001b[0;32m 26\u001b[0m \u001b[39mfor\u001b[39;00m strike \u001b[39min\u001b[39;00m np\u001b[39m.\u001b[39mlinspace(\u001b[39m20\u001b[39m, \u001b[39m60\u001b[39m, \u001b[39m5\u001b[39m): \n\u001b[0;32m 28\u001b[0m option \u001b[39m=\u001b[39m CDSIndexOption(expiry_dt,\n\u001b[0;32m 29\u001b[0m maturity_dt, \n\u001b[0;32m 30\u001b[0m index_coupon, \n\u001b[0;32m 31\u001b[0m strike \u001b[39m/\u001b[39m \u001b[39m10000.0\u001b[39m, \n\u001b[0;32m 32\u001b[0m notional)\n", "File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python310\\site-packages\\financepy\\products\\credit\\cds_index_portfolio.py:449\u001b[0m, in \u001b[0;36mCDSIndexPortfolio.hazard_rate_adjust_intrinsic\u001b[1;34m(self, value_dt, issuer_curves, index_cpns, index_up_fronts, index_maturity_dts, index_recovery_rate, tolerance, max_iterations)\u001b[0m\n\u001b[0;32m 446\u001b[0m numIterations \u001b[39m+\u001b[39m\u001b[39m=\u001b[39m \u001b[39m1\u001b[39m\n\u001b[0;32m 448\u001b[0m \u001b[39mif\u001b[39;00m numIterations \u001b[39m>\u001b[39m max_iterations:\n\u001b[1;32m--> 449\u001b[0m \u001b[39mraise\u001b[39;00m FinError(\u001b[39m\"\u001b[39m\u001b[39mMax Iterations exceeded\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[0;32m 451\u001b[0m sumRPV01 \u001b[39m=\u001b[39m \u001b[39m0.0\u001b[39m\n\u001b[0;32m 452\u001b[0m sumProt \u001b[39m=\u001b[39m \u001b[39m0.0\u001b[39m\n", "\u001b[1;31mFinError\u001b[0m: Max Iterations exceeded" ] @@ -284,7 +284,7 @@ " \n", " for strike in np.linspace(20, 60, 5): \n", "\n", - " option = CDSIndexOption(expiry_date,\n", + " option = CDSIndexOption(expiry_dt,\n", " maturity_dt, \n", " index_coupon, \n", " strike / 10000.0, \n", diff --git a/notebooks/products/credit/FINCDSINDEX_ValuingCDSIndex.ipynb b/notebooks/products/credit/FINCDSINDEX_ValuingCDSIndex.ipynb index bc9281d0..7440474f 100644 --- a/notebooks/products/credit/FINCDSINDEX_ValuingCDSIndex.ipynb +++ b/notebooks/products/credit/FINCDSINDEX_ValuingCDSIndex.ipynb @@ -90,12 +90,12 @@ "depos = []\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"2Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"3Y\",swapType,0.0501,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"4Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"5Y\",swapType,0.0501,fixedFreq,dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"2Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"3Y\",swap_type,0.0501,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"4Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"5Y\",swap_type,0.0501,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -121,7 +121,7 @@ "metadata": {}, "outputs": [], "source": [ - "step_in_date = value_dt" + "step_in_dt = value_dt" ] }, { @@ -166,7 +166,7 @@ "long_protection = True\n", "index_coupon = 0.004 \n", "\n", - "cdsIndexContract = CDS(step_in_date, maturity_dt, index_coupon, notional, long_protection)" + "cdsIndexContract = CDS(step_in_dt, maturity_dt, index_coupon, notional, long_protection)" ] }, { @@ -261,7 +261,7 @@ } ], "source": [ - "prot_pv = cdsIndexContract.protection_leg_pv(value_dt, index_curve, cdsRecovery)\n", + "prot_pv = cdsIndexContract.prot_leg_pv(value_dt, index_curve, cdsRecovery)\n", "print(\"PROTECTION LEG PV\", prot_pv)" ] }, diff --git a/notebooks/products/credit/FINCDSOPTION_ValuingCDSOption.ipynb b/notebooks/products/credit/FINCDSOPTION_ValuingCDSOption.ipynb index 705f04cc..b66b79e1 100644 --- a/notebooks/products/credit/FINCDSOPTION_ValuingCDSOption.ipynb +++ b/notebooks/products/credit/FINCDSOPTION_ValuingCDSOption.ipynb @@ -82,12 +82,12 @@ "depo = IborDeposit(settle_dt, \"1D\", 0.0502, dcType)\n", "depos = [depo]\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"2Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"3Y\",swapType,0.0501,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"4Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"5Y\",swapType,0.0501,fixedFreq,dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"2Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"3Y\",swap_type,0.0501,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"4Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"5Y\",swap_type,0.0501,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -165,8 +165,8 @@ "metadata": {}, "outputs": [], "source": [ - "step_in_date = value_dt.add_days(1)\n", - "expiry_date = Date(20, 3, 2014)\n", + "step_in_dt = value_dt.add_days(1)\n", + "expiry_dt = Date(20, 3, 2014)\n", "maturity_dt = Date(20, 6, 2019) " ] }, @@ -194,13 +194,13 @@ "\n", "# Long Protection\n", "for strike in strikes:\n", - " cdsOption = CDSOption(expiry_date, maturity_dt, strike, notional, True)\n", + " cdsOption = CDSOption(expiry_dt, maturity_dt, strike, notional, True)\n", " v = cdsOption.value(value_dt, issuer_curve, volatility)\n", " longValues.append(v)\n", " \n", "# Short Protection\n", "for strike in strikes:\n", - " cdsOption = CDSOption(expiry_date, maturity_dt, strike, notional, False)\n", + " cdsOption = CDSOption(expiry_dt, maturity_dt, strike, notional, False)\n", " v = cdsOption.value(value_dt, issuer_curve, volatility)\n", " shortValues.append(v)\n", " " @@ -253,7 +253,7 @@ "fwdValues = []\n", "\n", "for strike in strikes:\n", - " fwdCDSContract = CDS(expiry_date, maturity_dt, strike, notional, True)\n", + " fwdCDSContract = CDS(expiry_dt, maturity_dt, strike, notional, True)\n", " v = fwdCDSContract.value(value_dt, issuer_curve, recovery_rate)\n", " fwdValues.append(v['dirty_pv'])" ] @@ -340,7 +340,7 @@ ], "source": [ "for strike in np.linspace(100, 200, 21):\n", - " cdsOption = CDSOption(expiry_date, maturity_dt, strike / 10000.0, notional, False)\n", + " cdsOption = CDSOption(expiry_dt, maturity_dt, strike / 10000.0, notional, False)\n", " v = cdsOption.value(value_dt, issuer_curve, volatility)\n", " vol = cdsOption.implied_volatility(value_dt, issuer_curve, v)\n", " print(\"%10d %12.5f %12.8f%%\" %(strike, v, vol*100))" diff --git a/notebooks/products/credit/FINCDSTRANCHE_CalculatingFairSpread.ipynb b/notebooks/products/credit/FINCDSTRANCHE_CalculatingFairSpread.ipynb index d951b35c..bdcc6e65 100644 --- a/notebooks/products/credit/FINCDSTRANCHE_CalculatingFairSpread.ipynb +++ b/notebooks/products/credit/FINCDSTRANCHE_CalculatingFairSpread.ipynb @@ -77,12 +77,12 @@ "depo = IborDeposit(settle_dt, \"1D\", 0.0500, dcType); depos.append(depo)\n", "\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", - "swap1 = IborSwap(settle_dt,\"1Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"2Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"3Y\",swapType,0.0501,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"4Y\",swapType,0.0502,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"5Y\",swapType,0.0501,fixedFreq,dcType)\n", + "swap_type = swap_types.PAY\n", + "swap1 = IborSwap(settle_dt,\"1Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"2Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"3Y\",swap_type,0.0501,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"4Y\",swap_type,0.0502,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"5Y\",swap_type,0.0501,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -108,7 +108,7 @@ "metadata": {}, "outputs": [], "source": [ - "step_in_date = value_dt.add_weekdays(1)" + "step_in_dt = value_dt.add_weekdays(1)" ] }, { @@ -117,10 +117,10 @@ "metadata": {}, "outputs": [], "source": [ - "maturity3Y = value_dt.next_cds_date(36)\n", - "maturity5Y = value_dt.next_cds_date(60)\n", - "maturity7Y = value_dt.next_cds_date(84)\n", - "maturity10Y = value_dt.next_cds_date(120)" + "maturity3Y = value_dt.next_cds_dt(36)\n", + "maturity5Y = value_dt.next_cds_dt(60)\n", + "maturity7Y = value_dt.next_cds_dt(84)\n", + "maturity10Y = value_dt.next_cds_dt(120)" ] }, { @@ -149,10 +149,10 @@ " spd7Y = float(splitRow[3]) / 10000.0\n", " spd10Y = float(splitRow[4]) / 10000.0\n", " recovery_rate = float(splitRow[5])\n", - " cds3Y = CDS(step_in_date, maturity3Y, spd3Y)\n", - " cds5Y = CDS(step_in_date, maturity5Y, spd5Y)\n", - " cds7Y = CDS(step_in_date, maturity7Y, spd7Y)\n", - " cds10Y = CDS(step_in_date, maturity10Y, spd10Y)\n", + " cds3Y = CDS(step_in_dt, maturity3Y, spd3Y)\n", + " cds5Y = CDS(step_in_dt, maturity5Y, spd5Y)\n", + " cds7Y = CDS(step_in_dt, maturity7Y, spd7Y)\n", + " cds10Y = CDS(step_in_dt, maturity10Y, spd10Y)\n", " cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n", " issuer_curve = CDSCurve(value_dt, cds_contracts, libor_curve, recovery_rate)\n", " heteroIssuerCurves.append(issuer_curve)" @@ -198,10 +198,10 @@ "metadata": {}, "outputs": [], "source": [ - "spd3Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity3Y, heteroIssuerCurves)\n", - "spd5Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity5Y, heteroIssuerCurves)\n", - "spd7Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity7Y, heteroIssuerCurves)\n", - "spd10Y = cdsIndex.intrinsic_spread(value_dt, step_in_date, maturity10Y, heteroIssuerCurves)" + "spd3Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity3Y, heteroIssuerCurves)\n", + "spd5Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity5Y, heteroIssuerCurves)\n", + "spd7Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity7Y, heteroIssuerCurves)\n", + "spd10Y = cdsIndex.intrinsic_spread(value_dt, step_in_dt, maturity10Y, heteroIssuerCurves)" ] }, { @@ -234,10 +234,10 @@ "outputs": [], "source": [ "for row in range(0,num_credits):\n", - " cds3Y = CDS(step_in_date, maturity3Y, spd3Y)\n", - " cds5Y = CDS(step_in_date, maturity5Y, spd5Y)\n", - " cds7Y = CDS(step_in_date, maturity7Y, spd7Y)\n", - " cds10Y = CDS(step_in_date, maturity10Y, spd10Y)\n", + " cds3Y = CDS(step_in_dt, maturity3Y, spd3Y)\n", + " cds5Y = CDS(step_in_dt, maturity5Y, spd5Y)\n", + " cds7Y = CDS(step_in_dt, maturity7Y, spd7Y)\n", + " cds10Y = CDS(step_in_dt, maturity10Y, spd10Y)\n", " cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n", " issuer_curve = CDSCurve(value_dt, cds_contracts, libor_curve, recovery_rate)\n", " homoIssuerCurves.append(issuer_curve)" @@ -461,3 +461,4 @@ "nbformat": 4, "nbformat_minor": 2 } +s \ No newline at end of file diff --git a/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModel.ipynb b/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModel.ipynb index c9dbb30c..67d7e77e 100644 --- a/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModel.ipynb +++ b/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModel.ipynb @@ -108,18 +108,18 @@ "depo5 = IborDeposit(settle_dt, \"12M\", 0.004449, dcType)\n", "depos = [depo1,depo2,depo3,depo4,depo5]\n", "\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swap1 = IborSwap(settle_dt,\"2Y\", swapType, 0.002155,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\", swapType, 0.002305,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\", swapType, 0.002665,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\", swapType, 0.003290,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\", swapType, 0.004025,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\", swapType, 0.004725,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\", swapType, 0.005430,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\", swapType, 0.006075,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\", swapType, 0.006640,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"2Y\", swap_type, 0.002155,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\", swap_type, 0.002305,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\", swap_type, 0.002665,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\", swap_type, 0.003290,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\", swap_type, 0.004025,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\", swap_type, 0.004725,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\", swap_type, 0.005430,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\", swap_type, 0.006075,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\", swap_type, 0.006640,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -394,13 +394,13 @@ "name": "stdout", "output_type": "stream", "text": [ - "PROTECTION_PV 47386.047104632395\n" + "prot_PV 47386.047104632395\n" ] } ], "source": [ - "prot_pv = cds_contract.protection_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", - "print(\"PROTECTION_PV\", prot_pv)" + "prot_pv = cds_contract.prot_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", + "print(\"prot_PV\", prot_pv)" ] }, { diff --git a/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModelV2.ipynb b/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModelV2.ipynb index 33f87d25..a691e8b6 100644 --- a/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModelV2.ipynb +++ b/notebooks/products/credit/FINCDS_ComparisonWithMarkitCDSModelV2.ipynb @@ -90,18 +90,18 @@ "depo5 = IborDeposit(settle_dt, \"12M\", 0.004449, dcType)\n", "depos = [depo1,depo2,depo3,depo4,depo5]\n", "\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swap1 = IborSwap(settle_dt,\"2Y\", swapType, 0.002155,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\", swapType, 0.002305,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\", swapType, 0.002665,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\", swapType, 0.003290,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\", swapType, 0.004025,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\", swapType, 0.004725,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\", swapType, 0.005430,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\", swapType, 0.006075,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\", swapType, 0.006640,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"2Y\", swap_type, 0.002155,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\", swap_type, 0.002305,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\", swap_type, 0.002665,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\", swap_type, 0.003290,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\", swap_type, 0.004025,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\", swap_type, 0.004725,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\", swap_type, 0.005430,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\", swap_type, 0.006075,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\", swap_type, 0.006640,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -496,13 +496,13 @@ "name": "stdout", "output_type": "stream", "text": [ - "PROTECTION_PV 49789.06933833722\n" + "prot_PV 49789.06933833722\n" ] } ], "source": [ - "prot_pv = cds_contract.protection_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", - "print(\"PROTECTION_PV\", prot_pv)" + "prot_pv = cds_contract.prot_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", + "print(\"prot_PV\", prot_pv)" ] }, { diff --git a/notebooks/products/credit/FINCDS_CreatingAndValuingACDS.ipynb b/notebooks/products/credit/FINCDS_CreatingAndValuingACDS.ipynb index e92e222b..dd4489f1 100644 --- a/notebooks/products/credit/FINCDS_CreatingAndValuingACDS.ipynb +++ b/notebooks/products/credit/FINCDS_CreatingAndValuingACDS.ipynb @@ -111,18 +111,18 @@ "\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "\n", - "swap1 = IborSwap(settle_dt,\"2Y\",swapType,0.015910,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\",swapType,0.014990,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\",swapType,0.014725,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\",swapType,0.014640,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\",swapType,0.014800,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\",swapType,0.014995,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\",swapType,0.015180,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\",swapType,0.015610,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\",swapType,0.0159880,fixedFreq,dcType)\n", - "swap10 = IborSwap(settle_dt,\"12Y\",swapType,0.016430,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"2Y\",swap_type,0.015910,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\",swap_type,0.014990,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\",swap_type,0.014725,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\",swap_type,0.014640,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\",swap_type,0.014800,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\",swap_type,0.014995,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\",swap_type,0.015180,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\",swap_type,0.015610,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\",swap_type,0.0159880,fixedFreq,dcType)\n", + "swap10 = IborSwap(settle_dt,\"12Y\",swap_type,0.016430,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9,swap10]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -331,13 +331,13 @@ "name": "stdout", "output_type": "stream", "text": [ - "PROTECTION_PV 228726.9467424124\n" + "prot_PV 228726.9467424124\n" ] } ], "source": [ - "prot_pv = cds_contract.protection_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", - "print(\"PROTECTION_PV\", prot_pv)" + "prot_pv = cds_contract.prot_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", + "print(\"prot_PV\", prot_pv)" ] }, { diff --git a/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkit.ipynb b/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkit.ipynb index 223ac4b9..f7d66af5 100644 --- a/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkit.ipynb +++ b/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkit.ipynb @@ -156,19 +156,19 @@ "depo5 = IborDeposit(settle_dt, \"12M\", 0.019093, dcType)\n", "depos = [depo1,depo2,depo3,depo4,depo5]\n", "\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swap1 = IborSwap(settle_dt,\"2Y\",swapType,0.015630,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\",swapType,0.015140,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\",swapType,0.015065,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\",swapType,0.015140,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\",swapType,0.015270,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\",swapType,0.015470,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\",swapType,0.015720,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\",swapType,0.016000,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\",swapType,0.016285,fixedFreq,dcType)\n", - "swap10 = IborSwap(settle_dt,\"12Y\",swapType,0.01670,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"2Y\",swap_type,0.015630,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\",swap_type,0.015140,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\",swap_type,0.015065,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\",swap_type,0.015140,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\",swap_type,0.015270,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\",swap_type,0.015470,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\",swap_type,0.015720,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\",swap_type,0.016000,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\",swap_type,0.016285,fixedFreq,dcType)\n", + "swap10 = IborSwap(settle_dt,\"12Y\",swap_type,0.01670,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9,swap10]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -372,13 +372,13 @@ "name": "stdout", "output_type": "stream", "text": [ - "PROTECTION_PV 47449.85309441838\n" + "prot_PV 47449.85309441838\n" ] } ], "source": [ - "prot_pv = cds_contract.protection_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", - "print(\"PROTECTION_PV\", prot_pv)" + "prot_pv = cds_contract.prot_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", + "print(\"prot_PV\", prot_pv)" ] }, { diff --git a/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkitV2.ipynb b/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkitV2.ipynb index a2d024e2..e0c890a9 100644 --- a/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkitV2.ipynb +++ b/notebooks/products/credit/FINCDS_ValuingCDSCompareToMarkitV2.ipynb @@ -161,19 +161,19 @@ "depo5 = IborDeposit(settle_dt, \"12M\", 0.019093, dcType)\n", "depos = [depo1,depo2,depo3,depo4,depo5]\n", "\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swap1 = IborSwap(settle_dt,\"2Y\",swapType,0.015630,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\",swapType,0.015140,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\",swapType,0.015065,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\",swapType,0.015140,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\",swapType,0.015270,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\",swapType,0.015470,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\",swapType,0.015720,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\",swapType,0.016000,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\",swapType,0.016285,fixedFreq,dcType)\n", - "swap10 = IborSwap(settle_dt,\"12Y\",swapType,0.01670,fixedFreq,dcType)\n", + "swap1 = IborSwap(settle_dt,\"2Y\",swap_type,0.015630,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\",swap_type,0.015140,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\",swap_type,0.015065,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\",swap_type,0.015140,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\",swap_type,0.015270,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\",swap_type,0.015470,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\",swap_type,0.015720,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\",swap_type,0.016000,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\",swap_type,0.016285,fixedFreq,dcType)\n", + "swap10 = IborSwap(settle_dt,\"12Y\",swap_type,0.01670,fixedFreq,dcType)\n", "swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9,swap10]\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" @@ -383,13 +383,13 @@ "name": "stdout", "output_type": "stream", "text": [ - "PROTECTION_PV 47449.85309441838\n" + "prot_PV 47449.85309441838\n" ] } ], "source": [ - "prot_pv = cds_contract.protection_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", - "print(\"PROTECTION_PV\", prot_pv)" + "prot_pv = cds_contract.prot_leg_pv(settle_dt, issuer_curve, recovery_rate)\n", + "print(\"prot_PV\", prot_pv)" ] }, { diff --git a/notebooks/products/equity/EQUITY_AMERICANOPTION_BJERKSUND_STENSLAND_APPROX.ipynb b/notebooks/products/equity/EQUITY_AMERICANOPTION_BJERKSUND_STENSLAND_APPROX.ipynb index 3167d53c..85077f9f 100644 --- a/notebooks/products/equity/EQUITY_AMERICANOPTION_BJERKSUND_STENSLAND_APPROX.ipynb +++ b/notebooks/products/equity/EQUITY_AMERICANOPTION_BJERKSUND_STENSLAND_APPROX.ipynb @@ -73,7 +73,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(7, 5, 2018)" + "expiry_dt = Date(7, 5, 2018)" ] }, { @@ -113,7 +113,7 @@ } ], "source": [ - "amCallOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.AMERICAN_CALL)\n", + "amCallOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_CALL)\n", "amCallOption" ] }, @@ -147,7 +147,7 @@ } ], "source": [ - "euCallOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)\n", + "euCallOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)\n", "euCallOption " ] }, @@ -179,7 +179,7 @@ } ], "source": [ - "amPutOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.AMERICAN_PUT)\n", + "amPutOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_PUT)\n", "amPutOption" ] }, @@ -204,7 +204,7 @@ } ], "source": [ - "euPutOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.EUROPEAN_PUT)\n", + "euPutOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT)\n", "euPutOption" ] }, diff --git a/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample.ipynb b/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample.ipynb index f7a2fe82..1670b41b 100644 --- a/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample.ipynb +++ b/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample.ipynb @@ -100,7 +100,7 @@ }, "outputs": [], "source": [ - "expiry_date = Date(15, 1, 2016)" + "expiry_dt = Date(15, 1, 2016)" ] }, { @@ -139,7 +139,7 @@ }, "outputs": [], "source": [ - "amCallOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.AMERICAN_CALL)" + "amCallOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_CALL)" ] }, { @@ -190,7 +190,7 @@ }, "outputs": [], "source": [ - "euCallOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "euCallOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -241,7 +241,7 @@ }, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { diff --git a/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample_CHECK.ipynb b/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample_CHECK.ipynb index 24c57ecc..dbbecb6d 100644 --- a/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample_CHECK.ipynb +++ b/notebooks/products/equity/EQUITY_AMERICANOPTION_ComparisonWithQLExample_CHECK.ipynb @@ -72,7 +72,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(15, 1, 2016)" + "expiry_dt = Date(15, 1, 2016)" ] }, { @@ -97,7 +97,7 @@ "metadata": {}, "outputs": [], "source": [ - "amCallOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.AMERICAN_CALL)" + "amCallOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_CALL)" ] }, { @@ -134,7 +134,7 @@ "metadata": {}, "outputs": [], "source": [ - "euCallOption = EquityAmericanOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "euCallOption = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -171,7 +171,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { diff --git a/notebooks/products/equity/EQUITY_ASIAN_OPTIONS.ipynb b/notebooks/products/equity/EQUITY_ASIAN_OPTIONS.ipynb index f8fcfeae..53ff6fca 100644 --- a/notebooks/products/equity/EQUITY_ASIAN_OPTIONS.ipynb +++ b/notebooks/products/equity/EQUITY_ASIAN_OPTIONS.ipynb @@ -70,7 +70,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 1, 2021)" + "expiry_dt = Date(1, 1, 2021)" ] }, { @@ -95,7 +95,7 @@ "metadata": {}, "outputs": [], "source": [ - "num_observations = int(expiry_date - startAveragingDate)" + "num_observations = int(expiry_dt - startAveragingDate)" ] }, { @@ -105,7 +105,7 @@ "outputs": [], "source": [ "asianOption = EquityAsianOption(startAveragingDate, \n", - " expiry_date, \n", + " expiry_dt, \n", " strike_price, \n", " OptionTypes.EUROPEAN_CALL, \n", " num_observations)" diff --git a/notebooks/products/equity/EQUITY_BASKET_OPTIONS.ipynb b/notebooks/products/equity/EQUITY_BASKET_OPTIONS.ipynb index 04d3736e..a90c92f3 100644 --- a/notebooks/products/equity/EQUITY_BASKET_OPTIONS.ipynb +++ b/notebooks/products/equity/EQUITY_BASKET_OPTIONS.ipynb @@ -77,7 +77,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 1, 2021)" + "expiry_dt = Date(1, 1, 2021)" ] }, { @@ -95,7 +95,7 @@ "metadata": {}, "outputs": [], "source": [ - "basketCallOption = EquityBasketOption(expiry_date, strike_price, \n", + "basketCallOption = EquityBasketOption(expiry_dt, strike_price, \n", " OptionTypes.EUROPEAN_CALL, num_assets)" ] }, @@ -105,7 +105,7 @@ "metadata": {}, "outputs": [], "source": [ - "basketPutOption = EquityBasketOption(expiry_date, strike_price, \n", + "basketPutOption = EquityBasketOption(expiry_dt, strike_price, \n", " OptionTypes.EUROPEAN_PUT, num_assets)" ] }, diff --git a/notebooks/products/equity/EQUITY_CHOOSER_OPTION.ipynb b/notebooks/products/equity/EQUITY_CHOOSER_OPTION.ipynb index f32e2ecc..9a2cd5d5 100644 --- a/notebooks/products/equity/EQUITY_CHOOSER_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_CHOOSER_OPTION.ipynb @@ -77,8 +77,8 @@ "metadata": {}, "outputs": [], "source": [ - "call_expiry_date = Date(2, 12, 2007)\n", - "put_expiry_date = Date(2, 12, 2007) " + "call_expiry_dt = Date(2, 12, 2007)\n", + "put_expiry_dt = Date(2, 12, 2007) " ] }, { @@ -97,7 +97,7 @@ "metadata": {}, "outputs": [], "source": [ - "chooserOption = EquityChooserOption(chooseDate, call_expiry_date, put_expiry_date, call_strike, put_strike)" + "chooserOption = EquityChooserOption(chooseDate, call_expiry_dt, put_expiry_dt, call_strike, put_strike)" ] }, { diff --git a/notebooks/products/equity/EQUITY_CHOOSER_OPTION_ComparisonWithML.ipynb b/notebooks/products/equity/EQUITY_CHOOSER_OPTION_ComparisonWithML.ipynb index 326d370b..a0fcf03d 100644 --- a/notebooks/products/equity/EQUITY_CHOOSER_OPTION_ComparisonWithML.ipynb +++ b/notebooks/products/equity/EQUITY_CHOOSER_OPTION_ComparisonWithML.ipynb @@ -86,8 +86,8 @@ "metadata": {}, "outputs": [], "source": [ - "call_expiry_date = Date(2, 12, 2007)\n", - "put_expiry_date = Date(2, 12, 2007) " + "call_expiry_dt = Date(2, 12, 2007)\n", + "put_expiry_dt = Date(2, 12, 2007) " ] }, { @@ -106,7 +106,7 @@ "metadata": {}, "outputs": [], "source": [ - "chooserOption = EquityChooserOption(chooseDate, call_expiry_date, put_expiry_date, call_strike, put_strike)" + "chooserOption = EquityChooserOption(chooseDate, call_expiry_dt, put_expiry_dt, call_strike, put_strike)" ] }, { diff --git a/notebooks/products/equity/EQUITY_DIGITALOPTION_BasicValuation.ipynb b/notebooks/products/equity/EQUITY_DIGITALOPTION_BasicValuation.ipynb index 91625097..665602c7 100644 --- a/notebooks/products/equity/EQUITY_DIGITALOPTION_BasicValuation.ipynb +++ b/notebooks/products/equity/EQUITY_DIGITALOPTION_BasicValuation.ipynb @@ -77,7 +77,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 1, 2008)" + "expiry_dt = Date(1, 1, 2008)" ] }, { @@ -95,7 +95,7 @@ "metadata": {}, "outputs": [], "source": [ - "digitalCall = EquityDigitalOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL, underlying_type)" + "digitalCall = EquityDigitalOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL, underlying_type)" ] }, { @@ -104,7 +104,7 @@ "metadata": {}, "outputs": [], "source": [ - "digitalPut = EquityDigitalOption(expiry_date, strike_price, OptionTypes.EUROPEAN_PUT, underlying_type)" + "digitalPut = EquityDigitalOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT, underlying_type)" ] }, { diff --git a/notebooks/products/equity/EQUITY_DIGITAL_CASH_OR_NOTHING_OPTION.ipynb b/notebooks/products/equity/EQUITY_DIGITAL_CASH_OR_NOTHING_OPTION.ipynb index b9491681..91ce3c08 100644 --- a/notebooks/products/equity/EQUITY_DIGITAL_CASH_OR_NOTHING_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_DIGITAL_CASH_OR_NOTHING_OPTION.ipynb @@ -77,7 +77,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 10, 2008)" + "expiry_dt = Date(1, 10, 2008)" ] }, { @@ -95,7 +95,7 @@ "metadata": {}, "outputs": [], "source": [ - "digitalCall = EquityDigitalOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL, underlying_type)" + "digitalCall = EquityDigitalOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL, underlying_type)" ] }, { @@ -104,7 +104,7 @@ "metadata": {}, "outputs": [], "source": [ - "digitalPut = EquityDigitalOption(expiry_date, strike_price, OptionTypes.EUROPEAN_PUT, underlying_type)" + "digitalPut = EquityDigitalOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT, underlying_type)" ] }, { diff --git a/notebooks/products/equity/EQUITY_FIXED_LOOKBACK_OPTION.ipynb b/notebooks/products/equity/EQUITY_FIXED_LOOKBACK_OPTION.ipynb index 2764fab2..381160e1 100644 --- a/notebooks/products/equity/EQUITY_FIXED_LOOKBACK_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_FIXED_LOOKBACK_OPTION.ipynb @@ -69,7 +69,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 1, 2021)" + "expiry_dt = Date(1, 1, 2021)" ] }, { @@ -97,8 +97,8 @@ "metadata": {}, "outputs": [], "source": [ - "lookbackCall = EquityFixedLookbackOption(expiry_date, option_typeCall, strike_price)\n", - "lookbackPut = EquityFixedLookbackOption(expiry_date, option_typePut, strike_price)" + "lookbackCall = EquityFixedLookbackOption(expiry_dt, option_typeCall, strike_price)\n", + "lookbackPut = EquityFixedLookbackOption(expiry_dt, option_typePut, strike_price)" ] }, { diff --git a/notebooks/products/equity/EQUITY_FLOAT_LOOKBACK_OPTION.ipynb b/notebooks/products/equity/EQUITY_FLOAT_LOOKBACK_OPTION.ipynb index 9c35e410..9ff605af 100644 --- a/notebooks/products/equity/EQUITY_FLOAT_LOOKBACK_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_FLOAT_LOOKBACK_OPTION.ipynb @@ -68,7 +68,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 1, 2021)" + "expiry_dt = Date(1, 1, 2021)" ] }, { @@ -96,8 +96,8 @@ "metadata": {}, "outputs": [], "source": [ - "lookbackCall = EquityFloatLookbackOption(expiry_date, option_typeCall)\n", - "lookbackPut = EquityFloatLookbackOption(expiry_date, option_typePut)" + "lookbackCall = EquityFloatLookbackOption(expiry_dt, option_typeCall)\n", + "lookbackPut = EquityFloatLookbackOption(expiry_dt, option_typePut)" ] }, { diff --git a/notebooks/products/equity/EQUITY_ONE_TOUCH_OPTION.ipynb b/notebooks/products/equity/EQUITY_ONE_TOUCH_OPTION.ipynb index 1b187eea..6c29e0ad 100644 --- a/notebooks/products/equity/EQUITY_ONE_TOUCH_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_ONE_TOUCH_OPTION.ipynb @@ -98,7 +98,7 @@ "outputs": [], "source": [ "value_dt = Date(1, 1, 2016)\n", - "expiry_date = Date(2, 7, 2016)\n", + "expiry_dt = Date(2, 7, 2016)\n", "interest_rate = 0.10\n", "discount_curve = DiscountCurveFlat(value_dt, interest_rate)\n", "volatility = 0.20\n", @@ -176,7 +176,7 @@ "source": [ "print(\"%60s %12s %12s\" % (\"Option Type\", \"Analytical\", \"Monte Carlo\"))\n", "for downType in downTypes:\n", - " option = EquityOneTouchOption(expiry_date,downType,barrier_level,payment_size)\n", + " option = EquityOneTouchOption(expiry_dt,downType,barrier_level,payment_size)\n", " v = option.value(value_dt,stock_price,discount_curve,dividend_curve,model)\n", " v_mc = option.value_mc(value_dt,stock_price,discount_curve,dividend_curve,model)\n", " print(\"%60s %12.5f %12.5f\" % (downType, v, v_mc))" @@ -228,7 +228,7 @@ "source": [ "print(\"%60s %12s %12s\" % (\"Option Type\", \"Analytical\", \"Monte Carlo\"))\n", "for upType in upTypes:\n", - " option = EquityOneTouchOption(expiry_date,upType,barrier_level,payment_size)\n", + " option = EquityOneTouchOption(expiry_dt,upType,barrier_level,payment_size)\n", " v = option.value(value_dt,stock_price,discount_curve,dividend_curve,model)\n", " v_mc = option.value_mc(value_dt,stock_price,discount_curve,dividend_curve,model)\n", " print(\"%60s %12.5f %12.5f\" % (downType, v, v_mc))" @@ -278,7 +278,7 @@ ], "source": [ "for downType in downTypes:\n", - " option = EquityOneTouchOption(expiry_date, downType, barrier_level)\n", + " option = EquityOneTouchOption(expiry_dt, downType, barrier_level)\n", " v = option.value(value_dt, stock_price, discount_curve, dividend_curve, model)\n", " v_mc = option.value_mc(value_dt, stock_price, discount_curve, dividend_curve, model)\n", " print(\"%60s %9.5f %9.5f\" % (downType, v, v_mc))" @@ -321,7 +321,7 @@ ], "source": [ "for upType in upTypes:\n", - " option = EquityOneTouchOption(expiry_date, upType, barrier_level)\n", + " option = EquityOneTouchOption(expiry_dt, upType, barrier_level)\n", " v = option.value(value_dt, stock_price, discount_curve, dividend_curve, model)\n", " v_mc = option.value_mc(value_dt, stock_price, discount_curve, dividend_curve, model)\n", " print(\"%60s %9.5f %9.5f\" % (upType, v, v_mc))" diff --git a/notebooks/products/equity/EQUITY_RAINBOW_OPTION.ipynb b/notebooks/products/equity/EQUITY_RAINBOW_OPTION.ipynb index e3aa2d47..99000e6a 100644 --- a/notebooks/products/equity/EQUITY_RAINBOW_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_RAINBOW_OPTION.ipynb @@ -105,7 +105,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 1, 2016)" + "expiry_dt = Date(1, 1, 2016)" ] }, { @@ -151,8 +151,8 @@ "metadata": {}, "outputs": [], "source": [ - "callRainbowOption = EquityRainbowOption(expiry_date, callPayoffType, payoff_params, num_assets)\n", - "putRainbowOption = EquityRainbowOption(expiry_date, putPayoffType, payoff_params, num_assets)" + "callRainbowOption = EquityRainbowOption(expiry_dt, callPayoffType, payoff_params, num_assets)\n", + "putRainbowOption = EquityRainbowOption(expiry_dt, putPayoffType, payoff_params, num_assets)" ] }, { @@ -394,8 +394,8 @@ "metadata": {}, "outputs": [], "source": [ - "callRainbowOption = EquityRainbowOption(expiry_date, callPayoffType, payoff_params, num_assets)\n", - "putRainbowOption = EquityRainbowOption(expiry_date, putPayoffType, payoff_params, num_assets)" + "callRainbowOption = EquityRainbowOption(expiry_dt, callPayoffType, payoff_params, num_assets)\n", + "putRainbowOption = EquityRainbowOption(expiry_dt, putPayoffType, payoff_params, num_assets)" ] }, { @@ -605,7 +605,7 @@ "source": [ "for n in range(0, num_assets):\n", " payoff_params = [n+1, strike_price]\n", - " nthRainbowOption = EquityRainbowOption(expiry_date, payoff_type, payoff_params, num_assets)\n", + " nthRainbowOption = EquityRainbowOption(expiry_dt, payoff_type, payoff_params, num_assets)\n", " v_mc = nthRainbowOption.value_mc(value_dt, stock_prices, discount_curve, dividend_curves, volatilities, corr_matrix)\n", " print(n+1, v_mc)" ] @@ -647,7 +647,7 @@ "for n in range(0, num_assets):\n", " payoff_type = EquityRainbowOptionTypes.PUT_ON_NTH\n", " payoff_params = [n+1, strike_price]\n", - " nthRainbowOption = EquityRainbowOption(expiry_date, payoff_type, payoff_params, num_assets)\n", + " nthRainbowOption = EquityRainbowOption(expiry_dt, payoff_type, payoff_params, num_assets)\n", " v_mc = nthRainbowOption.value_mc(value_dt, stock_prices, discount_curve, dividend_curves, volatilities, corr_matrix)\n", " print(n+1, v_mc)" ] diff --git a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_SOBOL.ipynb b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_SOBOL.ipynb index 9bf49ade..1439611f 100644 --- a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_SOBOL.ipynb +++ b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_SOBOL.ipynb @@ -56,7 +56,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = value_dt.add_years(0.5)" + "expiry_dt = value_dt.add_years(0.5)" ] }, { @@ -76,7 +76,7 @@ } ], "source": [ - "expiry_date" + "expiry_dt" ] }, { @@ -94,7 +94,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { diff --git a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_TIMINGS.ipynb b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_TIMINGS.ipynb index c1fd014e..ce62bf03 100644 --- a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_TIMINGS.ipynb +++ b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_MONTE_CARLO_TIMINGS.ipynb @@ -72,7 +72,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 6, 2018)" + "expiry_dt = Date(1, 6, 2018)" ] }, { @@ -92,7 +92,7 @@ } ], "source": [ - "expiry_date" + "expiry_dt" ] }, { @@ -110,7 +110,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { diff --git a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION HIGH VOL LIMIT.ipynb b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION HIGH VOL LIMIT.ipynb index fd4c26e2..6cb7667b 100644 --- a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION HIGH VOL LIMIT.ipynb +++ b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION HIGH VOL LIMIT.ipynb @@ -56,7 +56,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = value_dt.add_years(0.5)" + "expiry_dt = value_dt.add_years(0.5)" ] }, { @@ -76,7 +76,7 @@ } ], "source": [ - "expiry_date" + "expiry_dt" ] }, { @@ -94,7 +94,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -103,7 +103,7 @@ "metadata": {}, "outputs": [], "source": [ - "put_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_PUT)" + "put_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT)" ] }, { diff --git a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION.ipynb b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION.ipynb index 63b19eb8..80aeb086 100644 --- a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION.ipynb +++ b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION.ipynb @@ -69,7 +69,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = value_dt.add_years(0.5)" + "expiry_dt = value_dt.add_years(0.5)" ] }, { @@ -89,7 +89,7 @@ } ], "source": [ - "expiry_date" + "expiry_dt" ] }, { @@ -107,7 +107,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -116,7 +116,7 @@ "metadata": {}, "outputs": [], "source": [ - "put_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_PUT)" + "put_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT)" ] }, { diff --git a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION_VECTORISATION.ipynb b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION_VECTORISATION.ipynb index 20058095..242d1a4f 100644 --- a/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION_VECTORISATION.ipynb +++ b/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION_VECTORISATION.ipynb @@ -147,7 +147,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(20, 6, 2020)" + "expiry_dt = Date(20, 6, 2020)" ] }, { @@ -165,7 +165,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -241,7 +241,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -317,7 +317,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_dates = value_dt.add_years(np.linspace(0.5,10,20))" + "expiry_dts = value_dt.add_years(np.linspace(0.5,10,20))" ] }, { @@ -356,7 +356,7 @@ } ], "source": [ - "expiry_dates" + "expiry_dts" ] }, { @@ -381,7 +381,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_dates, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dts, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -480,7 +480,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, option_types)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, option_types)" ] }, { diff --git a/notebooks/products/equity/EQUITY_VANILLA_OPTION_ValuationAndGreeks_ERROR.ipynb b/notebooks/products/equity/EQUITY_VANILLA_OPTION_ValuationAndGreeks_ERROR.ipynb index c49fe2a5..60a7d496 100644 --- a/notebooks/products/equity/EQUITY_VANILLA_OPTION_ValuationAndGreeks_ERROR.ipynb +++ b/notebooks/products/equity/EQUITY_VANILLA_OPTION_ValuationAndGreeks_ERROR.ipynb @@ -68,7 +68,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = Date(1, 6, 2021)\n", + "expiry_dt = Date(1, 6, 2021)\n", "strike_price = 100.0" ] }, @@ -85,7 +85,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_CALL)" + "call_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -115,7 +115,7 @@ "metadata": {}, "outputs": [], "source": [ - "put_option = EquityVanillaOption(expiry_date, strike_price, OptionTypes.EUROPEAN_PUT)" + "put_option = EquityVanillaOption(expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT)" ] }, { @@ -366,7 +366,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_options = EquityVanillaOption(expiry_date, strike_prices, OptionTypes.EUROPEAN_CALL)" + "call_options = EquityVanillaOption(expiry_dt, strike_prices, OptionTypes.EUROPEAN_CALL)" ] }, { @@ -462,7 +462,7 @@ "metadata": {}, "outputs": [], "source": [ - "put_options = EquityVanillaOption(expiry_date, strike_prices, OptionTypes.EUROPEAN_PUT)" + "put_options = EquityVanillaOption(expiry_dt, strike_prices, OptionTypes.EUROPEAN_PUT)" ] }, { diff --git a/notebooks/products/fx/FXOneTouchOption.ipynb b/notebooks/products/fx/FXOneTouchOption.ipynb index c2f84c6a..b842ce62 100644 --- a/notebooks/products/fx/FXOneTouchOption.ipynb +++ b/notebooks/products/fx/FXOneTouchOption.ipynb @@ -89,8 +89,8 @@ "metadata": {}, "outputs": [], "source": [ - "dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate)\n", - "for_discount_curve = DiscountCurveFlat(value_dt, forCCRate)" + "domestic_curve = DiscountCurveFlat(value_dt, domCCRate)\n", + "foreign_curve = DiscountCurveFlat(value_dt, forCCRate)" ] }, { @@ -109,7 +109,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = value_dt.add_tenor(\"1Y\")" + "expiry_dt = value_dt.add_tenor(\"1Y\")" ] }, { @@ -134,7 +134,7 @@ "metadata": {}, "outputs": [], "source": [ - "one_touch = FXOneTouchOption(expiry_date, TouchOptionTypes.DOWN_AND_IN_ASSET_AT_EXPIRY, 1.0)" + "one_touch = FXOneTouchOption(expiry_dt, TouchOptionTypes.DOWN_AND_IN_ASSET_AT_EXPIRY, 1.0)" ] }, { @@ -226,7 +226,7 @@ } ], "source": [ - "v = one_touch.value(value_dt, spot_fx_rate, dom_discount_curve, for_discount_curve, model)" + "v = one_touch.value(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model)" ] }, { @@ -345,7 +345,7 @@ "v_mc = []\n", "\n", "for s in spot_fx_rate:\n", - " v = one_touch.value_mc(value_dt, s, dom_discount_curve, for_discount_curve, model)\n", + " v = one_touch.value_mc(value_dt, s, domestic_curve, foreign_curve, model)\n", " v_mc.append(v)\n", " \n", "len(v_mc)" diff --git a/notebooks/products/fx/FXOptionAnalysisAndDeltas.ipynb b/notebooks/products/fx/FXOptionAnalysisAndDeltas.ipynb index aeac79de..acf56e54 100644 --- a/notebooks/products/fx/FXOptionAnalysisAndDeltas.ipynb +++ b/notebooks/products/fx/FXOptionAnalysisAndDeltas.ipynb @@ -77,8 +77,8 @@ "metadata": {}, "outputs": [], "source": [ - "dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate)\n", - "for_discount_curve = DiscountCurveFlat(value_dt, forCCRate)" + "domestic_curve = DiscountCurveFlat(value_dt, domCCRate)\n", + "foreign_curve = DiscountCurveFlat(value_dt, forCCRate)" ] }, { @@ -97,7 +97,7 @@ "metadata": {}, "outputs": [], "source": [ - "expiry_date = value_dt.add_tenor(\"1Y\")" + "expiry_dt = value_dt.add_tenor(\"1Y\")" ] }, { @@ -122,7 +122,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_option = FXVanillaOption(expiry_date, strike_price, currency_pair, OptionTypes.EUROPEAN_CALL, 1.0, \"EUR\")" + "call_option = FXVanillaOption(expiry_dt, strike_price, currency_pair, OptionTypes.EUROPEAN_CALL, 1.0, \"EUR\")" ] }, { @@ -209,7 +209,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_value = call_option.value(value_dt, spot_fx_rate, dom_discount_curve, for_discount_curve, model)" + "call_value = call_option.value(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model)" ] }, { @@ -261,7 +261,7 @@ "metadata": {}, "outputs": [], "source": [ - "deltaValue = call_option.delta(value_dt, spot_fx_rate, dom_discount_curve, for_discount_curve, model)" + "deltaValue = call_option.delta(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model)" ] }, { @@ -338,7 +338,7 @@ "source": [ "volatilities = np.linspace(0.01,10,100)\n", "models = BlackScholes(volatilities)\n", - "values = call_option.value(value_dt, spot_fx_rate, dom_discount_curve, for_discount_curve, models)" + "values = call_option.value(value_dt, spot_fx_rate, domestic_curve, foreign_curve, models)" ] }, { @@ -402,7 +402,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_options = FXVanillaOption(expiry_date, strike_prices, currency_pair, OptionTypes.EUROPEAN_CALL, 1.0, \"EUR\")" + "call_options = FXVanillaOption(expiry_dt, strike_prices, currency_pair, OptionTypes.EUROPEAN_CALL, 1.0, \"EUR\")" ] }, { @@ -425,7 +425,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_values = call_options.value(value_dt, spot_fx_rate, dom_discount_curve, for_discount_curve, model)" + "call_values = call_options.value(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model)" ] }, { @@ -480,7 +480,7 @@ "metadata": {}, "outputs": [], "source": [ - "call_options = FXVanillaOption(expiry_date, strike_prices, currency_pair, OptionTypes.EUROPEAN_CALL, 1.0, \"EUR\")" + "call_options = FXVanillaOption(expiry_dt, strike_prices, currency_pair, OptionTypes.EUROPEAN_CALL, 1.0, \"EUR\")" ] }, { @@ -489,7 +489,7 @@ "metadata": {}, "outputs": [], "source": [ - "deltaValues = call_options.delta(value_dt, spot_fx_rate, dom_discount_curve, for_discount_curve, model)" + "deltaValues = call_options.delta(value_dt, spot_fx_rate, domestic_curve, foreign_curve, model)" ] }, { diff --git a/notebooks/products/rates/FINIBORBERMUDANSWAPTION_All_Valuation_Models.ipynb b/notebooks/products/rates/FINIBORBERMUDANSWAPTION_All_Valuation_Models.ipynb index b6f91254..8d89d85b 100644 --- a/notebooks/products/rates/FINIBORBERMUDANSWAPTION_All_Valuation_Models.ipynb +++ b/notebooks/products/rates/FINIBORBERMUDANSWAPTION_All_Valuation_Models.ipynb @@ -124,7 +124,7 @@ "swap_fixed_coupon = 0.060\n", "swap_fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "swapFixedDayCountType = DayCountTypes.ACT_365F\n", - "swapType = SwapTypes.PAY " + "swap_type = swap_types.PAY " ] }, { @@ -142,7 +142,7 @@ "source": [ "swap = IborSwap(exercise_dt,\n", " swap_maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", " swapFixedDayCountType)" @@ -285,7 +285,7 @@ "europeanSwaptionPay = IborSwaption(settle_dt,\n", " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.PAY,\n", + " swap_types.PAY,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", " swapFixedDayCountType)" @@ -300,7 +300,7 @@ "europeanSwaptionRec = IborSwaption(settle_dt,\n", " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.RECEIVE,\n", + " swap_types.RECEIVE,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", " swapFixedDayCountType)" @@ -317,7 +317,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 01-JAN-2011\n", "EXERCISE DATE: 01-JAN-2012\n", - "SWAP FIXED LEG TYPE: SwapTypes.PAY\n", + "SWAP FIXED LEG TYPE: swap_types.PAY\n", "SWAP MATURITY DATE: 01-JAN-2015\n", "SWAP NOTIONAL: 1000000\n", "FIXED COUPON: 6.0\n", @@ -708,7 +708,7 @@ "europeanBermSwaptionPay = IborBermudanSwaption(settle_dt,\n", " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.PAY,\n", + " swap_types.PAY,\n", " FinExerciseTypes.EUROPEAN,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", @@ -724,7 +724,7 @@ "europeanBermSwaptionRec = IborBermudanSwaption(settle_dt,\n", " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.RECEIVE,\n", + " swap_types.RECEIVE,\n", " FinExerciseTypes.EUROPEAN,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", @@ -751,7 +751,7 @@ "metadata": {}, "outputs": [], "source": [ - "blackVol = 0.0000001" + "black_vol = 0.0000001" ] }, { @@ -760,7 +760,7 @@ "metadata": {}, "outputs": [], "source": [ - "sigma = blackVol\n", + "sigma = black_vol\n", "a = 0.01\n", "num_time_steps = 200\n", "model = BKTree(sigma, a, num_time_steps)" @@ -1000,7 +1000,7 @@ "bermudan_swaption_pay = IborBermudanSwaption(settle_dt,\n", " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.PAY,\n", + " swap_types.PAY,\n", " FinExerciseTypes.BERMUDAN,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", @@ -1016,7 +1016,7 @@ "bermudan_swaption_rec = IborBermudanSwaption(settle_dt,\n", " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.RECEIVE,\n", + " swap_types.RECEIVE,\n", " FinExerciseTypes.BERMUDAN,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", diff --git a/notebooks/products/rates/FINIBORBERMUDANSWAPTION_Hull_White_Tree.ipynb b/notebooks/products/rates/FINIBORBERMUDANSWAPTION_Hull_White_Tree.ipynb index 120b14f1..a59468ec 100644 --- a/notebooks/products/rates/FINIBORBERMUDANSWAPTION_Hull_White_Tree.ipynb +++ b/notebooks/products/rates/FINIBORBERMUDANSWAPTION_Hull_White_Tree.ipynb @@ -86,7 +86,7 @@ "metadata": {}, "outputs": [], "source": [ - "zero_dates = [Date(1,1,2008), Date(1,1,2009), Date(1,1,2010)]\n", + "zero_dts = [Date(1,1,2008), Date(1,1,2009), Date(1,1,2010)]\n", "zero_rates = [0.035, 0.04, 0.045]" ] }, @@ -96,7 +96,7 @@ "metadata": {}, "outputs": [], "source": [ - "discount_curve = DiscountCurveZeros(settle_dt, zero_dates, zero_rates, \n", + "discount_curve = DiscountCurveZeros(settle_dt, zero_dts, zero_rates, \n", " FrequencyTypes.ANNUAL)" ] }, @@ -175,12 +175,12 @@ "metadata": {}, "outputs": [], "source": [ - "call_dates = []\n", + "call_dts = []\n", "call_prices = []\n", "start_dt = Date(1, 1, 2008)\n", "years = np.linspace(0.0, 2.0, 50)\n", - "put_dates = start_dt.add_years(years)\n", - "put_prices = [100.0] * len(put_dates)" + "put_dts = start_dt.add_years(years)\n", + "put_prices = [100.0] * len(put_dts)" ] }, { @@ -197,7 +197,7 @@ "outputs": [], "source": [ "puttable_bond = BondEmbeddedOption(issue_dt, maturity_dt, coupon, frequencyType, dc_type,\n", - " call_dates, call_prices, put_dates, put_prices)" + " call_dts, call_prices, put_dts, put_prices)" ] }, { diff --git a/notebooks/products/rates/FINIBORCAPFLOOR_ValuationAcrossAllModels.ipynb b/notebooks/products/rates/FINIBORCAPFLOOR_ValuationAcrossAllModels.ipynb index 5912fa6b..8f677e90 100644 --- a/notebooks/products/rates/FINIBORCAPFLOOR_ValuationAcrossAllModels.ipynb +++ b/notebooks/products/rates/FINIBORCAPFLOOR_ValuationAcrossAllModels.ipynb @@ -92,17 +92,17 @@ "accrual = DayCountTypes.THIRTY_E_360\n", "freq = FrequencyTypes.SEMI_ANNUAL\n", "longEnd = DateGenRuleTypes.BACKWARD\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "\n", "spot_days = 2\n", "settle_dt = value_dt.add_weekdays(spot_days)\n", "\n", "swaps = []\n", - "swap = IborSwap(settle_dt, \"1Y\", swapType, 0.0250, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, 0.0255, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.0260, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.0265, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.0270, freq, accrual); swaps.append(swap)" + "swap = IborSwap(settle_dt, \"1Y\", swap_type, 0.0250, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, 0.0255, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.0260, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.0265, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.0270, freq, accrual); swaps.append(swap)" ] }, { diff --git a/notebooks/products/rates/FINIBORDUALCURVE_BuildingASimpleDualIborCurve.ipynb b/notebooks/products/rates/FINIBORDUALCURVE_BuildingASimpleDualIborCurve.ipynb index 1bb79204..79e02a50 100644 --- a/notebooks/products/rates/FINIBORDUALCURVE_BuildingASimpleDualIborCurve.ipynb +++ b/notebooks/products/rates/FINIBORDUALCURVE_BuildingASimpleDualIborCurve.ipynb @@ -130,17 +130,17 @@ "outputs": [], "source": [ "oiss = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = OIS(settle_dt, \"1Y\", swapType, onRate + 0.0001, fixed_freq_type, fixedDCCType); oiss.append(swap)\n", - "swap = OIS(settle_dt, \"2Y\", swapType, onRate + 0.0003, fixed_freq_type, fixedDCCType); oiss.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, onRate + 0.0010, fixed_freq_type, fixedDCCType); oiss.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, onRate + 0.0015, fixed_freq_type, fixedDCCType); oiss.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, onRate + 0.0020, fixed_freq_type, fixedDCCType); oiss.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, onRate + 0.0030, fixed_freq_type, fixedDCCType); oiss.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, onRate + 0.0035, fixed_freq_type, fixedDCCType); oiss.append(swap)" + "swap = OIS(settle_dt, \"1Y\", swap_type, onRate + 0.0001, fixed_freq_type, fixed_dcc_type); oiss.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, onRate + 0.0003, fixed_freq_type, fixed_dcc_type); oiss.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, onRate + 0.0010, fixed_freq_type, fixed_dcc_type); oiss.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, onRate + 0.0015, fixed_freq_type, fixed_dcc_type); oiss.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, onRate + 0.0020, fixed_freq_type, fixed_dcc_type); oiss.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, onRate + 0.0030, fixed_freq_type, fixed_dcc_type); oiss.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, onRate + 0.0035, fixed_freq_type, fixed_dcc_type); oiss.append(swap)" ] }, { @@ -223,54 +223,54 @@ "depos = []\n", "depo = IborDeposit(settle_dt, \"1D\", onRate, depoDCCType); depos.append(depo)\n", "\n", - "payFixed = True\n", + "pay_fixed = True\n", "fras = []\n", "\n", "# 1 x 4 FRA\n", - "fraRate = onRate + 0.0003\n", + "fra_rate = onRate + 0.0003\n", "fraSettlementDate = settle_dt.add_months(1)\n", "fraMaturityDate = settle_dt.add_months(4)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)\n", "\n", "# 2 x 5 FRA\n", - "fraRate = onRate + 0.0005\n", + "fra_rate = onRate + 0.0005\n", "fraSettlementDate = settle_dt.add_months(2)\n", "fraMaturityDate = settle_dt.add_months(5)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)\n", "\n", "# 3 x 6 FRA\n", - "fraRate = onRate + 0.0007\n", + "fra_rate = onRate + 0.0007\n", "fraSettlementDate = settle_dt.add_months(3)\n", "fraMaturityDate = settle_dt.add_months(6)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)\n", "\n", "# 4 x 7 FRA\n", - "fraRate = onRate + 0.0007\n", + "fra_rate = onRate + 0.0007\n", "fraSettlementDate = settle_dt.add_months(4)\n", "fraMaturityDate = settle_dt.add_months(7)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)\n", "\n", "# 5 x 8 FRA\n", - "fraRate = onRate + 0.0008\n", + "fra_rate = onRate + 0.0008\n", "fraSettlementDate = settle_dt.add_months(5)\n", "fraMaturityDate = settle_dt.add_months(8)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"1Y\", swapType, 0.0470, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.0475, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.0490, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 0.0510, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 0.0520, fixed_freq_type, fixedDCCType); swaps.append(swap)" + "swap = IborSwap(settle_dt, \"1Y\", swap_type, 0.0470, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.0475, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.0490, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 0.0510, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 0.0520, fixed_freq_type, fixed_dcc_type); swaps.append(swap)" ] }, { diff --git a/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveFollowingQLExample.ipynb b/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveFollowingQLExample.ipynb index 176feff4..2fc97ee6 100644 --- a/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveFollowingQLExample.ipynb +++ b/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveFollowingQLExample.ipynb @@ -95,14 +95,14 @@ "depo = IborDeposit(settle_dt, \"1D\", 0.0400/100.0, depoDCCType); depos.append(depo)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", - "swap = OIS(settle_dt, \"1W\", swapType, 0.0700/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2W\", swapType, 0.0690/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3W\", swapType, 0.0780/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4W\", swapType, 0.0740/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1W\", swap_type, 0.0700/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2W\", swap_type, 0.0690/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3W\", swap_type, 0.0780/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4W\", swap_type, 0.0740/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "m1Date = Date(16,1,2013)\n", "m2Date = Date(13,2,2013)\n", @@ -112,31 +112,31 @@ "m6Date = Date(12,6,2013)\n", "\n", "# This OIS stops at the next meeting date\n", - "swap = OIS(m1Date, m2Date, swapType, 0.0460/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m2Date, m3Date, swapType, 0.0160/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m3Date, m4Date, swapType, -0.007/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m4Date, m5Date, swapType, -0.013/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m5Date, m6Date, swapType, -0.014/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(m1Date, m2Date, swap_type, 0.0460/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m2Date, m3Date, swap_type, 0.0160/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m3Date, m4Date, swap_type, -0.007/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m4Date, m5Date, swap_type, -0.013/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m5Date, m6Date, swap_type, -0.014/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"15M\", swapType, 0.002/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"18M\", swapType, 0.008/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"21M\", swapType, 0.021/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2Y\", swapType, 0.036/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, 0.127/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, 0.274/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, 0.456/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6Y\", swapType, 0.647/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, 0.827/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"8Y\", swapType, 0.996/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9Y\", swapType, 1.147/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, 1.280/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"11Y\", swapType, 1.404/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12Y\", swapType, 1.516/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"15Y\", swapType, 1.764/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"20Y\", swapType, 1.939/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"25Y\", swapType, 2.003/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30Y\", swapType, 2.038/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)" + "swap = OIS(settle_dt, \"15M\", swap_type, 0.002/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"18M\", swap_type, 0.008/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"21M\", swap_type, 0.021/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, 0.036/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, 0.127/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, 0.274/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, 0.456/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6Y\", swap_type, 0.647/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, 0.827/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"8Y\", swap_type, 0.996/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9Y\", swap_type, 1.147/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, 1.280/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"11Y\", swap_type, 1.404/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12Y\", swap_type, 1.516/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"15Y\", swap_type, 1.764/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"20Y\", swap_type, 1.939/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"25Y\", swap_type, 2.003/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30Y\", swap_type, 2.038/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)" ] }, { @@ -275,28 +275,28 @@ "fra = IborFRA(settle_dt.add_tenor(\"18M\"), \"6M\", 0.409/100.0, depoDCCType); fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", "# Standard IRS with standard annual terms\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.424/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.576/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.762/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, 0.954/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 1.135/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, 1.303/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, 1.452/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 1.584/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, 1.809/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, 2.037/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 2.187/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 2.234/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, 2.256/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"35Y\", swapType, 2.295/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, 2.348/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"45Y\", swapType, 2.421/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, 2.463/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)" + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.424/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.576/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.762/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, 0.954/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 1.135/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, 1.303/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, 1.452/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 1.584/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, 1.809/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, 2.037/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 2.187/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 2.234/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, 2.256/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"35Y\", swap_type, 2.295/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, 2.348/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"45Y\", swap_type, 2.421/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, 2.463/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)" ] }, { diff --git a/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveSwapValuationQLExampleDeriscope.ipynb b/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveSwapValuationQLExampleDeriscope.ipynb index 62f6e196..0100573a 100644 --- a/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveSwapValuationQLExampleDeriscope.ipynb +++ b/notebooks/products/rates/FINIBORDUALCURVE_BuildingEuriborDualCurveSwapValuationQLExampleDeriscope.ipynb @@ -91,7 +91,7 @@ "start_dt = Date(27, 12, 2017)\n", "maturity_dt = Date(27, 12, 2067)\n", "notional = 10 * ONE_MILLION\n", - "swapType = SwapTypes.RECEIVE" + "swap_type = swap_types.RECEIVE" ] }, { @@ -108,7 +108,7 @@ "outputs": [], "source": [ "fixedRate = 0.0150\n", - "fixedDCCType = DayCountTypes.THIRTY_360_BOND\n", + "fixed_dcc_type = DayCountTypes.THIRTY_360_BOND\n", "fixed_freq_type = FrequencyTypes.ANNUAL" ] }, @@ -137,8 +137,8 @@ "metadata": {}, "outputs": [], "source": [ - "offMarketSwap = IborSwap(start_dt, maturity_dt, swapType, \n", - " fixedRate, fixed_freq_type, fixedDCCType,\n", + "offMarketSwap = IborSwap(start_dt, maturity_dt, swap_type, \n", + " fixedRate, fixed_freq_type, fixed_dcc_type,\n", " notional,\n", " float_spread, float_freq_type, floatDCCType, \n", " CalendarTypes.TARGET)" @@ -187,29 +187,29 @@ "fra = IborFRA(settle_dt.add_tenor(\"11M\"), \"6M\", -0.1510/100.0, fraDCCType); fras.append(fra)\n", "fra = IborFRA(settle_dt.add_tenor(\"12M\"), \"6M\", -0.1360/100.0, fraDCCType); fras.append(fra)\n", "\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.THIRTY_360_BOND\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.THIRTY_360_BOND\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, -0.1525/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, -0.0185/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.1315/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.2745/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, 0.4135/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 0.5439/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, 0.6652/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, 0.7784/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 0.8799/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"11Y\", swapType, 0.9715/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, 1.0517/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, 1.2369/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 1.3965/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 1.4472/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, 1.4585/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"35Y\", swapType, 1.4595/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, 1.4535/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"45Y\", swapType, 1.4410/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, 1.4335/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, -0.1525/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, -0.0185/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.1315/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.2745/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, 0.4135/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 0.5439/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, 0.6652/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, 0.7784/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 0.8799/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"11Y\", swap_type, 0.9715/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, 1.0517/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, 1.2369/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 1.3965/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 1.4472/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, 1.4585/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"35Y\", swap_type, 1.4595/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, 1.4535/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"45Y\", swap_type, 1.4410/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, 1.4335/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "iborSingleCurve = IborSingleCurve(value_dt, depos, fras, swaps, interp_type)" ] @@ -384,45 +384,45 @@ "fras = []\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"2W\", swapType, -0.3600/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"1M\", swapType, -0.3560/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2M\", swapType, -0.3570/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3M\", swapType, -0.3580/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4M\", swapType, -0.3575/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5M\", swapType, -0.3578/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6M\", swapType, -0.3580/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7M\", swapType, -0.3600/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"8M\", swapType, -0.3575/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9M\", swapType, -0.3569/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10M\", swapType, -0.3553/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"11M\", swapType, -0.3534/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12M\", swapType, -0.3496/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"18M\", swapType, -0.3173/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2W\", swap_type, -0.3600/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1M\", swap_type, -0.3560/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2M\", swap_type, -0.3570/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3M\", swap_type, -0.3580/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4M\", swap_type, -0.3575/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5M\", swap_type, -0.3578/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6M\", swap_type, -0.3580/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7M\", swap_type, -0.3600/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"8M\", swap_type, -0.3575/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9M\", swap_type, -0.3569/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10M\", swap_type, -0.3553/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"11M\", swap_type, -0.3534/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12M\", swap_type, -0.3496/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"18M\", swap_type, -0.3173/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", - "swap = OIS(settle_dt, \"2Y\", swapType, -0.2671/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30M\", swapType, -0.2070/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, -0.1410/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, -0.0060/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, 0.1285/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6Y\", swapType, 0.2590/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, 0.3830/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"8Y\", swapType, 0.5020/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9Y\", swapType, 0.6140/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, 0.7160/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"11Y\", swapType, 0.8070/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12Y\", swapType, 0.8890/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"15Y\", swapType, 1.0790/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"20Y\", swapType, 1.2460/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"25Y\", swapType, 1.3055/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30Y\", swapType, 1.3270/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"35Y\", swapType, 1.3315/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"40Y\", swapType, 1.3300/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"50Y\", swapType, 1.3270/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, -0.2671/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30M\", swap_type, -0.2070/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, -0.1410/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, -0.0060/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, 0.1285/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6Y\", swap_type, 0.2590/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, 0.3830/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"8Y\", swap_type, 0.5020/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9Y\", swap_type, 0.6140/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, 0.7160/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"11Y\", swap_type, 0.8070/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12Y\", swap_type, 0.8890/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"15Y\", swap_type, 1.0790/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"20Y\", swap_type, 1.2460/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"25Y\", swap_type, 1.3055/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30Y\", swap_type, 1.3270/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"35Y\", swap_type, 1.3315/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"40Y\", swap_type, 1.3300/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"50Y\", swap_type, 1.3270/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "oisDepos = depos.copy()\n", "oisFras = fras.copy()\n", diff --git a/notebooks/products/rates/FINIBORDUALCURVE_BuildingUSDDualCurveSwapValuationQLExampleDeriscope.ipynb b/notebooks/products/rates/FINIBORDUALCURVE_BuildingUSDDualCurveSwapValuationQLExampleDeriscope.ipynb index 2e1d507f..c740857e 100644 --- a/notebooks/products/rates/FINIBORDUALCURVE_BuildingUSDDualCurveSwapValuationQLExampleDeriscope.ipynb +++ b/notebooks/products/rates/FINIBORDUALCURVE_BuildingUSDDualCurveSwapValuationQLExampleDeriscope.ipynb @@ -129,27 +129,27 @@ "fra = IborFRA(f6, f7, 2.074814539/100.0, fraDCCType, cal_type=cal); fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.THIRTY_E_360_ISDA\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.THIRTY_E_360_ISDA\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, 2.289249897/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 2.218399525/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 2.200400352/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 2.209749699/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, 2.233999729/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 2.262149811/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, 2.293599606/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, 2.326499939/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 2.358519554/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"11Y\", swapType, 2.388500214/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, 2.416099548/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, 2.475949764/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 2.528799534/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 2.545499325/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, 2.551049709/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, 2.534699440/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, 2.504999638/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, 2.289249897/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 2.218399525/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 2.200400352/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 2.209749699/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, 2.233999729/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 2.262149811/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, 2.293599606/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, 2.326499939/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 2.358519554/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"11Y\", swap_type, 2.388500214/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, 2.416099548/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, 2.475949764/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 2.528799534/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 2.545499325/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, 2.551049709/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, 2.534699440/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, 2.504999638/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", "\n", "iborDepos = depos.copy()\n", "iborFras = fras.copy()\n", @@ -262,38 +262,38 @@ "fras = []\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "spot_days = 2\n", "settle_dt = value_dt.add_weekdays(spot_days)\n", - "fixedDCCType = DayCountTypes.ACT_360\n", + "fixed_dcc_type = DayCountTypes.ACT_360\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"1W\", swapType, 2.38829947/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2W\", swapType, 2.38419962/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3W\", swapType, 2.39200020/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"1M\", swapType, 2.38549948/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2M\", swapType, 2.38499975/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3M\", swapType, 2.37699986/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4M\", swapType, 2.36999989/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5M\", swapType, 2.35499954/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6M\", swapType, 2.33832979/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9M\", swapType, 2.2810001373/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12M\", swapType, 2.2280001640/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"18M\", swapType, 2.1263647078/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2Y\", swapType, 2.0547046661/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, 1.9829993844/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, 1.9649996758/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, 1.9729995728/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, 2.0252024253/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, 2.1155184592/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12Y\", swapType, 2.1703001490/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"15Y\", swapType, 2.2254047478/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"20Y\", swapType, 2.2718827283/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"25Y\", swapType, 2.2859679587/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30Y\", swapType, 2.2865169760/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"40Y\", swapType, 2.2714174506/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"50Y\", swapType, 2.2406175848/100.0, fixed_freq_type, fixedDCCType, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1W\", swap_type, 2.38829947/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2W\", swap_type, 2.38419962/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3W\", swap_type, 2.39200020/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1M\", swap_type, 2.38549948/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2M\", swap_type, 2.38499975/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3M\", swap_type, 2.37699986/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4M\", swap_type, 2.36999989/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5M\", swap_type, 2.35499954/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6M\", swap_type, 2.33832979/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9M\", swap_type, 2.2810001373/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12M\", swap_type, 2.2280001640/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"18M\", swap_type, 2.1263647078/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, 2.0547046661/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, 1.9829993844/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, 1.9649996758/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, 1.9729995728/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, 2.0252024253/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, 2.1155184592/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12Y\", swap_type, 2.1703001490/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"15Y\", swap_type, 2.2254047478/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"20Y\", swap_type, 2.2718827283/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"25Y\", swap_type, 2.2859679587/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30Y\", swap_type, 2.2865169760/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"40Y\", swap_type, 2.2714174506/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"50Y\", swap_type, 2.2406175848/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal); swaps.append(swap)\n", "\n", "oisDepos = depos.copy()\n", "oisFras = fras.copy()\n", diff --git a/notebooks/products/rates/FINIBORDUALCURVE_Building_EURIBOR_DualCurve_Bloomberg_Example.ipynb b/notebooks/products/rates/FINIBORDUALCURVE_Building_EURIBOR_DualCurve_Bloomberg_Example.ipynb index d9ea074c..4c26cdd7 100644 --- a/notebooks/products/rates/FINIBORDUALCURVE_Building_EURIBOR_DualCurve_Bloomberg_Example.ipynb +++ b/notebooks/products/rates/FINIBORDUALCURVE_Building_EURIBOR_DualCurve_Bloomberg_Example.ipynb @@ -119,49 +119,49 @@ "fras = []\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "spot_days = 2\n", "settle_dt = value_dt.add_weekdays(spot_days)\n", - "fixedDCCType = DayCountTypes.ACT_360\n", + "fixed_dcc_type = DayCountTypes.ACT_360\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "lag = 1 # days\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"1W\", swapType, -0.47000/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2W\", swapType, -0.47150/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"1M\", swapType, -0.47300/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2M\", swapType, -0.47700/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3M\", swapType, -0.48150/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4M\", swapType, -0.48500/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5M\", swapType, -0.48900/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6M\", swapType, -0.49300/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7M\", swapType, -0.49700/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"8M\", swapType, -0.50065/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9M\", swapType, -0.50375/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10M\", swapType, -0.50790/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"11M\", swapType, -0.51100/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12M\", swapType, -0.51400/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"18M\", swapType, -0.53250/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2Y\", swapType, -0.54300/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30M\", swapType, -0.54850/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, -0.54900/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, -0.53700/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, -0.51350/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6Y\", swapType, -0.48300/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1W\", swap_type, -0.47000/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2W\", swap_type, -0.47150/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1M\", swap_type, -0.47300/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2M\", swap_type, -0.47700/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3M\", swap_type, -0.48150/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4M\", swap_type, -0.48500/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5M\", swap_type, -0.48900/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6M\", swap_type, -0.49300/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7M\", swap_type, -0.49700/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"8M\", swap_type, -0.50065/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9M\", swap_type, -0.50375/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10M\", swap_type, -0.50790/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"11M\", swap_type, -0.51100/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12M\", swap_type, -0.51400/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"18M\", swap_type, -0.53250/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, -0.54300/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30M\", swap_type, -0.54850/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, -0.54900/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, -0.53700/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, -0.51350/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6Y\", swap_type, -0.48300/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", "\n", - "swap = OIS(settle_dt, \"7Y\", swapType, -0.44650/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"8Y\", swapType, -0.40480/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9Y\", swapType, -0.36220/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, -0.31550/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"11Y\", swapType, -0.27100/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12Y\", swapType, -0.22850/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"15Y\", swapType, -0.12300/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"20Y\", swapType, -0.04000/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"25Y\", swapType, -0.03450/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30Y\", swapType, -0.05750/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"35Y\", swapType, -0.08160/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"40Y\", swapType, -0.10485/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"50Y\", swapType, -0.14300/100.0, fixed_freq_type, fixedDCCType, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, -0.44650/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"8Y\", swap_type, -0.40480/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9Y\", swap_type, -0.36220/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, -0.31550/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"11Y\", swap_type, -0.27100/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12Y\", swap_type, -0.22850/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"15Y\", swap_type, -0.12300/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"20Y\", swap_type, -0.04000/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"25Y\", swap_type, -0.03450/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30Y\", swap_type, -0.05750/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"35Y\", swap_type, -0.08160/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"40Y\", swap_type, -0.10485/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"50Y\", swap_type, -0.14300/100.0, fixed_freq_type, fixed_dcc_type, cal_type = cal, payment_lag=lag); swaps.append(swap)\n", "\n", "oisDepos = depos.copy()\n", "oisFras = fras.copy()\n", @@ -252,11 +252,11 @@ "for swap in oisSwaps:\n", " start = swap._effective_dt\n", " maturity_dt = swap._fixed_leg._maturity_dt\n", - " payment_date = swap._fixed_leg._payment_dates[-1]\n", - " df = oisCurve.df(payment_date) / df_start\n", + " payment_dt = swap._fixed_leg._payment_dts[-1]\n", + " df = oisCurve.df(payment_dt) / df_start\n", " days = maturity_dt - settle_dt\n", - " ccZeroRate = oisCurve.zero_rate(payment_date, FrequencyTypes.CONTINUOUS, DayCountTypes.ACT_365F)\n", - " print(\"%12s %12s %12s %5.0f %12.9f %9.6f\"% (start, maturity_dt, payment_date, days, df, ccZeroRate*100))" + " ccZeroRate = oisCurve.zero_rate(payment_dt, FrequencyTypes.CONTINUOUS, DayCountTypes.ACT_365F)\n", + " print(\"%12s %12s %12s %5.0f %12.9f %9.6f\"% (start, maturity_dt, payment_dt, days, df, ccZeroRate*100))" ] }, { @@ -275,7 +275,7 @@ "fixedCpn = -0.51350/100 # CHANGED\n", "start_dt = settle_dt\n", "maturity_dt = Date(28, 10, 2025,)\n", - "fixedDCCType = DayCountTypes.ACT_360\n", + "fixed_dcc_type = DayCountTypes.ACT_360\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "floatDCCType = DayCountTypes.ACT_360\n", "float_freq_type = FrequencyTypes.ANNUAL\n", @@ -288,8 +288,8 @@ "metadata": {}, "outputs": [], "source": [ - "oisSwap = OIS(start_dt, maturity_dt, SwapTypes.RECEIVE, \n", - " fixedCpn, fixed_freq_type, fixedDCCType, \n", + "oisSwap = OIS(start_dt, maturity_dt, swap_types.RECEIVE, \n", + " fixedCpn, fixed_freq_type, fixed_dcc_type, \n", " notional, lag, \n", " 0.0, float_freq_type, floatDCCType)" ] @@ -348,7 +348,7 @@ "COUPON (%): -0.5135\n", "FREQUENCY: FrequencyTypes.ANNUAL\n", "DAY COUNT: DayCountTypes.ACT_360\n", - "PAY_DATE ACCR_START ACCR_END DAYS YEARFRAC RATE PAYMENT DF PV CUM PV\n", + "PAY_dt ACCR_START ACCR_END DAYS YEARFRAC RATE PAYMENT DF PV CUM PV\n", "29-OCT-2021 28-OCT-2020 28-OCT-2021 365 1.013889 -0.51350 -52063.19 1.00525414 -52336.74 -52336.74\n", "31-OCT-2022 28-OCT-2021 28-OCT-2022 365 1.013889 -0.51350 -52063.19 1.01115027 -52643.71 -104980.45\n", "31-OCT-2023 28-OCT-2022 30-OCT-2023 367 1.019444 -0.51350 -52348.47 1.01693070 -53234.77 -158215.22\n", @@ -375,7 +375,7 @@ "SPREAD (BPS): 0.0\n", "FREQUENCY: FrequencyTypes.ANNUAL\n", "DAY COUNT: DayCountTypes.ACT_360\n", - "PAY_DATE ACCR_START ACCR_END DAYS YEARFRAC IBOR PAYMENT DF PV CUM PV\n", + "PAY_dt ACCR_START ACCR_END DAYS YEARFRAC IBOR PAYMENT DF PV CUM PV\n", "29-OCT-2021 28-OCT-2020 28-OCT-2021 365 1.013889 -0.51400 -52113.89 1.00525414 -52387.70 -52387.70\n", "31-OCT-2022 28-OCT-2021 28-OCT-2022 365 1.013889 -0.57183 -57977.30 1.01115027 -58623.76 -111011.46\n", "31-OCT-2023 28-OCT-2022 30-OCT-2023 367 1.019444 -0.56085 -57175.63 1.01693070 -58143.66 -169155.12\n", @@ -434,27 +434,27 @@ "fra = IborFRA(settle_dt.add_tenor(\"12M\"), \"6M\", -0.519/100.0, fraDCCType, cal_type=cal); fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.THIRTY_E_360_ISDA\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.THIRTY_E_360_ISDA\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, -0.51375/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, -0.50600/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, -0.48225/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, -0.45100/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, -0.41500/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, -0.37530/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, -0.33250/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, -0.28810/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, -0.24180/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"11Y\", swapType, -0.198/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, -0.156/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, -0.05375/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 0.02325/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 0.02300/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, -0.00510/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, -0.0627/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, -0.1125/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, -0.51375/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, -0.50600/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, -0.48225/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, -0.45100/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, -0.41500/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, -0.37530/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, -0.33250/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, -0.28810/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, -0.24180/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"11Y\", swap_type, -0.198/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, -0.156/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, -0.05375/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 0.02325/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 0.02300/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, -0.00510/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, -0.0627/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, -0.1125/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", "\n", "iborDepos = depos.copy()\n", "iborFras = fras.copy()\n", @@ -532,7 +532,7 @@ "fixedCpn = -0.4510/100.0\n", "start_dt = settle_dt\n", "maturity_dt = Date(28, 10, 2025)\n", - "fixedDCCType = DayCountTypes.THIRTY_E_360_ISDA\n", + "fixed_dcc_type = DayCountTypes.THIRTY_E_360_ISDA\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "floatDCCType = DayCountTypes.ACT_360\n", "float_freq_type = FrequencyTypes.SEMI_ANNUAL\n", @@ -545,8 +545,8 @@ "metadata": {}, "outputs": [], "source": [ - "iborSwap = IborSwap(start_dt, maturity_dt, SwapTypes.RECEIVE, \n", - " fixedCpn, fixed_freq_type, fixedDCCType, \n", + "iborSwap = IborSwap(start_dt, maturity_dt, swap_types.RECEIVE, \n", + " fixedCpn, fixed_freq_type, fixed_dcc_type, \n", " notional, \n", " 0.0, float_freq_type, floatDCCType)" ] @@ -605,7 +605,7 @@ "COUPON (%): -0.451\n", "FREQUENCY: FrequencyTypes.ANNUAL\n", "DAY COUNT: DayCountTypes.THIRTY_E_360_ISDA\n", - "PAY_DATE ACCR_START ACCR_END DAYS YEARFRAC RATE PAYMENT DF PV CUM PV\n", + "PAY_dt ACCR_START ACCR_END DAYS YEARFRAC RATE PAYMENT DF PV CUM PV\n", "28-OCT-2021 28-OCT-2020 28-OCT-2021 360 1.000000 -0.45100 -45100.00 1.00523869 -45336.26 -45336.26\n", "28-OCT-2022 28-OCT-2021 28-OCT-2022 360 1.000000 -0.45100 -45100.00 1.01110078 -45600.65 -90936.91\n", "30-OCT-2023 28-OCT-2022 30-OCT-2023 362 1.005556 -0.45100 -45350.56 1.01691506 -46117.66 -137054.57\n", @@ -632,7 +632,7 @@ "SPREAD (BPS): 0.0\n", "FREQUENCY: FrequencyTypes.SEMI_ANNUAL\n", "DAY COUNT: DayCountTypes.ACT_360\n", - "PAY_DATE ACCR_START ACCR_END DAYS YEARFRAC IBOR PAYMENT DF PV CUM PV\n", + "PAY_dt ACCR_START ACCR_END DAYS YEARFRAC IBOR PAYMENT DF PV CUM PV\n", "28-APR-2021 28-OCT-2020 28-APR-2021 182 0.505556 -0.49600 -25075.56 1.00249862 -25138.21 -25138.21\n", "28-OCT-2021 28-APR-2021 28-OCT-2021 183 0.508333 -0.50100 -25467.50 1.00523869 -25600.92 -50739.13\n", "28-APR-2022 28-OCT-2021 28-APR-2022 182 0.505556 -0.51900 -26238.33 1.00814172 -26451.96 -77191.08\n", diff --git a/notebooks/products/rates/FINIBORDUALCURVE_ValueUSDSwapUsingDifferentCurveBuildingAssumptions.ipynb b/notebooks/products/rates/FINIBORDUALCURVE_ValueUSDSwapUsingDifferentCurveBuildingAssumptions.ipynb index aed85ece..7d59a9cf 100644 --- a/notebooks/products/rates/FINIBORDUALCURVE_ValueUSDSwapUsingDifferentCurveBuildingAssumptions.ipynb +++ b/notebooks/products/rates/FINIBORDUALCURVE_ValueUSDSwapUsingDifferentCurveBuildingAssumptions.ipynb @@ -90,36 +90,36 @@ "fras = []\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"1W\", swapType, 2.3883/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2W\", swapType, 2.3842/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3W\", swapType, 2.3920/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"1M\", swapType, 2.3885/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2M\", swapType, 2.3850/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3M\", swapType, 2.3770/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4M\", swapType, 2.3700/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5M\", swapType, 2.3550/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6M\", swapType, 2.3383/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9M\", swapType, 2.2810/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12M\", swapType, 2.2280/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"18M\", swapType, 2.1264/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2Y\", swapType, 2.0547/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, 1.9830/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, 1.9650/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, 1.9730/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, 2.0252/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, 2.1155/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12Y\", swapType, 2.1703/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"15Y\", swapType, 2.2254/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"20Y\", swapType, 2.2719/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"25Y\", swapType, 2.2860/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30Y\", swapType, 2.2865/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"40Y\", swapType, 2.2714/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"50Y\", swapType, 2.2406/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1W\", swap_type, 2.3883/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2W\", swap_type, 2.3842/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3W\", swap_type, 2.3920/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1M\", swap_type, 2.3885/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2M\", swap_type, 2.3850/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3M\", swap_type, 2.3770/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4M\", swap_type, 2.3700/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5M\", swap_type, 2.3550/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6M\", swap_type, 2.3383/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9M\", swap_type, 2.2810/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12M\", swap_type, 2.2280/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"18M\", swap_type, 2.1264/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, 2.0547/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, 1.9830/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, 1.9650/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, 1.9730/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, 2.0252/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, 2.1155/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12Y\", swap_type, 2.1703/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"15Y\", swap_type, 2.2254/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"20Y\", swap_type, 2.2719/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"25Y\", swap_type, 2.2860/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30Y\", swap_type, 2.2865/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"40Y\", swap_type, 2.2714/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"50Y\", swap_type, 2.2406/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "oisDepos = depos.copy()\n", "oisFras = fras.copy()\n", @@ -182,27 +182,27 @@ "fra = IborFRA(f6, f7, 2.0748/100, mmDCType); fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.THIRTY_360_BOND\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.THIRTY_360_BOND\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, 2.2892/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 2.2184/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 2.2004/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 2.2097/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, 2.2340/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 2.2621/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, 2.2936/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, 2.3265/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 2.3585/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"11Y\", swapType, 2.3885/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, 2.4161/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, 2.4759/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 2.5288/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 2.5455/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, 2.5510/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, 2.5347/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, 2.5050/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, 2.2892/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 2.2184/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 2.2004/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 2.2097/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, 2.2340/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 2.2621/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, 2.2936/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, 2.3265/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 2.3585/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"11Y\", swap_type, 2.3885/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, 2.4161/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, 2.4759/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 2.5288/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 2.5455/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, 2.5510/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, 2.5347/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, 2.5050/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "iborDepos = depos.copy()\n", "iborFras = fras.copy()\n", @@ -249,9 +249,9 @@ "start_dt = settle_dt.add_tenor(\"7M\")\n", "maturity_dt = start_dt.add_tenor(\"5Y\")\n", "notional = ONE_MILLION\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "fixedRate = 0.0218\n", - "fixedDCCType = DayCountTypes.THIRTY_360_BOND\n", + "fixed_dcc_type = DayCountTypes.THIRTY_360_BOND\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "float_spread = 0.0\n", "floatDCCType = DayCountTypes.ACT_360\n", @@ -264,8 +264,8 @@ "metadata": {}, "outputs": [], "source": [ - "offMarketSwap = IborSwap(start_dt, maturity_dt, swapType, \n", - " fixedRate, fixed_freq_type, fixedDCCType,\n", + "offMarketSwap = IborSwap(start_dt, maturity_dt, swap_type, \n", + " fixedRate, fixed_freq_type, fixed_dcc_type,\n", " notional,\n", " float_spread, float_freq_type, floatDCCType, \n", " CalendarTypes.UNITED_KINGDOM)" diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_AnalysisOfForwards.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_AnalysisOfForwards.ipynb index 5d7cb6a1..33231960 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_AnalysisOfForwards.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_AnalysisOfForwards.ipynb @@ -122,7 +122,7 @@ "source": [ "dcType = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreq = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY" + "swap_type = swap_types.PAY" ] }, { @@ -131,16 +131,16 @@ "metadata": {}, "outputs": [], "source": [ - "swap1 = IborSwap(settle_dt,\"2Y\",swapType,0.015910,fixedFreq,dcType)\n", - "swap2 = IborSwap(settle_dt,\"3Y\",swapType,0.014990,fixedFreq,dcType)\n", - "swap3 = IborSwap(settle_dt,\"4Y\",swapType,0.014725,fixedFreq,dcType)\n", - "swap4 = IborSwap(settle_dt,\"5Y\",swapType,0.014640,fixedFreq,dcType)\n", - "swap5 = IborSwap(settle_dt,\"6Y\",swapType,0.014800,fixedFreq,dcType)\n", - "swap6 = IborSwap(settle_dt,\"7Y\",swapType,0.014995,fixedFreq,dcType)\n", - "swap7 = IborSwap(settle_dt,\"8Y\",swapType,0.015180,fixedFreq,dcType)\n", - "swap8 = IborSwap(settle_dt,\"9Y\",swapType,0.015610,fixedFreq,dcType)\n", - "swap9 = IborSwap(settle_dt,\"10Y\",swapType,0.0159880,fixedFreq,dcType)\n", - "swap10 = IborSwap(settle_dt,\"12Y\",swapType,0.016430,fixedFreq,dcType)" + "swap1 = IborSwap(settle_dt,\"2Y\",swap_type,0.015910,fixedFreq,dcType)\n", + "swap2 = IborSwap(settle_dt,\"3Y\",swap_type,0.014990,fixedFreq,dcType)\n", + "swap3 = IborSwap(settle_dt,\"4Y\",swap_type,0.014725,fixedFreq,dcType)\n", + "swap4 = IborSwap(settle_dt,\"5Y\",swap_type,0.014640,fixedFreq,dcType)\n", + "swap5 = IborSwap(settle_dt,\"6Y\",swap_type,0.014800,fixedFreq,dcType)\n", + "swap6 = IborSwap(settle_dt,\"7Y\",swap_type,0.014995,fixedFreq,dcType)\n", + "swap7 = IborSwap(settle_dt,\"8Y\",swap_type,0.015180,fixedFreq,dcType)\n", + "swap8 = IborSwap(settle_dt,\"9Y\",swap_type,0.015610,fixedFreq,dcType)\n", + "swap9 = IborSwap(settle_dt,\"10Y\",swap_type,0.0159880,fixedFreq,dcType)\n", + "swap10 = IborSwap(settle_dt,\"12Y\",swap_type,0.016430,fixedFreq,dcType)" ] }, { diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingASimpleIborCurve.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingASimpleIborCurve.ipynb index 8c713a1b..ca6b1b93 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingASimpleIborCurve.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingASimpleIborCurve.ipynb @@ -82,16 +82,16 @@ "depo = IborDeposit(settle_dt, \"12M\", 0.0310, depoDCCType); depos.append(depo)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, 0.0320, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.0350, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.0375, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.0400, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 0.0420, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 0.0410, fixed_freq_type, fixedDCCType); swaps.append(swap)" + "swap = IborSwap(settle_dt, \"2Y\", swap_type, 0.0320, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.0350, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.0375, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.0400, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 0.0420, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 0.0410, fixed_freq_type, fixed_dcc_type); swaps.append(swap)" ] }, { diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingAnIborCurve.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingAnIborCurve.ipynb index 167d5a1a..c5cc7fa9 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingAnIborCurve.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingAnIborCurve.ipynb @@ -120,21 +120,21 @@ "outputs": [], "source": [ "# 1 x 4 FRA\n", - "payFixed = True\n", + "pay_fixed = True\n", "notional = 1000\n", "fras = []\n", "\n", - "fraRate = 0.05\n", + "fra_rate = 0.05\n", "fraSettlementDate = settle_dt.add_months(12)\n", "fraMaturityDate = settle_dt.add_months(16)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)\n", "\n", "# 4 x 7 FRA\n", - "fraRate = 0.08\n", + "fra_rate = 0.08\n", "fraSettlementDate = settle_dt.add_months(16)\n", "fraMaturityDate = settle_dt.add_months(20)\n", - "fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType)\n", + "fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType)\n", "fras.append(fra)" ] }, @@ -152,38 +152,38 @@ "outputs": [], "source": [ "swaps = []\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "\n", "swap_rate = 0.050\n", "maturity_dt = settle_dt.add_months(24)\n", - "swap = IborSwap(settle_dt, maturity_dt, swapType, swap_rate, fixed_freq_type, fixedDCCType)\n", + "swap = IborSwap(settle_dt, maturity_dt, swap_type, swap_rate, fixed_freq_type, fixed_dcc_type)\n", "swaps.append(swap)\n", "\n", "swap_rate = 0.052\n", "maturity_dt = settle_dt.add_months(36)\n", - "swap = IborSwap(settle_dt, maturity_dt, swapType, swap_rate, fixed_freq_type, fixedDCCType)\n", + "swap = IborSwap(settle_dt, maturity_dt, swap_type, swap_rate, fixed_freq_type, fixed_dcc_type)\n", "swaps.append(swap)\n", "\n", "swap_rate = 0.0535\n", "maturity_dt = settle_dt.add_months(48)\n", - "swap = IborSwap(settle_dt, maturity_dt, swapType, swap_rate, fixed_freq_type, fixedDCCType)\n", + "swap = IborSwap(settle_dt, maturity_dt, swap_type, swap_rate, fixed_freq_type, fixed_dcc_type)\n", "swaps.append(swap)\n", "\n", "swap_rate = 0.055\n", "maturity_dt = settle_dt.add_months(60)\n", - "swap = IborSwap(settle_dt, maturity_dt, swapType, swap_rate, fixed_freq_type, fixedDCCType)\n", + "swap = IborSwap(settle_dt, maturity_dt, swap_type, swap_rate, fixed_freq_type, fixed_dcc_type)\n", "swaps.append(swap)\n", "\n", "swap_rate = 0.0565\n", "maturity_dt = settle_dt.add_months(84)\n", - "swap = IborSwap(settle_dt, maturity_dt, swapType, swap_rate, fixed_freq_type, fixedDCCType)\n", + "swap = IborSwap(settle_dt, maturity_dt, swap_type, swap_rate, fixed_freq_type, fixed_dcc_type)\n", "swaps.append(swap)\n", "\n", "swap_rate = 0.057\n", "maturity_dt = settle_dt.add_months(120)\n", - "swap = IborSwap(settle_dt, maturity_dt, swapType, swap_rate, fixed_freq_type, fixedDCCType)\n", + "swap = IborSwap(settle_dt, maturity_dt, swap_type, swap_rate, fixed_freq_type, fixed_dcc_type)\n", "swaps.append(swap)" ] }, diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationCOMPLEX.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationCOMPLEX.ipynb index 96ddf462..fff08c87 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationCOMPLEX.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationCOMPLEX.ipynb @@ -106,27 +106,27 @@ "fra = IborFRA(settle_dt.add_tenor(\"12M\"), \"6M\", -0.519/100.0, fraDCCType, cal_type=cal); fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.THIRTY_E_360_ISDA\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.THIRTY_E_360_ISDA\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, -0.514/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, -0.506/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, -0.482/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, -0.451/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, -0.415/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, -0.375/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, -0.333/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, -0.288/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, -0.242/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"11Y\", swapType, -0.198/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, -0.156/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, -0.054/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 0.023/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 0.023/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, -0.005/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, -0.063/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, -0.113/100.0, fixed_freq_type, fixedDCCType, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, -0.514/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, -0.506/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, -0.482/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, -0.451/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, -0.415/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, -0.375/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, -0.333/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, -0.288/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, -0.242/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"11Y\", swap_type, -0.198/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, -0.156/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, -0.054/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 0.023/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 0.023/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, -0.005/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, -0.063/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, -0.113/100.0, fixed_freq_type, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", "\n", "iborDepos = depos.copy()\n", "iborFras = fras.copy()\n", diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationSIMPLE.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationSIMPLE.ipynb index fc84adb2..2b7bbfcd 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationSIMPLE.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingIborCurveInterpolationSIMPLE.ipynb @@ -96,12 +96,12 @@ "fra = IborFRA(settle_dt.add_tenor(\"12M\"), \"6M\", -0.306/100.0, fraDCCType, cal_type=cal); fras.append(fra)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.THIRTY_E_360_ISDA\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.THIRTY_E_360_ISDA\n", "fixedFreqType = FrequencyTypes.ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, -0.325/100.0, fixedFreqType, fixedDCCType, cal_type=cal); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, -0.347/100.0, fixedFreqType, fixedDCCType, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"2Y\", swap_type, -0.325/100.0, fixedFreqType, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, -0.347/100.0, fixedFreqType, fixed_dcc_type, cal_type=cal); swaps.append(swap)\n", "\n", "iborDepos = depos.copy()\n", "iborFras = fras.copy()\n", @@ -133,13 +133,13 @@ "metadata": {}, "outputs": [], "source": [ - "grid_dates = []\n", - "dt = Date(12, 5, 2020); grid_dates.append(dt)\n", - "dt = dt.add_tenor(\"6M\"); grid_dates.append(dt)\n", - "dt = dt.add_tenor(\"6M\"); grid_dates.append(dt)\n", - "dt = dt.add_tenor(\"6M\"); grid_dates.append(dt)\n", - "dt = dt.add_tenor(\"6M\"); grid_dates.append(dt)\n", - "dt = dt.add_tenor(\"12M\"); grid_dates.append(dt)" + "grid_dts = []\n", + "dt = Date(12, 5, 2020); grid_dts.append(dt)\n", + "dt = dt.add_tenor(\"6M\"); grid_dts.append(dt)\n", + "dt = dt.add_tenor(\"6M\"); grid_dts.append(dt)\n", + "dt = dt.add_tenor(\"6M\"); grid_dts.append(dt)\n", + "dt = dt.add_tenor(\"6M\"); grid_dts.append(dt)\n", + "dt = dt.add_tenor(\"12M\"); grid_dts.append(dt)" ] }, { @@ -168,7 +168,7 @@ " print(\"%13s \"% interp.name[0:15], end=\"\")\n", "print(\"\")\n", " \n", - "for dt in grid_dates:\n", + "for dt in grid_dts:\n", " print(\"%12s\"% dt.str(\"X\"), end=\"\")\n", " for interp in InterpTypes:\n", " iborCurve = iborCurves[interp]\n", @@ -198,7 +198,7 @@ "outputs": [], "source": [ "shiftedDates = []\n", - "for dt in grid_dates:\n", + "for dt in grid_dts:\n", " shiftedDates.append(dt.add_tenor(\"15D\"))" ] }, diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingInterpolationChoice.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingInterpolationChoice.ipynb index 93d971d3..8328867f 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_BuildingInterpolationChoice.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_BuildingInterpolationChoice.ipynb @@ -62,9 +62,9 @@ "metadata": {}, "outputs": [], "source": [ - "def plotCurve(start_date, tmax):\n", + "def plotCurve(start_dt, tmax):\n", " years = np.linspace(1/365, tmax, 500)\n", - " dates = start_date.add_years(years)\n", + " dates = start_dt.add_years(years)\n", " zero_rates = libor_curve.zero_rate(dates)\n", " fwd_rates = libor_curve.fwd(dates)\n", "\n", @@ -103,7 +103,7 @@ "metadata": {}, "outputs": [], "source": [ - "spot_date = Date(6, 6, 2018)" + "spot_dt = Date(6, 6, 2018)" ] }, { @@ -113,7 +113,7 @@ "outputs": [], "source": [ "spot_days = 0\n", - "settle_dt = spot_date.add_weekdays(spot_days)\n", + "settle_dt = spot_dt.add_weekdays(spot_days)\n", "depoDCCType = DayCountTypes.ACT_360" ] }, @@ -322,7 +322,7 @@ "outputs": [], "source": [ "spot_days = 2\n", - "settle_dt = spot_date.add_weekdays(spot_days)" + "settle_dt = spot_dt.add_weekdays(spot_days)" ] }, { @@ -332,12 +332,12 @@ "outputs": [], "source": [ "futs = []\n", - "fut = IborFuture(spot_date, 1) ; futs.append(fut)\n", - "fut = IborFuture(spot_date, 2) ; futs.append(fut)\n", - "fut = IborFuture(spot_date, 3) ; futs.append(fut)\n", - "fut = IborFuture(spot_date, 4) ; futs.append(fut)\n", - "fut = IborFuture(spot_date, 5) ; futs.append(fut)\n", - "fut = IborFuture(spot_date, 6) ; futs.append(fut)" + "fut = IborFuture(spot_dt, 1) ; futs.append(fut)\n", + "fut = IborFuture(spot_dt, 2) ; futs.append(fut)\n", + "fut = IborFuture(spot_dt, 3) ; futs.append(fut)\n", + "fut = IborFuture(spot_dt, 4) ; futs.append(fut)\n", + "fut = IborFuture(spot_dt, 5) ; futs.append(fut)\n", + "fut = IborFuture(spot_dt, 6) ; futs.append(fut)" ] }, { diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingBBGExample.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingBBGExample.ipynb index 354366fa..952cb3b5 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingBBGExample.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingBBGExample.ipynb @@ -166,7 +166,7 @@ "accrual = DayCountTypes.THIRTY_E_360\n", "freq = FrequencyTypes.SEMI_ANNUAL\n", "longEnd = DateGenRuleTypes.BACKWARD\n", - "swapType = SwapTypes.PAY" + "swap_type = swap_types.PAY" ] }, { @@ -187,23 +187,23 @@ "outputs": [], "source": [ "swaps = []\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, (2.77417+2.77844)/200, freq, accrual, notional); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, (2.86098+2.86582)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, (2.90240+2.90620)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, (2.92944+2.92906)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, (2.94001+2.94499)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, (2.95352+2.95998)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, (2.96830+2.97400)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, (2.98403+2.98817)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, (2.99716+3.00394)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"11Y\", swapType, (3.01344+3.01596)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"12Y\", swapType, (3.02276+3.02684)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, (3.04092+3.04508)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, (3.04417+3.05183)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, (3.03219+3.03621)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, (3.01030+3.01370)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"40Y\", swapType, (2.96946+2.97354)/200, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"50Y\", swapType, (2.91552+2.93748)/200, freq, accrual); swaps.append(swap)" + "swap = IborSwap(settle_dt, \"2Y\", swap_type, (2.77417+2.77844)/200, freq, accrual, notional); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, (2.86098+2.86582)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, (2.90240+2.90620)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, (2.92944+2.92906)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, (2.94001+2.94499)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, (2.95352+2.95998)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, (2.96830+2.97400)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, (2.98403+2.98817)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, (2.99716+3.00394)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"11Y\", swap_type, (3.01344+3.01596)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"12Y\", swap_type, (3.02276+3.02684)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, (3.04092+3.04508)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, (3.04417+3.05183)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, (3.03219+3.03621)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, (3.01030+3.01370)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"40Y\", swap_type, (2.96946+2.97354)/200, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"50Y\", swap_type, (2.91552+2.93748)/200, freq, accrual); swaps.append(swap)" ] }, { diff --git a/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingQuantlibExample.ipynb b/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingQuantlibExample.ipynb index f1edb3f5..93e48876 100644 --- a/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingQuantlibExample.ipynb +++ b/notebooks/products/rates/FINIBORSINGLECURVE_ReplicatingQuantlibExample.ipynb @@ -231,7 +231,7 @@ "accrual = DayCountTypes.ACT_360\n", "freq = FrequencyTypes.ANNUAL\n", "longEnd = DateGenRuleTypes.BACKWARD\n", - "swapType = SwapTypes.PAY" + "swap_type = swap_types.PAY" ] }, { @@ -251,10 +251,10 @@ "outputs": [], "source": [ "swaps = []\n", - "swap = IborSwap(settle_dt, \"2Y\", swapType, 0.0089268, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.0123343, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.0147985, freq, accrual); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.0165843, freq, accrual); swaps.append(swap)" + "swap = IborSwap(settle_dt, \"2Y\", swap_type, 0.0089268, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.0123343, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.0147985, freq, accrual); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.0165843, freq, accrual); swaps.append(swap)" ] }, { diff --git a/notebooks/products/rates/FINIBORSWAPTION_All_Models_Analysis.ipynb b/notebooks/products/rates/FINIBORSWAPTION_All_Models_Analysis.ipynb index 0656593b..3c9b449c 100644 --- a/notebooks/products/rates/FINIBORSWAPTION_All_Models_Analysis.ipynb +++ b/notebooks/products/rates/FINIBORSWAPTION_All_Models_Analysis.ipynb @@ -108,13 +108,13 @@ "metadata": {}, "outputs": [], "source": [ - "exercise_date = settle_dt.add_tenor(\"1Y\")\n", + "exercise_dt = settle_dt.add_tenor(\"1Y\")\n", "swap_maturity_dt = settle_dt.add_tenor(\"4Y\")\n", "\n", "swap_fixed_coupon = 0.060\n", "swapFixedFrequencyType = FrequencyTypes.SEMI_ANNUAL\n", "swapFixedDayCountType = DayCountTypes.ACT_365F\n", - "swapType = SwapTypes.PAY " + "swap_type = swap_types.PAY " ] }, { @@ -134,7 +134,7 @@ } ], "source": [ - "exercise_date" + "exercise_dt" ] }, { @@ -164,9 +164,9 @@ "outputs": [], "source": [ "swaptionPay = IborSwaption(settle_dt,\n", - " exercise_date,\n", + " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.PAY ,\n", + " swap_types.PAY ,\n", " swap_fixed_coupon,\n", " swapFixedFrequencyType,\n", " swapFixedDayCountType)" @@ -179,9 +179,9 @@ "outputs": [], "source": [ "swaptionRec = IborSwaption(settle_dt,\n", - " exercise_date,\n", + " exercise_dt,\n", " swap_maturity_dt,\n", - " SwapTypes.RECEIVE,\n", + " swap_types.RECEIVE,\n", " swap_fixed_coupon,\n", " swapFixedFrequencyType,\n", " swapFixedDayCountType)" @@ -249,9 +249,9 @@ "metadata": {}, "outputs": [], "source": [ - "swap = IborSwap(exercise_date,\n", + "swap = IborSwap(exercise_dt,\n", " swap_maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " swap_fixed_coupon,\n", " swapFixedFrequencyType,\n", " swapFixedDayCountType)" diff --git a/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithMLExample.ipynb b/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithMLExample.ipynb index fcea21a1..f16d4363 100644 --- a/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithMLExample.ipynb +++ b/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithMLExample.ipynb @@ -79,7 +79,7 @@ "float_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "float_dc_type = DayCountTypes.THIRTY_E_360\n", "notional = 100.0\n", - "swapType = SwapTypes.PAY \n", + "swap_type = swap_types.PAY \n", "cal_type = CalendarTypes.NONE\n", "bd_type = BusDayAdjustTypes.NONE\n", "dg_type = DateGenRuleTypes.BACKWARD" @@ -94,7 +94,7 @@ "swaption = IborSwaption(settle_dt, \n", " exercise_date,\n", " maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " fixed_coupon,\n", " fixed_freq_type,\n", " fixed_dc_type, \n", @@ -118,7 +118,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 01-JAN-2011\n", "EXERCISE DATE: 01-JAN-2016\n", - "SWAP FIXED LEG TYPE: SwapTypes.PAY\n", + "SWAP FIXED LEG TYPE: swap_types.PAY\n", "SWAP MATURITY DATE: 01-JAN-2019\n", "SWAP NOTIONAL: 100.0\n", "FIXED COUPON: 6.2\n", @@ -189,7 +189,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 01-JAN-2011\n", "EXERCISE DATE: 01-JAN-2016\n", - "SWAP FIXED LEG TYPE: SwapTypes.PAY\n", + "SWAP FIXED LEG TYPE: swap_types.PAY\n", "SWAP MATURITY DATE: 01-JAN-2019\n", "SWAP NOTIONAL: 100.0\n", "FIXED COUPON: 6.2\n", @@ -323,7 +323,7 @@ "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "fixed_dc_type = DayCountTypes.THIRTY_E_360\n", "notional = 1000.0\n", - "swaptionType = SwapTypes.RECEIVE " + "swaptionType = swap_types.RECEIVE " ] }, { @@ -390,7 +390,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 01-JAN-2011\n", "EXERCISE DATE: 01-JAN-2012\n", - "SWAP FIXED LEG TYPE: SwapTypes.RECEIVE\n", + "SWAP FIXED LEG TYPE: swap_types.RECEIVE\n", "SWAP MATURITY DATE: 01-JAN-2017\n", "SWAP NOTIONAL: 1000.0\n", "FIXED COUPON: 3.0\n", diff --git a/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithQLExample.ipynb b/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithQLExample.ipynb index b7de69c1..4ab2cf6b 100644 --- a/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithQLExample.ipynb +++ b/notebooks/products/rates/FINIBORSWAPTION_ComparisonWithQLExample.ipynb @@ -77,22 +77,22 @@ "# No convexity correction provided so I omit interest rate futures\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.00790, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.01200, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.01570, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, 0.01865, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 0.02160, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, 0.02350, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, 0.02540, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 0.0273, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, 0.0297, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 0.0316, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 0.0335, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, 0.0354, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.00790, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.01200, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.01570, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, 0.01865, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 0.02160, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, 0.02350, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, 0.02540, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 0.0273, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, 0.0297, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 0.0316, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 0.0335, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, 0.0354, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" ] @@ -114,7 +114,7 @@ "swapFloatDayCountType = DayCountTypes.ACT_360\n", "\n", "swapNotional = ONE_MILLION\n", - "swapType = SwapTypes.PAY \n", + "swap_type = swap_types.PAY \n", "cal_type = CalendarTypes.TARGET\n", "bd_type = BusDayAdjustTypes.MODIFIED_FOLLOWING\n", "dg_type = DateGenRuleTypes.BACKWARD" @@ -129,7 +129,7 @@ "swaption = IborSwaption(settle_dt,\n", " exercise_date,\n", " swap_maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " swap_fixed_coupon,\n", " swapFixedFrequencyType,\n", " swapFixedDayCountType, \n", @@ -153,7 +153,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 04-MAR-2014\n", "EXERCISE DATE: 04-MAR-2019\n", - "SWAP FIXED LEG TYPE: SwapTypes.PAY\n", + "SWAP FIXED LEG TYPE: swap_types.PAY\n", "SWAP MATURITY DATE: 04-MAR-2024\n", "SWAP NOTIONAL: 1000000\n", "FIXED COUPON: 4.0852\n", @@ -224,7 +224,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 04-MAR-2014\n", "EXERCISE DATE: 04-MAR-2019\n", - "SWAP FIXED LEG TYPE: SwapTypes.PAY\n", + "SWAP FIXED LEG TYPE: swap_types.PAY\n", "SWAP MATURITY DATE: 04-MAR-2024\n", "SWAP NOTIONAL: 1000000\n", "FIXED COUPON: 4.0852\n", diff --git a/notebooks/products/rates/FINIBORSWAPTION_ValuingAcrossModels.ipynb b/notebooks/products/rates/FINIBORSWAPTION_ValuingAcrossModels.ipynb index fa2d1585..9b3aa5ca 100644 --- a/notebooks/products/rates/FINIBORSWAPTION_ValuingAcrossModels.ipynb +++ b/notebooks/products/rates/FINIBORSWAPTION_ValuingAcrossModels.ipynb @@ -85,22 +85,22 @@ "# No convexity correction provided so I omit interest rate futures\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "\n", - "swap = IborSwap(settle_dt, \"3Y\", swapType, 0.00790, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"4Y\", swapType, 0.01200, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"5Y\", swapType, 0.01570, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"6Y\", swapType, 0.01865, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"7Y\", swapType, 0.02160, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"8Y\", swapType, 0.02350, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"9Y\", swapType, 0.02540, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"10Y\", swapType, 0.0273, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"15Y\", swapType, 0.0297, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"20Y\", swapType, 0.0316, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"25Y\", swapType, 0.0335, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = IborSwap(settle_dt, \"30Y\", swapType, 0.0354, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"3Y\", swap_type, 0.00790, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"4Y\", swap_type, 0.01200, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"5Y\", swap_type, 0.01570, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"6Y\", swap_type, 0.01865, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"7Y\", swap_type, 0.02160, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"8Y\", swap_type, 0.02350, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"9Y\", swap_type, 0.02540, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"10Y\", swap_type, 0.0273, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"15Y\", swap_type, 0.0297, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"20Y\", swap_type, 0.0316, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"25Y\", swap_type, 0.0335, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = IborSwap(settle_dt, \"30Y\", swap_type, 0.0354, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "libor_curve = IborSingleCurve(value_dt, depos, [], swaps)" ] @@ -111,15 +111,15 @@ "metadata": {}, "outputs": [], "source": [ - "exercise_date = settle_dt.add_tenor(\"5Y\")\n", - "swap_maturity_dt = exercise_date.add_tenor(\"5Y\")\n", + "exercise_dt = settle_dt.add_tenor(\"5Y\")\n", + "swap_maturity_dt = exercise_dt.add_tenor(\"5Y\")\n", "swap_fixed_coupon = 0.040852\n", "swap_fixed_freq_type = FrequencyTypes.SEMI_ANNUAL\n", "swapFixedDayCountType = DayCountTypes.THIRTY_E_360_ISDA\n", "swapFloatFrequencyType = FrequencyTypes.QUARTERLY\n", "swapFloatDayCountType = DayCountTypes.ACT_360\n", "swapNotional = ONE_MILLION\n", - "swapType = SwapTypes.PAY \n", + "swap_type = swap_types.PAY \n", "cal_type = CalendarTypes.WEEKEND\n", "bd_type = BusDayAdjustTypes.NONE\n", "dg_type = DateGenRuleTypes.BACKWARD" @@ -132,9 +132,9 @@ "outputs": [], "source": [ "swaption = IborSwaption(settle_dt,\n", - " exercise_date,\n", + " exercise_dt,\n", " swap_maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " swap_fixed_coupon,\n", " swap_fixed_freq_type,\n", " swapFixedDayCountType, \n", @@ -381,7 +381,7 @@ "OBJECT TYPE: IborSwaption\n", "SETTLEMENT DATE: 04-MAR-2014\n", "EXERCISE DATE: 04-MAR-2019\n", - "SWAP FIXED LEG TYPE: SwapTypes.PAY\n", + "SWAP FIXED LEG TYPE: swap_types.PAY\n", "SWAP MATURITY DATE: 04-MAR-2024\n", "SWAP NOTIONAL: 1000000\n", "FIXED COUPON: 4.0852\n", @@ -420,7 +420,7 @@ "COUPON (%): 4.0852\n", "FREQUENCY: FrequencyTypes.SEMI_ANNUAL\n", "DAY COUNT: DayCountTypes.THIRTY_E_360_ISDA\n", - "PAY_DATE ACCR_START ACCR_END DAYS YEARFRAC RATE PAYMENT DF PV CUM PV\n", + "PAY_dt ACCR_START ACCR_END DAYS YEARFRAC RATE PAYMENT DF PV CUM PV\n", "04-SEP-2019 04-MAR-2019 04-SEP-2019 180 0.500000 4.08520 20426.00 0.90796633 18546.12 18546.12\n", "04-MAR-2020 04-SEP-2019 04-MAR-2020 180 0.500000 4.08520 20426.00 0.89260443 18232.34 36778.46\n", "04-SEP-2020 04-MAR-2020 04-SEP-2020 180 0.500000 4.08520 20426.00 0.87443197 17861.15 54639.61\n", diff --git a/notebooks/products/rates/FINIBORSWAP_BusinessDayConventions.ipynb b/notebooks/products/rates/FINIBORSWAP_BusinessDayConventions.ipynb index bdeaee91..ffbd0092 100644 --- a/notebooks/products/rates/FINIBORSWAP_BusinessDayConventions.ipynb +++ b/notebooks/products/rates/FINIBORSWAP_BusinessDayConventions.ipynb @@ -70,7 +70,7 @@ "metadata": {}, "outputs": [], "source": [ - "swapType = SwapTypes.PAY" + "swap_type = swap_types.PAY" ] }, { @@ -124,7 +124,7 @@ "source": [ "swap = IborSwap(effective_dt, \n", " maturity_dt, \n", - " swapType,\n", + " swap_type,\n", " swap_rate, \n", " fixed_freq_type=FrequencyTypes.SEMI_ANNUAL, \n", " fixed_dc_type= DayCountTypes.ACT_360,\n", @@ -193,7 +193,7 @@ "source": [ "swap = IborSwap(effective_dt, \n", " maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " swap_rate,\n", " fixed_freq_type=FrequencyTypes.SEMI_ANNUAL, \n", " fixed_dc_type= DayCountTypes.ACT_360,\n", diff --git a/notebooks/products/rates/FINIBORSWAP_ComparisonWithQLExample.ipynb b/notebooks/products/rates/FINIBORSWAP_ComparisonWithQLExample.ipynb index 31f2bf79..622ace68 100644 --- a/notebooks/products/rates/FINIBORSWAP_ComparisonWithQLExample.ipynb +++ b/notebooks/products/rates/FINIBORSWAP_ComparisonWithQLExample.ipynb @@ -184,7 +184,7 @@ "metadata": {}, "outputs": [], "source": [ - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "notional = 10 * ONE_MILLION" ] }, @@ -210,7 +210,7 @@ "source": [ "swap = IborSwap(settle_dt,\n", " maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " fixed_coupon,\n", " fixed_freq_type,\n", " fixed_dc_type,\n", diff --git a/notebooks/products/rates/FINIBORSWAP_DefiningAFixedFloatingSwap.ipynb b/notebooks/products/rates/FINIBORSWAP_DefiningAFixedFloatingSwap.ipynb index 2da19532..7a015c7f 100644 --- a/notebooks/products/rates/FINIBORSWAP_DefiningAFixedFloatingSwap.ipynb +++ b/notebooks/products/rates/FINIBORSWAP_DefiningAFixedFloatingSwap.ipynb @@ -113,7 +113,7 @@ "metadata": {}, "outputs": [], "source": [ - "swapType = SwapTypes.RECEIVE\n", + "swap_type = swap_types.RECEIVE\n", "notional = 10 * ONE_MILLION" ] }, @@ -149,7 +149,7 @@ "source": [ "swap = IborSwap(start_dt,\n", " maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " fixed_coupon,\n", " fixed_freq_type,\n", " fixed_dc_type,\n", @@ -178,7 +178,7 @@ "MATURITY DATE: 22-SEP-2025\n", "NOTIONAL: 10000000\n", "PRINCIPAL: 0.0\n", - "LEG TYPE: SwapTypes.RECEIVE\n", + "LEG TYPE: swap_types.RECEIVE\n", "COUPON: 0.05\n", "FREQUENCY: FrequencyTypes.ANNUAL\n", "DAY COUNT: DayCountTypes.ACT_360\n", @@ -191,7 +191,7 @@ "TERMINATION DATE: 20-SEP-2025\n", "MATURITY DATE: 22-SEP-2025\n", "NOTIONAL: 10000000\n", - "SWAP TYPE: SwapTypes.PAY\n", + "SWAP TYPE: swap_types.PAY\n", "SPREAD (BPS): 0.0\n", "FREQUENCY: FrequencyTypes.SEMI_ANNUAL\n", "DAY COUNT: DayCountTypes.ACT_360\n", diff --git a/notebooks/products/rates/FINIBORSWAP_SettingTheScheduleDirectly.ipynb b/notebooks/products/rates/FINIBORSWAP_SettingTheScheduleDirectly.ipynb index 4af2bc03..d7e6b1b1 100644 --- a/notebooks/products/rates/FINIBORSWAP_SettingTheScheduleDirectly.ipynb +++ b/notebooks/products/rates/FINIBORSWAP_SettingTheScheduleDirectly.ipynb @@ -183,7 +183,7 @@ "metadata": {}, "outputs": [], "source": [ - "swapType = SwapTypes.PAY\n", + "swap_type = swap_types.PAY\n", "notional = 10 * ONE_MILLION" ] }, @@ -209,7 +209,7 @@ "source": [ "swap = IborSwap(settle_dt,\n", " maturity_dt,\n", - " swapType,\n", + " swap_type,\n", " fixed_coupon,\n", " fixed_freq_type,\n", " fixed_dc_type,\n", diff --git a/notebooks/products/rates/FINOISCURVE_BuildingAnOISCurveWithMeetingDates.ipynb b/notebooks/products/rates/FINOISCURVE_BuildingAnOISCurveWithMeetingDates.ipynb index 4a731ff8..26d1776d 100644 --- a/notebooks/products/rates/FINOISCURVE_BuildingAnOISCurveWithMeetingDates.ipynb +++ b/notebooks/products/rates/FINOISCURVE_BuildingAnOISCurveWithMeetingDates.ipynb @@ -103,25 +103,25 @@ "settle_dt = value_dt.add_weekdays(spot_days)\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", "# This OIS stops at the next meeting date\n", - "swap = OIS(settle_dt, m1Date, swapType, 0.0420, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(settle_dt, m1Date, swap_type, 0.0420, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "# These OIS are forward starting and last between MM meeting dates\n", - "swap = OIS(m1Date, m2Date, swapType, 0.0320, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m2Date, m3Date, swapType, 0.0520, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m3Date, m4Date, swapType, 0.0320, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(m1Date, m2Date, swap_type, 0.0320, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m2Date, m3Date, swap_type, 0.0520, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m3Date, m4Date, swap_type, 0.0320, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"2Y\", swapType, 0.0330, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, 0.0350, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, 0.0375, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, 0.0400, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, 0.0420, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, 0.0430, fixed_freq_type, fixedDCCType); swaps.append(swap)" + "swap = OIS(settle_dt, \"2Y\", swap_type, 0.0330, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, 0.0350, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, 0.0375, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, 0.0400, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, 0.0420, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, 0.0430, fixed_freq_type, fixed_dcc_type); swaps.append(swap)" ] }, { @@ -338,9 +338,9 @@ ], "source": [ "for swap in swaps:\n", - " s_ff = oisCurveFF.swap_rate(swap._effective_dt,swap._termination_dt, fixed_freq_type, fixedDCCType) \n", - " s_lf = oisCurveLF.swap_rate(swap._effective_dt, swap._termination_dt, fixed_freq_type, fixedDCCType) \n", - " s_lz = oisCurveLZ.swap_rate(swap._effective_dt, swap._termination_dt, fixed_freq_type, fixedDCCType) \n", + " s_ff = oisCurveFF.swap_rate(swap._effective_dt,swap._termination_dt, fixed_freq_type, fixed_dcc_type) \n", + " s_lf = oisCurveLF.swap_rate(swap._effective_dt, swap._termination_dt, fixed_freq_type, fixed_dcc_type) \n", + " s_lz = oisCurveLZ.swap_rate(swap._effective_dt, swap._termination_dt, fixed_freq_type, fixed_dcc_type) \n", " print(\"%12s %12.6f %12.6f %12.6f\" % (swap._maturity_dt, s_ff*100, s_lf*100, s_lz*100))" ] }, diff --git a/notebooks/products/rates/FINOISCURVE_BuildingEONIACurveFollowingQLExample.ipynb b/notebooks/products/rates/FINOISCURVE_BuildingEONIACurveFollowingQLExample.ipynb index 0033554b..2552a3af 100644 --- a/notebooks/products/rates/FINOISCURVE_BuildingEONIACurveFollowingQLExample.ipynb +++ b/notebooks/products/rates/FINOISCURVE_BuildingEONIACurveFollowingQLExample.ipynb @@ -85,14 +85,14 @@ "###################################### OIS SWAPS START HERE ################################################\n", "\n", "swaps = []\n", - "swapType = SwapTypes.PAY\n", - "fixedDCCType = DayCountTypes.ACT_365F\n", + "swap_type = swap_types.PAY\n", + "fixed_dcc_type = DayCountTypes.ACT_365F\n", "fixed_freq_type = FrequencyTypes.ANNUAL\n", "\n", - "swap = OIS(settle_dt, \"1W\", swapType, 0.0700/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2W\", swapType, 0.0690/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3W\", swapType, 0.0780/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"1M\", swapType, 0.0740/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1W\", swap_type, 0.0700/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2W\", swap_type, 0.0690/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3W\", swap_type, 0.0780/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"1M\", swap_type, 0.0740/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "m1Date = Date(16,1,2013)\n", "m2Date = Date(13,2,2013)\n", @@ -102,31 +102,31 @@ "m6Date = Date(12,6,2013)\n", "\n", "# This OIS stops at the next meeting date\n", - "swap = OIS(m1Date, m2Date, swapType, 0.0460/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m2Date, m3Date, swapType, 0.0160/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m3Date, m4Date, swapType, -0.007/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m4Date, m5Date, swapType, -0.013/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(m5Date, m6Date, swapType, -0.014/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", + "swap = OIS(m1Date, m2Date, swap_type, 0.0460/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m2Date, m3Date, swap_type, 0.0160/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m3Date, m4Date, swap_type, -0.007/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m4Date, m5Date, swap_type, -0.013/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(m5Date, m6Date, swap_type, -0.014/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", "\n", "# Standard OIS with standard annual terms\n", - "swap = OIS(settle_dt, \"15M\", swapType, 0.002/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"18M\", swapType, 0.008/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"21M\", swapType, 0.021/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"2Y\", swapType, 0.036/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"3Y\", swapType, 0.127/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"4Y\", swapType, 0.274/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"5Y\", swapType, 0.456/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"6Y\", swapType, 0.647/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"7Y\", swapType, 0.827/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"8Y\", swapType, 0.996/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"9Y\", swapType, 1.147/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"10Y\", swapType, 1.280/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"11Y\", swapType, 1.404/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"12Y\", swapType, 1.516/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"15Y\", swapType, 1.764/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"20Y\", swapType, 1.939/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"25Y\", swapType, 2.003/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)\n", - "swap = OIS(settle_dt, \"30Y\", swapType, 2.038/100.0, fixed_freq_type, fixedDCCType); swaps.append(swap)" + "swap = OIS(settle_dt, \"15M\", swap_type, 0.002/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"18M\", swap_type, 0.008/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"21M\", swap_type, 0.021/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"2Y\", swap_type, 0.036/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"3Y\", swap_type, 0.127/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"4Y\", swap_type, 0.274/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"5Y\", swap_type, 0.456/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"6Y\", swap_type, 0.647/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"7Y\", swap_type, 0.827/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"8Y\", swap_type, 0.996/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"9Y\", swap_type, 1.147/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"10Y\", swap_type, 1.280/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"11Y\", swap_type, 1.404/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"12Y\", swap_type, 1.516/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"15Y\", swap_type, 1.764/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"20Y\", swap_type, 1.939/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"25Y\", swap_type, 2.003/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)\n", + "swap = OIS(settle_dt, \"30Y\", swap_type, 2.038/100.0, fixed_freq_type, fixed_dcc_type); swaps.append(swap)" ] }, { diff --git a/tests/test_FinBond.py b/tests/test_FinBond.py index 2afc0b5c..86059051 100644 --- a/tests/test_FinBond.py +++ b/tests/test_FinBond.py @@ -280,7 +280,7 @@ def test_bond_cfets(): df = pd.read_csv(path, parse_dates=['settlement_date', 'issue_date', 'maturity_date']) - + for row in df.itertuples(index=False): issue_dt = Date(row.issue_date.day, @@ -325,7 +325,7 @@ def test_bond_cfets(): def test_key_rate_durations_bloomberg_example(): - dc_type, freq_type, settlementDays, exDiv, calendar = \ + dc_type, freq_type, settle_days, exDiv, calendar = \ get_bond_market_conventions(BondMarkets.UNITED_STATES) # interest accrues on this date. Issue date is 01/08/2022 @@ -334,7 +334,7 @@ def test_key_rate_durations_bloomberg_example(): coupon = 2.75/100.0 ex_div_days = 0 - dc_type, freq_type, settlementDays, exDiv, calendar =\ + dc_type, freq_type, settle_days, exDiv, calendar =\ get_bond_market_conventions(BondMarkets.UNITED_STATES) bond = Bond(issue_dt, maturity_dt, coupon, diff --git a/tests/test_FinBondConvertible.py b/tests/test_FinBondConvertible.py index 494b949b..d0a72215 100644 --- a/tests/test_FinBondConvertible.py +++ b/tests/test_FinBondConvertible.py @@ -19,13 +19,13 @@ start_convert_date = Date(31, 12, 2003) conversion_ratio = 3.84615 # adjust for face -call_dates = [Date(20, 3, 2007), +call_dts = [Date(20, 3, 2007), Date(15, 3, 2012), Date(15, 3, 2017)] call_price = 1100 call_prices = np.array([call_price, call_price, call_price]) -put_dates = [Date(20, 3, 2007), +put_dts = [Date(20, 3, 2007), Date(15, 3, 2012), Date(15, 3, 2017)] @@ -38,9 +38,9 @@ freq_type, start_convert_date, conversion_ratio, - call_dates, + call_dts, call_prices, - put_dates, + put_dts, put_prices, accrualBasis) diff --git a/tests/test_FinBondEmbeddedOption.py b/tests/test_FinBondEmbeddedOption.py index 179120d6..a48bf486 100644 --- a/tests/test_FinBondEmbeddedOption.py +++ b/tests/test_FinBondEmbeddedOption.py @@ -44,20 +44,20 @@ bond_matlab = Bond(issue_dt, maturity_dt, coupon, freq_type, dc_type) -call_dates = [] +call_dts = [] call_prices = [] -put_dates = [] +put_dts = [] put_prices = [] -put_date = Date(1, 1, 2008) +put_dt = Date(1, 1, 2008) for _ in range(0, 24): - put_dates.append(put_date) + put_dts.append(put_dt) put_prices.append(100) - put_date = put_date.add_months(1) + put_dt = put_dt.add_months(1) puttable_bond_matlab = BondEmbeddedOption(issue_dt, maturity_dt, coupon, freq_type, dc_type, - call_dates, call_prices, - put_dates, put_prices) + call_dts, call_prices, + put_dts, put_prices) def test_matlab_clean_price_from_discount_curve(): @@ -110,19 +110,19 @@ def test_matlab_hw(): coupon, freq_type, dc_type) nextCallDate = Date(15, 9, 2016) -call_dates = [nextCallDate] +call_dts = [nextCallDate] call_prices = [100.0] -put_dates = [] +put_dts = [] put_prices = [] for _ in range(1, 24): nextCallDate = nextCallDate.add_months(3) - call_dates.append(nextCallDate) + call_dts.append(nextCallDate) call_prices.append(100.0) puttable_bond_quantlib = BondEmbeddedOption(issue_dt, maturity_dt, coupon, freq_type, dc_type, - call_dates, call_prices, - put_dates, put_prices) + call_dts, call_prices, + put_dts, put_prices) def test_quantlib_clean_price_from_discount_curve(): diff --git a/tests/test_FinBondOption.py b/tests/test_FinBondOption.py index bf848b33..966e35d1 100644 --- a/tests/test_FinBondOption.py +++ b/tests/test_FinBondOption.py @@ -31,7 +31,7 @@ dfs = np.exp(-0.05*times) discount_curve = DiscountCurve(settle_dt, dates, dfs) -expiry_date = settle_dt.add_tenor("18m") +expiry_dt = settle_dt.add_tenor("18m") face = 100.0 num_time_steps = 100 @@ -42,7 +42,7 @@ def test_european_call_bk(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.20 a = 0.1 @@ -59,7 +59,7 @@ def test_american_call_bk(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.01 a = 0.1 @@ -75,7 +75,7 @@ def test_european_put_bk(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.01 a = 0.1 @@ -91,7 +91,7 @@ def test_american_put_bk(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.02 a = 0.1 @@ -107,7 +107,7 @@ def test_european_call_bdt(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.20 model = BDTTree(sigma, num_time_steps) @@ -122,7 +122,7 @@ def test_american_call_bdt(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.20 model = BDTTree(sigma, num_time_steps) @@ -137,7 +137,7 @@ def test_european_put_bdt(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.01 model = BDTTree(sigma, num_time_steps) @@ -152,7 +152,7 @@ def test_american_put_bdt(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.02 model = BDTTree(sigma, num_time_steps) @@ -170,7 +170,7 @@ def test_european_call_hw(): num_time_steps = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.01 a = 0.1 @@ -186,7 +186,7 @@ def test_american_call_hw(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.01 a = 0.1 @@ -202,7 +202,7 @@ def test_european_put_hw(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.01 a = 0.1 @@ -218,7 +218,7 @@ def test_american_put_hw(): strike_price = 100 bond_option = BondOption( - bond, expiry_date, strike_price, option_type) + bond, expiry_dt, strike_price, option_type) sigma = 0.02 a = 0.1 diff --git a/tests/test_FinBondYieldCurve.py b/tests/test_FinBondYieldCurve.py index 6d95cf7f..112d6465 100644 --- a/tests/test_FinBondYieldCurve.py +++ b/tests/test_FinBondYieldCurve.py @@ -75,10 +75,10 @@ def test_nelson_siegel_svensson(): assert round(fitted_curve._curve_fit._tau_2, 4) == 100.0000 -def test_interpolated_yield(): +def test_interp_yield(): curveFitMethod = CurveFitBSpline() fitted_curve = BondYieldCurve(settlement, bonds, ylds, curveFitMethod) maturity_dt = Date(19, 9, 2030) - interpolated_yield = fitted_curve.interpolated_yield(maturity_dt) - assert round(float(interpolated_yield), 8) == 0.02601858 + interp_yield = fitted_curve.interp_yield(maturity_dt) + assert round(float(interp_yield), 8) == 0.02601858 diff --git a/tests/test_FinCDS.py b/tests/test_FinCDS.py index 2558601c..fa18855e 100644 --- a/tests/test_FinCDS.py +++ b/tests/test_FinCDS.py @@ -437,12 +437,12 @@ def test_accrued_interest(): assert round(accrued_interest, 4) == -8333.3333 -def test_protection_leg_pv(): - prot_pv = cds_contract1.protection_leg_pv( +def test_prot_leg_pv(): + prot_pv = cds_contract1.prot_leg_pv( value_dt1, issuer_curve1, cdsRecovery) assert round(prot_pv, 4) == 273023.5221 - prot_pv = cds_contract2.protection_leg_pv( + prot_pv = cds_contract2.prot_leg_pv( value_dt2, issuer_curve2, cdsRecovery) assert round(prot_pv, 4) == 47629.7343 diff --git a/tests/test_FinCDSBasket.py b/tests/test_FinCDSBasket.py index 83646fe9..fdefbc47 100644 --- a/tests/test_FinCDSBasket.py +++ b/tests/test_FinCDSBasket.py @@ -12,7 +12,7 @@ tradeDate = Date(1, 3, 2007) -step_in_date = tradeDate.add_days(1) +step_in_dt = tradeDate.add_days(1) value_dt = tradeDate.add_days(1) libor_curve = build_Ibor_Curve(tradeDate) @@ -33,25 +33,25 @@ def test_inhomogeneous_curve(): intrinsicSpd = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, basketMaturity, issuer_curves) * 10000.0 assert round(intrinsicSpd, 4) == 32.0971 totalSpd = cdsIndex.total_spread(value_dt, - step_in_date, + step_in_dt, basketMaturity, issuer_curves) * 10000.0 assert round(totalSpd, 4) == 161.3169 minSpd = cdsIndex.min_spread(value_dt, - step_in_date, + step_in_dt, basketMaturity, issuer_curves) * 10000.0 assert round(minSpd, 4) == 10.6722 maxSpd = cdsIndex.max_spread(value_dt, - step_in_date, + step_in_dt, basketMaturity, issuer_curves) * 10000.0 assert round(maxSpd, 4) == 81.1466 diff --git a/tests/test_FinCDSIndex.py b/tests/test_FinCDSIndex.py index b4025b01..48645cee 100644 --- a/tests/test_FinCDSIndex.py +++ b/tests/test_FinCDSIndex.py @@ -18,8 +18,8 @@ tradeDate = Date(7, 2, 2006) libor_curve = build_Ibor_Curve(tradeDate) issuer_curve = buildIssuerCurve(tradeDate, libor_curve) -step_in_date = tradeDate.add_days(1) -value_dt = step_in_date +step_in_dt = tradeDate.add_days(1) +value_dt = step_in_dt maturity_dt = Date(20, 6, 2010) cdsRecovery = 0.40 @@ -27,7 +27,7 @@ long_protection = True index_coupon = 0.004 -cdsIndexContract = CDS(step_in_date, +cdsIndexContract = CDS(step_in_dt, maturity_dt, index_coupon, notional, @@ -52,7 +52,7 @@ def test_cds_index(): accrued_interest = cdsIndexContract.accrued_interest() assert round(accrued_interest, 4) == -5555.5556 - prot_pv = cdsIndexContract.protection_leg_pv( + prot_pv = cdsIndexContract.prot_leg_pv( value_dt, issuer_curve, cdsRecovery) assert round(prot_pv, 4) == 188423.9948 diff --git a/tests/test_FinCDSIndexAdjustHazards.py b/tests/test_FinCDSIndexAdjustHazards.py index bf10cec4..43c94e91 100644 --- a/tests/test_FinCDSIndexAdjustHazards.py +++ b/tests/test_FinCDSIndexAdjustHazards.py @@ -13,8 +13,8 @@ def test_performCDSIndexHazardRateAdjustment(): tradeDate = Date(1, 8, 2007) - step_in_date = tradeDate.add_days(1) - value_dt = step_in_date + step_in_dt = tradeDate.add_days(1) + value_dt = step_in_dt libor_curve = build_Ibor_Curve(tradeDate) @@ -40,10 +40,10 @@ def test_performCDSIndexHazardRateAdjustment(): spd10Y = float(splitRow[4]) / 10000.0 recovery_rate = float(splitRow[5]) - cds3Y = CDS(step_in_date, maturity3Y, spd3Y) - cds5Y = CDS(step_in_date, maturity5Y, spd5Y) - cds7Y = CDS(step_in_date, maturity7Y, spd7Y) - cds10Y = CDS(step_in_date, maturity10Y, spd10Y) + cds3Y = CDS(step_in_dt, maturity3Y, spd3Y) + cds5Y = CDS(step_in_dt, maturity5Y, spd5Y) + cds7Y = CDS(step_in_dt, maturity7Y, spd7Y) + cds10Y = CDS(step_in_dt, maturity10Y, spd10Y) cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y] issuer_curve = CDSCurve(value_dt, @@ -57,22 +57,22 @@ def test_performCDSIndexHazardRateAdjustment(): cdsIndex = CDSIndexPortfolio() averageSpd3Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity3Y, issuer_curves) * 10000.0 averageSpd5Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity5Y, issuer_curves) * 10000.0 averageSpd7Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity7Y, issuer_curves) * 10000.0 averageSpd10Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity10Y, issuer_curves) * 10000.0 @@ -86,22 +86,22 @@ def test_performCDSIndexHazardRateAdjustment(): cdsIndex = CDSIndexPortfolio() intrinsicSpd3Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity3Y, issuer_curves) * 10000.0 intrinsicSpd5Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity5Y, issuer_curves) * 10000.0 intrinsicSpd7Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity7Y, issuer_curves) * 10000.0 intrinsicSpd10Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity10Y, issuer_curves) * 10000.0 diff --git a/tests/test_FinCDSIndexAdjustSpreads.py b/tests/test_FinCDSIndexAdjustSpreads.py index 5d2ad63d..faa6bcf9 100644 --- a/tests/test_FinCDSIndexAdjustSpreads.py +++ b/tests/test_FinCDSIndexAdjustSpreads.py @@ -13,7 +13,7 @@ def test_CDSIndexAdjustSpreads(): tradeDate = Date(1, 8, 2007) - step_in_date = tradeDate.add_days(1) + step_in_dt = tradeDate.add_days(1) value_dt = tradeDate.add_days(1) libor_curve = build_Ibor_Curve(tradeDate) @@ -40,10 +40,10 @@ def test_CDSIndexAdjustSpreads(): spd10Y = float(splitRow[4]) / 10000.0 recovery_rate = float(splitRow[5]) - cds3Y = CDS(step_in_date, maturity3Y, spd3Y) - cds5Y = CDS(step_in_date, maturity5Y, spd5Y) - cds7Y = CDS(step_in_date, maturity7Y, spd7Y) - cds10Y = CDS(step_in_date, maturity10Y, spd10Y) + cds3Y = CDS(step_in_dt, maturity3Y, spd3Y) + cds5Y = CDS(step_in_dt, maturity5Y, spd5Y) + cds7Y = CDS(step_in_dt, maturity7Y, spd7Y) + cds10Y = CDS(step_in_dt, maturity10Y, spd10Y) cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y] issuer_curve = CDSCurve(value_dt, @@ -57,22 +57,22 @@ def test_CDSIndexAdjustSpreads(): cdsIndex = CDSIndexPortfolio() averageSpd3Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity3Y, issuer_curves) * 10000.0 averageSpd5Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity5Y, issuer_curves) * 10000.0 averageSpd7Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity7Y, issuer_curves) * 10000.0 averageSpd10Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity10Y, issuer_curves) * 10000.0 @@ -86,22 +86,22 @@ def test_CDSIndexAdjustSpreads(): cdsIndex = CDSIndexPortfolio() intrinsicSpd3Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity3Y, issuer_curves) * 10000.0 intrinsicSpd5Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity5Y, issuer_curves) * 10000.0 intrinsicSpd7Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity7Y, issuer_curves) * 10000.0 intrinsicSpd10Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity10Y, issuer_curves) * 10000.0 diff --git a/tests/test_FinCDSIndexOption.py b/tests/test_FinCDSIndexOption.py index 20ca0f38..f3c9123a 100644 --- a/tests/test_FinCDSIndexOption.py +++ b/tests/test_FinCDSIndexOption.py @@ -20,8 +20,8 @@ def test_dirty_priceCDSIndexOption(): tradeDate = Date(1, 8, 2007) - step_in_date = tradeDate.add_days(1) - value_dt = step_in_date + step_in_dt = tradeDate.add_days(1) + value_dt = step_in_dt libor_curve = build_Ibor_Curve(tradeDate) @@ -46,10 +46,10 @@ def test_dirty_priceCDSIndexOption(): spd10Y = float(splitRow[4]) / 10000.0 recovery_rate = float(splitRow[5]) - cds3Y = CDS(step_in_date, maturity3Y, spd3Y) - cds5Y = CDS(step_in_date, maturity5Y, spd5Y) - cds7Y = CDS(step_in_date, maturity7Y, spd7Y) - cds10Y = CDS(step_in_date, maturity10Y, spd10Y) + cds3Y = CDS(step_in_dt, maturity3Y, spd3Y) + cds5Y = CDS(step_in_dt, maturity5Y, spd5Y) + cds7Y = CDS(step_in_dt, maturity7Y, spd7Y) + cds10Y = CDS(step_in_dt, maturity10Y, spd10Y) cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y] issuer_curve = CDSCurve(value_dt, @@ -71,7 +71,7 @@ def test_dirty_priceCDSIndexOption(): index_coupon = 0.004 volatility = 0.50 - expiry_date = Date(1, 2, 2008) + expiry_dt = Date(1, 2, 2008) maturity_dt = Date(20, 12, 2011) notional = 10000.0 tolerance = 1e-6 @@ -108,7 +108,7 @@ def test_dirty_priceCDSIndexOption(): ####################################################################### - option = CDSIndexOption(expiry_date, + option = CDSIndexOption(expiry_dt, maturity_dt, index_coupon, strike / 10000.0, diff --git a/tests/test_FinCDSIndexPortfolio.py b/tests/test_FinCDSIndexPortfolio.py index dc94d528..37e8b944 100644 --- a/tests/test_FinCDSIndexPortfolio.py +++ b/tests/test_FinCDSIndexPortfolio.py @@ -12,8 +12,8 @@ def test_CDSIndexPortfolio(): tradeDate = Date(1, 8, 2007) - step_in_date = tradeDate.add_days(1) - value_dt = step_in_date + step_in_dt = tradeDate.add_days(1) + value_dt = step_in_dt libor_curve = build_Ibor_Curve(tradeDate) @@ -38,10 +38,10 @@ def test_CDSIndexPortfolio(): spd10Y = float(splitRow[4]) / 10000.0 recovery_rate = float(splitRow[5]) - cds3Y = CDS(step_in_date, maturity3Y, spd3Y) - cds5Y = CDS(step_in_date, maturity5Y, spd5Y) - cds7Y = CDS(step_in_date, maturity7Y, spd7Y) - cds10Y = CDS(step_in_date, maturity10Y, spd10Y) + cds3Y = CDS(step_in_dt, maturity3Y, spd3Y) + cds5Y = CDS(step_in_dt, maturity5Y, spd5Y) + cds7Y = CDS(step_in_dt, maturity7Y, spd7Y) + cds10Y = CDS(step_in_dt, maturity10Y, spd10Y) cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y] issuer_curve = CDSCurve(value_dt, @@ -55,22 +55,22 @@ def test_CDSIndexPortfolio(): cdsIndex = CDSIndexPortfolio() averageSpd3Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity3Y, issuer_curves) * 10000.0 averageSpd5Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity5Y, issuer_curves) * 10000.0 averageSpd7Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity7Y, issuer_curves) * 10000.0 averageSpd10Y = cdsIndex.average_spread(value_dt, - step_in_date, + step_in_dt, maturity10Y, issuer_curves) * 10000.0 @@ -84,22 +84,22 @@ def test_CDSIndexPortfolio(): cdsIndex = CDSIndexPortfolio() intrinsicSpd3Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity3Y, issuer_curves) * 10000.0 intrinsicSpd5Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity5Y, issuer_curves) * 10000.0 intrinsicSpd7Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity7Y, issuer_curves) * 10000.0 intrinsicSpd10Y = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, maturity10Y, issuer_curves) * 10000.0 diff --git a/tests/test_FinCDSOption.py b/tests/test_FinCDSOption.py index 6b15c31d..65aa3087 100644 --- a/tests/test_FinCDSOption.py +++ b/tests/test_FinCDSOption.py @@ -10,9 +10,9 @@ # This reproduces example on page 38 of Open Gamma note on CDS Option tradeDate = Date(5, 2, 2014) _, issuer_curve = buildFullIssuerCurve(tradeDate) -step_in_date = tradeDate.add_days(1) -value_dt = step_in_date -expiry_date = Date(20, 3, 2014) +step_in_dt = tradeDate.add_days(1) +value_dt = step_in_dt +expiry_dt = Date(20, 3, 2014) maturity_dt = Date(20, 6, 2019) notional = 100.0 @@ -28,7 +28,7 @@ def test_cds_option(): ] for strike, result in strike_result: - cdsOption = CDSOption(expiry_date, + cdsOption = CDSOption(expiry_dt, maturity_dt, strike / 10000.0, notional) diff --git a/tests/test_FinCDSTranche.py b/tests/test_FinCDSTranche.py index 898375fb..b4711ad3 100644 --- a/tests/test_FinCDSTranche.py +++ b/tests/test_FinCDSTranche.py @@ -10,7 +10,7 @@ tradeDate = Date(1, 3, 2007) -step_in_date = tradeDate.add_days(1) +step_in_dt = tradeDate.add_days(1) value_dt = tradeDate.add_days(1) libor_curve = build_Ibor_Curve(tradeDate) @@ -58,7 +58,7 @@ def test_homogeneous(): num_credits) intrinsicSpd = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, trancheMaturity, issuer_curves) * 10000.0 @@ -120,7 +120,7 @@ def test_heterogeneous(): libor_curve) intrinsicSpd = cdsIndex.intrinsic_spread(value_dt, - step_in_date, + step_in_dt, trancheMaturity, issuer_curves) * 10000.0 diff --git a/tests/test_FinEquityAmericanOption.py b/tests/test_FinEquityAmericanOption.py index 9f59917e..aba95ec2 100644 --- a/tests/test_FinEquityAmericanOption.py +++ b/tests/test_FinEquityAmericanOption.py @@ -10,7 +10,7 @@ value_dt = Date(1, 1, 2016) -expiry_date = Date(1, 1, 2017) +expiry_dt = Date(1, 1, 2017) stock_price = 50.0 interest_rate = 0.06 dividend_yield = 0.04 @@ -28,7 +28,7 @@ def test_european_put(): put_option = EquityAmericanOption( - expiry_date, strike_price, OptionTypes.EUROPEAN_PUT) + expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT) value = put_option.value(value_dt, stock_price, discount_curve, dividend_curve, model) @@ -38,7 +38,7 @@ def test_european_put(): def test_american_put(): put_option = EquityAmericanOption( - expiry_date, strike_price, OptionTypes.AMERICAN_PUT) + expiry_dt, strike_price, OptionTypes.AMERICAN_PUT) value = put_option.value(value_dt, stock_price, discount_curve, dividend_curve, model) @@ -48,7 +48,7 @@ def test_american_put(): def test_european_call(): call_option = EquityAmericanOption( - expiry_date, strike_price, OptionTypes.EUROPEAN_CALL) + expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL) value = call_option.value(value_dt, stock_price, discount_curve, dividend_curve, model) @@ -58,7 +58,7 @@ def test_european_call(): def test_american_call(): call_option = EquityAmericanOption( - expiry_date, strike_price, OptionTypes.AMERICAN_CALL) + expiry_dt, strike_price, OptionTypes.AMERICAN_CALL) value = call_option.value(value_dt, stock_price, discount_curve, dividend_curve, model) diff --git a/tests/test_FinEquityAsianOption.py b/tests/test_FinEquityAsianOption.py index f18a3c25..fedd1015 100644 --- a/tests/test_FinEquityAsianOption.py +++ b/tests/test_FinEquityAsianOption.py @@ -11,8 +11,8 @@ value_dt = Date(1, 1, 2014) -startAveragingDate = Date(1, 6, 2014) -expiry_date = Date(1, 1, 2015) +start_averaging_dt = Date(1, 6, 2014) +expiry_dt = Date(1, 1, 2015) stock_price = 100.0 volatility = 0.20 interest_rate = 0.30 @@ -27,8 +27,8 @@ discount_curve = DiscountCurveFlat(value_dt, interest_rate) dividend_curve = DiscountCurveFlat(value_dt, dividend_yield) -asianOption = EquityAsianOption(startAveragingDate, - expiry_date, +asianOption = EquityAsianOption(start_averaging_dt, + expiry_dt, K, OptionTypes.EUROPEAN_CALL, num_observations) diff --git a/tests/test_FinEquityBinomialTree.py b/tests/test_FinEquityBinomialTree.py index ee2e33c7..30d58af1 100644 --- a/tests/test_FinEquityBinomialTree.py +++ b/tests/test_FinEquityBinomialTree.py @@ -18,7 +18,7 @@ volatility = 0.40 value_dt = Date(1, 1, 2016) -expiry_date = Date(1, 1, 2017) +expiry_dt = Date(1, 1, 2017) model = BlackScholes(volatility) discount_curve = DiscountCurveFlat(value_dt, risk_free_rate) @@ -44,7 +44,7 @@ def test_european_put(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) @@ -65,7 +65,7 @@ def test_american_put(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) @@ -86,7 +86,7 @@ def test_european_call(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) @@ -107,7 +107,7 @@ def test_american_call(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) diff --git a/tests/test_FinEquityCliquetOption.py b/tests/test_FinEquityCliquetOption.py index bfc3b1bb..ca912297 100644 --- a/tests/test_FinEquityCliquetOption.py +++ b/tests/test_FinEquityCliquetOption.py @@ -13,12 +13,12 @@ def test_EquityCliquetOption(): start_dt = Date(1, 1, 2014) - final_expiry_date = Date(1, 1, 2017) + final_expiry_dt = Date(1, 1, 2017) freq_type = FrequencyTypes.QUARTERLY option_type = OptionTypes.EUROPEAN_CALL cliquetOption = EquityCliquetOption(start_dt, - final_expiry_date, + final_expiry_dt, option_type, freq_type) diff --git a/tests/test_FinEquityCompoundOption.py b/tests/test_FinEquityCompoundOption.py index 49827bd2..ac6b4fc7 100644 --- a/tests/test_FinEquityCompoundOption.py +++ b/tests/test_FinEquityCompoundOption.py @@ -12,8 +12,8 @@ value_dt = Date(1, 1, 2015) -expiry_date1 = Date(1, 1, 2017) -expiry_date2 = Date(1, 1, 2018) +expiry_dt1 = Date(1, 1, 2017) +expiry_dt2 = Date(1, 1, 2018) k1 = 5.0 k2 = 95.0 stock_price = 85.0 @@ -34,8 +34,8 @@ def test_european(): option_type1 = OptionTypes.EUROPEAN_CALL option_type2 = OptionTypes.EUROPEAN_CALL - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -47,8 +47,8 @@ def test_european(): option_type1 = OptionTypes.EUROPEAN_CALL option_type2 = OptionTypes.EUROPEAN_PUT - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -60,8 +60,8 @@ def test_european(): option_type1 = OptionTypes.EUROPEAN_PUT option_type2 = OptionTypes.EUROPEAN_CALL - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -73,8 +73,8 @@ def test_european(): option_type1 = OptionTypes.EUROPEAN_PUT option_type2 = OptionTypes.EUROPEAN_PUT - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -90,8 +90,8 @@ def test_american(): option_type1 = OptionTypes.AMERICAN_CALL option_type2 = OptionTypes.AMERICAN_CALL - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -103,8 +103,8 @@ def test_american(): option_type1 = OptionTypes.AMERICAN_CALL option_type2 = OptionTypes.AMERICAN_PUT - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -116,8 +116,8 @@ def test_american(): option_type1 = OptionTypes.AMERICAN_PUT option_type2 = OptionTypes.AMERICAN_CALL - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -129,8 +129,8 @@ def test_american(): option_type1 = OptionTypes.AMERICAN_PUT option_type2 = OptionTypes.AMERICAN_PUT - cmpdOption = EquityCompoundOption(expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + cmpdOption = EquityCompoundOption(expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) value = cmpdOption.value(value_dt, stock_price, discount_curve, dividend_curve, model) values = cmpdOption._value_tree(value_dt, stock_price, discount_curve, @@ -145,8 +145,8 @@ def test_greeks(): option_type1 = OptionTypes.EUROPEAN_CALL option_type2 = OptionTypes.EUROPEAN_PUT cmpdOption = EquityCompoundOption( - expiry_date1, option_type1, k1, - expiry_date2, option_type2, k2) + expiry_dt1, option_type1, k1, + expiry_dt2, option_type2, k2) delta = cmpdOption.delta( value_dt, diff --git a/tests/test_FinEquityDigitalOption.py b/tests/test_FinEquityDigitalOption.py index 45d0b6be..602011a1 100644 --- a/tests/test_FinEquityDigitalOption.py +++ b/tests/test_FinEquityDigitalOption.py @@ -14,7 +14,7 @@ underlying_type = FinDigitalOptionTypes.CASH_OR_NOTHING value_dt = Date(1, 1, 2015) -expiry_date = Date(1, 1, 2016) +expiry_dt = Date(1, 1, 2016) stock_price = 100.0 volatility = 0.30 interest_rate = 0.05 @@ -30,7 +30,7 @@ def test_value(): call_option = EquityDigitalOption( - expiry_date, 100.0, OptionTypes.EUROPEAN_CALL, underlying_type) + expiry_dt, 100.0, OptionTypes.EUROPEAN_CALL, underlying_type) value = call_option.value( value_dt, stock_price, @@ -51,7 +51,7 @@ def test_value(): def test_greeks(): call_option = EquityDigitalOption( - expiry_date, 100.0, OptionTypes.EUROPEAN_CALL, underlying_type) + expiry_dt, 100.0, OptionTypes.EUROPEAN_CALL, underlying_type) delta = call_option.delta( value_dt, diff --git a/tests/test_FinEquityForward.py b/tests/test_FinEquityForward.py index 3668f62a..92e0d43d 100644 --- a/tests/test_FinEquityForward.py +++ b/tests/test_FinEquityForward.py @@ -11,20 +11,20 @@ def test_equity_forward(): value_dt = Date(13, 2, 2018) - expiry_date = value_dt.add_months(12) + expiry_dt = value_dt.add_months(12) stock_price = 130.0 forward_price = 125.0 # Locked discount_rate = 0.05 dividend_rate = 0.02 - expiry_date = value_dt.add_months(12) + expiry_dt = value_dt.add_months(12) notional = 100.0 discount_curve = DiscountCurveFlat(value_dt, discount_rate) dividend_curve = DiscountCurveFlat(value_dt, dividend_rate) - equityForward = EquityForward(expiry_date, + equityForward = EquityForward(expiry_dt, forward_price, notional, FinLongShort.LONG) diff --git a/tests/test_FinEquityLookbackOption.py b/tests/test_FinEquityLookbackOption.py index 50b416cf..f46d97ed 100644 --- a/tests/test_FinEquityLookbackOption.py +++ b/tests/test_FinEquityLookbackOption.py @@ -10,7 +10,7 @@ value_dt = Date(1, 1, 2015) -expiry_date = Date(1, 1, 2016) +expiry_dt = Date(1, 1, 2016) stock_price = 100.0 volatility = 0.3 interest_rate = 0.05 @@ -26,7 +26,7 @@ def test_european_call(): option_type = OptionTypes.EUROPEAN_CALL k = 100.0 - option = EquityFixedLookbackOption(expiry_date, option_type, k) + option = EquityFixedLookbackOption(expiry_dt, option_type, k) stockMax = stock_price + 10.0 value = option.value( @@ -53,7 +53,7 @@ def test_european_call(): def test_european_put(): option_type = OptionTypes.EUROPEAN_PUT k = 100.0 - option = EquityFixedLookbackOption(expiry_date, option_type, k) + option = EquityFixedLookbackOption(expiry_dt, option_type, k) stockMin = stock_price - 10 value = option.value( diff --git a/tests/test_FinEquityOneTouchOption.py b/tests/test_FinEquityOneTouchOption.py index da528f25..70e78db3 100644 --- a/tests/test_FinEquityOneTouchOption.py +++ b/tests/test_FinEquityOneTouchOption.py @@ -9,7 +9,7 @@ from financepy.products.equity.equity_one_touch_option import EquityOneTouchOption value_dt = Date(1, 1, 2016) -expiry_date = Date(2, 7, 2016) +expiry_dt = Date(2, 7, 2016) interest_rate = 0.10 volatility = 0.20 barrier_level = 100.0 # H @@ -27,7 +27,7 @@ def test_DOWN_AND_IN_CASH_AT_HIT(): stock_price = 105.0 downType = TouchOptionTypes.DOWN_AND_IN_CASH_AT_HIT - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -52,7 +52,7 @@ def test_DOWN_AND_IN_CASH_AT_HIT(): def test_DOWN_AND_IN_CASH_AT_EXPIRY(): stock_price = 105.0 downType = TouchOptionTypes.DOWN_AND_IN_CASH_AT_EXPIRY - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -77,7 +77,7 @@ def test_DOWN_AND_IN_CASH_AT_EXPIRY(): def test_DOWN_AND_OUT_CASH_OR_NOTHING(): stock_price = 105.0 downType = TouchOptionTypes.DOWN_AND_OUT_CASH_OR_NOTHING - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -102,7 +102,7 @@ def test_DOWN_AND_OUT_CASH_OR_NOTHING(): def test_UP_AND_IN_CASH_AT_HIT(): stock_price = 95.0 downType = TouchOptionTypes.UP_AND_IN_CASH_AT_HIT - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -127,7 +127,7 @@ def test_UP_AND_IN_CASH_AT_HIT(): def test_UP_AND_IN_CASH_AT_EXPIRY(): stock_price = 95.0 downType = TouchOptionTypes.UP_AND_IN_CASH_AT_EXPIRY - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -152,7 +152,7 @@ def test_UP_AND_IN_CASH_AT_EXPIRY(): def test_UP_AND_OUT_CASH_OR_NOTHING(): stock_price = 95.0 downType = TouchOptionTypes.UP_AND_OUT_CASH_OR_NOTHING - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -177,7 +177,7 @@ def test_UP_AND_OUT_CASH_OR_NOTHING(): def test_DOWN_AND_IN_ASSET_AT_HIT(): stock_price = 105.0 downType = TouchOptionTypes.DOWN_AND_IN_ASSET_AT_HIT - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -202,7 +202,7 @@ def test_DOWN_AND_IN_ASSET_AT_HIT(): def test_DOWN_AND_IN_ASSET_AT_EXPIRY(): stock_price = 105.0 downType = TouchOptionTypes.DOWN_AND_IN_ASSET_AT_EXPIRY - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -227,7 +227,7 @@ def test_DOWN_AND_IN_ASSET_AT_EXPIRY(): def test_DOWN_AND_OUT_ASSET_OR_NOTHING(): stock_price = 105.0 downType = TouchOptionTypes.DOWN_AND_OUT_ASSET_OR_NOTHING - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -252,7 +252,7 @@ def test_DOWN_AND_OUT_ASSET_OR_NOTHING(): def test_UP_AND_IN_ASSET_AT_HIT(): stock_price = 95.0 downType = TouchOptionTypes.UP_AND_IN_ASSET_AT_HIT - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -277,7 +277,7 @@ def test_UP_AND_IN_ASSET_AT_HIT(): def test_UP_AND_IN_ASSET_AT_EXPIRY(): stock_price = 95.0 downType = TouchOptionTypes.UP_AND_IN_ASSET_AT_EXPIRY - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -302,7 +302,7 @@ def test_UP_AND_IN_ASSET_AT_EXPIRY(): def test_UP_AND_OUT_ASSET_OR_NOTHING(): stock_price = 95.0 downType = TouchOptionTypes.UP_AND_OUT_ASSET_OR_NOTHING - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) diff --git a/tests/test_FinEquityRainbowOption.py b/tests/test_FinEquityRainbowOption.py index 2360f5b6..816556f2 100644 --- a/tests/test_FinEquityRainbowOption.py +++ b/tests/test_FinEquityRainbowOption.py @@ -11,7 +11,7 @@ from math import sqrt value_dt = Date(1, 1, 2015) -expiry_date = Date(1, 1, 2016) +expiry_dt = Date(1, 1, 2016) interest_rate = 0.05 discount_curve = DiscountCurveFlat(value_dt, interest_rate) @@ -38,7 +38,7 @@ def test_call_on_max(): payoff_type = EquityRainbowOptionTypes.CALL_ON_MAXIMUM payoff_params = [strike] rainbowOption = EquityRainbowOption( - expiry_date, payoff_type, payoff_params, num_assets) + expiry_dt, payoff_type, payoff_params, num_assets) betas = np.ones(num_assets) * sqrt(correlation) corr_matrix = beta_vector_to_corr_matrix(betas) @@ -68,7 +68,7 @@ def test_call_on_min(): payoff_type = EquityRainbowOptionTypes.CALL_ON_MINIMUM payoff_params = [strike] rainbowOption = EquityRainbowOption( - expiry_date, payoff_type, payoff_params, num_assets) + expiry_dt, payoff_type, payoff_params, num_assets) betas = np.ones(num_assets) * sqrt(correlation) corr_matrix = beta_vector_to_corr_matrix(betas) @@ -98,7 +98,7 @@ def test_put_on_max(): payoff_type = EquityRainbowOptionTypes.PUT_ON_MAXIMUM payoff_params = [strike] rainbowOption = EquityRainbowOption( - expiry_date, payoff_type, payoff_params, num_assets) + expiry_dt, payoff_type, payoff_params, num_assets) betas = np.ones(num_assets) * sqrt(correlation) corr_matrix = beta_vector_to_corr_matrix(betas) @@ -128,7 +128,7 @@ def test_put_on_min(): payoff_type = EquityRainbowOptionTypes.PUT_ON_MINIMUM payoff_params = [strike] rainbowOption = EquityRainbowOption( - expiry_date, payoff_type, payoff_params, num_assets) + expiry_dt, payoff_type, payoff_params, num_assets) betas = np.ones(num_assets) * sqrt(correlation) corr_matrix = beta_vector_to_corr_matrix(betas) @@ -180,7 +180,7 @@ def test_call_on_nth(): print(n) payoff_params = [n, strike] rainbowOption = EquityRainbowOption( - expiry_date, payoff_type, payoff_params, num_assets) + expiry_dt, payoff_type, payoff_params, num_assets) betas = np.ones(num_assets) * sqrt(correlation) corr_matrix = beta_vector_to_corr_matrix(betas) @@ -225,7 +225,7 @@ def test_put_on_nth(): print(n) payoff_params = [n, strike] rainbowOption = EquityRainbowOption( - expiry_date, payoff_type, payoff_params, num_assets) + expiry_dt, payoff_type, payoff_params, num_assets) betas = np.ones(num_assets) * sqrt(correlation) corr_matrix = beta_vector_to_corr_matrix(betas) diff --git a/tests/test_FinEquityVolSurface.py b/tests/test_FinEquityVolSurface.py index ae7b4883..f323d64f 100644 --- a/tests/test_FinEquityVolSurface.py +++ b/tests/test_FinEquityVolSurface.py @@ -2,13 +2,13 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +import numpy as np import matplotlib.pyplot as plt from financepy.models.volatility_fns import VolFuncTypes from financepy.utils.date import Date from financepy.market.volatility.equity_vol_surface import EquityVolSurface from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -import numpy as np def test_equity_vol_surface(): @@ -54,18 +54,18 @@ def test_equity_vol_surface(): expiry_dt = expiry_dts[0] delta = 0.10 - vol = equitySurface.vol_from_delta_dt(delta, expiry_dt) + vol = equitySurface.vol_from_delta_date(delta, expiry_dt) assert round(vol[0], 4) == 0.1544 assert round(vol[1], 4) == 4032.9156 expiry_dt = expiry_dts[1] delta = 0.20 - vol = equitySurface.vol_from_delta_dt(delta, expiry_dt) + vol = equitySurface.vol_from_delta_date(delta, expiry_dt) assert round(vol[0], 4) == 0.1555 assert round(vol[1], 4) == 4019.3793 expiry_dt = expiry_dts[6] delta = 0.90 - vol = equitySurface.vol_from_delta_dt(delta, expiry_dt) + vol = equitySurface.vol_from_delta_date(delta, expiry_dt) assert round(vol[0], 4) == 0.3498 assert round(vol[1], 4) == 2199.6665 diff --git a/tests/test_FinFXAmericanOption.py b/tests/test_FinFXAmericanOption.py index d4e77958..bc71deb7 100644 --- a/tests/test_FinFXAmericanOption.py +++ b/tests/test_FinFXAmericanOption.py @@ -28,8 +28,8 @@ strike_fx_rate = 1.250 volatility = 0.10 -dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) -for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) +domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) +foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -46,8 +46,8 @@ def test_call(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -59,8 +59,8 @@ def test_call(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -78,8 +78,8 @@ def test_call(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -91,8 +91,8 @@ def test_call(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -110,8 +110,8 @@ def test_call(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -123,8 +123,8 @@ def test_call(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -144,8 +144,8 @@ def test_put(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -157,8 +157,8 @@ def test_put(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -176,8 +176,8 @@ def test_put(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -189,8 +189,8 @@ def test_put(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -208,8 +208,8 @@ def test_put(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -221,8 +221,8 @@ def test_put(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) diff --git a/tests/test_FinFXBarrierOption.py b/tests/test_FinFXBarrierOption.py index 8a439845..e4803fa7 100644 --- a/tests/test_FinFXBarrierOption.py +++ b/tests/test_FinFXBarrierOption.py @@ -12,7 +12,7 @@ value_dt = Date(1, 1, 2015) -expiry_date = Date(1, 1, 2016) +expiry_dt = Date(1, 1, 2016) currency_pair = "USDJPY" volatility = 0.20 dom_interest_rate = 0.05 @@ -24,8 +24,8 @@ drift = dom_interest_rate - forInterestRate scheme = FinGBMNumericalScheme.ANTITHETIC process_type = ProcessTypes.GBM -dom_discount_curve = DiscountCurveFlat(value_dt, dom_interest_rate) -for_discount_curve = DiscountCurveFlat(value_dt, forInterestRate) +domestic_curve = DiscountCurveFlat(value_dt, dom_interest_rate) +foreign_curve = DiscountCurveFlat(value_dt, forInterestRate) model = BlackScholes(volatility) num_observations_per_year = 100 @@ -37,7 +37,7 @@ def test_DOWN_AND_OUT_CALL(): spot_fx_rate = 50 option_type = FinFXBarrierTypes.DOWN_AND_OUT_CALL - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -48,26 +48,26 @@ def test_DOWN_AND_OUT_CALL(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 0.0000 @@ -80,7 +80,7 @@ def test_DOWN_AND_IN_CALL(): spot_fx_rate = 100 option_type = FinFXBarrierTypes.DOWN_AND_IN_CALL - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -91,26 +91,26 @@ def test_DOWN_AND_IN_CALL(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 9.2270 @@ -123,7 +123,7 @@ def test_UP_AND_OUT_CALL(): spot_fx_rate = 50 option_type = FinFXBarrierTypes.UP_AND_OUT_CALL - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -134,26 +134,26 @@ def test_UP_AND_OUT_CALL(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 0.0003 @@ -166,7 +166,7 @@ def test_UP_AND_IN_CALL(): spot_fx_rate = 100 option_type = FinFXBarrierTypes.UP_AND_IN_CALL - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -177,26 +177,26 @@ def test_UP_AND_IN_CALL(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 9.2067 @@ -209,7 +209,7 @@ def test_UP_AND_OUT_PUT(): spot_fx_rate = 50 option_type = FinFXBarrierTypes.UP_AND_OUT_PUT - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -220,26 +220,26 @@ def test_UP_AND_OUT_PUT(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 46.1145 @@ -252,7 +252,7 @@ def test_UP_AND_IN_PUT(): spot_fx_rate = 100 option_type = FinFXBarrierTypes.UP_AND_IN_PUT - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -263,26 +263,26 @@ def test_UP_AND_IN_PUT(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 2.7444 @@ -295,7 +295,7 @@ def test_DOWN_AND_OUT_PUT(): spot_fx_rate = 50 option_type = FinFXBarrierTypes.DOWN_AND_OUT_PUT - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -306,26 +306,26 @@ def test_DOWN_AND_OUT_PUT(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 0.0000 @@ -338,7 +338,7 @@ def test_DOWN_AND_IN_PUT(): spot_fx_rate = 100 option_type = FinFXBarrierTypes.DOWN_AND_IN_PUT - barrier_option = FXBarrierOption(expiry_date, + barrier_option = FXBarrierOption(expiry_dt, K, currency_pair, option_type, @@ -349,26 +349,26 @@ def test_DOWN_AND_IN_PUT(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value, 4) == 6.3301 diff --git a/tests/test_FinFXForward.py b/tests/test_FinFXForward.py index 458a468b..1cfbb503 100644 --- a/tests/test_FinFXForward.py +++ b/tests/test_FinFXForward.py @@ -39,7 +39,7 @@ def test_FinFXForward(): depo = IborDeposit(settle_dt, maturity_dt, deposit_rate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - for_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + foreign_curve = IborSingleCurve(value_dt, depos, fras, swaps) depos = [] fras = [] @@ -48,7 +48,7 @@ def test_FinFXForward(): depo = IborDeposit(settle_dt, maturity_dt, deposit_rate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - dom_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + domestic_curve = IborSingleCurve(value_dt, depos, fras, swaps) notional = 100.0 notional_currency = forName @@ -60,13 +60,13 @@ def test_FinFXForward(): notional_currency) fwdValue = fxForward.value(value_dt, spot_fx_rate, - dom_discount_curve, for_discount_curve) + domestic_curve, foreign_curve) - fwdFXRate = fxForward.forward(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve) + fwd_fx_rate = fxForward.forward(value_dt, spot_fx_rate, + domestic_curve, + foreign_curve) - assert round(fwdFXRate, 4) == 1.3388 + assert round(fwd_fx_rate, 4) == 1.3388 assert round(fwdValue['value'], 4) == -2.4978 assert round(fwdValue['cash_dom'], 4) == -249.7797 diff --git a/tests/test_FinFXLookbackOption.py b/tests/test_FinFXLookbackOption.py index 1e4acd96..53ca3217 100644 --- a/tests/test_FinFXLookbackOption.py +++ b/tests/test_FinFXLookbackOption.py @@ -10,7 +10,7 @@ value_dt = Date(1, 1, 2015) -expiry_date = Date(1, 1, 2016) +expiry_dt = Date(1, 1, 2016) stock_price = 100.0 volatility = 0.3 num_paths = 10000 @@ -26,7 +26,7 @@ def test_european_call(): option_type = OptionTypes.EUROPEAN_CALL - option = FXFloatLookbackOption(expiry_date, option_type) + option = FXFloatLookbackOption(expiry_dt, option_type) stockMin = stock_price - 10 value = option.value( value_dt, @@ -50,7 +50,7 @@ def test_european_call(): assert round(value_mc, 4) == 23.3281 k = 100.0 - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMin = stock_price value = option.value( value_dt, @@ -76,7 +76,7 @@ def test_european_call(): def test_european_put(): option_type = OptionTypes.EUROPEAN_PUT - option = FXFloatLookbackOption(expiry_date, option_type) + option = FXFloatLookbackOption(expiry_dt, option_type) stockMax = stock_price + 10 value = option.value( value_dt, @@ -100,7 +100,7 @@ def test_european_put(): assert round(value_mc, 4) == 24.2806 k = 105.0 - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMin = stock_price - 10.0 value = option.value( value_dt, diff --git a/tests/test_FinFXOptionSABR.py b/tests/test_FinFXOptionSABR.py index 907c1116..02935f00 100644 --- a/tests/test_FinFXOptionSABR.py +++ b/tests/test_FinFXOptionSABR.py @@ -28,8 +28,8 @@ notional = 1000000.0 -dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) -for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) +domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) +foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -51,8 +51,8 @@ def test_european_call(): "USD") valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueEuropean, 4) == 0.0251 @@ -67,8 +67,8 @@ def test_european_call(): "USD") valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueEuropean, 4) == 0.5277 @@ -85,8 +85,8 @@ def test_american_call(): "USD") valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueAmerican, 4) == 0.0255 @@ -101,8 +101,8 @@ def test_american_call(): "USD") valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueAmerican, 4) == 0.5500 @@ -119,8 +119,8 @@ def test_european_put(): "USD") valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueEuropean, 4) == 0.0797 @@ -135,8 +135,8 @@ def test_european_put(): "USD") valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueEuropean, 4) == 0.0000 @@ -153,8 +153,8 @@ def test_american_put(): "USD") valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueAmerican, 4) == 0.0798 @@ -169,8 +169,8 @@ def test_american_put(): "USD") valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] assert round(valueAmerican, 4) == 0.0000 diff --git a/tests/test_FinFXVanillaOption.py b/tests/test_FinFXVanillaOption.py index 42e4d5bb..85eb6417 100644 --- a/tests/test_FinFXVanillaOption.py +++ b/tests/test_FinFXVanillaOption.py @@ -40,8 +40,8 @@ def test_FinFXVanillaOptionWystupExample1(): notional = 1000000.0 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -57,8 +57,8 @@ def test_FinFXVanillaOptionWystupExample1(): value = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) notional = 1250000.0 @@ -72,8 +72,8 @@ def test_FinFXVanillaOptionWystupExample1(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value['v'], 4) == 0.0251 @@ -91,8 +91,8 @@ def test_FinFXVanillaOptionWystupExample1(): delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(delta['pips_spot_delta'], 4) == 0.3315 @@ -126,8 +126,8 @@ def test_FinFXVanillaOptionWystupExample2(): notional = 1000000.0 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -144,8 +144,8 @@ def test_FinFXVanillaOptionWystupExample2(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value['v'], 4) == 0.0436 @@ -163,8 +163,8 @@ def test_FinFXVanillaOptionWystupExample2(): delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(delta['pips_spot_delta'], 4) == -0.4700 @@ -208,7 +208,7 @@ def test_FinFXVanillaOptionBloombergExample(): depo = IborDeposit(settle_dt, maturity_dt, domDepoRate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - dom_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + domestic_curve = IborSingleCurve(value_dt, depos, fras, swaps) depos = [] fras = [] @@ -216,7 +216,7 @@ def test_FinFXVanillaOptionBloombergExample(): depo = IborDeposit(settle_dt, maturity_dt, forDepoRate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - for_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + foreign_curve = IborSingleCurve(value_dt, depos, fras, swaps) model = BlackScholes(volatility) @@ -230,8 +230,8 @@ def test_FinFXVanillaOptionBloombergExample(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(value['v'], 4) == 0.0601 @@ -249,8 +249,8 @@ def test_FinFXVanillaOptionBloombergExample(): delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(delta['pips_spot_delta'], 4) == 0.3671 @@ -268,8 +268,8 @@ def test_value_mc(): dom_interest_rate = 0.08 forInterestRate = 0.11 model = BlackScholes(volatility) - dom_discount_curve = DiscountCurveFlat(value_dt, dom_interest_rate) - for_discount_curve = DiscountCurveFlat(value_dt, forInterestRate) + domestic_curve = DiscountCurveFlat(value_dt, dom_interest_rate) + foreign_curve = DiscountCurveFlat(value_dt, forInterestRate) num_paths = 100000 strike_fx_rate = 1.6 @@ -284,8 +284,8 @@ def test_value_mc(): value_mc = call_option.value_mc( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model, num_paths) @@ -301,8 +301,8 @@ def test_value_mc(): value_mc = put_option.value_mc( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model, num_paths) @@ -318,8 +318,8 @@ def test_vega_theta(): dom_interest_rate = 0.08 forInterestRate = 0.11 model = BlackScholes(volatility) - dom_discount_curve = DiscountCurveFlat(value_dt, dom_interest_rate) - for_discount_curve = DiscountCurveFlat(value_dt, forInterestRate) + domestic_curve = DiscountCurveFlat(value_dt, dom_interest_rate) + foreign_curve = DiscountCurveFlat(value_dt, forInterestRate) strike_fx_rate = 1.6 @@ -333,8 +333,8 @@ def test_vega_theta(): vega = call_option.vega( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(vega, 4) == 0.3518 @@ -342,8 +342,8 @@ def test_vega_theta(): theta = call_option.theta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) assert round(theta, 4) == -0.0504 diff --git a/tests/test_FinFXVolSurface.py b/tests/test_FinFXVolSurface.py index d7e403b8..41394600 100644 --- a/tests/test_FinFXVolSurface.py +++ b/tests/test_FinFXVolSurface.py @@ -24,8 +24,8 @@ def test_FinFXMktVolSurface1(capsys): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -37,7 +37,7 @@ def test_FinFXMktVolSurface1(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK @@ -45,13 +45,13 @@ def test_FinFXMktVolSurface1(capsys): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -71,8 +71,8 @@ def test_FinFXMktVolSurface2(capsys): forCCRate = 0.0294 # EUR domCCRate = 0.0171 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 90.72 @@ -84,20 +84,20 @@ def test_FinFXMktVolSurface2(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ delta_method = FinFXDeltaMethod.SPOT_DELTA_PREM_ADJ fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) fxMarket.check_calibration(verboseCalibration, tol=0.0005) @@ -116,8 +116,8 @@ def test_FinFXMktVolSurface3(capsys): forCCRate = 0.020113 # EUR domCCRate = 0.003525 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3088 @@ -129,20 +129,20 @@ def test_FinFXMktVolSurface3(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) fxMarket.check_calibration(verboseCalibration) @@ -160,8 +160,8 @@ def test_FinFXMktVolSurface4(capsys): forCCRate = 0.003525 # USD domCCRate = 0.0042875 # JPY - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 90.68 @@ -173,20 +173,20 @@ def test_FinFXMktVolSurface4(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA_PREM_ADJ fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) fxMarket.check_calibration(verboseCalibration) diff --git a/tests/test_FinFXVolSurfacePlus.py b/tests/test_FinFXVolSurfacePlus.py index 7fc22aac..053eabbc 100644 --- a/tests/test_FinFXVolSurfacePlus.py +++ b/tests/test_FinFXVolSurfacePlus.py @@ -27,8 +27,8 @@ def test_FinFXMktVolSurface1(capsys): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -43,7 +43,7 @@ def test_FinFXMktVolSurface1(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK5 alpha = 0.5 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -52,8 +52,8 @@ def test_FinFXMktVolSurface1(capsys): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -61,7 +61,7 @@ def test_FinFXMktVolSurface1(capsys): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -81,8 +81,8 @@ def test_FinFXMktVolSurface2(capsys): forCCRate = 0.0294 # EUR domCCRate = 0.0171 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 90.72 @@ -98,7 +98,7 @@ def test_FinFXMktVolSurface2(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ delta_method = FinFXDeltaMethod.SPOT_DELTA_PREM_ADJ vol_functionType = VolFuncTypes.CLARK5 @@ -106,8 +106,8 @@ def test_FinFXMktVolSurface2(capsys): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -115,7 +115,7 @@ def test_FinFXMktVolSurface2(capsys): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -136,8 +136,8 @@ def test_FinFXMktVolSurface3(capsys): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -154,7 +154,7 @@ def test_FinFXMktVolSurface3(capsys): # I HAVE NO YET MADE DELTA METHOD A VECTOR FOR EACH TERM AS I WOULD # NEED TO DO AS DESCRIBED IN CLARK PAGE 70 - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.FORWARD_DELTA # THIS IS DIFFERENT vol_functionType = VolFuncTypes.CLARK5 alpha = 0.5 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -163,8 +163,8 @@ def test_FinFXMktVolSurface3(capsys): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -172,7 +172,7 @@ def test_FinFXMktVolSurface3(capsys): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -196,8 +196,8 @@ def test_FinFXMktVolSurface4(capsys): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -215,7 +215,7 @@ def test_FinFXMktVolSurface4(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK alpha = 0.50 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -224,8 +224,8 @@ def test_FinFXMktVolSurface4(capsys): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -233,7 +233,7 @@ def test_FinFXMktVolSurface4(capsys): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -257,8 +257,8 @@ def test_FinFXMktVolSurface5(capsys): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -276,7 +276,7 @@ def test_FinFXMktVolSurface5(capsys): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK alpha = 0.50 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -285,8 +285,8 @@ def test_FinFXMktVolSurface5(capsys): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -294,11 +294,10 @@ def test_FinFXMktVolSurface5(capsys): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) fxMarketPlus.check_calibration(verboseCalibration) captured = capsys.readouterr() assert captured.out == "" - diff --git a/tests/test_FinIborDualCurve.py b/tests/test_FinIborDualCurve.py index 650b2f65..07bb2858 100644 --- a/tests/test_FinIborDualCurve.py +++ b/tests/test_FinIborDualCurve.py @@ -33,99 +33,99 @@ def buildOIS(value_dt): swaps = [] fixed_freq_type = FrequencyTypes.SEMI_ANNUAL - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F swap_rate = 0.000022 maturity_dt = settle_dt.add_months(24) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, - fixed_freq_type, fixedDCCType) + fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap_rate += 0.000 fixed_leg_type = SwapTypes.PAY maturity_dt = settle_dt.add_months(36) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, - fixed_freq_type, fixedDCCType) + fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap_rate += 0.000 maturity_dt = settle_dt.add_months(48) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) swap_rate = 0.02 maturity_dt = settle_dt.add_months(60) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(72) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(84) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(96) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(108) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(120) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(132) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(144) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(180) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(240) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(300) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(360) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) oisCurve = OISCurve(value_dt, diff --git a/tests/test_FinModelCIR.py b/tests/test_FinModelCIR.py index e2ee086e..0a725de8 100644 --- a/tests/test_FinModelCIR.py +++ b/tests/test_FinModelCIR.py @@ -2,8 +2,8 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### -from financepy.models.cir_mc import CIRNumericalScheme -from financepy.models.cir_mc import zero_price_mc, zero_price +from financepy.models.cir_montecarlo import CIRNumericalScheme +from financepy.models.cir_montecarlo import zero_price_mc, zero_price import numpy as np r0 = 0.05 diff --git a/tests/test_FinModelHeston.py b/tests/test_FinModelHeston.py index 4d47d472..13ef0349 100644 --- a/tests/test_FinModelHeston.py +++ b/tests/test_FinModelHeston.py @@ -11,7 +11,7 @@ # Reference see table 4.1 of Rouah book value_dt = Date(1, 1, 2015) -expiry_date = Date(1, 4, 2015) +expiry_dt = Date(1, 4, 2015) v0 = 0.05 # initial variance of volatility theta = 0.05 # long term variance kappa = 2.0 # speed of variance reversion @@ -33,7 +33,7 @@ def test_heston(): hestonModel = Heston(v0, kappa, theta, sigma, rho) call_option = EquityVanillaOption( - expiry_date, strike_price, OptionTypes.EUROPEAN_CALL) + expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL) value_mc_Heston = hestonModel.value_mc( value_dt, diff --git a/tests/test_FinModelMerton.py b/tests/test_FinModelMerton.py index 947f4989..98fc2d3f 100644 --- a/tests/test_FinModelMerton.py +++ b/tests/test_FinModelMerton.py @@ -10,16 +10,16 @@ def test_merton(): # Input Equity values and equity vols equity_value = [2.6406, 2.6817, 3.977, 2.947, 2.528] equity_vol = [0.7103, 0.3929, 0.3121, 0.4595, 0.6181] - bondFace = [4.0, 3.5, 3.5, 3.2, 4.0] + bond_face = [4.0, 3.5, 3.5, 3.2, 4.0] risk_free_rate = [0.05, 0.05, 0.05, 0.05, 0.05] - assetGrowthRate = [0.0306, 0.03, 0.031, 0.0302, 0.0305] - timeToMaturity = 1.0 # np.linspace(0.1, 10, 100) + asset_growth_rate = [0.0306, 0.03, 0.031, 0.0302, 0.0305] + years_to_maturity = 1.0 # np.linspace(0.1, 10, 100) model = MertonFirmMkt(equity_value, - bondFace, - timeToMaturity, + bond_face, + years_to_maturity, risk_free_rate, - assetGrowthRate, + asset_growth_rate, equity_vol) assert [round(x, 4) for x in model.debt_value()] == [ @@ -31,15 +31,15 @@ def test_merton(): assert [round(x*1e2, 4) for x in model.prob_default() ] == [6.3791, .0768, 0.0005, 0.2622, 3.4408] - assetValue = model._A - assetVol = model._vA + asset_value = model._A + asset_vol = model._vA - model = MertonFirm(assetValue, - bondFace, - timeToMaturity, + model = MertonFirm(asset_value, + bond_face, + years_to_maturity, risk_free_rate, - assetGrowthRate, - assetVol) + asset_growth_rate, + asset_vol) assert [round(x, 4) for x in model.debt_value()] == [ 3.7804, 3.3292, 3.3293, 3.0436, 3.7951] @@ -52,19 +52,19 @@ def test_merton(): assert [round(x, 4) for x in model.dist_default()] == [ 1.5237, 3.1679, 4.4298, 2.7916, 1.8196] - assetValue = 140.0 - bondFace = 100.0 - timeToMaturity = 1.0 + asset_value = 140.0 + bond_face = 100.0 + years_to_maturity = 1.0 risk_free_rate = 0.05 - assetGrowthRate = 0.05 - assetVol = 0.20 + asset_growth_rate = 0.05 + asset_vol = 0.20 - model = MertonFirm(assetValue, - bondFace, - timeToMaturity, + model = MertonFirm(asset_value, + bond_face, + years_to_maturity, risk_free_rate, - assetGrowthRate, - assetVol) + asset_growth_rate, + asset_vol) assert round(model.debt_value(), 4) == 94.8894 assert round(model.credit_spread()*10000, 4) == 24.5829 diff --git a/tests/test_FinModelRatesLMM.py b/tests/test_FinModelRatesLMM.py index 749bab4d..8237c123 100644 --- a/tests/test_FinModelRatesLMM.py +++ b/tests/test_FinModelRatesLMM.py @@ -35,17 +35,17 @@ def test_HullBookExamples(capsys): ########################################################################### use_sobol = 1 - numeraireIndex = 0 + numeraire_index = 0 # We need the volatility for the forward rates out to the one starting in # 10 years. So we have 11 elements. The one starting today has zero vol. - numFactors = 1 + num_factors = 1 gammas1FList = [0.00, 0.1550, 0.2063674, 0.1720986, 0.1721993, 0.1524579, 0.1414779, 0.1297711, 0.1381053, 0.135955, 0.1339842] gammas1F = np.array(gammas1FList) # One factor model - fwds1F = lmm_simulate_fwds_1f(numFwds, num_paths, numeraireIndex, fwd0, + fwds1F = lmm_simulate_fwds_1f(numFwds, num_paths, numeraire_index, fwd0, gammas1F, taus, use_sobol, seed) # LMMPrintForwards(fwds1F) @@ -68,13 +68,13 @@ def test_HullBookExamples(capsys): check_vector_differences(vStickyCaplets, hullStickyCaplets1F, 1e-2) - numFactors = 1 + num_factors = 1 lambdas1FList = [[0.0, 0.1550, 0.2064, 0.1721, 0.1722, 0.1525, 0.1415, 0.1298, 0.1381, 0.1360, 0.1340]] lambdas1F = np.array(lambdas1FList) # One factor model - fwdsMF = lmm_simulate_fwds_mf(numFwds, numFactors, num_paths, numeraireIndex, + fwdsMF = lmm_simulate_fwds_mf(numFwds, num_factors, num_paths, numeraire_index, fwd0, lambdas1F, taus, use_sobol, seed) vRatchetCaplets = lmm_ratchet_caplet_pricer(spread, numFwds, num_paths, @@ -93,7 +93,7 @@ def test_HullBookExamples(capsys): check_vector_differences(vStickyCaplets, hullStickyCaplets1F, 1e-2) - numFactors = 3 + num_factors = 3 lambdas3FList = [[0.00, 0.1365, 0.1928, 0.1672, 0.1698, 0.1485, 0.1395, 0.1261, 0.1290, 0.1197, 0.1097], [0.0, -0.0662, -0.0702, -0.0406, -0.0206, 0.00, @@ -103,7 +103,7 @@ def test_HullBookExamples(capsys): lambdas3F = np.array(lambdas3FList) # Three factor model - fwds3F = lmm_simulate_fwds_mf(numFwds, numFactors, num_paths, numeraireIndex, + fwds3F = lmm_simulate_fwds_mf(numFwds, num_factors, num_paths, numeraire_index, fwd0, lambdas3F, taus, use_sobol, seed) hullRatchetCaplets3F = [0.00, 0.194, 0.207, 0.205, 0.198, 0.193, diff --git a/tests/test_FinOISCurve.py b/tests/test_FinOISCurve.py index 0469b383..01599822 100644 --- a/tests/test_FinOISCurve.py +++ b/tests/test_FinOISCurve.py @@ -27,10 +27,10 @@ def test_bloombergPricingExample(): # We do the O/N rate which settles on trade date spot_days = 0 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) accrual = DayCountTypes.THIRTY_E_360 - depo = IborDeposit(settleDt, "1D", 1.712 / 100.0, accrual) + depo = IborDeposit(settle_dt, "1D", 1.712 / 100.0, accrual) depos = [depo] futs = [] @@ -58,60 +58,60 @@ def test_bloombergPricingExample(): accrual = DayCountTypes.THIRTY_E_360 freq = FrequencyTypes.SEMI_ANNUAL spot_days = 2 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) payRec = SwapTypes.PAY lag = 1 # Not used swaps = [] - swap = OIS(settleDt, "2Y", payRec, + swap = OIS(settle_dt, "2Y", payRec, (2.77417 + 2.77844) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "3Y", payRec, + swap = OIS(settle_dt, "3Y", payRec, (2.86098 + 2.86582) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "4Y", payRec, + swap = OIS(settle_dt, "4Y", payRec, (2.90240 + 2.90620) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "5Y", payRec, + swap = OIS(settle_dt, "5Y", payRec, (2.92944 + 2.92906) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "6Y", payRec, + swap = OIS(settle_dt, "6Y", payRec, (2.94001 + 2.94499) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "7Y", payRec, + swap = OIS(settle_dt, "7Y", payRec, (2.95352 + 2.95998) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "8Y", payRec, + swap = OIS(settle_dt, "8Y", payRec, (2.96830 + 2.97400) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "9Y", payRec, + swap = OIS(settle_dt, "9Y", payRec, (2.98403 + 2.98817) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "10Y", payRec, + swap = OIS(settle_dt, "10Y", payRec, (2.99716 + 3.00394) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "11Y", payRec, + swap = OIS(settle_dt, "11Y", payRec, (3.01344 + 3.01596) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "12Y", payRec, + swap = OIS(settle_dt, "12Y", payRec, (3.02276 + 3.02684) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "15Y", payRec, + swap = OIS(settle_dt, "15Y", payRec, (3.04092 + 3.04508) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "20Y", payRec, + swap = OIS(settle_dt, "20Y", payRec, (3.04417 + 3.05183) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "25Y", payRec, + swap = OIS(settle_dt, "25Y", payRec, (3.03219 + 3.03621) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "30Y", payRec, + swap = OIS(settle_dt, "30Y", payRec, (3.01030 + 3.01370) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "40Y", payRec, + swap = OIS(settle_dt, "40Y", payRec, (2.96946 + 2.97354) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "50Y", payRec, + swap = OIS(settle_dt, "50Y", payRec, (2.91552 + 2.93748) / 200, freq, accrual) swaps.append(swap) @@ -124,8 +124,8 @@ def test_bloombergPricingExample(): assert round(swaps[0]._float_leg.value( value_dt, oisCurve, None), 4) == 53708.2780 - assert round(swaps[0].value(settleDt, oisCurve, None), 4) == 0.0 - assert round(-swaps[0]._fixed_leg.value(settleDt, + assert round(swaps[0].value(settle_dt, oisCurve, None), 4) == 0.0 + assert round(-swaps[0]._fixed_leg.value(settle_dt, oisCurve), 4) == 53714.3020 assert round(swaps[0]._float_leg.value( - settleDt, oisCurve, None), 4) == 53714.3020 + settle_dt, oisCurve, None), 4) == 53714.3020 diff --git a/tests_golden/TestFinBond.py b/tests_golden/TestFinBond.py index ee074125..05414578 100644 --- a/tests_golden/TestFinBond.py +++ b/tests_golden/TestFinBond.py @@ -87,7 +87,7 @@ def build_Ibor_Curve(value_dt): depos.append(depo5) fras = [] - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F fixed_freq_type = FrequencyTypes.SEMI_ANNUAL swaps = [] @@ -100,7 +100,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) # print(swap1._fixed_leg._payment_dts) @@ -113,7 +113,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap2) # print(swap2._fixed_leg._payment_dts) @@ -125,7 +125,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap3) # print(swap3._fixed_leg._payment_dts) @@ -137,7 +137,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap4) # print(swap4._fixed_leg._payment_dts) @@ -149,7 +149,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap5) # print(swap5._fixed_leg._payment_dts) @@ -161,7 +161,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap6) # print(swap6._fixed_leg._payment_dts) @@ -173,7 +173,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap7) # print(swap7._fixed_leg._payment_dts) @@ -185,7 +185,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap8) # print(swap8._fixed_leg._payment_dts) @@ -197,7 +197,7 @@ def build_Ibor_Curve(value_dt): SwapTypes.PAY, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap9) # print(swap9._fixed_leg._payment_dts) @@ -503,7 +503,7 @@ def test_BondExDividend(): settle_dt = Date(7, 9, 2003) accrued = bond.accrued_interest(settle_dt, face) - test_cases.print("SettlementDate:", settle_dt) + test_cases.print("settle_dt:", settle_dt) test_cases.print("Accrued:", accrued) ########################################################################### @@ -617,7 +617,7 @@ def test_key_rate_durations(): coupon = 0.0275 ex_div_days = 0 - dc_type, freq_type, settlementDays, exDiv, calendar = \ + dc_type, freq_type, settle_days, exDiv, calendar = \ get_bond_market_conventions(BondMarkets.UNITED_STATES) bond = Bond(issue_dt, maturity_dt, coupon, freq_type, dc_type, ex_div_days) @@ -636,7 +636,7 @@ def test_key_rate_durations(): def test_key_rate_durations_Bloomberg_example(): - dc_type, frequencyType, settlementDays, exDiv, calendar =\ + dc_type, frequencyType, settle_days, exDiv, calendar =\ get_bond_market_conventions(BondMarkets.UNITED_STATES) # interest accrues on this date. Issue date is 01/08/2022 @@ -645,7 +645,7 @@ def test_key_rate_durations_Bloomberg_example(): coupon = 2.75/100.0 ex_div_days = 0 - dc_type, freq_type, settlementDays, exDiv, calendar =\ + dc_type, freq_type, settle_days, exDiv, calendar =\ get_bond_market_conventions(BondMarkets.UNITED_STATES) bond = Bond(issue_dt, maturity_dt, coupon, @@ -722,13 +722,13 @@ def test_div_dts(): clean_price = 99.7808417 # if face is 1 then this must be 0.99780842 - settlementDate = Date(15, 5, 2023) - print(bond.bond_payments(settlementDate, face)) + settle_dt = Date(15, 5, 2023) + print(bond.bond_payments(settle_dt, face)) current_yield = bond.current_yield(clean_price)*100 print("Currnt Yield: %10.5f %%" % (current_yield)) - ytm = bond.yield_to_maturity(settlementDate, clean_price) * 100.0 + ytm = bond.yield_to_maturity(settle_dt, clean_price) * 100.0 print("Yield to Mat: %10.5f %%" % (ytm)) ############################################################################### diff --git a/tests_golden/TestFinBondConvertible.py b/tests_golden/TestFinBondConvertible.py index a4410367..c966025e 100644 --- a/tests_golden/TestFinBondConvertible.py +++ b/tests_golden/TestFinBondConvertible.py @@ -32,13 +32,13 @@ def test_BondConvertible(): accrualBasis = DayCountTypes.ACT_365F call_price = 1100 - call_dates = [Date(20, 3, 2007), + call_dts = [Date(20, 3, 2007), Date(15, 3, 2012), Date(15, 3, 2017)] call_prices = np.array([call_price, call_price, call_price]) putPrice = 90 - put_dates = [Date(20, 3, 2007), + put_dts = [Date(20, 3, 2007), Date(15, 3, 2012), Date(15, 3, 2017)] put_prices = np.array([putPrice, putPrice, putPrice]) @@ -48,9 +48,9 @@ def test_BondConvertible(): freq_type, start_convert_date, conversion_ratio, - call_dates, + call_dts, call_prices, - put_dates, + put_dts, put_prices, accrualBasis) # print(bond) diff --git a/tests_golden/TestFinBondFRN.py b/tests_golden/TestFinBondFRN.py index 6fa49117..678d5c2d 100644 --- a/tests_golden/TestFinBondFRN.py +++ b/tests_golden/TestFinBondFRN.py @@ -26,7 +26,7 @@ def build_Ibor_Curve(value_dt): depoDCCType = DayCountTypes.THIRTY_E_360_ISDA depos = [] - payFixed = SwapTypes.PAY + pay_fixed = SwapTypes.PAY spot_days = 2 settle_dt = value_dt.add_weekdays(spot_days) @@ -74,7 +74,7 @@ def build_Ibor_Curve(value_dt): depos.append(depo5) fras = [] - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F fixed_freq_type = FrequencyTypes.SEMI_ANNUAL swaps = [] @@ -85,9 +85,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap1) maturity_dt = settle_dt.add_months(36) @@ -95,9 +95,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap2) maturity_dt = settle_dt.add_months(48) @@ -105,9 +105,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap3) maturity_dt = settle_dt.add_months(60) @@ -115,9 +115,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap4) maturity_dt = settle_dt.add_months(72) @@ -125,9 +125,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap5) maturity_dt = settle_dt.add_months(84) @@ -135,9 +135,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap6) maturity_dt = settle_dt.add_months(96) @@ -145,9 +145,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap7) maturity_dt = settle_dt.add_months(108) @@ -155,9 +155,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap8) maturity_dt = settle_dt.add_months(120) @@ -165,9 +165,9 @@ def build_Ibor_Curve(value_dt): settle_dt, maturity_dt, swap_rate, - payFixed, + pay_fixed, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap9) libor_curve = IborSingleCurve(value_dt, diff --git a/tests_golden/TestFinBondYieldCurve.py b/tests_golden/TestFinBondYieldCurve.py index c7083d7c..505d4463 100644 --- a/tests_golden/TestFinBondYieldCurve.py +++ b/tests_golden/TestFinBondYieldCurve.py @@ -103,8 +103,8 @@ def test_BondYieldCurve(): ############################################################################### maturity_dt = Date(19, 9, 2030) - interpolated_yield = fitted_curve5.interpolated_yield(maturity_dt) - test_cases.print(maturity_dt, interpolated_yield) + interp_yield = fitted_curve5.interp_yield(maturity_dt) + test_cases.print(maturity_dt, interp_yield) ############################################################################### diff --git a/tests_golden/TestFinCDS.py b/tests_golden/TestFinCDS.py index 6e7571c5..a5f9d975 100644 --- a/tests_golden/TestFinCDS.py +++ b/tests_golden/TestFinCDS.py @@ -420,18 +420,18 @@ def test_dirty_priceCDS1(): accrued_interest = cds_contract.accrued_interest() test_cases.print("ACCRUED_COUPON", accrued_interest) - prot_pv = cds_contract.protection_leg_pv( + prot_pv = cds_contract.prot_leg_pv( value_dt, issuer_curve, cdsRecovery) - test_cases.print("PROTECTION_PV", prot_pv) + test_cases.print("prot_PV", prot_pv) premPV = cds_contract.premium_leg_pv( value_dt, issuer_curve, cdsRecovery) test_cases.print("PREMIUM_PV", premPV) - dirtyRPV01, cleanRPV01 = cds_contract.risky_pv01( + dirty_rpv01, clean_rpv01 = cds_contract.risky_pv01( value_dt, issuer_curve) - test_cases.print("DIRTY_RPV01", dirtyRPV01) - test_cases.print("CLEAN_RPV01", cleanRPV01) + test_cases.print("DIRTY_RPV01", dirty_rpv01) + test_cases.print("CLEAN_RPV01", clean_rpv01) # cds_contract.print_payments(issuer_curve) @@ -635,9 +635,9 @@ def test_dirty_priceCDSModelCheck(): accrued_interest = cds_contract.accrued_interest() test_cases.print("ACCRUED_COUPON", accrued_interest) - prot_pv = cds_contract.protection_leg_pv( + prot_pv = cds_contract.prot_leg_pv( value_dt, issuer_curve, cdsRecovery) - test_cases.print("PROTECTION_PV", prot_pv) + test_cases.print("prot_PV", prot_pv) premPV = cds_contract.premium_leg_pv( value_dt, issuer_curve, cdsRecovery) diff --git a/tests_golden/TestFinCDSCurve.py b/tests_golden/TestFinCDSCurve.py index 45ccdd46..eabca2fc 100644 --- a/tests_golden/TestFinCDSCurve.py +++ b/tests_golden/TestFinCDSCurve.py @@ -2,11 +2,11 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### -import numpy as np - import sys sys.path.append("..") +import numpy as np + from FinTestCases import FinTestCases, globalTestCaseMode from financepy.utils.global_types import SwapTypes from financepy.utils.date import Date @@ -106,18 +106,18 @@ def test_CDS_recovery_rate(): value_dt = Date(15, 8, 2022) settle_dt = value_dt - swapType = SwapTypes.PAY + swap_type = SwapTypes.PAY dcType = DayCountTypes.ACT_360 fixedFreq = FrequencyTypes.MONTHLY - swap1 = IborSwap(settle_dt,"2Y",swapType,0.03512100,fixedFreq,dcType) - swap2 = IborSwap(settle_dt,"3Y",swapType,0.03259300,fixedFreq,dcType) - swap3 = IborSwap(settle_dt,"4Y",swapType,0.03069300,fixedFreq,dcType) - swap4 = IborSwap(settle_dt,"5Y",swapType,0.02952200,fixedFreq,dcType) - swap5 = IborSwap(settle_dt,"6Y",swapType,0.02889300,fixedFreq,dcType) - swap6 = IborSwap(settle_dt,"7Y",swapType,0.02850200,fixedFreq,dcType) - swap7 = IborSwap(settle_dt,"8Y",swapType,0.02827400,fixedFreq,dcType) - swap8 = IborSwap(settle_dt,"9Y",swapType,0.02818500,fixedFreq,dcType) - swap9 = IborSwap(settle_dt,"10Y",swapType,0.02823000,fixedFreq,dcType) + swap1 = IborSwap(settle_dt,"2Y",swap_type,0.03512100,fixedFreq,dcType) + swap2 = IborSwap(settle_dt,"3Y",swap_type,0.03259300,fixedFreq,dcType) + swap3 = IborSwap(settle_dt,"4Y",swap_type,0.03069300,fixedFreq,dcType) + swap4 = IborSwap(settle_dt,"5Y",swap_type,0.02952200,fixedFreq,dcType) + swap5 = IborSwap(settle_dt,"6Y",swap_type,0.02889300,fixedFreq,dcType) + swap6 = IborSwap(settle_dt,"7Y",swap_type,0.02850200,fixedFreq,dcType) + swap7 = IborSwap(settle_dt,"8Y",swap_type,0.02827400,fixedFreq,dcType) + swap8 = IborSwap(settle_dt,"9Y",swap_type,0.02818500,fixedFreq,dcType) + swap9 = IborSwap(settle_dt,"10Y",swap_type,0.02823000,fixedFreq,dcType) swaps = [swap1,swap2,swap3,swap4,swap5,swap6,swap7,swap8,swap9] libor_curve = IborSingleCurve(value_dt, [], [], swaps) diff --git a/tests_golden/TestFinCDSIndex.py b/tests_golden/TestFinCDSIndex.py index 5dd027d9..c2db2c7d 100644 --- a/tests_golden/TestFinCDSIndex.py +++ b/tests_golden/TestFinCDSIndex.py @@ -160,7 +160,7 @@ def test_valueCDSIndex(): accrued_interest = cdsIndexContract.accrued_interest() test_cases.print("ACCRUED COUPON", accrued_interest) - prot_pv = cdsIndexContract.protection_leg_pv( + prot_pv = cdsIndexContract.prot_leg_pv( value_dt, issuer_curve, cdsRecovery) test_cases.print("PROTECTION LEG PV", prot_pv) @@ -168,10 +168,10 @@ def test_valueCDSIndex(): value_dt, issuer_curve, cdsRecovery) test_cases.print("PREMIUM LEG PV", premPV) - dirtyRPV01, cleanRPV01 = cdsIndexContract.risky_pv01( + dirty_rpv01, clean_rpv01 = cdsIndexContract.risky_pv01( value_dt, issuer_curve) - test_cases.print("DIRTY RPV01", dirtyRPV01) - test_cases.print("CLEAN RPV01", cleanRPV01) + test_cases.print("DIRTY RPV01", dirty_rpv01) + test_cases.print("CLEAN RPV01", clean_rpv01) # cdsIndexContract.print_payments(issuer_curve) diff --git a/tests_golden/TestFinCDSOption.py b/tests_golden/TestFinCDSOption.py index 5213a6f4..18034f95 100644 --- a/tests_golden/TestFinCDSOption.py +++ b/tests_golden/TestFinCDSOption.py @@ -258,7 +258,7 @@ def test_dirty_priceCDSwaption(): accrued_interest = cds_contract.accrued_interest() test_cases.print("ACCRUED COUPON", accrued_interest) - prot_pv = cds_contract.protection_leg_pv( + prot_pv = cds_contract.prot_leg_pv( value_dt, issuer_curve, cdsRecovery) test_cases.print("PROTECTION LEG PV", prot_pv) @@ -266,10 +266,10 @@ def test_dirty_priceCDSwaption(): value_dt, issuer_curve, cdsRecovery) test_cases.print("PREMIUM LEG PV", premPV) - fullRPV01, cleanRPV01 = cds_contract.risky_pv01( + fullRPV01, clean_rpv01 = cds_contract.risky_pv01( value_dt, issuer_curve) test_cases.print("FULL RPV01", fullRPV01) - test_cases.print("CLEAN RPV01", cleanRPV01) + test_cases.print("CLEAN RPV01", clean_rpv01) # cds_contract.print_payments(issuer_curve) @@ -294,7 +294,7 @@ def test_dirty_priceCDSwaption(): test_cases.print("DIRTY VALUE", v['dirty_pv']) test_cases.print("CLEAN VALUE", v['clean_pv']) - prot_pv = cds_contract.protection_leg_pv( + prot_pv = cds_contract.prot_leg_pv( value_dt, issuer_curve, cdsRecovery) test_cases.print("PROTECTION LEG PV", prot_pv) @@ -302,10 +302,10 @@ def test_dirty_priceCDSwaption(): value_dt, issuer_curve, cdsRecovery) test_cases.print("PREMIUM LEG PV", premPV) - dirtyRPV01, cleanRPV01 = cds_contract.risky_pv01( + dirty_rpv01, clean_rpv01 = cds_contract.risky_pv01( value_dt, issuer_curve) - test_cases.print("DIRTY RPV01", dirtyRPV01) - test_cases.print("CLEAN RPV01", cleanRPV01) + test_cases.print("DIRTY RPV01", dirty_rpv01) + test_cases.print("CLEAN RPV01", clean_rpv01) # cds_contract.print_payments(issuer_curve) diff --git a/tests_golden/TestFinDayCount.py b/tests_golden/TestFinDayCount.py index 6f013bf8..ef040464 100644 --- a/tests_golden/TestFinDayCount.py +++ b/tests_golden/TestFinDayCount.py @@ -25,10 +25,10 @@ def test_FinDayCount(): start_dt = Date(1, 1, 2019) next_dt = start_dt - numDays = 20 + num_days = 20 day_count = DayCount(day_count_method) - for _ in range(0, numDays): + for _ in range(0, num_days): next_dt = next_dt.add_days(7) dcf = day_count.year_frac( start_dt, next_dt, next_dt, finFreq) diff --git a/tests_golden/TestFinEquityAmericanOption.py b/tests_golden/TestFinEquityAmericanOption.py index 49a9027a..cec2ff9f 100644 --- a/tests_golden/TestFinEquityAmericanOption.py +++ b/tests_golden/TestFinEquityAmericanOption.py @@ -22,7 +22,7 @@ def testEquityAmericanOption(): value_dt = Date(1, 1, 2016) - expiry_date = Date(1, 1, 2017) + expiry_dt = Date(1, 1, 2017) stock_price = 50.0 interest_rate = 0.06 dividend_yield = 0.04 @@ -35,7 +35,7 @@ def testEquityAmericanOption(): test_cases.banner("================== EUROPEAN PUT =======================") put_option = EquityAmericanOption( - expiry_date, strike_price, OptionTypes.EUROPEAN_PUT) + expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT) num_steps = 4 @@ -56,7 +56,7 @@ def testEquityAmericanOption(): test_cases.print("EUROPEAN_PUT_BS", value, delta, gamma, theta) option = EquityAmericanOption( - expiry_date, strike_price, OptionTypes.EUROPEAN_PUT) + expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT) test_cases.header("OPTION_TYPE", "NUMSTEPS", "VALUE DELTA GAMMA THETA", "TIME") @@ -79,7 +79,7 @@ def testEquityAmericanOption(): test_cases.banner("================== AMERICAN PUT =======================") option = EquityAmericanOption( - expiry_date, + expiry_dt, strike_price, OptionTypes.AMERICAN_PUT) @@ -106,7 +106,7 @@ def testEquityAmericanOption(): "================== EUROPEAN CALL =======================") call_option = EquityAmericanOption( - expiry_date, + expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL) @@ -123,7 +123,7 @@ def testEquityAmericanOption(): test_cases.print("EUROPEAN_CALL_BS", value, delta, gamma, theta) option = EquityAmericanOption( - expiry_date, + expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL) @@ -153,7 +153,7 @@ def testEquityAmericanOption(): "VALUE DELTA GAMMA THETA", "TIME") - option = EquityAmericanOption(expiry_date, strike_price, + option = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_CALL) for num_steps in num_steps_list: @@ -179,7 +179,7 @@ def testEquityAmericanOption(): "VALUE DELTA GAMMA THETA", "TIME") - option = EquityAmericanOption(expiry_date, strike_price, + option = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_PUT) for num_steps in num_steps_list: diff --git a/tests_golden/TestFinEquityBinomialTree.py b/tests_golden/TestFinEquityBinomialTree.py index 183b7d72..2605815c 100644 --- a/tests_golden/TestFinEquityBinomialTree.py +++ b/tests_golden/TestFinEquityBinomialTree.py @@ -30,7 +30,7 @@ def test_FinBinomialTree(): volatility = 0.40 value_dt = Date(1, 1, 2016) - expiry_date = Date(1, 1, 2017) + expiry_dt = Date(1, 1, 2017) model = BlackScholes(volatility) discount_curve = DiscountCurveFlat(value_dt, risk_free_rate) @@ -43,7 +43,7 @@ def test_FinBinomialTree(): test_cases.banner("================== EUROPEAN PUT =======================") put_option = EquityVanillaOption( - expiry_date, + expiry_dt, strike_price, OptionTypes.EUROPEAN_PUT) value = put_option.value(value_dt, stock_price, @@ -74,7 +74,7 @@ def test_FinBinomialTree(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) @@ -101,7 +101,7 @@ def test_FinBinomialTree(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) @@ -113,7 +113,7 @@ def test_FinBinomialTree(): "================== EUROPEAN CALL =======================") call_option = EquityVanillaOption( - expiry_date, + expiry_dt, strike_price, OptionTypes.EUROPEAN_CALL) value = call_option.value(value_dt, stock_price, @@ -144,7 +144,7 @@ def test_FinBinomialTree(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) @@ -173,7 +173,7 @@ def test_FinBinomialTree(): num_steps, value_dt, payoff, - expiry_date, + expiry_dt, payoff, exercise, params) diff --git a/tests_golden/TestFinEquityCliquetOption.py b/tests_golden/TestFinEquityCliquetOption.py index 76e6c827..de521d70 100644 --- a/tests_golden/TestFinEquityCliquetOption.py +++ b/tests_golden/TestFinEquityCliquetOption.py @@ -21,12 +21,12 @@ def test_EquityCliquetOption(): start_dt = Date(1, 1, 2014) - final_expiry_date = Date(1, 1, 2017) + final_expiry_dt = Date(1, 1, 2017) freq_type = FrequencyTypes.QUARTERLY option_type = OptionTypes.EUROPEAN_CALL cliquetOption = EquityCliquetOption(start_dt, - final_expiry_date, + final_expiry_dt, option_type, freq_type) diff --git a/tests_golden/TestFinEquityOneTouchOption.py b/tests_golden/TestFinEquityOneTouchOption.py index f5f98959..74108f7c 100644 --- a/tests_golden/TestFinEquityOneTouchOption.py +++ b/tests_golden/TestFinEquityOneTouchOption.py @@ -25,7 +25,7 @@ def test_EquityOneTouchOption(): # Agreement not exact at t is not exactly 0.50 value_dt = Date(1, 1, 2016) - expiry_date = Date(2, 7, 2016) + expiry_dt = Date(2, 7, 2016) interest_rate = 0.10 volatility = 0.20 barrier_level = 100.0 # H @@ -50,7 +50,7 @@ def test_EquityOneTouchOption(): for downType in downTypes: - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level, payment_size) @@ -84,7 +84,7 @@ def test_EquityOneTouchOption(): for upType in upTypes: - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, upType, barrier_level, payment_size) @@ -120,7 +120,7 @@ def test_EquityOneTouchOption(): test_cases.header("TYPE", "VALUE", "VALUE_MC") for downType in downTypes: - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, downType, barrier_level) @@ -150,7 +150,7 @@ def test_EquityOneTouchOption(): for upType in upTypes: - option = EquityOneTouchOption(expiry_date, + option = EquityOneTouchOption(expiry_dt, upType, barrier_level) diff --git a/tests_golden/TestFinEquityVolSurface.py b/tests_golden/TestFinEquityVolSurface.py index 58416c28..3f6d09a2 100644 --- a/tests_golden/TestFinEquityVolSurface.py +++ b/tests_golden/TestFinEquityVolSurface.py @@ -33,7 +33,7 @@ def test_equity_vol_surface(verboseCalibration): stock_price = 3800.0 # Check - expiry_dates = [Date(11, 2, 2021), Date(11, 3, 2021), + expiry_dts = [Date(11, 2, 2021), Date(11, 3, 2021), Date(11, 4, 2021), Date(11, 7, 2021), Date(11, 10, 2021), Date(11, 1, 2022), Date(11, 1, 2023)] @@ -64,7 +64,7 @@ def test_equity_vol_surface(verboseCalibration): stock_price, discount_curve, dividend_curve, - expiry_dates, + expiry_dts, strikes, volSurface, vol_functionType) @@ -84,8 +84,8 @@ def test_equity_vol_surface(verboseCalibration): dbns = equitySurface.implied_dbns(mins, maxs, 1000) for i in range(0, len(dbns)): - expiry_date_str = str(equitySurface._expiry_dates[i]) - plt.plot(dbns[i]._x, dbns[i]._densitydx, label=expiry_date_str) + expiry_dt_str = str(equitySurface._expiry_dts[i]) + plt.plot(dbns[i]._x, dbns[i]._densitydx, label=expiry_dt_str) plt.title(vol_functionType) plt.legend() print("SUM:", dbns[i].sum()) @@ -93,10 +93,10 @@ def test_equity_vol_surface(verboseCalibration): deltas = np.linspace(0.10, 0.90, 9) test_cases.header("EXPIRY", "DELTA", "VOL", "STRIKE") - for expiry_date in expiry_dates: + for expiry_dt in expiry_dts: for delta in deltas: - vol = equitySurface.vol_from_delta_dt(delta, expiry_date) - test_cases.print(expiry_date, delta, vol[0], vol[1]) + vol = equitySurface.vol_from_delta_dt(delta, expiry_dt) + test_cases.print(expiry_dt, delta, vol[0], vol[1]) ############################################################################### diff --git a/tests_golden/TestFinFXAmericanOption.py b/tests_golden/TestFinFXAmericanOption.py index 040360d8..17a4c472 100644 --- a/tests_golden/TestFinFXAmericanOption.py +++ b/tests_golden/TestFinFXAmericanOption.py @@ -2,17 +2,16 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.models.black_scholes import BlackScholes +from financepy.products.fx.fx_vanilla_option import FXVanillaOption +from financepy.utils.global_types import OptionTypes +from financepy.utils.date import Date +import numpy as np import sys sys.path.append("..") -import numpy as np -from financepy.utils.date import Date -from financepy.utils.global_types import OptionTypes -from financepy.products.fx.fx_vanilla_option import FXVanillaOption -from financepy.models.black_scholes import BlackScholes -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from FinTestCases import FinTestCases, globalTestCaseMode - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -40,8 +39,8 @@ def test_FinFXAmericanOption(): strike_fx_rate = 1.250 volatility = 0.10 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -63,8 +62,8 @@ def test_FinFXAmericanOption(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -76,8 +75,8 @@ def test_FinFXAmericanOption(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -94,8 +93,8 @@ def test_FinFXAmericanOption(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -107,8 +106,8 @@ def test_FinFXAmericanOption(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) diff --git a/tests_golden/TestFinFXBarrierOption.py b/tests_golden/TestFinFXBarrierOption.py index 0fb8ce8b..e7f5ec1e 100644 --- a/tests_golden/TestFinFXBarrierOption.py +++ b/tests_golden/TestFinFXBarrierOption.py @@ -2,18 +2,17 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.utils.date import Date +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.products.fx.fx_barrier_option import FXBarrierOption +from financepy.products.fx.fx_barrier_option import FinFXBarrierTypes +from financepy.models.black_scholes import BlackScholes +from financepy.models.process_simulator import FinGBMNumericalScheme +from financepy.models.process_simulator import ProcessTypes import sys sys.path.append("..") -from financepy.models.process_simulator import ProcessTypes -from financepy.models.process_simulator import FinGBMNumericalScheme -from financepy.models.black_scholes import BlackScholes -from financepy.products.fx.fx_barrier_option import FinFXBarrierTypes -from financepy.products.fx.fx_barrier_option import FXBarrierOption -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.utils.date import Date -from FinTestCases import FinTestCases, globalTestCaseMode - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -36,8 +35,8 @@ def test_FinFXBarrierOption(): drift = dom_interest_rate - forInterestRate scheme = FinGBMNumericalScheme.ANTITHETIC process_type = ProcessTypes.GBM - dom_discount_curve = DiscountCurveFlat(value_dt, dom_interest_rate) - for_discount_curve = DiscountCurveFlat(value_dt, forInterestRate) + domestic_curve = DiscountCurveFlat(value_dt, dom_interest_rate) + foreign_curve = DiscountCurveFlat(value_dt, forInterestRate) model = BlackScholes(volatility) ########################################################################### @@ -49,7 +48,7 @@ def test_FinFXBarrierOption(): for option_type in FinFXBarrierTypes: test_cases.header("Type", "K", "B", "S", "Value", - "ValueMC", "TIME", "Diff") + "ValueMC", "TIME", "Diff") for spot_fx_rate in range(60, 140, 20): B = 110.0 @@ -61,7 +60,7 @@ def test_FinFXBarrierOption(): notional, notional_currency) value = option.value(value_dt, spot_fx_rate, - dom_discount_curve, for_discount_curve, model) + domestic_curve, foreign_curve, model) start = time.time() model_params = (spot_fx_rate, drift, volatility, scheme) @@ -74,7 +73,7 @@ def test_FinFXBarrierOption(): diff = value_mc - value test_cases.print(option_type, K, B, spot_fx_rate, value, value_mc, - time_elapsed, diff) + time_elapsed, diff) for spot_fx_rate in range(60, 140, 20): B = 100.0 @@ -86,7 +85,7 @@ def test_FinFXBarrierOption(): notional, notional_currency) value = option.value(value_dt, spot_fx_rate, - dom_discount_curve, for_discount_curve, model) + domestic_curve, foreign_curve, model) start = time.time() model_params = (spot_fx_rate, drift, volatility, scheme) @@ -101,7 +100,7 @@ def test_FinFXBarrierOption(): diff = value_mc - value test_cases.print(option_type, K, B, spot_fx_rate, value, value_mc, - time_elapsed, diff) + time_elapsed, diff) end = time.time() @@ -110,7 +109,8 @@ def test_FinFXBarrierOption(): spot_fx_rates = range(50, 150, 50) B = 105.0 - test_cases.header("Type", "K", "B", "S:", "Value", "Delta", "Vega", "Theta") + test_cases.header("Type", "K", "B", "S:", "Value", + "Delta", "Vega", "Theta") for option_type in FinFXBarrierTypes: for spot_fx_rate in spot_fx_rates: @@ -125,36 +125,36 @@ def test_FinFXBarrierOption(): value = barrier_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = barrier_option.delta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = barrier_option.vega(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = barrier_option.theta(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) test_cases.print(option_type, - K, - B, - spot_fx_rate, - value, - delta, - vega, - theta) + K, + B, + spot_fx_rate, + value, + delta, + vega, + theta) ############################################################################### diff --git a/tests_golden/TestFinFXDigitalOption.py b/tests_golden/TestFinFXDigitalOption.py index 8820220c..afc9d581 100644 --- a/tests_golden/TestFinFXDigitalOption.py +++ b/tests_golden/TestFinFXDigitalOption.py @@ -2,23 +2,21 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from financepy.utils.global_types import OptionTypes +from financepy.products.fx.fx_digital_option import FXDigitalOption +from financepy.models.black_scholes import BlackScholes +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.utils.day_count import DayCountTypes +from financepy.utils.calendar import CalendarTypes +from financepy.products.rates.ibor_single_curve import IborSingleCurve +from financepy.products.rates.ibor_deposit import IborDeposit +from financepy.utils.date import Date +from FinTestCases import FinTestCases, globalTestCaseMode +import numpy as np +import time import sys sys.path.append("..") -import time -import numpy as np - -from FinTestCases import FinTestCases, globalTestCaseMode -from financepy.utils.date import Date -from financepy.products.rates.ibor_deposit import IborDeposit -from financepy.products.rates.ibor_single_curve import IborSingleCurve -from financepy.utils.calendar import CalendarTypes -from financepy.utils.day_count import DayCountTypes -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.models.black_scholes import BlackScholes -from financepy.products.fx.fx_digital_option import FXDigitalOption -from financepy.utils.global_types import OptionTypes - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -47,8 +45,8 @@ def test_FinFXDigitalOption(): notional = 1.0 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -63,8 +61,8 @@ def test_FinFXDigitalOption(): value = digital_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) ############################################################################### diff --git a/tests_golden/TestFinFXDoubleDigitalOption.py b/tests_golden/TestFinFXDoubleDigitalOption.py index 37040463..531029e5 100644 --- a/tests_golden/TestFinFXDoubleDigitalOption.py +++ b/tests_golden/TestFinFXDoubleDigitalOption.py @@ -2,18 +2,17 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from financepy.products.fx.fx_double_digital_option import FXDoubleDigitalOption +from financepy.models.black_scholes import BlackScholes +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.utils.date import Date +from FinTestCases import FinTestCases, globalTestCaseMode import time import numpy as np import sys sys.path.append("..") -from FinTestCases import FinTestCases, globalTestCaseMode -from financepy.utils.date import Date -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.models.black_scholes import BlackScholes -from financepy.products.fx.fx_double_digital_option import FXDoubleDigitalOption - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -23,7 +22,7 @@ def test_FinFXDoubleDigitalOption(): value_dt = Date(10, 4, 2020) - expiry_date = Date(18, 9, 2020) + expiry_dt = Date(18, 9, 2020) forName = "EUR" domName = "USD" @@ -33,8 +32,8 @@ def test_FinFXDoubleDigitalOption(): currency_pair = forName + domName # Always FORDOM spot_fx_rate = 1.20 - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) volatility = 0.20 @@ -46,7 +45,7 @@ def test_FinFXDoubleDigitalOption(): model = BlackScholes(volatility) double_digital_option = FXDoubleDigitalOption( - expiry_date, + expiry_dt, upper_strike, lower_strike, currency_pair, @@ -59,8 +58,8 @@ def test_FinFXDoubleDigitalOption(): value = double_digital_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) ############################################################################### diff --git a/tests_golden/TestFinFXForward.py b/tests_golden/TestFinFXForward.py index ebecc81a..02713896 100644 --- a/tests_golden/TestFinFXForward.py +++ b/tests_golden/TestFinFXForward.py @@ -2,17 +2,16 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.utils.date import Date +from financepy.products.rates.ibor_deposit import IborDeposit +from financepy.products.rates.ibor_single_curve import IborSingleCurve +from financepy.utils.calendar import CalendarTypes +from financepy.utils.day_count import DayCountTypes +from financepy.products.fx.fx_forward import FXForward import sys sys.path.append("..") -from financepy.products.fx.fx_forward import FXForward -from financepy.utils.day_count import DayCountTypes -from financepy.utils.calendar import CalendarTypes -from financepy.products.rates.ibor_single_curve import IborSingleCurve -from financepy.products.rates.ibor_deposit import IborDeposit -from financepy.utils.date import Date -from FinTestCases import FinTestCases, globalTestCaseMode - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -51,7 +50,7 @@ def test_FinFXForward(): depo = IborDeposit(settle_dt, maturity_dt, deposit_rate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - for_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + foreign_curve = IborSingleCurve(value_dt, depos, fras, swaps) depos = [] fras = [] @@ -60,7 +59,7 @@ def test_FinFXForward(): depo = IborDeposit(settle_dt, maturity_dt, deposit_rate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - dom_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + domestic_curve = IborSingleCurve(value_dt, depos, fras, swaps) notional = 100.0 notional_currency = forName @@ -74,13 +73,13 @@ def test_FinFXForward(): test_cases.header("SPOT FX", "FX FWD", "VALUE_BS") fwdValue = fxForward.value(value_dt, spot_fx_rate, - dom_discount_curve, for_discount_curve) + domestic_curve, foreign_curve) - fwdFXRate = fxForward.forward(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve) + fwd_fx_rate = fxForward.forward(value_dt, spot_fx_rate, + domestic_curve, + foreign_curve) - test_cases.print(spot_fx_rate, fwdFXRate, fwdValue) + test_cases.print(spot_fx_rate, fwd_fx_rate, fwdValue) ############################################################################### diff --git a/tests_golden/TestFinFXLookbackOption.py b/tests_golden/TestFinFXLookbackOption.py index c60d6acc..336ebdec 100644 --- a/tests_golden/TestFinFXLookbackOption.py +++ b/tests_golden/TestFinFXLookbackOption.py @@ -20,7 +20,7 @@ def test_EquityLookBackOption(): value_dt = Date(1, 1, 2015) - expiry_date = Date(1, 1, 2016) + expiry_dt = Date(1, 1, 2016) stock_price = 100.0 volatility = 0.3 num_pathsRange = [10000] @@ -48,7 +48,7 @@ def test_EquityLookBackOption(): option_type = OptionTypes.EUROPEAN_CALL for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFloatLookbackOption(expiry_date, option_type) + option = FXFloatLookbackOption(expiry_dt, option_type) stockMin = stock_price value = option.value( value_dt, @@ -93,7 +93,7 @@ def test_EquityLookBackOption(): option_type = OptionTypes.EUROPEAN_CALL for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFloatLookbackOption(expiry_date, option_type) + option = FXFloatLookbackOption(expiry_dt, option_type) stockMin = stock_price - 10 value = option.value( value_dt, @@ -138,7 +138,7 @@ def test_EquityLookBackOption(): option_type = OptionTypes.EUROPEAN_PUT for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFloatLookbackOption(expiry_date, option_type) + option = FXFloatLookbackOption(expiry_dt, option_type) stockMax = stock_price value = option.value( value_dt, @@ -183,7 +183,7 @@ def test_EquityLookBackOption(): option_type = OptionTypes.EUROPEAN_PUT for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFloatLookbackOption(expiry_date, option_type) + option = FXFloatLookbackOption(expiry_dt, option_type) stockMax = stock_price + 10 value = option.value( value_dt, @@ -236,7 +236,7 @@ def test_EquityLookBackOption(): k = 95.0 for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMax = stock_price value = option.value( value_dt, @@ -284,7 +284,7 @@ def test_EquityLookBackOption(): k = 100.0 for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMax = stock_price value = option.value( value_dt, @@ -332,7 +332,7 @@ def test_EquityLookBackOption(): k = 105.0 for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMax = stock_price + 10.0 value = option.value( value_dt, @@ -380,7 +380,7 @@ def test_EquityLookBackOption(): k = 95.0 for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMin = stock_price value = option.value( value_dt, @@ -428,7 +428,7 @@ def test_EquityLookBackOption(): k = 100.0 for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMin = stock_price value = option.value( value_dt, @@ -476,7 +476,7 @@ def test_EquityLookBackOption(): k = 105.0 for stock_price in stock_priceRange: for num_paths in num_pathsRange: - option = FXFixedLookbackOption(expiry_date, option_type, k) + option = FXFixedLookbackOption(expiry_dt, option_type, k) stockMin = stock_price - 10.0 value = option.value( value_dt, diff --git a/tests_golden/TestFinFXOneTouchOption.py b/tests_golden/TestFinFXOneTouchOption.py index 23c94ce0..1a13a2af 100644 --- a/tests_golden/TestFinFXOneTouchOption.py +++ b/tests_golden/TestFinFXOneTouchOption.py @@ -33,8 +33,8 @@ def test_FinFXOneTouchOption(): num_paths = 50000 num_steps_per_year = 252 * 2 - domCurve = DiscountCurveFlat(value_dt, domesticRate) - forCurve = DiscountCurveFlat(value_dt, foreignRate) + dom_curve = DiscountCurveFlat(value_dt, domesticRate) + for_curve = DiscountCurveFlat(value_dt, foreignRate) spot_fx_rate = 1.050 payment_size = 1.5 @@ -56,14 +56,14 @@ def test_FinFXOneTouchOption(): v = option.value(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model) v_mc = option.value_mc(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model, num_steps_per_year, num_paths) @@ -92,14 +92,14 @@ def test_FinFXOneTouchOption(): v = option.value(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model) v_mc = option.value_mc(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model, num_steps_per_year, num_paths) @@ -132,8 +132,8 @@ def test_BBGOneTouchOption(): num_paths = 50000 num_steps_per_year = 252 - domCurve = DiscountCurveFlat(value_dt, domRate) - forCurve = DiscountCurveFlat(value_dt, forRate) + dom_curve = DiscountCurveFlat(value_dt, domRate) + for_curve = DiscountCurveFlat(value_dt, forRate) payment_size = 1000000 # EUR @@ -146,34 +146,34 @@ def test_BBGOneTouchOption(): v = option.value(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model) v_mc = option.value_mc(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model, num_steps_per_year, num_paths) d = option.delta(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model) g = option.gamma(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model) v = option.vega(value_dt, spot_fx_rate, - domCurve, - forCurve, + dom_curve, + for_curve, model) # I SHOULD GET 49.4934% OR 494,934 in EUR diff --git a/tests_golden/TestFinFXOptionSABR.py b/tests_golden/TestFinFXOptionSABR.py index 354f91e4..704a2bef 100644 --- a/tests_golden/TestFinFXOptionSABR.py +++ b/tests_golden/TestFinFXOptionSABR.py @@ -2,16 +2,16 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.models.black_scholes import BlackScholes +from financepy.products.fx.fx_vanilla_option import FXVanillaOption +from financepy.utils.global_types import OptionTypes +from financepy.utils.date import Date +import numpy as np import sys sys.path.append("..") -import numpy as np -from financepy.utils.date import Date -from financepy.utils.global_types import OptionTypes -from financepy.products.fx.fx_vanilla_option import FXVanillaOption -from financepy.models.black_scholes import BlackScholes -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from FinTestCases import FinTestCases, globalTestCaseMode test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -39,8 +39,8 @@ def test_FinFXOptionSABR(): notional = 1000000.0 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -63,8 +63,8 @@ def test_FinFXOptionSABR(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -76,8 +76,8 @@ def test_FinFXOptionSABR(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) @@ -101,8 +101,8 @@ def test_FinFXOptionSABR(): valueEuropean = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] call_option = FXVanillaOption(expiry_dt, @@ -114,16 +114,16 @@ def test_FinFXOptionSABR(): valueAmerican = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] diff = (valueAmerican - valueEuropean) test_cases.print("PUT:", - "%9.6f" % spot_fx_rate, - "%9.7f" % valueEuropean, - "%9.7f" % valueAmerican, - "%9.7f" % diff) + "%9.6f" % spot_fx_rate, + "%9.7f" % valueEuropean, + "%9.7f" % valueAmerican, + "%9.7f" % diff) ############################################################################### diff --git a/tests_golden/TestFinFXVanillaOption.py b/tests_golden/TestFinFXVanillaOption.py index 988514cf..94a79c60 100644 --- a/tests_golden/TestFinFXVanillaOption.py +++ b/tests_golden/TestFinFXVanillaOption.py @@ -2,23 +2,22 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +import numpy as np +import time +from financepy.utils.global_types import OptionTypes +from financepy.products.fx.fx_vanilla_option import FXVanillaOption +from financepy.models.sabr import SABR +from financepy.models.black_scholes import BlackScholes +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.utils.day_count import DayCountTypes +from financepy.utils.calendar import CalendarTypes +from financepy.products.rates.ibor_single_curve import IborSingleCurve +from financepy.products.rates.ibor_deposit import IborDeposit +from financepy.utils.date import Date +from FinTestCases import FinTestCases, globalTestCaseMode import sys sys.path.append("..") -from FinTestCases import FinTestCases, globalTestCaseMode -from financepy.utils.date import Date -from financepy.products.rates.ibor_deposit import IborDeposit -from financepy.products.rates.ibor_single_curve import IborSingleCurve -from financepy.utils.calendar import CalendarTypes -from financepy.utils.day_count import DayCountTypes -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.models.black_scholes import BlackScholes -from financepy.models.sabr import SABR -from financepy.products.fx.fx_vanilla_option import FXVanillaOption -from financepy.utils.global_types import OptionTypes -import time -import numpy as np - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -50,8 +49,8 @@ def test_FinFXVanillaOptionWystupExample1(): notional = 1000000.0 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -66,8 +65,8 @@ def test_FinFXVanillaOptionWystupExample1(): "EUR", 2) value = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, model) + domestic_curve, + foreign_curve, model) notional = 1250000.0 call_option = FXVanillaOption(expiry_dt, @@ -80,15 +79,15 @@ def test_FinFXVanillaOptionWystupExample1(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) test_cases.header("value", "delta") @@ -120,8 +119,8 @@ def test_FinFXVanillaOptionWystupExample2(): notional = 1000000.0 - dom_discount_curve = DiscountCurveFlat(value_dt, ccy2CCRate) - for_discount_curve = DiscountCurveFlat(value_dt, ccy1CCRate) + domestic_curve = DiscountCurveFlat(value_dt, ccy2CCRate) + foreign_curve = DiscountCurveFlat(value_dt, ccy1CCRate) model = BlackScholes(volatility) @@ -138,15 +137,15 @@ def test_FinFXVanillaOptionWystupExample2(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) test_cases.header("value", "delta") @@ -189,7 +188,7 @@ def test_FinFXVanillaOptionBloombergExample(): depo = IborDeposit(settle_dt, maturity_dt, domDepoRate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - dom_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + domestic_curve = IborSingleCurve(value_dt, depos, fras, swaps) depos = [] fras = [] @@ -197,7 +196,7 @@ def test_FinFXVanillaOptionBloombergExample(): depo = IborDeposit(settle_dt, maturity_dt, forDepoRate, DayCountTypes.ACT_360, notional, cal_type) depos.append(depo) - for_discount_curve = IborSingleCurve(value_dt, depos, fras, swaps) + foreign_curve = IborSingleCurve(value_dt, depos, fras, swaps) model = BlackScholes(volatility) @@ -211,15 +210,15 @@ def test_FinFXVanillaOptionBloombergExample(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) test_cases.header("value", "delta") @@ -238,8 +237,8 @@ def test_FinFXVanillaOptionHullExample(): dom_interest_rate = 0.08 forInterestRate = 0.11 model = BlackScholes(volatility) - dom_discount_curve = DiscountCurveFlat(value_dt, dom_interest_rate) - for_discount_curve = DiscountCurveFlat(value_dt, forInterestRate) + domestic_curve = DiscountCurveFlat(value_dt, dom_interest_rate) + foreign_curve = DiscountCurveFlat(value_dt, forInterestRate) num_paths_list = [10000, 20000, 40000, 80000, 160000, 320000] @@ -258,8 +257,8 @@ def test_FinFXVanillaOptionHullExample(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) start = time.time() @@ -267,8 +266,8 @@ def test_FinFXVanillaOptionHullExample(): value_mc = call_option.value_mc( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model, num_paths) @@ -296,15 +295,15 @@ def test_FinFXVanillaOptionHullExample(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) start = time.time() value_mc = call_option.value_mc( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model, num_paths) end = time.time() @@ -330,15 +329,15 @@ def test_FinFXVanillaOptionHullExample(): value = put_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) start = time.time() value_mc = put_option.value_mc( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model, num_paths) end = time.time() @@ -367,26 +366,26 @@ def test_FinFXVanillaOptionHullExample(): value = call_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = call_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = call_option.vega( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = call_option.theta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) # call_option.rho(value_dt,stock_price, interest_rate, # dividend_yield, modelType, model_params) @@ -412,26 +411,26 @@ def test_FinFXVanillaOptionHullExample(): value = put_option.value( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) delta = put_option.delta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) vega = put_option.vega( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) theta = put_option.theta( value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model) # put_option.rho(value_dt,stock_price, interest_rate, dividend_yield, # modelType, model_params) @@ -454,20 +453,21 @@ def test_FinFXVanillaOptionHullExample(): value = call_option.value(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, model)['v'] impliedVol = call_option.implied_volatility(value_dt, spot_fx_rate, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, value) test_cases.print(spot_fx_rate, value, volatility, impliedVol) ############################################################################### + def test_FinFXVanillaOptionSABRExample(): """ Test case for FXVanilla option pricing with SABR model @@ -478,8 +478,8 @@ def test_FinFXVanillaOptionSABRExample(): domName = "JPY" forCCRate = 0.0381 # USD domCCRate = 0.000396 # JPY - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 131.32 strike_price = 130 @@ -501,9 +501,9 @@ def test_FinFXVanillaOptionSABRExample(): nu = 0.5 model = SABR(alpha, beta, rho, nu) - blackVol = volatility + black_vol = volatility t_exp = 0.8444 # 10M - model.set_alpha_from_black_vol(blackVol, + model.set_alpha_from_black_vol(black_vol, spot_fx_rate, strike_price, t_exp) @@ -514,8 +514,8 @@ def test_FinFXVanillaOptionSABRExample(): for f in spot_fx_rate: - call_value = call_option.value(value_dt, f, dom_discount_curve, - for_discount_curve, model)['cash_dom'] + call_value = call_option.value(value_dt, f, domestic_curve, + foreign_curve, model)['cash_dom'] call_values.append(call_value) diff --git a/tests_golden/TestFinFXVolSurface.py b/tests_golden/TestFinFXVolSurface.py index e584e854..8b754924 100644 --- a/tests_golden/TestFinFXVolSurface.py +++ b/tests_golden/TestFinFXVolSurface.py @@ -2,19 +2,18 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +import time +import matplotlib.pyplot as plt +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.models.volatility_fns import VolFuncTypes +from financepy.utils.date import Date +from financepy.market.volatility.fx_vol_surface import FinFXDeltaMethod +from financepy.market.volatility.fx_vol_surface import FinFXATMMethod +from financepy.market.volatility.fx_vol_surface import FXVolSurface +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat import sys sys.path.append("..") -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.market.volatility.fx_vol_surface import FXVolSurface -from financepy.market.volatility.fx_vol_surface import FinFXATMMethod -from financepy.market.volatility.fx_vol_surface import FinFXDeltaMethod -from financepy.utils.date import Date -from financepy.models.volatility_fns import VolFuncTypes -from FinTestCases import FinTestCases, globalTestCaseMode -import matplotlib.pyplot as plt -import time - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -42,8 +41,8 @@ def test_FinFXMktVolSurface1(verboseCalibration): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -55,7 +54,7 @@ def test_FinFXMktVolSurface1(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK @@ -63,20 +62,20 @@ def test_FinFXMktVolSurface1(verboseCalibration): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method, vol_functionType) fxMarket.check_calibration(verboseCalibration) # EXPLORE AND TEST DIFFERENT CATEGORICAL PARAMETERS - # for atmMethod in FinFXATMMethod: + # for atm_method in FinFXATMMethod: # for delta_method in FinFXDeltaMethod: # for vol_functionType in VolFuncTypes: @@ -84,13 +83,13 @@ def test_FinFXMktVolSurface1(verboseCalibration): # spot_fx_rate, # currency_pair, # notional_currency, - # dom_discount_curve, - # for_discount_curve, + # domestic_curve, + # foreign_curve, # tenors, # atm_vols, # marketStrangle25DeltaVols, # riskReversal25DeltaVols, - # atmMethod, + # atm_method, # delta_method, # vol_functionType) @@ -124,8 +123,8 @@ def test_FinFXMktVolSurface2(verboseCalibration): forCCRate = 0.0294 # EUR domCCRate = 0.0171 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 90.72 @@ -137,20 +136,20 @@ def test_FinFXMktVolSurface2(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ delta_method = FinFXDeltaMethod.SPOT_DELTA_PREM_ADJ fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) fxMarket.check_calibration(verboseCalibration) @@ -175,8 +174,8 @@ def test_FinFXMktVolSurface3(verboseCalibration): forCCRate = 0.020113 # EUR domCCRate = 0.003525 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3088 @@ -188,20 +187,20 @@ def test_FinFXMktVolSurface3(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) fxMarket.check_calibration(verboseCalibration) @@ -224,8 +223,8 @@ def test_FinFXMktVolSurface4(verboseCalibration): forCCRate = 0.003525 # USD domCCRate = 0.0042875 # JPY - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 90.68 @@ -237,20 +236,20 @@ def test_FinFXMktVolSurface4(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA_PREM_ADJ fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) fxMarket.check_calibration(verboseCalibration) diff --git a/tests_golden/TestFinFXVolSurfacePlus.py b/tests_golden/TestFinFXVolSurfacePlus.py index 7812786b..13cf3842 100644 --- a/tests_golden/TestFinFXVolSurfacePlus.py +++ b/tests_golden/TestFinFXVolSurfacePlus.py @@ -2,20 +2,19 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +import time +import matplotlib.pyplot as plt +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.models.volatility_fns import VolFuncTypes +from financepy.utils.date import Date +from financepy.market.volatility.fx_vol_surface_plus import FinFXDeltaMethod +from financepy.market.volatility.fx_vol_surface_plus import FinFXATMMethod +from financepy.market.volatility.fx_vol_surface_plus import FXVolSurfacePlus +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +import numpy as np import sys sys.path.append("..") -import numpy as np - -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.market.volatility.fx_vol_surface_plus import FXVolSurfacePlus -from financepy.market.volatility.fx_vol_surface_plus import FinFXATMMethod -from financepy.market.volatility.fx_vol_surface_plus import FinFXDeltaMethod -from financepy.utils.date import Date -from financepy.models.volatility_fns import VolFuncTypes -from FinTestCases import FinTestCases, globalTestCaseMode -import matplotlib.pyplot as plt -import time test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -44,8 +43,8 @@ def test_FinFXMktVolSurface1(verboseCalibration): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -60,7 +59,7 @@ def test_FinFXMktVolSurface1(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK5 alpha = 0.5 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -69,8 +68,8 @@ def test_FinFXMktVolSurface1(verboseCalibration): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -78,7 +77,7 @@ def test_FinFXMktVolSurface1(verboseCalibration): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -114,8 +113,8 @@ def test_FinFXMktVolSurface2(verboseCalibration): forCCRate = 0.0294 # EUR domCCRate = 0.0171 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 90.72 @@ -131,7 +130,7 @@ def test_FinFXMktVolSurface2(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL_PREM_ADJ delta_method = FinFXDeltaMethod.SPOT_DELTA_PREM_ADJ vol_functionType = VolFuncTypes.CLARK5 @@ -139,8 +138,8 @@ def test_FinFXMktVolSurface2(verboseCalibration): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -148,7 +147,7 @@ def test_FinFXMktVolSurface2(verboseCalibration): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -185,8 +184,8 @@ def test_FinFXMktVolSurface3(verboseCalibration): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -203,7 +202,7 @@ def test_FinFXMktVolSurface3(verboseCalibration): # I HAVE NO YET MADE DELTA METHOD A VECTOR FOR EACH TERM AS I WOULD # NEED TO DO AS DESCRIBED IN CLARK PAGE 70 - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.FORWARD_DELTA # THIS IS DIFFERENT vol_functionType = VolFuncTypes.CLARK5 alpha = 0.5 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -212,8 +211,8 @@ def test_FinFXMktVolSurface3(verboseCalibration): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -221,7 +220,7 @@ def test_FinFXMktVolSurface3(verboseCalibration): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -322,8 +321,8 @@ def test_FinFXMktVolSurface4(verboseCalibration): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -341,7 +340,7 @@ def test_FinFXMktVolSurface4(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK alpha = 0.50 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -350,8 +349,8 @@ def test_FinFXMktVolSurface4(verboseCalibration): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -359,7 +358,7 @@ def test_FinFXMktVolSurface4(verboseCalibration): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) @@ -417,8 +416,8 @@ def test_FinFXMktVolSurface5(verboseCalibration): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -436,7 +435,7 @@ def test_FinFXMktVolSurface5(verboseCalibration): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA vol_functionType = VolFuncTypes.CLARK alpha = 0.50 # FIT WINGS AT 10D if ALPHA = 1.0 @@ -445,8 +444,8 @@ def test_FinFXMktVolSurface5(verboseCalibration): spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, @@ -454,7 +453,7 @@ def test_FinFXMktVolSurface5(verboseCalibration): marketStrangle10DeltaVols, riskReversal10DeltaVols, alpha, - atmMethod, + atm_method, delta_method, vol_functionType) diff --git a/tests_golden/TestFinIborCapFloor.py b/tests_golden/TestFinIborCapFloor.py index 4c418bfa..c9aa017e 100644 --- a/tests_golden/TestFinIborCapFloor.py +++ b/tests_golden/TestFinIborCapFloor.py @@ -342,8 +342,8 @@ def test_IborCapFloorQLExample(): last_fixing, freq_type, dc_type, notional, cal_type, bd_type, dg_type) - blackVol = 0.547295 - model = Black(blackVol) + black_vol = 0.547295 + model = Black(black_vol) start = time.time() numRepeats = 10 diff --git a/tests_golden/TestFinIborDualCurve.py b/tests_golden/TestFinIborDualCurve.py index 754914a3..6c687101 100644 --- a/tests_golden/TestFinIborDualCurve.py +++ b/tests_golden/TestFinIborDualCurve.py @@ -48,99 +48,99 @@ def buildOIS(value_dt): swaps = [] fixed_freq_type = FrequencyTypes.SEMI_ANNUAL - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F swap_rate = 0.000022 maturity_dt = settle_dt.add_months(24) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, - fixed_freq_type, fixedDCCType) + fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap_rate += 0.000 fixed_leg_type = SwapTypes.PAY maturity_dt = settle_dt.add_months(36) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, - fixed_freq_type, fixedDCCType) + fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap_rate += 0.000 maturity_dt = settle_dt.add_months(48) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) swap_rate = 0.02 maturity_dt = settle_dt.add_months(60) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(72) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(84) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(96) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(108) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(120) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(132) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(144) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(180) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(240) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(300) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(360) swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) oisCurve = OISCurve(value_dt, @@ -347,7 +347,7 @@ def test_swapValuationExample(): fixed_leg_type = SwapTypes.RECEIVE fixedRate = 0.0150 - fixedDCCType = DayCountTypes.THIRTY_360_BOND + fixed_dcc_type = DayCountTypes.THIRTY_360_BOND fixed_freq_type = FrequencyTypes.ANNUAL float_spread = 0.0 @@ -355,7 +355,7 @@ def test_swapValuationExample(): float_freq_type = FrequencyTypes.SEMI_ANNUAL offMarketSwap = IborSwap(start_dt, maturity_dt, fixed_leg_type, - fixedRate, fixed_freq_type, fixedDCCType, + fixedRate, fixed_freq_type, fixed_dcc_type, notional, float_spread, float_freq_type, floatDCCType) @@ -415,65 +415,65 @@ def test_swapValuationExample(): swaps = [] fixed_leg_type = SwapTypes.PAY - fixedDCCType = DayCountTypes.THIRTY_360_BOND + fixed_dcc_type = DayCountTypes.THIRTY_360_BOND fixed_freq_type = FrequencyTypes.ANNUAL swap = IborSwap(settle_dt, "2Y", fixed_leg_type, - - 0.1525 / 100.0, fixed_freq_type, fixedDCCType) + 0.1525 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "3Y", fixed_leg_type, - - 0.0185 / 100.0, fixed_freq_type, fixedDCCType) + 0.0185 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "4Y", fixed_leg_type, - 0.1315 / 100.0, fixed_freq_type, fixedDCCType) + 0.1315 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "5Y", fixed_leg_type, - 0.2745 / 100.0, fixed_freq_type, fixedDCCType) + 0.2745 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "6Y", fixed_leg_type, - 0.4135 / 100.0, fixed_freq_type, fixedDCCType) + 0.4135 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "7Y", fixed_leg_type, - 0.5439 / 100.0, fixed_freq_type, fixedDCCType) + 0.5439 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "8Y", fixed_leg_type, - 0.6652 / 100.0, fixed_freq_type, fixedDCCType) + 0.6652 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "9Y", fixed_leg_type, - 0.7784 / 100.0, fixed_freq_type, fixedDCCType) + 0.7784 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "10Y", fixed_leg_type, - 0.8799 / 100.0, fixed_freq_type, fixedDCCType) + 0.8799 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "11Y", fixed_leg_type, - 0.9715 / 100.0, fixed_freq_type, fixedDCCType) + 0.9715 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "12Y", fixed_leg_type, - 1.0517 / 100.0, fixed_freq_type, fixedDCCType) + 1.0517 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "15Y", fixed_leg_type, - 1.2369 / 100.0, fixed_freq_type, fixedDCCType) + 1.2369 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "20Y", fixed_leg_type, - 1.3965 / 100.0, fixed_freq_type, fixedDCCType) + 1.3965 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "25Y", fixed_leg_type, - 1.4472 / 100.0, fixed_freq_type, fixedDCCType) + 1.4472 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "30Y", fixed_leg_type, - 1.4585 / 100.0, fixed_freq_type, fixedDCCType) + 1.4585 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "35Y", fixed_leg_type, - 1.4595 / 100.0, fixed_freq_type, fixedDCCType) + 1.4595 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "40Y", fixed_leg_type, - 1.4535 / 100.0, fixed_freq_type, fixedDCCType) + 1.4535 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "45Y", fixed_leg_type, - 1.4410 / 100.0, fixed_freq_type, fixedDCCType) + 1.4410 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = IborSwap(settle_dt, "50Y", fixed_leg_type, - 1.4335 / 100.0, fixed_freq_type, fixedDCCType) + 1.4335 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) iborDepos = depos.copy() @@ -504,109 +504,109 @@ def test_swapValuationExample(): swaps = [] fixed_leg_type = SwapTypes.PAY - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F fixed_freq_type = FrequencyTypes.ANNUAL # Standard OIS with standard annual terms swap = OIS(settle_dt, "2W", fixed_leg_type, - - 0.3600 / 100.0, fixed_freq_type, fixedDCCType) + 0.3600 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "1M", fixed_leg_type, - - 0.3560 / 100.0, fixed_freq_type, fixedDCCType) + 0.3560 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "2M", fixed_leg_type, - - 0.3570 / 100.0, fixed_freq_type, fixedDCCType) + 0.3570 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "3M", fixed_leg_type, - - 0.3580 / 100.0, fixed_freq_type, fixedDCCType) + 0.3580 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "4M", fixed_leg_type, - - 0.3575 / 100.0, fixed_freq_type, fixedDCCType) + 0.3575 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "5M", fixed_leg_type, - - 0.3578 / 100.0, fixed_freq_type, fixedDCCType) + 0.3578 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "6M", fixed_leg_type, - - 0.3580 / 100.0, fixed_freq_type, fixedDCCType) + 0.3580 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "7M", fixed_leg_type, - - 0.3600 / 100.0, fixed_freq_type, fixedDCCType) + 0.3600 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "8M", fixed_leg_type, - - 0.3575 / 100.0, fixed_freq_type, fixedDCCType) + 0.3575 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "9M", fixed_leg_type, - - 0.3569 / 100.0, fixed_freq_type, fixedDCCType) + 0.3569 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "10M", fixed_leg_type, - - 0.3553 / 100.0, fixed_freq_type, fixedDCCType) + 0.3553 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "11M", fixed_leg_type, - - 0.3534 / 100.0, fixed_freq_type, fixedDCCType) + 0.3534 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "12M", fixed_leg_type, - - 0.3496 / 100.0, fixed_freq_type, fixedDCCType) + 0.3496 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "18M", fixed_leg_type, - - 0.3173 / 100.0, fixed_freq_type, fixedDCCType) + 0.3173 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "2Y", fixed_leg_type, - - 0.2671 / 100.0, fixed_freq_type, fixedDCCType) + 0.2671 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "30M", fixed_leg_type, - - 0.2070 / 100.0, fixed_freq_type, fixedDCCType) + 0.2070 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "3Y", fixed_leg_type, - - 0.1410 / 100.0, fixed_freq_type, fixedDCCType) + 0.1410 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "4Y", fixed_leg_type, - - 0.0060 / 100.0, fixed_freq_type, fixedDCCType) + 0.0060 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "5Y", fixed_leg_type, - 0.1285 / 100.0, fixed_freq_type, fixedDCCType) + 0.1285 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "6Y", fixed_leg_type, - 0.2590 / 100.0, fixed_freq_type, fixedDCCType) + 0.2590 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "7Y", fixed_leg_type, - 0.3830 / 100.0, fixed_freq_type, fixedDCCType) + 0.3830 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "8Y", fixed_leg_type, - 0.5020 / 100.0, fixed_freq_type, fixedDCCType) + 0.5020 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "9Y", fixed_leg_type, - 0.6140 / 100.0, fixed_freq_type, fixedDCCType) + 0.6140 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "10Y", fixed_leg_type, - 0.7160 / 100.0, fixed_freq_type, fixedDCCType) + 0.7160 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "11Y", fixed_leg_type, - 0.8070 / 100.0, fixed_freq_type, fixedDCCType) + 0.8070 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "12Y", fixed_leg_type, - 0.8890 / 100.0, fixed_freq_type, fixedDCCType) + 0.8890 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "15Y", fixed_leg_type, - 1.0790 / 100.0, fixed_freq_type, fixedDCCType) + 1.0790 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "20Y", fixed_leg_type, - 1.2460 / 100.0, fixed_freq_type, fixedDCCType) + 1.2460 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "25Y", fixed_leg_type, - 1.3055 / 100.0, fixed_freq_type, fixedDCCType) + 1.3055 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "30Y", fixed_leg_type, - 1.3270 / 100.0, fixed_freq_type, fixedDCCType) + 1.3270 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "35Y", fixed_leg_type, - 1.3315 / 100.0, fixed_freq_type, fixedDCCType) + 1.3315 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "40Y", fixed_leg_type, - 1.3300 / 100.0, fixed_freq_type, fixedDCCType) + 1.3300 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) swap = OIS(settle_dt, "50Y", fixed_leg_type, - 1.3270 / 100.0, fixed_freq_type, fixedDCCType) + 1.3270 / 100.0, fixed_freq_type, fixed_dcc_type) swaps.append(swap) oisDepos = depos.copy() diff --git a/tests_golden/TestFinIborLMMProducts.py b/tests_golden/TestFinIborLMMProducts.py index 227aeac8..95919fb2 100644 --- a/tests_golden/TestFinIborLMMProducts.py +++ b/tests_golden/TestFinIborLMMProducts.py @@ -2,24 +2,23 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.products.rates.ibor_cap_floor import IborCapFloor +from financepy.products.rates.ibor_lmm_products import IborLMMProducts +from financepy.utils.global_types import FinCapFloorTypes +from financepy.products.rates.ibor_swaption import IborSwaption +from financepy.products.rates.ibor_swaption import SwapTypes +from financepy.utils.frequency import FrequencyTypes +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.models.black import Black +from financepy.utils.day_count import DayCountTypes +from financepy.utils.date import Date +from financepy.market.volatility.ibor_cap_vol_curve import IborCapVolCurve import numpy as np import sys sys.path.append("..") -from financepy.market.volatility.ibor_cap_vol_curve import IborCapVolCurve -from financepy.utils.date import Date -from financepy.utils.day_count import DayCountTypes -from financepy.models.black import Black -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.utils.frequency import FrequencyTypes -from financepy.products.rates.ibor_swaption import SwapTypes -from financepy.products.rates.ibor_swaption import IborSwaption -from financepy.utils.global_types import FinCapFloorTypes -from financepy.products.rates.ibor_lmm_products import IborLMMProducts -from financepy.products.rates.ibor_cap_floor import IborCapFloor -from FinTestCases import FinTestCases, globalTestCaseMode - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -44,7 +43,7 @@ # 0.04, # FrequencyTypes.ANNUAL) -# swaptionVol = 15.54 +# swaption_vol = 15.54 # liborSwaption = IborSwaption(settle_dt, # exercise_dt, @@ -54,7 +53,7 @@ # FrequencyTypes.ANNUAL, # DayCountTypes.ACT_360) -# model = Black(swaptionVol/100.0) +# model = Black(swaption_vol/100.0) # v_BLK = liborSwaption.value(value_dt, discount_curve, model) # dt = 0.5 @@ -79,9 +78,9 @@ # strike = r # PAYSwaption = 1 # use_sobol = 0 -# numeraireIndex = 0 +# numeraire_index = 0 -# fwds1F = LMMSimulateFwds1F(numFwds, num_paths, numeraireIndex, fwd0, +# fwds1F = LMMSimulateFwds1F(numFwds, num_paths, numeraire_index, fwd0, # zetas, taus, use_sobol, seed) # for iExp in range(1, 10): @@ -96,7 +95,7 @@ # swaption_priceNF = LMMSwaptionPricer(strike, a, b, num_paths, # fwd0, fwdsNF, taus, PAYSwaption) -# swaptionVol = LMMSwaptionVolApprox(a, b, fwd0, taus, zetas, correl) +# swaption_vol = LMMSwaptionVolApprox(a, b, fwd0, taus, zetas, correl) # swapVolSim1F = LMMSimSwaptionVol(a, b, fwd0, fwds1F, taus) # swapVolSimNF = LMMSimSwaptionVol(a, b, fwd0, fwdsNF, taus) @@ -128,13 +127,13 @@ # float_freq_type, # float_dc_type) -# model = Black(swaptionVol) +# model = Black(swaption_vol) # blackSwaptionPrice = swaption.value(value_dt, libor_curve, model) # test_cases.print("K:%6.5f t_exp:%8.2f FwdVol:%9.5f SimVol1F:%9.5f " + # " SimVolNF:%9.5f RebVol:%9.5f SimPx1F:%9.5f SimPxNF:%9.5f Black Px:%9.5f" # % (strike, t_exp, fwd_rateVol, swapVolSim1F, swapVolSimNF, -# swaptionVol, swaption_price1F, swaption_priceNF, +# swaption_vol, swaption_price1F, swaption_priceNF, # blackSwaptionPrice)) ############################################################################### @@ -185,16 +184,16 @@ # capVolDates = [] # capletVolTenor = "1Y" # capletDt = value_dt -# numForwards = endYear - startYear +# num_fwds = endYear - startYear -# # Capvol dates has numForwards + 1 elements including today +# # Capvol dates has num_fwds + 1 elements including today # capVolDates.append(value_dt) -# for i in range(0, numForwards): +# for i in range(0, num_fwds): # capletDt = capletDt.add_tenor(capletVolTenor) # capVolDates.append(capletDt) -# # Capvol dates has numForwards + 1 elements including zero today -# capVolatilities = [capVol] * (numForwards+1) +# # Capvol dates has num_fwds + 1 elements including zero today +# capVolatilities = [capVol] * (num_fwds+1) # capVolatilities[0] = 0.0 # capVolatilities = np.array(capVolatilities)/100.0 @@ -211,16 +210,16 @@ # lambdas2F = np.array(lambdas2FList) # # Simulate paths of future Libor rates -# numFactors = 1 +# num_factors = 1 # test_cases.header("NUMPATHS", "VLMM", "VBLK", "ERROR") # for num_paths in [10000, 20000, 50000, 100000, 200000, 400000, 1000000]: -# if numFactors == 1: +# if num_factors == 1: # lmmProducts.simulate1F(discount_curve, volCurve, num_paths, 0, True) -# elif numFactors == 2: -# lmmProducts.simulateMF(discount_curve, numFactors, lambdas2F, +# elif num_factors == 2: +# lmmProducts.simulateMF(discount_curve, num_factors, lambdas2F, # num_paths, 0, True) # v_lmm = lmmProducts.valueCapFloor(settle_dt, diff --git a/tests_golden/TestFinIborSingleCurve.py b/tests_golden/TestFinIborSingleCurve.py index 4cfc0369..4060b5b2 100644 --- a/tests_golden/TestFinIborSingleCurve.py +++ b/tests_golden/TestFinIborSingleCurve.py @@ -2,9 +2,13 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +import sys +sys.path.append("..") + import time as time import numpy as np import matplotlib.pyplot as plt + from financepy.utils.date import Date from financepy.utils.day_count import DayCountTypes from financepy.utils.frequency import FrequencyTypes @@ -19,8 +23,6 @@ from financepy.utils.math import ONE_MILLION from financepy.utils.global_types import SwapTypes from FinTestCases import FinTestCases, globalTestCaseMode -import sys -sys.path.append("..") test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -102,25 +104,25 @@ def test_FinIborFRAsOnly(): depoDCCType = DayCountTypes.ACT_360 notional = 100.0 - payFixed = True + pay_fixed = True cal_type = CalendarTypes.TARGET fras = [] # 1 x 4 FRA - fraRate = 0.04 + fra_rate = 0.04 fraSettlementDate = settle_dt.add_months(1) fraMaturityDate = settle_dt.add_months(4) - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, - depoDCCType, notional, payFixed, cal_type) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, + depoDCCType, notional, pay_fixed, cal_type) fras.append(fra) # 4 x 7 FRA - fraRate = 0.08 + fra_rate = 0.08 fraSettlementDate = settle_dt.add_months(4) fraMaturityDate = settle_dt.add_months(7) - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, - depoDCCType, notional, payFixed, cal_type) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, + depoDCCType, notional, pay_fixed, cal_type) fras.append(fra) depos = [] @@ -178,119 +180,119 @@ def test_ibor_depositsFRAsSwaps(): fras = [] # 1 x 4 FRA - fraRate = 0.04 + fra_rate = 0.04 fraSettlementDate = settle_dt.add_months(9) fraMaturityDate = settle_dt.add_months(13) - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, dccType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, dccType) fras.append(fra) # 4 x 7 FRA - fraRate = 0.03 + fra_rate = 0.03 fraSettlementDate = settle_dt.add_months(13) fraMaturityDate = settle_dt.add_months(17) - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, dccType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, dccType) fras.append(fra) # 4 x 7 FRA - fraRate = 0.07 + fra_rate = 0.07 fraSettlementDate = settle_dt.add_months(17) fraMaturityDate = settle_dt.add_months(21) - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, dccType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, dccType) fras.append(fra) swaps = [] - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F fixed_freq_type = FrequencyTypes.SEMI_ANNUAL swap_rate = 0.05 # maturity_dt = settle_dt.add_months(24) # swap = IborSwap(settle_dt, maturity_dt, swap_rate, fixed_freq_type, -# fixedDCCType) +# fixed_dcc_type) # swaps.append(swap) fixed_leg_type = SwapTypes.PAY maturity_dt = settle_dt.add_months(36) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(48) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(60) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(72) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(84) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(96) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(108) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(120) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(132) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(144) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(180) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(240) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(300) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) maturity_dt = settle_dt.add_months(360) swap = IborSwap(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) libor_curve = IborSingleCurve(value_dt, @@ -321,14 +323,14 @@ def test_ibor_depositsFRAsSwaps(): # AGREEMENT IS VERY CLOSE - NOT SURE ABOUT SIZE OF LAST PAYMENT ON FIXED LEG! -def futureToFRARate(price, convexity): +def futureTofra_rate(price, convexity): futRate = (100-price)/100 if convexity < 0: - fraRate = futRate + convexity/100.0 + fra_rate = futRate + convexity/100.0 else: - fraRate = futRate - convexity/100.0 + fra_rate = futRate - convexity/100.0 - return fraRate + return fra_rate ############################################################################### @@ -358,40 +360,40 @@ def test_ibor_depositsFuturesSwaps(): fras = [] - fraRate = futureToFRARate(97.6675, -0.00005) + fra_rate = futureTofra_rate(97.6675, -0.00005) fraSettlementDate = spot_dt.next_imm_date() fraMaturityDate = fraSettlementDate.next_imm_date() - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.5200, -0.00060) + fra_rate = futureTofra_rate(97.5200, -0.00060) fraSettlementDate = fraMaturityDate fraMaturityDate = fraSettlementDate.next_imm_date() - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.3550, -0.00146) + fra_rate = futureTofra_rate(97.3550, -0.00146) fraSettlementDate = fraMaturityDate fraMaturityDate = fraSettlementDate.next_imm_date() - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.2450, -0.00263) + fra_rate = futureTofra_rate(97.2450, -0.00263) fraSettlementDate = fraMaturityDate fraMaturityDate = fraSettlementDate.next_imm_date() - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.1450, -0.00411) + fra_rate = futureTofra_rate(97.1450, -0.00411) fraSettlementDate = fraMaturityDate fraMaturityDate = fraSettlementDate.next_imm_date() - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.0750, -0.00589) + fra_rate = futureTofra_rate(97.0750, -0.00589) fraSettlementDate = fraSettlementDate.next_imm_date() fraMaturityDate = fraSettlementDate.next_imm_date() - fra = IborFRA(fraSettlementDate, fraMaturityDate, fraRate, depoDCCType) + fra = IborFRA(fraSettlementDate, fraMaturityDate, fra_rate, depoDCCType) fras.append(fra) ########################################################################### @@ -401,7 +403,7 @@ def test_ibor_depositsFuturesSwaps(): swaps = [] fixed_leg_type = SwapTypes.PAY - fixedDCCType = DayCountTypes.THIRTY_E_360 + fixed_dcc_type = DayCountTypes.THIRTY_E_360 fixed_freq_type = FrequencyTypes.SEMI_ANNUAL float_freq_type = FrequencyTypes.QUARTERLY notional = 1000000 @@ -414,7 +416,7 @@ def test_ibor_depositsFuturesSwaps(): swap_rate = 0.02776305 swap = IborSwap(start_dt, "2Y", fixed_leg_type, swap_rate, - fixed_freq_type, fixedDCCType, notional, + fixed_freq_type, fixed_dcc_type, notional, float_spread, float_freq_type, floatDCCType, cal_type, busDayAdjustRule) diff --git a/tests_golden/TestFinIborSwap.py b/tests_golden/TestFinIborSwap.py index e56e1550..b0870a8a 100644 --- a/tests_golden/TestFinIborSwap.py +++ b/tests_golden/TestFinIborSwap.py @@ -2,6 +2,9 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +import sys +sys.path.append("..") + import numpy as np from financepy.utils.math import ONE_MILLION from financepy.products.rates.ibor_single_curve import IborSingleCurve @@ -18,8 +21,6 @@ from financepy.market.curves.discount_curve import DiscountCurve from financepy.market.curves.interpolator import InterpTypes from FinTestCases import FinTestCases, globalTestCaseMode -import sys -sys.path.append("..") test_cases = FinTestCases(__file__, globalTestCaseMode) diff --git a/tests_golden/TestFinIborSwaption.py b/tests_golden/TestFinIborSwaption.py index 251bdd15..d719c543 100644 --- a/tests_golden/TestFinIborSwaption.py +++ b/tests_golden/TestFinIborSwaption.py @@ -347,12 +347,12 @@ def testFinIborCashSettledSwaption(): v = swaption.value(settle_dt, libor_curve, model) test_cases.print("Swaption No-Arb Value:", v) - fwdSwapRate1 = libor_curve.swap_rate(exercise_dt, + fwd_swap_rate1 = libor_curve.swap_rate(exercise_dt, swap_maturity_dt, swap_fixed_freq_type, swapFixedDayCountType) - test_cases.print("Curve Fwd Swap Rate:", fwdSwapRate1) + test_cases.print("Curve Fwd Swap Rate:", fwd_swap_rate1) fwdSwap = IborSwap(exercise_dt, swap_maturity_dt, @@ -361,14 +361,14 @@ def testFinIborCashSettledSwaption(): swap_fixed_freq_type, swapFixedDayCountType) - fwdSwapRate2 = fwdSwap.swap_rate(settle_dt, libor_curve) - test_cases.print("Fwd Swap Swap Rate:", fwdSwapRate2) + fwd_swap_rate2 = fwdSwap.swap_rate(settle_dt, libor_curve) + test_cases.print("Fwd Swap Swap Rate:", fwd_swap_rate2) model = Black(0.1533) v = swaption.cash_settled_value(value_dt, libor_curve, - fwdSwapRate2, + fwd_swap_rate2, model) test_cases.print("Swaption Cash Settled Value:", v) diff --git a/tests_golden/TestFinModelBlackScholes.py b/tests_golden/TestFinModelBlackScholes.py index 728c9883..a22c4ca2 100644 --- a/tests_golden/TestFinModelBlackScholes.py +++ b/tests_golden/TestFinModelBlackScholes.py @@ -27,7 +27,7 @@ def testBlackScholes(): value_dt = Date(8, 5, 2015) - expiry_date = Date(15, 1, 2016) + expiry_dt = Date(15, 1, 2016) strike_price = 130.0 stock_price = 127.62 @@ -38,13 +38,13 @@ def testBlackScholes(): option_type = OptionTypes.AMERICAN_CALL euOptionType = OptionTypes.EUROPEAN_CALL - amOption = EquityAmericanOption(expiry_date, strike_price, + amOption = EquityAmericanOption(expiry_dt, strike_price, option_type) - ameuOption = EquityAmericanOption(expiry_date, strike_price, + ameuOption = EquityAmericanOption(expiry_dt, strike_price, euOptionType) - euOption = EquityVanillaOption(expiry_date, strike_price, + euOption = EquityVanillaOption(expiry_dt, strike_price, euOptionType) discount_curve = DiscountCurveFlat(value_dt, interest_rate, diff --git a/tests_golden/TestFinModelCIR.py b/tests_golden/TestFinModelCIR.py index ef6a82de..34604432 100644 --- a/tests_golden/TestFinModelCIR.py +++ b/tests_golden/TestFinModelCIR.py @@ -2,14 +2,14 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### -import time -import numpy as np -from financepy.models.cir_mc import zero_price_mc, zero_price -from financepy.models.cir_mc import CIRNumericalScheme -from FinTestCases import FinTestCases, globalTestCaseMode import sys sys.path.append("..") +import time +import numpy as np +from financepy.models.cir_montecarlo import zero_price_mc, zero_price +from financepy.models.cir_montecarlo import CIRNumericalScheme +from FinTestCases import FinTestCases, globalTestCaseMode test_cases = FinTestCases(__file__, globalTestCaseMode) diff --git a/tests_golden/TestFinModelMerton.py b/tests_golden/TestFinModelMerton.py index f9687382..87014234 100644 --- a/tests_golden/TestFinModelMerton.py +++ b/tests_golden/TestFinModelMerton.py @@ -2,13 +2,12 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.models.merton_firm_mkt import MertonFirmMkt +from financepy.models.merton_firm import MertonFirm import sys sys.path.append("..") -from financepy.models.merton_firm import MertonFirm -from financepy.models.merton_firm_mkt import MertonFirmMkt -from FinTestCases import FinTestCases, globalTestCaseMode - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -20,16 +19,16 @@ def test_FinModelMertonCredit(): # Input Equity values and equity vols equity_value = [2.6406, 2.6817, 3.977, 2.947, 2.528] equity_vol = [0.7103, 0.3929, 0.3121, 0.4595, 0.6181] - bondFace = [4.0, 3.5, 3.5, 3.2, 4.0] + bond_face = [4.0, 3.5, 3.5, 3.2, 4.0] risk_free_rate = [0.05, 0.05, 0.05, 0.05, 0.05] - assetGrowthRate = [0.0306, 0.03, 0.031, 0.0302, 0.0305] - timeToMaturity = 1.0 # np.linspace(0.1, 10, 100) + asset_growth_rate = [0.0306, 0.03, 0.031, 0.0302, 0.0305] + years_to_maturity = 1.0 # np.linspace(0.1, 10, 100) model = MertonFirmMkt(equity_value, - bondFace, - timeToMaturity, + bond_face, + years_to_maturity, risk_free_rate, - assetGrowthRate, + asset_growth_rate, equity_vol) test_cases.header("MERTON MARKET MODEL", "VALUE") @@ -44,15 +43,15 @@ def test_FinModelMertonCredit(): test_cases.print("LEVERAGE", model.leverage()) test_cases.print("PROD DEFAULT", model.prob_default()) - assetValue = model._A - assetVol = model._vA + asset_value = model._A + asset_vol = model._vA - model = MertonFirm(assetValue, - bondFace, - timeToMaturity, + model = MertonFirm(asset_value, + bond_face, + years_to_maturity, risk_free_rate, - assetGrowthRate, - assetVol) + asset_growth_rate, + asset_vol) test_cases.header("BASIC MERTON MODEL", "VALUE") @@ -68,19 +67,19 @@ def test_FinModelMertonCredit(): test_cases.print("PROD DEFAULT", model.prob_default()) test_cases.print("DISTANCE DEFAULT", model.dist_default()) - assetValue = 140.0 - bondFace = 100.0 - timeToMaturity = 1.0 + asset_value = 140.0 + bond_face = 100.0 + years_to_maturity = 1.0 risk_free_rate = 0.05 - assetGrowthRate = 0.05 - assetVol = 0.20 + asset_growth_rate = 0.05 + asset_vol = 0.20 - model = MertonFirm(assetValue, - bondFace, - timeToMaturity, + model = MertonFirm(asset_value, + bond_face, + years_to_maturity, risk_free_rate, - assetGrowthRate, - assetVol) + asset_growth_rate, + asset_vol) test_cases.header("BASIC MERTON MODEL", "VALUE") diff --git a/tests_golden/TestFinModelRatesHW.py b/tests_golden/TestFinModelRatesHW.py index dd79864a..f40d79ce 100644 --- a/tests_golden/TestFinModelRatesHW.py +++ b/tests_golden/TestFinModelRatesHW.py @@ -39,8 +39,8 @@ def test_HullWhiteExampleOne(): a = 0.1 num_time_steps = 3 model = HWTree(sigma, a, num_time_steps) - treeMat = (end_dt - start_dt)/gDaysInYear - model.build_tree(treeMat, times, dfs) + tree_mat = (end_dt - start_dt)/gDaysInYear + model.build_tree(tree_mat, times, dfs) # print_tree(model._Q) # print("") # print_tree(model._rt) diff --git a/tests_golden/TestFinModelRatesLMM.py b/tests_golden/TestFinModelRatesLMM.py index cc0aa47d..075dfcc5 100644 --- a/tests_golden/TestFinModelRatesLMM.py +++ b/tests_golden/TestFinModelRatesLMM.py @@ -2,33 +2,33 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################## +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.models.lmm_mc import lmm_sticky_caplet_pricer +from financepy.models.lmm_mc import lmm_ratchet_caplet_pricer +from financepy.models.lmm_mc import lmm_fwd_fwd_correlation +from financepy.models.lmm_mc import lmm_swap_pricer +from financepy.models.lmm_mc import lmm_price_caps_black +from financepy.models.lmm_mc import lmm_cap_flr_pricer +from financepy.models.lmm_mc import lmm_swaption_vol_approx +from financepy.models.lmm_mc import lmm_sim_swaption_vol +from financepy.models.lmm_mc import lmm_swaption_pricer +from financepy.models.lmm_mc import lmm_simulate_fwds_mf +from financepy.models.lmm_mc import lmm_simulate_fwds_1f +from financepy.models.lmm_mc import lmm_simulate_fwds_nf +from financepy.utils.helpers import check_vector_differences +from financepy.products.rates.ibor_swaption import IborSwaption +from financepy.products.rates.ibor_swaption import SwapTypes +from financepy.utils.frequency import FrequencyTypes +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +from financepy.models.black import Black +from financepy.utils.day_count import DayCountTypes +from financepy.utils.date import Date +from financepy.market.volatility.ibor_cap_vol_curve import IborCapVolCurve import numpy as np import time as time import sys sys.path.append("..") -from financepy.market.volatility.ibor_cap_vol_curve import IborCapVolCurve -from financepy.utils.date import Date -from financepy.utils.day_count import DayCountTypes -from financepy.models.black import Black -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.utils.frequency import FrequencyTypes -from financepy.products.rates.ibor_swaption import SwapTypes -from financepy.products.rates.ibor_swaption import IborSwaption -from financepy.utils.helpers import check_vector_differences -from financepy.models.lmm_mc import lmm_simulate_fwds_nf -from financepy.models.lmm_mc import lmm_simulate_fwds_1f -from financepy.models.lmm_mc import lmm_simulate_fwds_mf -from financepy.models.lmm_mc import lmm_swaption_pricer -from financepy.models.lmm_mc import lmm_sim_swaption_vol -from financepy.models.lmm_mc import lmm_swaption_vol_approx -from financepy.models.lmm_mc import lmm_cap_flr_pricer -from financepy.models.lmm_mc import lmm_price_caps_black -from financepy.models.lmm_mc import lmm_swap_pricer -from financepy.models.lmm_mc import lmm_fwd_fwd_correlation -from financepy.models.lmm_mc import lmm_ratchet_caplet_pricer -from financepy.models.lmm_mc import lmm_sticky_caplet_pricer -from FinTestCases import FinTestCases, globalTestCaseMode test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -125,9 +125,9 @@ def getForwardCurve(numFwds, r): # strike = r # PAYSwaption = 1 # use_sobol = 0 -# numeraireIndex = 0 +# numeraire_index = 0 -# fwds1F = LMMSimulateFwds1F(numFwds, num_paths, numeraireIndex, fwd0, +# fwds1F = LMMSimulateFwds1F(numFwds, num_paths, numeraire_index, fwd0, # zetas, taus, use_sobol, seed) # for iExp in range(1, 10): @@ -142,7 +142,7 @@ def getForwardCurve(numFwds, r): # swaption_priceNF = LMMSwaptionPricer(strike, a, b, num_paths, # fwd0, fwdsNF, taus, PAYSwaption) -# swaptionVol = LMMSwaptionVolApprox(a, b, fwd0, taus, zetas, correl) +# swaption_vol = LMMSwaptionVolApprox(a, b, fwd0, taus, zetas, correl) # swapVolSim1F = LMMSimSwaptionVol(a, b, fwd0, fwds1F, taus) # swapVolSimNF = LMMSimSwaptionVol(a, b, fwd0, fwdsNF, taus) @@ -175,11 +175,11 @@ def getForwardCurve(numFwds, r): # float_freq_type, # float_dc_type) -# model = Black(swaptionVol) +# model = Black(swaption_vol) # blackSwaptionPrice = swaption.value(value_dt, libor_curve, model) # print("K:%6.5f t_exp:%8.2f FwdVol:%9.5f SimVol1F:%9.5f SimVolNF:%9.5f RebVol:%9.5f SimPx1F:%9.5f SimPxNF:%9.5f Black Px:%9.5f" -# % (strike, t_exp, fwd_rateVol, swapVolSim1F, swapVolSimNF, swaptionVol, +# % (strike, t_exp, fwd_rateVol, swapVolSim1F, swapVolSimNF, swaption_vol, # swaption_price1F, swaption_priceNF, blackSwaptionPrice)) # # print(swaption) @@ -207,8 +207,8 @@ def getForwardCurve(numFwds, r): # K = r # capletPricesBlack = LMMPriceCapsBlack(fwd0, zetas, numFwds, K, taus) -# numFactors = 1 -# numeraireIndex = 1 +# num_factors = 1 +# numeraire_index = 1 # use_sobol = 1 # # Examine variance for different seeds @@ -217,7 +217,7 @@ def getForwardCurve(numFwds, r): # print("=============================================================") # print("Seed:", seed) -# fwds1F = LMMSimulateFwds1F(numFwds, num_paths, numeraireIndex, fwd0, +# fwds1F = LMMSimulateFwds1F(numFwds, num_paths, numeraire_index, fwd0, # zetas, taus, use_sobol, seed) # sumCap1F = LMMCapFlrPricer(numFwds, num_paths, K, fwd0, fwds1F, taus, 1) @@ -270,17 +270,17 @@ def test_HullBookExamples(): ########################################################################### use_sobol = 1 - numeraireIndex = 0 + numeraire_index = 0 # We need the volatility for the forward rates out to the one starting in # 10 years. So we have 11 elements. The one starting today has zero vol. - numFactors = 1 + num_factors = 1 gammas1FList = [0.00, 0.1550, 0.2063674, 0.1720986, 0.1721993, 0.1524579, 0.1414779, 0.1297711, 0.1381053, 0.135955, 0.1339842] gammas1F = np.array(gammas1FList) # One factor model - fwds1F = lmm_simulate_fwds_1f(numFwds, num_paths, numeraireIndex, fwd0, + fwds1F = lmm_simulate_fwds_1f(numFwds, num_paths, numeraire_index, fwd0, gammas1F, taus, use_sobol, seed) # LMMPrintForwards(fwds1F) @@ -312,13 +312,13 @@ def test_HullBookExamples(): check_vector_differences(vStickyCaplets, hullStickyCaplets1F, 1e-2) - numFactors = 1 + num_factors = 1 lambdas1FList = [[0.0, 0.1550, 0.2064, 0.1721, 0.1722, 0.1525, 0.1415, 0.1298, 0.1381, 0.1360, 0.1340]] lambdas1F = np.array(lambdas1FList) # One factor model - fwdsMF = lmm_simulate_fwds_mf(numFwds, numFactors, num_paths, numeraireIndex, + fwdsMF = lmm_simulate_fwds_mf(numFwds, num_factors, num_paths, numeraire_index, fwd0, lambdas1F, taus, use_sobol, seed) vRatchetCaplets = lmm_ratchet_caplet_pricer(spread, numFwds, num_paths, @@ -347,7 +347,7 @@ def test_HullBookExamples(): test_cases.print("FINANCEPY GETS:", vStickyCaplets) test_cases.print("HULL GETS:", hullStickyCaplets1F) - numFactors = 2 + num_factors = 2 lambdas2FList = [[0.00, 0.1410, 0.1952, 0.1678, 0.1711, 0.1525, 0.1406, 0.1265, 0.1306, 0.1236, 0.1163], [0.00, -0.0645, -0.0670, -0.0384, -0.0196, 0.00, @@ -355,7 +355,7 @@ def test_HullBookExamples(): lambdas2F = np.array(lambdas2FList) # Two factor model - fwds2F = lmm_simulate_fwds_mf(numFwds, numFactors, num_paths, numeraireIndex, + fwds2F = lmm_simulate_fwds_mf(numFwds, num_factors, num_paths, numeraire_index, fwd0, lambdas2F, taus, use_sobol, seed) vRatchetCaplets = lmm_ratchet_caplet_pricer(spread, numFwds, num_paths, @@ -383,7 +383,7 @@ def test_HullBookExamples(): check_vector_differences(vStickyCaplets, hullStickyCaplets2F, 1e-2) - numFactors = 3 + num_factors = 3 lambdas3FList = [[0.00, 0.1365, 0.1928, 0.1672, 0.1698, 0.1485, 0.1395, 0.1261, 0.1290, 0.1197, 0.1097], [0.0, -0.0662, -0.0702, -0.0406, -0.0206, 0.00, @@ -393,7 +393,7 @@ def test_HullBookExamples(): lambdas3F = np.array(lambdas3FList) # Three factor model - fwds3F = lmm_simulate_fwds_mf(numFwds, numFactors, num_paths, numeraireIndex, + fwds3F = lmm_simulate_fwds_mf(numFwds, num_factors, num_paths, numeraire_index, fwd0, lambdas3F, taus, use_sobol, seed) hullRatchetCaplets3F = [0.00, 0.194, 0.207, 0.205, 0.198, 0.193, diff --git a/tests_golden/TestFinOISCurve.py b/tests_golden/TestFinOISCurve.py index 1dfa8631..1a01a4bd 100644 --- a/tests_golden/TestFinOISCurve.py +++ b/tests_golden/TestFinOISCurve.py @@ -36,35 +36,35 @@ def test_OISFRAsOnly(): value_dt = Date(23, 2, 2018) spot_days = 0 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) depoDCCType = DayCountTypes.ACT_360 notional = 100.0 - payFixed = True + pay_fixed = True cal_type = CalendarTypes.TARGET fras = [] # 1 x 4 FRA - fraRate = 0.04 - frasettleDt = settleDt.add_months(1) - fraMaturityDate = settleDt.add_months(4) - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, - depoDCCType, notional, payFixed, cal_type) + fra_rate = 0.04 + fra_settle_dt = settle_dt.add_months(1) + fra_maturity_dt = settle_dt.add_months(4) + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, + depoDCCType, notional, pay_fixed, cal_type) fras.append(fra) # 4 x 7 FRA - fraRate = 0.08 - frasettleDt = settleDt.add_months(4) - fraMaturityDate = settleDt.add_months(7) - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, - depoDCCType, notional, payFixed, cal_type) + fra_rate = 0.08 + fra_settle_dt = settle_dt.add_months(4) + fra_maturity_dt = settle_dt.add_months(7) + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, + depoDCCType, notional, pay_fixed, cal_type) fras.append(fra) swaps = [] - libor_curve = OISCurve(settleDt, + libor_curve = OISCurve(settle_dt, fras, swaps) @@ -72,7 +72,7 @@ def test_OISFRAsOnly(): """ Check calibration """ for fra in fras: - v = fra.value(settleDt, libor_curve) + v = fra.value(settle_dt, libor_curve) test_cases.print("FRA:", fra._maturity_dt, v) ############################################################################### @@ -86,7 +86,7 @@ def test_OISDepositsFRAsSwaps(): depos = [] spot_days = 0 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) depoDCCType = DayCountTypes.ACT_360 notional = 100.0 @@ -95,126 +95,126 @@ def test_OISDepositsFRAsSwaps(): # 1 month deposit_rate = 0.04 - maturity_dt = settleDt.add_months(1) - depo = IborDeposit(settleDt, maturity_dt, deposit_rate, + maturity_dt = settle_dt.add_months(1) + depo = IborDeposit(settle_dt, maturity_dt, deposit_rate, depoDCCType, notional, cal_type) depos.append(depo) fras = [] # 1 x 4 FRA - fraRate = 0.04 - frasettleDt = settleDt.add_months(9) - fraMaturityDate = settleDt.add_months(13) - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, dccType) + fra_rate = 0.04 + fra_settle_dt = settle_dt.add_months(9) + fra_maturity_dt = settle_dt.add_months(13) + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, dccType) fras.append(fra) # 4 x 7 FRA - fraRate = 0.03 - frasettleDt = settleDt.add_months(13) - fraMaturityDate = settleDt.add_months(17) - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, dccType) + fra_rate = 0.03 + fra_settle_dt = settle_dt.add_months(13) + fra_maturity_dt = settle_dt.add_months(17) + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, dccType) fras.append(fra) # 4 x 7 FRA - fraRate = 0.07 - frasettleDt = settleDt.add_months(17) - fraMaturityDate = settleDt.add_months(21) - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, dccType) + fra_rate = 0.07 + fra_settle_dt = settle_dt.add_months(17) + fra_maturity_dt = settle_dt.add_months(21) + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, dccType) fras.append(fra) swaps = [] - fixedDCCType = DayCountTypes.ACT_365F + fixed_dcc_type = DayCountTypes.ACT_365F fixed_freq_type = FrequencyTypes.SEMI_ANNUAL swap_rate = 0.05 -# maturity_dt = settleDt.add_months(24) -# swap = IborSwap(settleDt, maturity_dt, swap_rate, fixed_freq_type, -# fixedDCCType) +# maturity_dt = settle_dt.add_months(24) +# swap = IborSwap(settle_dt, maturity_dt, swap_rate, fixed_freq_type, +# fixed_dcc_type) # swaps.append(swap) fixed_leg_type = SwapTypes.PAY - maturity_dt = settleDt.add_months(36) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(36) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(48) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(48) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(60) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(60) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(72) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(72) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(84) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(84) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(96) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(96) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(108) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(108) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(120) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(120) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(132) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(132) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(144) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(144) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(180) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(180) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(240) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(240) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(300) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(300) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) - maturity_dt = settleDt.add_months(360) - swap = OIS(settleDt, maturity_dt, fixed_leg_type, swap_rate, + maturity_dt = settle_dt.add_months(360) + swap = OIS(settle_dt, maturity_dt, fixed_leg_type, swap_rate, fixed_freq_type, - fixedDCCType) + fixed_dcc_type) swaps.append(swap) libor_curve = OISCurve(value_dt, @@ -222,10 +222,10 @@ def test_OISDepositsFRAsSwaps(): fras, swaps) - df = libor_curve.df(settleDt) + df = libor_curve.df(settle_dt) test_cases.header("SETTLEMENT DATE", "DF") - test_cases.print(str(settleDt), df) + test_cases.print(str(settle_dt), df) test_cases.header("DATE", "DF") for deposit in depos: @@ -245,14 +245,14 @@ def test_OISDepositsFRAsSwaps(): # AGREEMENT IS VERY CLOSE - NOT SURE ABOUT SIZE OF LAST PAYMENT ON FIXED LEG! -def futureToFRARate(price, convexity): +def futureTofra_rate(price, convexity): futRate = (100-price)/100 if convexity < 0: - fraRate = futRate + convexity/100.0 + fra_rate = futRate + convexity/100.0 else: - fraRate = futRate - convexity/100.0 + fra_rate = futRate - convexity/100.0 - return fraRate + return fra_rate ############################################################################### @@ -261,48 +261,48 @@ def test_OISDepositsFuturesSwaps(): spot_dt = Date(6, 6, 2018) spot_days = 0 - settleDt = spot_dt.add_weekdays(spot_days) + settle_dt = spot_dt.add_weekdays(spot_days) depoDCCType = DayCountTypes.THIRTY_E_360_ISDA - depo = IborDeposit(settleDt, "1D", 1.712 / 100.0, depoDCCType) + depo = IborDeposit(settle_dt, "1D", 1.712 / 100.0, depoDCCType) depos = [depo] fras = [] - fraRate = futureToFRARate(97.6675, -0.00005) - frasettleDt = spot_dt.next_imm_date() - fraMaturityDate = frasettleDt.next_imm_date() - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, depoDCCType) + fra_rate = futureTofra_rate(97.6675, -0.00005) + fra_settle_dt = spot_dt.next_imm_date() + fra_maturity_dt = fra_settle_dt.next_imm_date() + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.5200, -0.00060) - frasettleDt = fraMaturityDate - fraMaturityDate = frasettleDt.next_imm_date() - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, depoDCCType) + fra_rate = futureTofra_rate(97.5200, -0.00060) + fra_settle_dt = fra_maturity_dt + fra_maturity_dt = fra_settle_dt.next_imm_date() + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.3550, -0.00146) - frasettleDt = fraMaturityDate - fraMaturityDate = frasettleDt.next_imm_date() - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, depoDCCType) + fra_rate = futureTofra_rate(97.3550, -0.00146) + fra_settle_dt = fra_maturity_dt + fra_maturity_dt = fra_settle_dt.next_imm_date() + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.2450, -0.00263) - frasettleDt = fraMaturityDate - fraMaturityDate = frasettleDt.next_imm_date() - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, depoDCCType) + fra_rate = futureTofra_rate(97.2450, -0.00263) + fra_settle_dt = fra_maturity_dt + fra_maturity_dt = fra_settle_dt.next_imm_date() + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.1450, -0.00411) - frasettleDt = fraMaturityDate - fraMaturityDate = frasettleDt.next_imm_date() - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, depoDCCType) + fra_rate = futureTofra_rate(97.1450, -0.00411) + fra_settle_dt = fra_maturity_dt + fra_maturity_dt = fra_settle_dt.next_imm_date() + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, depoDCCType) fras.append(fra) - fraRate = futureToFRARate(97.0750, -0.00589) - frasettleDt = frasettleDt.next_imm_date() - fraMaturityDate = frasettleDt.next_imm_date() - fra = IborFRA(frasettleDt, fraMaturityDate, fraRate, depoDCCType) + fra_rate = futureTofra_rate(97.0750, -0.00589) + fra_settle_dt = fra_settle_dt.next_imm_date() + fra_maturity_dt = fra_settle_dt.next_imm_date() + fra = IborFRA(fra_settle_dt, fra_maturity_dt, fra_rate, depoDCCType) fras.append(fra) ########################################################################### @@ -312,7 +312,7 @@ def test_OISDepositsFuturesSwaps(): swaps = [] fixed_leg_type = SwapTypes.PAY - fixedDCCType = DayCountTypes.THIRTY_E_360 + fixed_dcc_type = DayCountTypes.THIRTY_E_360 fixed_freq_type = FrequencyTypes.SEMI_ANNUAL float_freq_type = FrequencyTypes.QUARTERLY notional = 1000000 @@ -325,7 +325,7 @@ def test_OISDepositsFuturesSwaps(): payment_lag = 1 swap = OIS(start_dt, "2Y", fixed_leg_type, - swap_rate, fixed_freq_type, fixedDCCType, notional, + swap_rate, fixed_freq_type, fixed_dcc_type, notional, payment_lag, float_spread, float_freq_type, floatDCCType, cal_type, busDayAdjustRule) @@ -355,7 +355,7 @@ def test_OISDepositsFuturesSwaps(): df = libor_curve.df(end_dt) print(end_dt, df) - end_dt = settleDt + end_dt = settle_dt df = libor_curve.df(end_dt) print(end_dt, df) @@ -387,7 +387,7 @@ def test_derivativePricingExample(): # We do the O/N rate which settles on trade date spot_days = 0 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) fras = [] @@ -398,42 +398,42 @@ def test_derivativePricingExample(): fixed_leg_type = SwapTypes.PAY swap_rate = 0.0058 - swap = OIS(settleDt, "1Y", fixed_leg_type, + swap = OIS(settle_dt, "1Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0060 - swap = OIS(settleDt, "2Y", fixed_leg_type, + swap = OIS(settle_dt, "2Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0072 - swap = OIS(settleDt, "3Y", fixed_leg_type, + swap = OIS(settle_dt, "3Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0096 - swap = OIS(settleDt, "4Y", fixed_leg_type, + swap = OIS(settle_dt, "4Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0124 - swap = OIS(settleDt, "5Y", fixed_leg_type, + swap = OIS(settle_dt, "5Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0173 - swap = OIS(settleDt, "7Y", fixed_leg_type, + swap = OIS(settle_dt, "7Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0219 - swap = OIS(settleDt, "10Y", fixed_leg_type, + swap = OIS(settle_dt, "10Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) swap_rate = 0.0283 - swap = OIS(settleDt, "30Y", fixed_leg_type, + swap = OIS(settle_dt, "30Y", fixed_leg_type, swap_rate, freq_type, dc_type) swaps.append(swap) @@ -472,10 +472,10 @@ def test_bloombergPricingExample(): # We do the O/N rate which settles on trade date spot_days = 0 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) accrual = DayCountTypes.THIRTY_E_360 - depo = IborDeposit(settleDt, "1D", 1.712 / 100.0, accrual) + depo = IborDeposit(settle_dt, "1D", 1.712 / 100.0, accrual) depos = [depo] futs = [] @@ -503,60 +503,60 @@ def test_bloombergPricingExample(): accrual = DayCountTypes.THIRTY_E_360 freq = FrequencyTypes.SEMI_ANNUAL spot_days = 2 - settleDt = value_dt.add_weekdays(spot_days) + settle_dt = value_dt.add_weekdays(spot_days) payRec = SwapTypes.PAY lag = 1 # Not used swaps = [] - swap = OIS(settleDt, "2Y", payRec, + swap = OIS(settle_dt, "2Y", payRec, (2.77417 + 2.77844) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "3Y", payRec, + swap = OIS(settle_dt, "3Y", payRec, (2.86098 + 2.86582) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "4Y", payRec, + swap = OIS(settle_dt, "4Y", payRec, (2.90240 + 2.90620) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "5Y", payRec, + swap = OIS(settle_dt, "5Y", payRec, (2.92944 + 2.92906) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "6Y", payRec, + swap = OIS(settle_dt, "6Y", payRec, (2.94001 + 2.94499) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "7Y", payRec, + swap = OIS(settle_dt, "7Y", payRec, (2.95352 + 2.95998) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "8Y", payRec, + swap = OIS(settle_dt, "8Y", payRec, (2.96830 + 2.97400) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "9Y", payRec, + swap = OIS(settle_dt, "9Y", payRec, (2.98403 + 2.98817) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "10Y", payRec, + swap = OIS(settle_dt, "10Y", payRec, (2.99716 + 3.00394) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "11Y", payRec, + swap = OIS(settle_dt, "11Y", payRec, (3.01344 + 3.01596) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "12Y", payRec, + swap = OIS(settle_dt, "12Y", payRec, (3.02276 + 3.02684) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "15Y", payRec, + swap = OIS(settle_dt, "15Y", payRec, (3.04092 + 3.04508) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "20Y", payRec, + swap = OIS(settle_dt, "20Y", payRec, (3.04417 + 3.05183) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "25Y", payRec, + swap = OIS(settle_dt, "25Y", payRec, (3.03219 + 3.03621) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "30Y", payRec, + swap = OIS(settle_dt, "30Y", payRec, (3.01030 + 3.01370) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "40Y", payRec, + swap = OIS(settle_dt, "40Y", payRec, (2.96946 + 2.97354) / 200, freq, accrual) swaps.append(swap) - swap = OIS(settleDt, "50Y", payRec, + swap = OIS(settle_dt, "50Y", payRec, (2.91552 + 2.93748) / 200, freq, accrual) swaps.append(swap) @@ -575,10 +575,10 @@ def test_bloombergPricingExample(): value_dt, oisCurve, None)) test_cases.header("VALUATION TO SWAP SETTLEMENT DATE", " PV") - test_cases.print("VALUE:", swaps[0].value(settleDt, oisCurve, None)) - test_cases.print("FIXED:", -swaps[0]._fixed_leg.value(settleDt, oisCurve)) + test_cases.print("VALUE:", swaps[0].value(settle_dt, oisCurve, None)) + test_cases.print("FIXED:", -swaps[0]._fixed_leg.value(settle_dt, oisCurve)) test_cases.print("FLOAT:", swaps[0]._float_leg.value( - settleDt, oisCurve, None)) + settle_dt, oisCurve, None)) # swaps[0].print_fixed_leg_pv() # swaps[0].print_float_leg_pv() diff --git a/tests_golden/TestFinOptionImpliedDbn.py b/tests_golden/TestFinOptionImpliedDbn.py index f0829265..ab3f688a 100644 --- a/tests_golden/TestFinOptionImpliedDbn.py +++ b/tests_golden/TestFinOptionImpliedDbn.py @@ -2,18 +2,17 @@ # Copyright (C) 2018, 2019, 2020 Dominic O'Kane ############################################################################### +from FinTestCases import FinTestCases, globalTestCaseMode +from financepy.market.volatility.fx_vol_surface import FinFXDeltaMethod +from financepy.market.volatility.fx_vol_surface import FinFXATMMethod +from financepy.market.volatility.fx_vol_surface import FXVolSurface +from financepy.models.volatility_fns import vol_function_clark +from financepy.utils.date import Date +from financepy.market.curves.discount_curve_flat import DiscountCurveFlat +import numpy as np import sys sys.path.append("..") -import numpy as np -from financepy.market.curves.discount_curve_flat import DiscountCurveFlat -from financepy.utils.date import Date -from financepy.models.volatility_fns import vol_function_clark -from financepy.market.volatility.fx_vol_surface import FXVolSurface -from financepy.market.volatility.fx_vol_surface import FinFXATMMethod -from financepy.market.volatility.fx_vol_surface import FinFXDeltaMethod -from FinTestCases import FinTestCases, globalTestCaseMode - test_cases = FinTestCases(__file__, globalTestCaseMode) @@ -34,8 +33,8 @@ def test_FinOptionImpliedDbn(): forCCRate = 0.03460 # EUR domCCRate = 0.02940 # USD - dom_discount_curve = DiscountCurveFlat(value_dt, domCCRate) - for_discount_curve = DiscountCurveFlat(value_dt, forCCRate) + domestic_curve = DiscountCurveFlat(value_dt, domCCRate) + foreign_curve = DiscountCurveFlat(value_dt, forCCRate) currency_pair = forName + domName spot_fx_rate = 1.3465 @@ -47,20 +46,20 @@ def test_FinOptionImpliedDbn(): notional_currency = forName - atmMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL + atm_method = FinFXATMMethod.FWD_DELTA_NEUTRAL delta_method = FinFXDeltaMethod.SPOT_DELTA fxMarket = FXVolSurface(value_dt, spot_fx_rate, currency_pair, notional_currency, - dom_discount_curve, - for_discount_curve, + domestic_curve, + foreign_curve, tenors, atm_vols, marketStrangle25DeltaVols, riskReversal25DeltaVols, - atmMethod, + atm_method, delta_method) # fxMarket.check_calibration(True) @@ -80,8 +79,8 @@ def test_FinOptionImpliedDbn(): num_steps = 10000 dFX = (endFX - startFX) / num_steps -# dom_df = dom_discount_curve._df(t_exp) -# for_df = for_discount_curve._df(t_exp) +# dom_df = domestic_curve._df(t_exp) +# for_df = foreign_curve._df(t_exp) # r_d = -np.log(dom_df) / t_exp # r_f = -np.log(for_df) / t_exp diff --git a/tests_golden/TestFinProcessSimulator.py b/tests_golden/TestFinProcessSimulator.py index f8dca55e..8a876a1e 100644 --- a/tests_golden/TestFinProcessSimulator.py +++ b/tests_golden/TestFinProcessSimulator.py @@ -23,7 +23,7 @@ def test_FinProcessSimulator(): import time num_paths = 20000 - numAnnSteps = 100 + num_annual_steps = 100 seed = 1919 t = 1.0 modelSim = FinProcessSimulator() @@ -41,7 +41,7 @@ def test_FinProcessSimulator(): ProcessTypes.GBM, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -63,7 +63,7 @@ def test_FinProcessSimulator(): ProcessTypes.GBM, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -87,7 +87,7 @@ def test_FinProcessSimulator(): ProcessTypes.HESTON, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -111,7 +111,7 @@ def test_FinProcessSimulator(): ProcessTypes.HESTON, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -135,7 +135,7 @@ def test_FinProcessSimulator(): ProcessTypes.HESTON, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -157,7 +157,7 @@ def test_FinProcessSimulator(): ProcessTypes.VASICEK, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -179,7 +179,7 @@ def test_FinProcessSimulator(): ProcessTypes.VASICEK, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() @@ -201,7 +201,7 @@ def test_FinProcessSimulator(): ProcessTypes.CIR, t, model_params, - numAnnSteps, + num_annual_steps, num_paths, seed) end = time.time() diff --git a/tests_golden/TestFinSwaptionVolSurface.py b/tests_golden/TestFinSwaptionVolSurface.py index 87ca508d..5150180a 100644 --- a/tests_golden/TestFinSwaptionVolSurface.py +++ b/tests_golden/TestFinSwaptionVolSurface.py @@ -26,7 +26,7 @@ ############################################################################### -def test_FinSwaptionVolSurface1(verboseCalibration): +def test_FinSwaptionVolSurface1(verbose): ########################################################################### @@ -110,9 +110,9 @@ def test_FinSwaptionVolSurface1(verboseCalibration): start = time.time() - verboseCalibration = False + verbose = False - test_FinSwaptionVolSurface1(verboseCalibration) + test_FinSwaptionVolSurface1(verbose) end = time.time() diff --git a/version.py b/version.py index 332a3a6e..6bd6a1d8 100644 --- a/version.py +++ b/version.py @@ -1 +1 @@ -__version__ = "0.34" +__version__ = "0.350"