diff --git a/README.md b/README.md index 60af1d55..3253b981 100644 --- a/README.md +++ b/README.md @@ -58,15 +58,15 @@ To upgrade an existing installation type: `pip install --upgrade financepy` -I have encountered problems using Anaconda3-2020.07 due to some Numba and LLVMLite problems. However Anaconda3-2020.02 works. +I have encountered problems using Anaconda3-2020.07 due to some Numba and LLVMLite problems. However, Anaconda3-2020.02 works. ## Using FinancePy in a Jupyter Notebook Once financepy has been installed, it is easy to get started. -Just download the project and examine the set of Jupyter Notebooks in the notebooks folder. +Just download the project and examine the set of Jupyter Notebooks in the notebook folder. -A pdf manual describing all of the functions can be found in the project directory. +A pdf manual describing all the functions can be found in the project directory. ## Overview @@ -139,7 +139,7 @@ See the changelog for a detailed history of changes. Contributions are very welcome. There are a number of requirements: * The code should be Pep8 compliant. -* Comments are required for every class and function and they should be a clear description. +* Comments are required for every class and function, and they should be a clear description. * At least one broad test case and a set of unit tests must be provided for every function. * Avoid very pythonic constructions. For example a loop is as good as a list comprehension. And with numba it can be faster. Readability is the priority. diff --git a/financepy/market/curves/discount_curve.py b/financepy/market/curves/discount_curve.py index fc7de31b..e25419bf 100644 --- a/financepy/market/curves/discount_curve.py +++ b/financepy/market/curves/discount_curve.py @@ -40,7 +40,6 @@ def __init__(self, specify any compounding convention or day count calculation since discount factors are pure prices. We do however need to specify a convention for interpolating the discount factors in time.""" - check_argument_types(self.__init__, locals()) # Validate curve @@ -85,7 +84,7 @@ def __init__(self, ########################################################################### def _zero_to_df(self, - value_dt: Date, #TODO: why is value_date not used ? + value_dt: Date, # TODO: why is value_date not used ? rates: (float, np.ndarray), times: (float, np.ndarray), freq_type: FrequencyTypes, diff --git a/financepy/market/curves/discount_curve_flat.py b/financepy/market/curves/discount_curve_flat.py index 047e9aab..996ffff7 100644 --- a/financepy/market/curves/discount_curve_flat.py +++ b/financepy/market/curves/discount_curve_flat.py @@ -23,8 +23,8 @@ class DiscountCurveFlat(DiscountCurve): - """ A very simple discount curve based on a single zero rate with its - own specified compounding method. Hence the curve is assumed to be flat. + """A very simple discount curve based on a single zero rate with its + own specified compounding method. Hence, the curve is assumed to be flat. It is used for quick and dirty analysis and when limited information is available. It inherits several methods from FinDiscountCurve. """ @@ -49,7 +49,7 @@ def __init__(self, self._freq_type = freq_type self._dc_type = dc_type - # This is used by some inherited functions so we choose the simplest + # This is used by some inherited functions, so we choose the simplest self._interp_type = InterpTypes.FLAT_FWD_RATES # Need to set up a grid of times and discount factors @@ -64,7 +64,7 @@ def __init__(self, def bump(self, bump_size: float): - """ Creates a new FinDiscountCurveFlat object with the entire curve + """ Create a new FinDiscountCurveFlat object with the entire curve bumped up by the bumpsize. All other parameters are preserved.""" rate_bumped = self._flat_rate + bump_size @@ -80,7 +80,7 @@ def df(self, dts: (Date, list)): """ Return discount factors given a single or vector of dts. The discount factor depends on the rate and this in turn depends on its - compounding frequency and it defaults to continuous compounding. It + compounding frequency, and it defaults to continuous compounding. It also depends on the day count convention. This was set in the construction of the curve to be ACT_ACT_ISDA. """ diff --git a/financepy/models/bdt_tree.py b/financepy/models/bdt_tree.py index d795d02f..1d6753c5 100644 --- a/financepy/models/bdt_tree.py +++ b/financepy/models/bdt_tree.py @@ -94,7 +94,7 @@ def search_root(x0, m, q_matrix, rt, df_end, dt, sigma): @njit(fastmath=True, cache=True) -def bermudan_swaption_tree_fast(t_exp, tmat, +def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, @@ -116,7 +116,7 @@ def bermudan_swaption_tree_fast(t_exp, tmat, num_time_steps, num_nodes = _Q.shape expiry_step = int(t_exp/_dt + 0.50) - maturity_step = int(tmat/_dt + 0.50) + maturity_step = int(t_mat/_dt + 0.50) ########################################################################### @@ -247,7 +247,7 @@ def bermudan_swaption_tree_fast(t_exp, tmat, @njit(fastmath=True, cache=True) -def american_bond_option_tree_fast(t_exp, tmat, +def american_bond_option_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_type_int, @@ -274,7 +274,7 @@ def american_bond_option_tree_fast(t_exp, tmat, num_time_steps, num_nodes = _Q.shape expiry_step = int(t_exp/_dt + 0.50) - maturity_step = int(tmat/_dt + 0.50) + maturity_step = int(t_mat/_dt + 0.50) ########################################################################### @@ -447,8 +447,8 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, ####################################################################### num_time_steps, num_nodes = _q_matrix.shape dt = _dt - tmat = cpn_times[-1] - maturity_step = int(tmat/dt + 0.50) + t_mat = cpn_times[-1] + maturity_step = int(t_mat/dt + 0.50) ########################################################################### # Map coupons onto tree while preserving their present value @@ -588,8 +588,8 @@ def build_tree_fast(sigma, tree_times, num_time_steps, discount_factors): dt = tree_maturity / (num_time_steps+1) # The short rate goes out one step extra to have the final short rate - # as it follows HW code but I am not sure this is needed. EXAMINE - # NOTE HW code uses this to have short rate at expiry so it can use + # as it follows HW code, but I am not sure if this is needed. EXAMINE + # NOTE HW code uses this to have short rate at expiry, so it can use # analytical solutions for the zero coupon bond price # This is the BDT model so x = log(r) @@ -616,7 +616,7 @@ def build_tree_fast(sigma, tree_times, num_time_steps, discount_factors): Q[1, 1] = 0.50 / ((1.0 + rt[0, 0]) ** dt) # The short rate goes out one step extra to have the final short rate - # as it follows HW code but I am not sure this is needed. EXAMINE + # as it follows HW code, but I am not sure if this is needed. EXAMINE for m in range(1, num_time_steps+1): df_end = discount_factors[m+1] @@ -713,9 +713,9 @@ def bond_option(self, t_exp, strike_price, face_amount, exercise_typeInt = option_exercise_types_to_int(exercise_type) - tmat = cpn_times[-1] + t_mat = cpn_times[-1] - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: @@ -724,7 +724,7 @@ def bond_option(self, t_exp, strike_price, face_amount, ####################################################################### call_value, put_value \ - = american_bond_option_tree_fast(t_exp, tmat, + = american_bond_option_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_typeInt, @@ -737,7 +737,7 @@ def bond_option(self, t_exp, strike_price, face_amount, ############################################################################### - def bermudan_swaption(self, t_exp, tmat, strike, face_amount, + def bermudan_swaption(self, t_exp, t_mat, strike, face_amount, cpn_times, cpn_flows, exercise_type): """ Swaption that can be exercised on specific dates over the exercise period. Due to non-analytical bond price we need to extend tree out to @@ -745,9 +745,9 @@ def bermudan_swaption(self, t_exp, tmat, strike, face_amount, exercise_type_int = option_exercise_types_to_int(exercise_type) - tmat = cpn_times[-1] + t_mat = cpn_times[-1] - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: @@ -756,7 +756,7 @@ def bermudan_swaption(self, t_exp, tmat, strike, face_amount, ####################################################################### payValue, recValue \ - = bermudan_swaption_tree_fast(t_exp, tmat, + = bermudan_swaption_tree_fast(t_exp, t_mat, strike, face_amount, cpn_times, cpn_flows, exercise_type_int, diff --git a/financepy/models/bk_tree.py b/financepy/models/bk_tree.py index fe519927..b639dce2 100644 --- a/financepy/models/bk_tree.py +++ b/financepy/models/bk_tree.py @@ -46,13 +46,13 @@ def option_exercise_types_to_int(optionExerciseType): fastmath=True, cache=True) def f(alpha, nm, Q, P, dX, dt, N): - sumQZ = 0.0 + sum_qz = 0.0 for j in range(-nm, nm+1): x = alpha + j*dX rdt = np.exp(x)*dt - sumQZ += Q[j+N] * np.exp(-rdt) + sum_qz += Q[j+N] * np.exp(-rdt) - obj_fn = sumQZ - P + obj_fn = sum_qz - P return obj_fn ############################################################################### @@ -62,13 +62,13 @@ def f(alpha, nm, Q, P, dX, dt, N): fastmath=True, cache=True) def fprime(alpha, nm, Q, P, dX, dt, N): - sumQZdZ = 0.0 + sum_q_zd_z = 0.0 for j in range(-nm, nm+1): x = alpha + j*dX rdt = np.exp(x)*dt - sumQZdZ += Q[j+N] * np.exp(-rdt) * np.exp(x) + sum_q_zd_z += Q[j+N] * np.exp(-rdt) * np.exp(x) - deriv = -sumQZdZ*dt + deriv = -sum_q_zd_z*dt return deriv ############################################################################### @@ -101,7 +101,7 @@ def search_root(x0, nm, Q, P, dX, dt, N): x1 = x f1 = f(x1, nm, Q, P, dX, dt, N) - if (abs(f1) <= max_error): + if abs(f1) <= max_error: return x1 raise FinError("Search root deriv FAILED to find alpha.") @@ -141,7 +141,7 @@ def search_root_deriv(x0, nm, Q, P, dX, dt, N): @njit(fastmath=True, cache=True) -def bermudan_swaption_tree_fast(t_exp, tmat, +def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_type_int, @@ -157,10 +157,10 @@ def bermudan_swaption_tree_fast(t_exp, tmat, num_time_steps, num_nodes = _Q.shape j_max = ceil(0.1835/(_a * _dt)) expiry_step = int(t_exp/_dt + 0.50) - maturity_step = int(tmat/_dt + 0.50) + maturity_step = int(t_mat/_dt + 0.50) ########################################################################### - # I shove the floating rate value into the grid so it is handled in terms + # I shove the floating rate value into the grid, so it is handled in terms # of PV - it will not sit on a grid date so needs to be PV adjusted. # This is the value of the floating leg - this is a ONE CURVE approach. ########################################################################### @@ -368,7 +368,7 @@ def bermudan_swaption_tree_fast(t_exp, tmat, @njit(fastmath=True, cache=True) -def american_bond_option_tree_fast(t_exp, tmat, +def american_bond_option_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_type_int, @@ -388,7 +388,7 @@ def american_bond_option_tree_fast(t_exp, tmat, num_time_steps, num_nodes = _Q.shape j_max = ceil(0.1835/(_a * _dt)) expiry_step = int(t_exp/_dt + 0.50) - maturity_step = int(tmat/_dt + 0.50) + maturity_step = int(t_mat/_dt + 0.50) ########################################################################### @@ -607,8 +607,8 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, num_time_steps, num_nodes = _Q.shape dt = _dt j_max = ceil(0.1835/(_a * _dt)) - tmat = cpn_times[-1] - maturity_step = int(tmat/dt + 0.50) + t_mat = cpn_times[-1] + maturity_step = int(t_mat/dt + 0.50) ########################################################################### # Map coupons onto tree while preserving their present value @@ -900,7 +900,7 @@ def __init__(self, ############################################################################### - def build_tree(self, tmat, df_times, df_values): + def build_tree(self, t_mat, df_times, df_values): if isinstance(df_times, np.ndarray) is False: raise FinError("DF TIMES must be a numpy vector") @@ -910,7 +910,7 @@ def build_tree(self, tmat, df_times, df_values): interp = InterpTypes.FLAT_FWD_RATES.value - treeMaturity = tmat * (self._num_time_steps+1)/self._num_time_steps + treeMaturity = t_mat * (self._num_time_steps+1)/self._num_time_steps tree_times = np.linspace(0.0, treeMaturity, self._num_time_steps + 2) self._tree_times = tree_times @@ -939,9 +939,9 @@ def bond_option(self, t_exp, strike_price, face_amount, exercise_type_int = option_exercise_types_to_int(exercise_type) - tmat = cpn_times[-1] + t_mat = cpn_times[-1] - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: @@ -950,7 +950,7 @@ def bond_option(self, t_exp, strike_price, face_amount, ####################################################################### call_value, put_value \ - = american_bond_option_tree_fast(t_exp, tmat, + = american_bond_option_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_type_int, @@ -964,7 +964,7 @@ def bond_option(self, t_exp, strike_price, face_amount, ############################################################################### - def bermudan_swaption(self, t_exp, tmat, strike_price, face_amount, + def bermudan_swaption(self, t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_type): """ Swaption that can be exercised on specific dates over the exercise period. Due to non-analytical bond price we need to extend tree out to @@ -972,9 +972,9 @@ def bermudan_swaption(self, t_exp, tmat, strike_price, face_amount, exercise_type_int = option_exercise_types_to_int(exercise_type) - tmat = cpn_times[-1] + t_mat = cpn_times[-1] - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: @@ -983,7 +983,7 @@ def bermudan_swaption(self, t_exp, tmat, strike_price, face_amount, ####################################################################### payValue, recValue \ - = bermudan_swaption_tree_fast(t_exp, tmat, + = bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_type_int, diff --git a/financepy/models/black.py b/financepy/models/black.py index 9979e608..f9eb997e 100644 --- a/financepy/models/black.py +++ b/financepy/models/black.py @@ -381,7 +381,7 @@ def _estimate_vol_from_price(fwd, t, k, european_option_type, european_price): # NOTE: # Instead of european price, american price is # passed to an approximation formula for european option. - # But it's just a initial point, so no affect on the calibration. + # But it's just an initial point, so has no affect on the calibration. sigma0 = _estimate_vol_from_price( fwd, t, k, OptionTypes.EUROPEAN_CALL, price) elif option_type == OptionTypes.AMERICAN_PUT: diff --git a/financepy/models/black_scholes_mc_tests.py b/financepy/models/black_scholes_mc_tests.py index 5986426d..f55510dd 100644 --- a/financepy/models/black_scholes_mc_tests.py +++ b/financepy/models/black_scholes_mc_tests.py @@ -15,7 +15,7 @@ def value_mc1(s0, t, k, r, q, v, num_paths, seed): - vsqrtt = v * sqrt(t) + v_sqrtt = v * sqrt(t) st = s0 * exp((r - q - v*v / 2.0) * t) np.random.seed(seed) diff --git a/financepy/models/hw_tree.py b/financepy/models/hw_tree.py index a1847135..0638a1e5 100644 --- a/financepy/models/hw_tree.py +++ b/financepy/models/hw_tree.py @@ -411,7 +411,7 @@ def american_bond_option_tree_fast(t_exp, @njit(fastmath=True, cache=True) -def bermudan_swaption_tree_fast(t_exp, tmat, strike_price, face_amount, +def bermudan_swaption_tree_fast(t_exp, t_mat, strike_price, face_amount, cpn_times, cpn_flows, exercise_typeInt, _df_times, _df_values, @@ -424,7 +424,7 @@ def bermudan_swaption_tree_fast(t_exp, tmat, 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(tmat/_dt + 0.50) + maturityStep = int(t_mat/_dt + 0.50) ########################################################################### @@ -622,8 +622,8 @@ def callable_puttable_bond_tree_fast(cpn_times, cpn_flows, num_time_steps, num_nodes = _Q.shape dt = _dt j_max = ceil(0.1835/(_a * dt)) - tmat = cpn_times[-1] - maturityStep = int(tmat/dt + 0.50) + t_mat = cpn_times[-1] + maturityStep = int(t_mat/dt + 0.50) ########################################################################### # Map coupons onto tree while preserving their present value @@ -876,21 +876,21 @@ def __init__(self, ############################################################################### def option_on_zcb(self, - t_exp, tmat, + t_exp, t_mat, strike, face_amount, df_times, df_values): """ Price an option on a zero coupon bond using analytical solution of Hull-White model. User provides bond face and option strike and expiry date and maturity date. """ - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: raise FinError("Option expiry time negative.") pt_exp = _uinterpolate(t_exp, df_times, df_values, interp) - ptmat = _uinterpolate(tmat, df_times, df_values, interp) + pt_mat = _uinterpolate(t_mat, df_times, df_values, interp) sigma = self._sigma a = self._a @@ -898,17 +898,17 @@ def option_on_zcb(self, if abs(a) < small: a = small - sigmap = (sigma/a) * (1.0 - np.exp(-a*(tmat-t_exp))) + sigmap = (sigma/a) * (1.0 - np.exp(-a*(t_mat-t_exp))) sigmap *= np.sqrt((1.0-np.exp(-2.0*a*t_exp))/2.0/a) if abs(sigmap) < small: sigmap = small - h = np.log((face_amount*ptmat)/(strike * pt_exp)) / \ + h = np.log((face_amount*pt_mat)/(strike * pt_exp)) / \ sigmap + sigmap / 2.0 - call_value = face_amount * ptmat * 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 * ptmat * N(-h) + N(-h + sigmap) - face_amount * pt_mat * N(-h) return {'call': call_value, 'put': put_value} @@ -1053,13 +1053,13 @@ def european_bond_option_expiry_only(self, def option_on_zero_coupon_bond_tree(self, t_exp, - tmat, + t_mat, strike_price, face_amount): """ Price an option on a zero coupon bond using a HW trinomial tree. The discount curve was already supplied to the tree build. """ - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: @@ -1076,7 +1076,7 @@ def option_on_zero_coupon_bond_tree(self, pt_exp = _uinterpolate(t_exp, self._df_times, self._dfs, interp) ptdelta = _uinterpolate(tdelta, self._df_times, self._dfs, interp) - ptmat = _uinterpolate(tmat, self._df_times, self._dfs, interp) + pt_mat = _uinterpolate(t_mat, self._df_times, self._dfs, interp) _, num_nodes = self._Q.shape expiry_step = int(t_exp/dt+0.50) @@ -1089,8 +1089,8 @@ def option_on_zero_coupon_bond_tree(self, q = self._Q[expiry_step, k] r_t = self._r_t[expiry_step, k] - zcb = p_fast(t_exp, tmat, - r_t, dt, pt_exp, ptdelta, ptmat, + zcb = p_fast(t_exp, t_mat, + r_t, dt, pt_exp, ptdelta, pt_mat, self._sigma, self._a) putPayoff = max(strike_price - zcb * face_amount, 0.0) @@ -1102,7 +1102,7 @@ def option_on_zero_coupon_bond_tree(self, ############################################################################### - def bermudan_swaption(self, t_exp, tmat, strike, face, + def bermudan_swaption(self, t_exp, t_mat, strike, face, cpn_times, cpn_flows, exercise_type): """ Swaption that can be exercised on specific dates over the exercise period. Due to non-analytical bond price we need to extend tree out to @@ -1110,9 +1110,9 @@ def bermudan_swaption(self, t_exp, tmat, strike, face, exercise_typeInt = option_exercise_types_to_int(exercise_type) - tmat = cpn_times[-1] + t_mat = cpn_times[-1] - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: @@ -1121,7 +1121,7 @@ def bermudan_swaption(self, t_exp, tmat, strike, face, ####################################################################### payValue, recValue \ - = bermudan_swaption_tree_fast(t_exp, tmat, strike, face, + = bermudan_swaption_tree_fast(t_exp, t_mat, strike, face, cpn_times, cpn_flows, exercise_typeInt, self._df_times, self._dfs, @@ -1242,26 +1242,26 @@ def callable_puttable_bond_tree(self, ############################################################################### - def df_tree(self, tmat): - """ Discount factor as seen from now to time tmat as long as the time + def df_tree(self, t_mat): + """ Discount factor as seen from now to time t_mat as long as the time is on the tree grid. """ - if tmat == 0.0: + if t_mat == 0.0: return 1.0 _, num_nodes = self._Q.shape - fn1 = tmat/self._dt - fn2 = float(int(tmat/self._dt)) + fn1 = t_mat/self._dt + fn2 = float(int(t_mat/self._dt)) if abs(fn1 - fn2) > 1e-6: raise FinError("Time not on tree time grid") - timeStep = int(tmat / self._dt) + 1 + timeStep = int(t_mat / self._dt) + 1 p = 0.0 for i in range(0, num_nodes): ad = self._Q[timeStep, i] p += ad - zero_rate = -np.log(p)/tmat + zero_rate = -np.log(p)/t_mat return p, zero_rate ############################################################################### diff --git a/financepy/models/rates_ho_lee.py b/financepy/models/rates_ho_lee.py index c35d3319..e50e23d4 100644 --- a/financepy/models/rates_ho_lee.py +++ b/financepy/models/rates_ho_lee.py @@ -64,32 +64,32 @@ def zcb(self, rt1, t1, t2, discount_curve): ############################################################################### - def option_on_zcb(self, t_exp, tmat, + def option_on_zcb(self, t_exp, t_mat, strike_price, face_amount, df_times, df_values): """ Price an option on a zero coupon bond using analytical solution of Hull-White model. User provides bond face and option strike and expiry date and maturity date. """ - if t_exp > tmat: + if t_exp > t_mat: raise FinError("Option expiry after bond matures.") if t_exp < 0.0: raise FinError("Option expiry time negative.") pt_exp = _uinterpolate(t_exp, df_times, df_values, interp) - ptmat = _uinterpolate(tmat, df_times, df_values, interp) + pt_mat = _uinterpolate(t_mat, df_times, df_values, interp) sigma = self._sigma - sigmap = sigma * (tmat-t_exp) * np.sqrt(t_exp) + sigmap = sigma * (t_mat-t_exp) * np.sqrt(t_exp) - h = np.log((face_amount*ptmat)/(strike_price*pt_exp))/sigmap+sigmap/2.0 + h = np.log((face_amount*pt_mat)/(strike_price*pt_exp))/sigmap+sigmap/2.0 - call_value = face_amount * ptmat * \ + call_value = face_amount * pt_mat * \ N(h) - strike_price * pt_exp * N(h - sigmap) put_value = strike_price * pt_exp * \ - N(-h + sigmap) - face_amount * ptmat * N(-h) + N(-h + sigmap) - face_amount * pt_mat * N(-h) return {'call': call_value, 'put': put_value} diff --git a/financepy/products/bonds/bond.py b/financepy/products/bonds/bond.py index 1328d7f7..a203b5cc 100644 --- a/financepy/products/bonds/bond.py +++ b/financepy/products/bonds/bond.py @@ -40,7 +40,6 @@ from ...market.curves.interpolator import InterpTypes from .zero_curve import BondZeroCurve - # References https://www.dmo.gov.uk/media/15011/yldeqns_v1.pdf # DO TRUE YIELD # JAPANESE SIMPLE YIELD @@ -72,6 +71,7 @@ def _f(ytm, *args): obj_fn = px - price return obj_fn + ############################################################################### @@ -85,6 +85,7 @@ def _g(oas, *args): obj_fn = px - price return obj_fn + ############################################################################### @@ -141,6 +142,7 @@ def __init__(self, raise FinError("Ex dividend days cannot be more than 90" + str(ex_div_days)) + self._ex_div_dt = None self._ex_div_days = ex_div_days self._par = 100.0 # This is how price is quoted and amount at maturity @@ -173,17 +175,17 @@ def _calculate_cpn_dts(self): # dg_type = DateGenRuleTypes.BACKWARD self._cpn_dts = Schedule(self._issue_dt, - self._maturity_dt, - self._freq_type, - CalendarTypes.NONE, - self._bd_type, - self._dg_type, - end_of_month=self._end_of_month)._generate() + self._maturity_dt, + self._freq_type, + CalendarTypes.NONE, + self._bd_type, + self._dg_type, + end_of_month=self._end_of_month)._generate() ########################################################################### def _calculate_payment_dts(self): - """ For the actual payment dates, they are adjusted + """ For the actual payment dates, they are adjusted, and so we then use the calendar payment dates. Although payments are calculated as though coupon periods are the same length, payments that fall on a Saturday or Sunday can only be made on the next business day @@ -199,14 +201,14 @@ def _calculate_payment_dts(self): # Expect at least an issue date and a maturity date - if not - problem if len(self._cpn_dts) < 2: - raise FinError("Unable to calculate pmnt dates with only one pmnt") + raise FinError("Unable to calculate payment dates with only one payment") # I do not adjust the first date as it is the issue date self._payment_dts.append(self._cpn_dts[0]) for cpn_dt in self._cpn_dts[1:]: pmt_dt = calendar.adjust(cpn_dt, - bus_day_adj_type) + bus_day_adj_type) self._payment_dts.append(pmt_dt) @@ -235,7 +237,7 @@ def dirty_price_from_ytm(self, if convention not in YTMCalcType: raise FinError("Yield convention unknown." + str(convention)) - # TODO check that no unneccesary calculations are being done + # TODO check that no unnecessary calculations are being done self.accrued_interest(settle_dt, 1.0) ####################################################################### @@ -278,7 +280,7 @@ def dirty_price_from_ytm(self, term3 = (c / f) * v * v * (1.0 - v ** (n - 1)) / (1.0 - v) term4 = (v ** n) dp = (v ** (self._alpha)) * (term1 + term2 + term3 + term4) -# print(term1, term2, term3, term4, v, self._alpha, dp) + # print(term1, term2, term3, term4, v, self._alpha, dp) elif convention == YTMCalcType.US_TREASURY: if n == 0: dp = (v ** (self._alpha)) * (1.0 + c / f) @@ -424,7 +426,7 @@ def key_rate_durations(bond, # if it is None, create an array of key rates from 0.5 to 30 years if key_rate_tenors is None: - key_rate_tenors = np.array([0.5, 1, 2, 3, 5, 7, 10, 20, 30]) + key_rate_tenors = np.array([0.5, 1, 2, 3, 5, 7, 10, 20, 30]) # set the shift to a small value if not give if not shift: @@ -449,7 +451,6 @@ def key_rate_durations(bond, par_bonds = [] for tenor, cpn in zip(key_rate_tenors, rates): - mat_dt = settle_dt.add_years(tenor) par_bond = Bond(settle_dt, mat_dt, cpn, @@ -460,7 +461,6 @@ def key_rate_durations(bond, clean_prices = [] for par_bond, ytm in zip(par_bonds, rates): - clean_price = par_bond.clean_price_from_ytm(settle_dt, ytm, us_street) @@ -481,7 +481,6 @@ def key_rate_durations(bond, par_bonds = [] for tenor, cpn in zip(key_rate_tenors, rates): - mat = settle_dt.add_years(tenor) par_bond = Bond(settle_dt, mat, cpn, @@ -492,7 +491,6 @@ def key_rate_durations(bond, clean_prices = [] for par_bond, ytm in zip(par_bonds, rates): - clean_price = par_bond.clean_price_from_ytm(settle_dt, ytm, us_street) @@ -515,7 +513,6 @@ def key_rate_durations(bond, par_bonds = [] for tenor, cpn in zip(key_rate_tenors, rates): - mat = settle_dt.add_years(tenor) par_bond = Bond(settle_dt, mat, cpn, @@ -526,7 +523,6 @@ def key_rate_durations(bond, clean_prices = [] for par_bond, ytm in zip(par_bonds, rates): - clean_price = par_bond.clean_price_from_ytm(settle_dt, ytm, us_street) @@ -617,8 +613,7 @@ def dirty_price_from_discount_curve(self, cal = Calendar(self._cal_type) - self._ex_div_dt = cal.add_business_days(self._ncd, - -self._ex_div_days) + self._ex_div_dt = cal.add_business_days(self._ncd, -self._ex_div_days) pay_first_cpn = 1.0 if settle_dt > self._ex_div_dt: @@ -682,7 +677,6 @@ def yield_to_maturity(self, ytms = [] for dirty_price in dirty_prices: - argtuple = (self, settle_dt, dirty_price, convention) ytm = optimize.newton(_f, @@ -722,15 +716,15 @@ def _calc_pcd_ncd(self, def accrued_interest(self, settle_dt: Date, face: float = 100.0): - ''' Calculate the amount of coupon that has accrued between the + """ Calculate the amount of coupon that has accrued between the previous coupon date and the settlement date. Note that for some day count schemes (such as 30E/360) this is not actually the number of days between the previous coupon payment date and settlement date. If the bond trades with ex-coupon dates then you need to use the number of days before the coupon date the ex-coupon date is. You can specify the calendar to be used in the bond constructor - NONE means only calendar - days, WEEKEND is only weekends or you can specify a country calendar - for business days.''' + days, WEEKEND is only weekends, or you can specify a country calendar + for business days.""" self._calc_pcd_ncd(settle_dt) @@ -738,7 +732,7 @@ def accrued_interest(self, cal = Calendar(self._cal_type) self._ex_div_dt = cal.add_business_days(self._ncd, - -self._ex_div_days) + -self._ex_div_days) (acc_factor, num, _) = dc.year_frac(self._pcd, settle_dt, @@ -771,7 +765,7 @@ def asset_swap_spread( swapFloatBusDayAdjustRuleType=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 + is an Ibor curve that is passed in. This function is vectorised with respect to the clean price. """ clean_price = np.array(clean_price) @@ -779,7 +773,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:]: @@ -787,9 +781,9 @@ def asset_swap_spread( # coupons paid on a 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 + pv_ibor += df # Calculate the PV01 of the floating leg of the asset swap # I assume here that the coupon starts accruing on the settlement date @@ -811,7 +805,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 ########################################################################### @@ -826,6 +820,7 @@ def dirty_price_from_oas(self, self.accrued_interest(settle_dt, 1.0) f = self._freq c = self._cpn + df_adjusted = 1.0 pv = 0.0 for dt in self._cpn_dts[1:]: @@ -916,7 +911,7 @@ def bond_payments(self, settle_dt: Date, face: (float)): def print_payments(self, settle_dt: Date, - face: (float) = 100.0): + face: float = 100.0): """ Print a list of the unadjusted coupon payment dates used in analytic calculations for the bond. """ @@ -1023,7 +1018,7 @@ def calc_ror(self, dates_cfs.append((begin_dt, -buy_price)) dates_cfs.append((end_dt, sell_price)) - times_cfs = [((d - begin_dt)/365, c) for (d, c) in dates_cfs] + times_cfs = [((d - begin_dt) / 365, c) for (d, c) in dates_cfs] pnl = sum(c for (t, c) in times_cfs) simple_return = (pnl / buy_price) * 365 / (end_dt - begin_dt) brentq_up_bound = 5 @@ -1050,7 +1045,7 @@ def __repr__(self): s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("ISSUE DATE", self._issue_dt) s += label_to_string("MATURITY DATE", self._maturity_dt) - s += label_to_string("COUPON (%)", self._cpn*100.0) + s += label_to_string("COUPON (%)", self._cpn * 100.0) s += label_to_string("FREQUENCY", self._freq_type) s += label_to_string("DAY COUNT TYPE", self._dc_type) s += label_to_string("EX_DIV DAYS", self._ex_div_days, "") diff --git a/financepy/products/bonds/bond_callable.py b/financepy/products/bonds/bond_callable.py index 578a072f..ff6c21dd 100644 --- a/financepy/products/bonds/bond_callable.py +++ b/financepy/products/bonds/bond_callable.py @@ -57,7 +57,7 @@ def __init__(self, put_dts: List[Date], put_prices: List[float]): """ Create a BondEmbeddedOption object with a maturity date, coupon - and all of the bond inputs. """ + and all the bond inputs. """ check_argument_types(self.__init__, locals()) @@ -166,7 +166,7 @@ def value(self, put_prices = np.array(self._put_prices) maturity_dt = self._bond._maturity_dt - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear df_times = discount_curve._times df_values = discount_curve._dfs @@ -178,13 +178,13 @@ def value(self, more precise we only need to go out the the last option date but we can do that refinement at a later date. """ - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) v1 = model.callable_puttable_bond_tree(cpn_times, cpn_amounts, call_times, call_prices, put_times, put_prices, face_amount) model._num_time_steps += 1 - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) v2 = model.callable_puttable_bond_tree(cpn_times, cpn_amounts, call_times, call_prices, put_times, put_prices, @@ -201,13 +201,13 @@ def value(self, """ Because we not have a closed form bond price we need to build the tree out to the bond maturity which is after option expiry. """ - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) v1 = model.callable_puttable_bond_tree(cpn_times, cpn_amounts, call_times, call_prices, put_times, put_prices, face_amount) model._num_time_steps += 1 - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) v2 = model.callable_puttable_bond_tree(cpn_times, cpn_amounts, call_times, call_prices, put_times, put_prices, diff --git a/financepy/products/bonds/bond_convertible.py b/financepy/products/bonds/bond_convertible.py index 2cf6b698..eaa9709b 100644 --- a/financepy/products/bonds/bond_convertible.py +++ b/financepy/products/bonds/bond_convertible.py @@ -29,7 +29,7 @@ @njit(fastmath=True, cache=True) -def _value_convertible(tmat, +def _value_convertible(t_mat, face_amount, cpn_times, cpn_flows, @@ -54,23 +54,23 @@ def _value_convertible(tmat, interp = InterpTypes.FLAT_FWD_RATES.value if len(cpn_times) > 0: - if cpn_times[-1] > tmat: + if cpn_times[-1] > t_mat: raise FinError("Coupon after maturity") if len(call_times) > 0: - if call_times[-1] > tmat: + if call_times[-1] > t_mat: raise FinError("Call times after maturity") if len(put_times) > 0: - if put_times[-1] > tmat: + if put_times[-1] > t_mat: raise FinError("Put times after maturity") if len(df_times) > 0: - if df_times[-1] > tmat: + if df_times[-1] > t_mat: raise FinError("Discount times after maturity") if len(dividend_times) > 0: - if dividend_times[-1] > tmat: + if dividend_times[-1] > t_mat: raise FinError("Dividend times after maturity") if credit_spread < 0.0: @@ -86,13 +86,13 @@ def _value_convertible(tmat, raise FinError("Num Steps per year must more than 1.") if len(dividend_times) > 0.0: - if dividend_times[-1] > tmat: + if dividend_times[-1] > t_mat: raise FinError("Last dividend is after bond maturity.") if recovery_rate > 0.999 or recovery_rate < 0.0: raise FinError("Recovery rate must be between 0 and 0.999.") - num_times = int(num_steps_per_year * tmat) + 1 # add one for today time 0 + num_times = int(num_steps_per_year * t_mat) + 1 # add one for today time 0 num_times = num_steps_per_year # XXXXXXXX!!!!!!!!!!!!!!!!!!!!! if num_times < 5: @@ -101,9 +101,9 @@ def _value_convertible(tmat, numLevels = num_times # this is the size of the step - dt = tmat / (num_times - 1) + dt = t_mat / (num_times - 1) - tree_times = np.linspace(0.0, tmat, num_times) + tree_times = np.linspace(0.0, t_mat, num_times) treeDfs = np.zeros(num_times) for i in range(0, num_times): df = _uinterpolate(tree_times[i], df_times, df_values, interp) @@ -149,7 +149,7 @@ def _value_convertible(tmat, n = int(round(dividend_time / dt, 0)) treeDividendYield[n] = dividend_yields[i] - # Set up the tree of stock prices using a 2D matrix (half the matrix is + # 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, numLevels)) e = stock_volatility ** 2 - h @@ -254,7 +254,7 @@ def _value_convertible(tmat, class BondConvertible: """ Class for convertible bonds. These bonds embed rights to call and put - the bond in return for equity. Until then they are bullet bonds which + the bond in return for equity. Until then, they are bullet bonds which means they have regular coupon payments of a known size that are paid on known dates plus a payment of par at maturity. As the options are price based, the decision to convert to equity depends on the stock price, @@ -273,7 +273,7 @@ def __init__(self, dc_type: DayCountTypes, # day count type for accrued cal_type: CalendarTypes = CalendarTypes.WEEKEND): """ Create BondConvertible object by providing the bond Maturity - date, coupon, frequency type, accrual convention type and then all of + date, coupon, frequency type, accrual convention type and then all the details regarding the conversion option including the list of the call and put dates and the corresponding list of call and put prices. """ @@ -392,9 +392,9 @@ def value(self, self._calculate_cpn_dts(settle_dt) - tmat = (self._maturity_dt - settle_dt) / gDaysInYear + t_mat = (self._maturity_dt - settle_dt) / gDaysInYear - if tmat <= 0.0: + if t_mat <= 0.0: raise FinError("Maturity must not be on or before the value date.") # We include time zero in the coupon times and flows @@ -414,7 +414,7 @@ def value(self, if np.any(cpn_times < 0.0): raise FinError("No coupon times can be before the value date.") - if np.any(cpn_times > tmat): + if np.any(cpn_times > t_mat): raise FinError("No coupon times can be after the maturity date.") call_times = [] @@ -429,7 +429,7 @@ def value(self, if np.any(call_times < 0.0): raise FinError("No call times can be before the value date.") - if np.any(call_times > tmat): + if np.any(call_times > t_mat): raise FinError("No call times can be after the maturity date.") put_times = [] @@ -441,7 +441,7 @@ def value(self, put_times = np.array(put_times) put_prices = np.array(self._put_prices) - if np.any(put_times > tmat): + if np.any(put_times > t_mat): raise FinError("No put times can be after the maturity date.") if np.any(put_times <= 0.0): @@ -484,7 +484,7 @@ def value(self, if test_monotonicity(dividend_times) is False: raise FinError("Coupon times not monotonic") - v1 = _value_convertible(tmat, + v1 = _value_convertible(t_mat, self._par, cpn_times, cpn_flows, @@ -506,7 +506,7 @@ def value(self, # Tree details num_steps_per_year) - v2 = _value_convertible(tmat, + v2 = _value_convertible(t_mat, self._par, cpn_times, cpn_flows, diff --git a/financepy/products/bonds/bond_frn.py b/financepy/products/bonds/bond_frn.py index 87ab900c..79e342bd 100644 --- a/financepy/products/bonds/bond_frn.py +++ b/financepy/products/bonds/bond_frn.py @@ -105,7 +105,7 @@ def dirty_price_from_dm(self, """ Calculate the full price of the bond from its discount margin (DM) using standard model based on assumptions about future Ibor rates. The next Ibor payment which has reset is entered, so to is the current - Ibor rate from settlement to the next coupon date (NCD). Finally there + Ibor rate from settlement to the next coupon date (NCD). Finally, there is the level of subsequent future Ibor payments and the discount margin. """ @@ -259,7 +259,7 @@ def modified_duration(self, """ Calculate the modified duration of the bond on a settlement date using standard model based on assumptions about future Ibor rates. The next Ibor payment which has reset is entered, so to is the current - Ibor rate from settlement to the next coupon date (NCD). Finally there + Ibor rate from settlement to the next coupon date (NCD). Finally, there is the level of subsequent future Ibor payments and the discount margin. """ @@ -288,7 +288,7 @@ def modified_credit_duration(self, """ Calculate the modified duration of the bond on a settlement date using standard model based on assumptions about future Ibor rates. The next Ibor payment which has reset is entered, so to is the current - Ibor rate from settlement to the next coupon date (NCD). Finally there + Ibor rate from settlement to the next coupon date (NCD). Finally, there is the level of subsequent future Ibor payments and the discount margin. """ @@ -317,7 +317,7 @@ def convexity_from_dm(self, """ Calculate the bond convexity from the discount margin (DM) using a standard model based on assumptions about future Ibor rates. The next Ibor payment which has reset is entered, so to is the current - Ibor rate from settlement to the next coupon date (NCD). Finally there + Ibor rate from settlement to the next coupon date (NCD). Finally, there is the level of subsequent future Ibor payments and the discount margin. """ @@ -355,7 +355,7 @@ def clean_price_from_dm(self, """ Calculate the bond clean price from the discount margin using standard model based on assumptions about future Ibor rates. The next Ibor payment which has reset is entered, so to is the current - Ibor rate from settlement to the next coupon date (NCD). Finally there + Ibor rate from settlement to the next coupon date (NCD). Finally, there is the level of subsequent future Ibor payments and the discount margin. """ diff --git a/financepy/products/bonds/bond_future.py b/financepy/products/bonds/bond_future.py index 72192a2a..3312fbfd 100644 --- a/financepy/products/bonds/bond_future.py +++ b/financepy/products/bonds/bond_future.py @@ -46,9 +46,9 @@ def conversion_factor(self, # https://www.cmegroup.com//trading//interest-rates//us-treasury-futures-conversion-factor-lookup-tables.html # for a reference. - tmat = (bond._maturity_dt - self._first_delivery_dt) / gDaysInYear - roundedTmatInMonths = int(tmat * 4.0) * 3 - new_mat = self._first_delivery_dt.add_months(roundedTmatInMonths) + t_mat = (bond._maturity_dt - self._first_delivery_dt) / gDaysInYear + roundedt_matInMonths = int(t_mat * 4.0) * 3 + new_mat = self._first_delivery_dt.add_months(roundedt_matInMonths) ex_div_days = 0 issue_dt = Date(new_mat._d, new_mat._m, 2000) @@ -103,7 +103,7 @@ def cheapest_to_deliver(self, bonds: list, bond_clean_prices: list, futures_price: float): - """ Determination of CTD as deliverable bond with lowest cost to buy + """ 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 diff --git a/financepy/products/bonds/bond_option.py b/financepy/products/bonds/bond_option.py index 9005200e..cfd8ecd4 100644 --- a/financepy/products/bonds/bond_option.py +++ b/financepy/products/bonds/bond_option.py @@ -61,12 +61,12 @@ def value(self, model which are all implemented as short rate tree models. """ t_exp = (self._expiry_dt - value_dt) / gDaysInYear - tmat = (self._bond._maturity_dt - value_dt) / gDaysInYear + t_mat = (self._bond._maturity_dt - value_dt) / gDaysInYear df_times = discount_curve._times df_values = discount_curve._dfs - # We need all of the flows in case the option is American + # We need all the flows in case the option is American # and some occur before expiry flow_dts = self._bond._cpn_dts flow_amounts = self._bond._flow_amounts @@ -112,7 +112,7 @@ def value(self, exercise_type = FinExerciseTypes.EUROPEAN # This is wasteful if model is Jamshidian but how to do neat design - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) v = model.bond_option(t_exp, self._strike_price, self._par, cpn_times, cpn_flows, exercise_type) diff --git a/financepy/products/bonds/zero_curve.py b/financepy/products/bonds/zero_curve.py index 2ba51aad..8bde80fc 100644 --- a/financepy/products/bonds/zero_curve.py +++ b/financepy/products/bonds/zero_curve.py @@ -60,8 +60,8 @@ def __init__(self, times = [] for bond in self._bonds: - tmat = (bond._maturity_dt - self._settle_dt)/gDaysInYear - times.append(tmat) + t_mat = (bond._maturity_dt - self._settle_dt)/gDaysInYear + times.append(t_mat) times = np.array(times) if test_monotonicity(times) is False: @@ -83,9 +83,9 @@ def _bootstrap_zero_rates(self): bond = self._bonds[i] maturity_dt = bond._maturity_dt clean_price = self._clean_prices[i] - tmat = (maturity_dt - self._settle_dt) / gDaysInYear + t_mat = (maturity_dt - self._settle_dt) / gDaysInYear argtuple = (self, self._settle_dt, bond, clean_price) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._values = np.append(self._values, df) optimize.newton(_f, x0=df, fprime=None, args=argtuple, diff --git a/financepy/products/credit/cds.py b/financepy/products/credit/cds.py index 30437a43..a3dcbe04 100644 --- a/financepy/products/credit/cds.py +++ b/financepy/products/credit/cds.py @@ -134,7 +134,7 @@ 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, - tmat, + t_mat, npIborTimes, npIborValues, npSurvTimes, @@ -147,8 +147,8 @@ def _protection_leg_pv_numba(teff, method = InterpTypes.FLAT_FWD_RATES.value dt = 1.0 / num_steps_per_year - num_steps = int((tmat-teff) * num_steps_per_year + 0.50) - dt = (tmat - teff) / num_steps + num_steps = int((t_mat-teff) * num_steps_per_year + 0.50) + dt = (t_mat - teff) / num_steps t = teff z1 = _uinterpolate(t, npIborTimes, npIborValues, method) @@ -542,7 +542,7 @@ def clean_price(self, ########################################################################### def accrued_days(self): - """ Number of days between the previous cpn and the currrent step + """ Number of days between the previous coupon and the currrent step in date. """ # I assume accrued runs to the effective date @@ -579,12 +579,12 @@ def protection_leg_pv(self, fast NUMBA code that has been defined above. """ teff = (self._step_in_dt - value_dt) / gDaysInYear - tmat = (self._maturity_dt - value_dt) / gDaysInYear + t_mat = (self._maturity_dt - value_dt) / gDaysInYear libor_curve = issuer_curve._libor_curve v = _protection_leg_pv_numba(teff, - tmat, + t_mat, libor_curve._times, libor_curve._dfs, issuer_curve._times, @@ -784,7 +784,7 @@ def print_payments(self, value_dt, issuer_curve): ########################################################################### def __repr__(self): - """ print out details of the CDS contract and all of the calculated + """ print out details of the CDS contract and all the calculated cash flows """ s = label_to_string("OBJECT TYPE", type(self).__name__) s += label_to_string("STEP-IN DATE", self._step_in_dt) diff --git a/financepy/products/credit/cds_basket.py b/financepy/products/credit/cds_basket.py index 4513e8b9..5ea654fa 100644 --- a/financepy/products/credit/cds_basket.py +++ b/financepy/products/credit/cds_basket.py @@ -93,7 +93,7 @@ def value_legs_mc(self, num_payments = len(payment_dts) day_count = DayCount(self._dc_type) - averageAccrualFactor = 0.0 + avg_acc_factor = 0.0 rpv01ToTimes = np.zeros(num_payments) @@ -103,13 +103,13 @@ def value_legs_mc(self, dt0 = payment_dts[i_time - 1] dt1 = payment_dts[i_time] accrual_factor = day_count.year_frac(dt0, dt1)[0] - averageAccrualFactor += accrual_factor + avg_acc_factor += accrual_factor rpv01ToTimes[i_time] = rpv01ToTimes[i_time - 1] + \ accrual_factor * libor_curve._df(t) - averageAccrualFactor /= num_payments + avg_acc_factor /= num_payments - tmat = (self._maturity_dt - value_dt) / gDaysInYear + t_mat = (self._maturity_dt - value_dt) / gDaysInYear rpv01 = 0.0 prot = 0.0 @@ -128,12 +128,11 @@ def value_legs_mc(self, # GET THE Nth DEFAULT TIME minTau = assetTau[n_to_default - 1] - if minTau < tmat: + if minTau < t_mat: - numPaymentsIndex = int(minTau / averageAccrualFactor) - rpv01_trial = rpv01ToTimes[numPaymentsIndex] - rpv01_trial += (minTau - numPaymentsIndex * - averageAccrualFactor) + num_pmnts_index = int(minTau / avg_acc_factor) + rpv01_trial = rpv01ToTimes[num_pmnts_index] + rpv01_trial += (minTau - num_pmnts_index * avg_acc_factor) # DETERMINE IDENTITY OF N-TO-DEFAULT CREDIT IF BASKET NOT HOMO assetIndex = 0 @@ -147,7 +146,7 @@ def value_legs_mc(self, else: - numPaymentsIndex = int(tmat / averageAccrualFactor) + num_pmnts_index = int(t_mat / avg_acc_factor) rpv01_trial = rpv01ToTimes[-1] prot_trial = 0.0 @@ -255,9 +254,9 @@ def value_1f_gaussian_homo(self, if n_to_default < 1 or n_to_default > num_credits: raise FinError("n_to_default must be 1 to num_credits") - tmat = (self._maturity_dt - value_dt) / gDaysInYear + t_mat = (self._maturity_dt - value_dt) / gDaysInYear - if tmat < 0.0: + if t_mat < 0.0: raise FinError("Value date is after maturity date") payment_dts = self._cds_contract._payment_dts @@ -299,13 +298,13 @@ def value_1f_gaussian_homo(self, basket_curve._times = basket_times basket_curve._values = basket_surv_curve - protLegPV = self._cds_contract.protection_leg_pv( + prot_leg_pv = self._cds_contract.protection_leg_pv( value_dt, basket_curve, curve_recovery) risky_pv01 = self._cds_contract.risky_pv01( value_dt, basket_curve)['clean_rpv01'] # Long protection - mtm = self._notional * (protLegPV - risky_pv01 * self._running_cpn) + mtm = self._notional * (prot_leg_pv - risky_pv01 * self._running_cpn) if not self._long_protection: mtm *= -1.0 @@ -313,8 +312,8 @@ def value_1f_gaussian_homo(self, basketOutput = np.zeros(4) basketOutput[0] = mtm basketOutput[1] = risky_pv01 * self._notional * self._running_cpn - basketOutput[2] = protLegPV * self._notional - basketOutput[3] = protLegPV / risky_pv01 + basketOutput[2] = prot_leg_pv * self._notional + basketOutput[3] = prot_leg_pv / risky_pv01 return basketOutput diff --git a/financepy/products/credit/cds_curve.py b/financepy/products/credit/cds_curve.py index 1719b94d..7032e3a4 100644 --- a/financepy/products/credit/cds_curve.py +++ b/financepy/products/credit/cds_curve.py @@ -164,10 +164,10 @@ def _build_curve(self): self._cds_contracts[i], self._recovery_rate) - tmat = (maturity_dt - self._value_dt) / gDaysInYear + t_mat = (maturity_dt - self._value_dt) / gDaysInYear q = self._values[i] - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._values = np.append(self._values, q) optimize.newton(f, x0=q, fprime=None, args=argtuple, diff --git a/financepy/products/credit/cds_index_portfolio.py b/financepy/products/credit/cds_index_portfolio.py index 580fee0d..8eee673f 100644 --- a/financepy/products/credit/cds_index_portfolio.py +++ b/financepy/products/credit/cds_index_portfolio.py @@ -62,7 +62,6 @@ def intrinsic_rpv01(self, intrinsic_rpv01 = 0.0 for m in range(0, num_credits): - retValue = cds_contract.risky_pv01(value_dt, issuer_curves[m]) @@ -258,7 +257,7 @@ def spread_adjust_intrinsic(self, + str(num_credits)) libor_curve = issuer_curves[0]._libor_curve - numIndexMaturityPoints = len(index_cpns) + num_index_maturity_points = len(index_cpns) cds_maturity_dts = [] for cds in issuer_curves[0]._cds_contracts: @@ -273,46 +272,45 @@ def spread_adjust_intrinsic(self, raise FinError( "All issuer discount must be from same cds maturities") - cdsSpreadMultipliers = [1.0] * num_cds_mat_points + cds_spread_multipliers = [1.0] * num_cds_mat_points # spreadDifference = [0.0] * num_cds_mat_points - adjustedCDSSpreads = [0.0] * num_cds_mat_points + adjusted_cds_spreads = [0.0] * num_cds_mat_points ####################################################################### # Set up CDS contracts used to build curve ####################################################################### - curveCDSContracts = [] + curve_cds_contracts = [] for j in range(0, num_cds_mat_points): - cds_coupon = 1.0 cds_contract = CDS(value_dt, cds_maturity_dts[j], cds_coupon) - curveCDSContracts.append(cds_contract) + curve_cds_contracts.append(cds_contract) ####################################################################### # We calibrate the individual CDS discount to fit each index maturity ####################################################################### - for i_maturity in range(0, numIndexMaturityPoints): + for i_maturity in range(0, num_index_maturity_points): alpha = 0.0 - numIterations = 0 + num_iterations = 0 while abs(alpha - 1.0) > tolerance: - numIterations += 1 + num_iterations += 1 - if numIterations > 20: + if num_iterations > 20: raise FinError("Num iterations > 20.") - sumRPV01 = 0.0 - sumProt = 0.0 + sum_rpv01 = 0.0 + sum_prot = 0.0 # This is for the specific index maturity date index_maturity_dt = index_maturity_dts[i_maturity] @@ -322,40 +320,38 @@ def spread_adjust_intrinsic(self, cds_contracts = issuer_curves[i_credit]._cds_contracts recovery_rate = issuer_curves[i_credit]._recovery_rate - adjustedCDSContracts = [] + adjusted_cds_contracts = [] for j in range(0, num_cds_mat_points): - - cdsSpread = cds_contracts[j]._running_cpn - adjustedCDSSpreads[j] = cdsSpread * \ - cdsSpreadMultipliers[j] - curveCDSContracts[j]._running_cpn = adjustedCDSSpreads[j] + cds_spread = cds_contracts[j]._running_cpn + adjusted_cds_spreads[j] = cds_spread * cds_spread_multipliers[j] + curve_cds_contracts[j]._running_cpn = adjusted_cds_spreads[j] adjusted_issuer_curve = CDSCurve(value_dt, - curveCDSContracts, - libor_curve, - recovery_rate) + curve_cds_contracts, + libor_curve, + recovery_rate) - indexProtectionPV = cds_index.protection_leg_pv(value_dt, - adjusted_issuer_curve, - index_recovery_rate) + index_protection_pv = cds_index.protection_leg_pv(value_dt, + adjusted_issuer_curve, + index_recovery_rate) - cleanRPV01 = cds_index.risky_pv01(value_dt, - adjusted_issuer_curve)['clean_rpv01'] + clean_rpv01 = cds_index.risky_pv01(value_dt, + adjusted_issuer_curve)['clean_rpv01'] - sumRPV01 += cleanRPV01 - sumProt += indexProtectionPV + sum_rpv01 += clean_rpv01 + sum_prot += index_protection_pv - sumRPV01 /= num_credits - sumProt /= num_credits + sum_rpv01 /= num_credits + sum_prot /= num_credits - sumPrem = sumRPV01 * index_cpns[i_maturity] + sum_prem = sum_rpv01 * index_cpns[i_maturity] - numerator = index_upfronts[i_maturity] + sumPrem - denominator = sumProt + numerator = index_upfronts[i_maturity] + sum_prem + denominator = sum_prot alpha = numerator / denominator - cdsSpreadMultipliers[i_maturity] *= alpha + cds_spread_multipliers[i_maturity] *= alpha # use spread multipliers to build and store adjusted discount adjusted_issuer_curves = [] @@ -364,25 +360,26 @@ def spread_adjust_intrinsic(self, recovery_rate = issuer_curves[i_credit]._recovery_rate - adjustedCDSContracts = [] - adjustedSpreads = [] + adjusted_cds_contracts = [] + adjusted_spreads = [] for j in range(0, num_cds_mat_points): - unadjustedSpread = issuer_curves[i_credit]._cds_contracts[j]._running_cpn - adjustedSpread = unadjustedSpread * cdsSpreadMultipliers[j] + unadjusted_spread = issuer_curves[i_credit]._cds_contracts[j]._running_cpn + + adjusted_spread = unadjusted_spread * cds_spread_multipliers[j] - adjustedcds_contract = CDS(value_dt, - cds_maturity_dts[j], - adjustedSpread) + adjusted_cds_contract = CDS(value_dt, + cds_maturity_dts[j], + adjusted_spread) - adjustedCDSContracts.append(adjustedcds_contract) - adjustedSpreads.append(adjustedSpread) + adjusted_cds_contracts.append(adjusted_cds_contract) + adjusted_spreads.append(adjusted_spread) adjusted_issuer_curve = CDSCurve(value_dt, - adjustedCDSContracts, - libor_curve, - recovery_rate) + adjusted_cds_contracts, + libor_curve, + recovery_rate) adjusted_issuer_curves.append(adjusted_issuer_curve) @@ -425,7 +422,6 @@ def hazard_rate_adjust_intrinsic(self, # making a copy of the issuer discount for issuer_curve in issuer_curves: - adjusted_issuer_curve = CDSCurve(value_dt, [], libor_curve, @@ -440,20 +436,19 @@ def hazard_rate_adjust_intrinsic(self, alpha = 1.0 ratio = 1.0 + 2.0 * tolerance - numIterations = 0 + num_iterations = 0 while abs(ratio - 1.0) > tolerance: - numIterations += 1 + num_iterations += 1 - if numIterations > max_iterations: + if num_iterations > max_iterations: raise FinError("Max Iterations exceeded") - sumRPV01 = 0.0 + sum_rpv01 = 0.0 sumProt = 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 @@ -463,36 +458,36 @@ def hazard_rate_adjust_intrinsic(self, adjusted_issuer_curves[i_credit]._values[i_maturity + 1] = q2NEW -# if i_maturity == 0 and index_cpns[0] == 0.006: -# print(i_credit, q1, q2NEW) + # if i_maturity == 0 and index_cpns[0] == 0.006: + # print(i_credit, q1, q2NEW) index_maturity_dt = index_maturity_dts[i_maturity] # the CDS spreads we extract here # should be to the index maturity dates cds_index = CDS(value_dt, - index_maturity_dt, - 0, - 1.0) + index_maturity_dt, + 0, + 1.0) indexProtPV = cds_index.protection_leg_pv(value_dt, - adjusted_issuer_curves[i_credit], - index_recovery_rate) + adjusted_issuer_curves[i_credit], + index_recovery_rate) rpv01Ret = cds_index.risky_pv01(value_dt, - adjusted_issuer_curves[i_credit]) + adjusted_issuer_curves[i_credit]) cleanRPV01 = rpv01Ret['clean_rpv01'] - sumRPV01 += cleanRPV01 + sum_rpv01 += cleanRPV01 sumProt += indexProtPV - sumRPV01 /= num_credits + sum_rpv01 /= num_credits sumProt /= num_credits - spd = sumProt / sumRPV01 + spd = sumProt / sum_rpv01 - sumPrem = sumRPV01 * index_cpns[i_maturity] + sumPrem = sum_rpv01 * index_cpns[i_maturity] numerator = index_up_fronts[i_maturity] + sumPrem denominator = sumProt @@ -500,8 +495,8 @@ def hazard_rate_adjust_intrinsic(self, ratio = numerator / denominator alpha *= ratio -# print("Maturity:", i_maturity, "Num:", numerator, "Den:", denominator, "Ratio:", ratio, "Alpha:", alpha) -# print("") + # print("Maturity:", i_maturity, "Num:", numerator, "Den:", denominator, "Ratio:", ratio, "Alpha:", alpha) + # print("") return adjusted_issuer_curves diff --git a/financepy/products/credit/cds_option.py b/financepy/products/credit/cds_option.py index 2e215a94..3acbccc9 100644 --- a/financepy/products/credit/cds_option.py +++ b/financepy/products/credit/cds_option.py @@ -133,7 +133,7 @@ def value(self, option_value = option_value * forward_rpv01 - # If the option does not knockout on a default before expiry then we + # If the option does not knock out on a default before expiry then we # need to include the cost of protection which is provided between # the value date and the expiry date if self._knockout_flag is False and self._long_protection is True: diff --git a/financepy/products/credit/cds_tranche.py b/financepy/products/credit/cds_tranche.py index e46fc9d2..4dffe549 100644 --- a/financepy/products/credit/cds_tranche.py +++ b/financepy/products/credit/cds_tranche.py @@ -106,9 +106,9 @@ def value_bc(self, num_credits = len(issuer_curves) k1 = self._k1 k2 = self._k2 - tmat = (self._maturity_dt - value_dt) / gDaysInYear + t_mat = (self._maturity_dt - value_dt) / gDaysInYear - if tmat < 0.0: + if t_mat < 0.0: raise FinError("Value date is after maturity date") if abs(k1 - k2) < 0.00000001: diff --git a/financepy/products/equity/equity_asian_option.py b/financepy/products/equity/equity_asian_option.py index 46868fb4..5a00f4c2 100644 --- a/financepy/products/equity/equity_asian_option.py +++ b/financepy/products/equity/equity_asian_option.py @@ -352,25 +352,25 @@ class EquityAsianOption: Monte-Carlo simulation.""" def __init__(self, - startAveragingDate: Date, + start_averaging_dt: Date, expiry_dt: Date, strike_price: float, option_type: OptionTypes, - numberOfObservations: int = 100): + num_obs: int = 100): """ Create an EquityAsian option object which takes a start date for the averaging, an expiry date, a strike price, an option type and a number of observations. """ check_argument_types(self.__init__, locals()) - if startAveragingDate > expiry_dt: + if start_averaging_dt > expiry_dt: raise FinError("Averaging starts after expiry date") - self._startAveragingDate = startAveragingDate + self._startAveragingDate = start_averaging_dt self._expiry_dt = expiry_dt self._strike_price = float(strike_price) self._option_type = option_type - self._num_observations = numberOfObservations + self._num_observations = num_obs ############################################################################### diff --git a/financepy/products/equity/equity_variance_swap.py b/financepy/products/equity/equity_variance_swap.py index 814cea5f..7a5f3b55 100644 --- a/financepy/products/equity/equity_variance_swap.py +++ b/financepy/products/equity/equity_variance_swap.py @@ -91,7 +91,7 @@ def fair_strike_approx(self, # TODO Linear interpolation - to be revisited atm_vol = np.interp(f, strikes, volatilities) - tmat = (self._maturity_dt - value_dt)/gDaysInYear + t_mat = (self._maturity_dt - value_dt)/gDaysInYear """ Calculate the slope of the volatility curve by taking the end points in the volatilities and strikes to calculate the gradient.""" @@ -99,7 +99,7 @@ def fair_strike_approx(self, dvol = volatilities[-1] - volatilities[0] dK = strikes[-1] - strikes[0] b = f * dvol / dK - var = (atm_vol**2) * np.sqrt(1.0 + 3.0*tmat*(b**2)) + var = (atm_vol**2) * np.sqrt(1.0 + 3.0*t_mat*(b**2)) return var ############################################################################### @@ -125,16 +125,16 @@ def fair_strike(self, call_type = OptionTypes.EUROPEAN_CALL put_type = OptionTypes.EUROPEAN_PUT - tmat = (self._maturity_dt - value_dt)/gDaysInYear + t_mat = (self._maturity_dt - value_dt)/gDaysInYear - df = discount_curve._df(tmat) - r = - np.log(df)/tmat + df = discount_curve._df(t_mat) + r = - np.log(df)/t_mat - dq = dividend_curve._df(tmat) - q = - np.log(dq)/tmat + dq = dividend_curve._df(t_mat) + q = - np.log(dq)/t_mat s0 = stock_price - g = np.exp((r-q)*tmat) + g = np.exp((r-q)*t_mat) fwd = stock_price * g # This fixes the centre strike of the replication options @@ -173,12 +173,12 @@ def fair_strike(self, self._call_strikes = callK - optionTotal = 2.0*(r*tmat - (s0*g/sstar-1.0) - np.log(sstar/s0))/tmat + optionTotal = 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) - def f(x): return (2.0/tmat)*((x-sstar)/sstar-np.log(x/sstar)) + def f(x): return (2.0/t_mat)*((x-sstar)/sstar-np.log(x/sstar)) sumWts = 0.0 for n in range(0, self._num_put_options): diff --git a/financepy/products/fx/fx_variance_swap.py b/financepy/products/fx/fx_variance_swap.py index 78ec49b9..b762ab15 100644 --- a/financepy/products/fx/fx_variance_swap.py +++ b/financepy/products/fx/fx_variance_swap.py @@ -100,7 +100,7 @@ def fair_strike_approx(self, # TODO Linear interpolation - to be revisited atm_vol = np.interp(f, strikes, volatilities) - tmat = (self._maturity_dt - value_dt)/gDaysInYear + t_mat = (self._maturity_dt - value_dt)/gDaysInYear """ Calculate the slope of the volatility curve by taking the end points in the volatilities and strikes to calculate the gradient.""" @@ -108,7 +108,7 @@ def fair_strike_approx(self, dvol = volatilities[-1] - volatilities[0] dK = strikes[-1] - strikes[0] b = f * dvol / dK - var = (atm_vol**2) * np.sqrt(1.0+3.0*tmat*(b**2)) + var = (atm_vol**2) * np.sqrt(1.0+3.0*t_mat*(b**2)) return var ############################################################################### @@ -134,16 +134,16 @@ def fair_strike(self, call_type = OptionTypes.EUROPEAN_CALL put_type = OptionTypes.EUROPEAN_PUT - tmat = (self._maturity_dt - value_dt)/gDaysInYear + t_mat = (self._maturity_dt - value_dt)/gDaysInYear - df = discount_curve.df(tmat) - r = - np.log(df)/tmat + df = discount_curve.df(t_mat) + r = - np.log(df)/t_mat - dq = dividend_curve.df(tmat) - q = - np.log(dq)/tmat + dq = dividend_curve.df(t_mat) + q = - np.log(dq)/t_mat s0 = stock_price - g = np.exp((r-q)*tmat) + g = np.exp((r-q)*t_mat) fwd = stock_price * g # This fixes the centre strike of the replication options @@ -182,12 +182,12 @@ def fair_strike(self, self._call_strikes = callK - optionTotal = 2.0*(r*tmat - (s0*g/sstar-1.0) - np.log(sstar/s0))/tmat + optionTotal = 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) - def f(x): return (2.0/tmat)*((x-sstar)/sstar-np.log(x/sstar)) + def f(x): return (2.0/t_mat)*((x-sstar)/sstar-np.log(x/sstar)) sumWts = 0.0 for n in range(0, self._num_put_options): diff --git a/financepy/products/inflation/FinInflationSwapCurve.py b/financepy/products/inflation/FinInflationSwapCurve.py index cb2e11b1..961c2ead 100644 --- a/financepy/products/inflation/FinInflationSwapCurve.py +++ b/financepy/products/inflation/FinInflationSwapCurve.py @@ -205,12 +205,12 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDepositMaturityDate = Date(1, 1, 1900) + lastDeposit_maturityDate = Date(1, 1, 1900) firstFRAMaturityDate = Date(1, 1, 1900) lastFRAMaturityDate = Date(1, 1, 1900) if num_depos > 0: - lastDepositMaturityDate = ibor_deposits[-1]._maturity_dt + lastDeposit_maturityDate = ibor_deposits[-1]._maturity_dt if num_fras > 0: firstFRAMaturityDate = ibor_fras[0]._maturity_dt @@ -220,9 +220,9 @@ def _validate_inputs(self, first_swap_maturity_dt = ibor_swaps[0]._maturity_dt if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDepositMaturityDate: + if firstFRAMaturityDate <= lastDeposit_maturityDate: print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDepositMaturityDate) + print("Last Deposit Date:", lastDeposit_maturityDate) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: @@ -247,7 +247,7 @@ def _build_curve_using_solver(self): self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -255,26 +255,26 @@ def _build_curve_using_solver(self): for depo in self._usedDeposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) - oldtmat = tmat + oldt_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < oldt_mat and t_mat > oldt_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, fra) @@ -286,9 +286,9 @@ def _build_curve_using_solver(self): # 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 - tmat = (maturity_dt - self._value_dt) / gDaysInYear + t_mat = (maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, swap) @@ -311,7 +311,7 @@ def _build_curve_linear_swap_rate_interpolation(self): self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -319,26 +319,26 @@ def _build_curve_linear_swap_rate_interpolation(self): for depo in self._usedDeposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) - oldtmat = tmat + oldt_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < oldt_mat and t_mat > oldt_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, fra) @@ -431,7 +431,7 @@ def _build_curve_linear_swap_rate_interpolation(self): for i in range(start_index, num_flows): dt = couponDates[i] - tmat = (dt - self._value_dt) / gDaysInYear + t_mat = (dt - self._value_dt) / gDaysInYear swap_rate = interpolatedSwapRates[i] acc = accrual_factors[i-1] pv01End = (acc * swap_rate + 1.0) @@ -441,7 +441,7 @@ def _build_curve_linear_swap_rate_interpolation(self): # print("IN: %12s %12.10f %12.10f %12.10f %12.10f OUT: %14.12f" % # (dt, swap_rate, acc, pv01, pv01End, df_mat)) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) pv01 += acc * df_mat diff --git a/financepy/products/rates/bermudan_swaption.py b/financepy/products/rates/bermudan_swaption.py index 0b3c0a5a..06651643 100644 --- a/financepy/products/rates/bermudan_swaption.py +++ b/financepy/products/rates/bermudan_swaption.py @@ -49,7 +49,7 @@ def __init__(self, bd_type=BusDayAdjustTypes.FOLLOWING, dg_type=DateGenRuleTypes.BACKWARD): """ Create a Bermudan swaption contract. This is an option to enter - into a payer or receiver swap at a fixed coupon on all of the fixed + into a payer or receiver swap at a fixed coupon on all the fixed # leg coupon dates until the exercise date inclusive. """ check_argument_types(self.__init__, locals()) @@ -118,7 +118,7 @@ def value(self, self._pv01 = self._underlying_swap.pv01(value_dt, discount_curve) t_exp = (self._exercise_dt - value_dt) / gDaysInYear - tmat = (self._maturity_dt - value_dt) / gDaysInYear + t_mat = (self._maturity_dt - value_dt) / gDaysInYear ####################################################################### # For the tree models we need to generate a vector of the coupons @@ -164,10 +164,10 @@ def value(self, if isinstance(model, BDTTree) or isinstance(model, BKTree) or isinstance(model, HWTree): - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) v = model.bermudan_swaption(t_exp, - tmat, + t_mat, strike_price, face_amount, cpn_times, diff --git a/financepy/products/rates/callable_swap.py b/financepy/products/rates/callable_swap.py index b9876fda..37566fc5 100644 --- a/financepy/products/rates/callable_swap.py +++ b/financepy/products/rates/callable_swap.py @@ -196,7 +196,7 @@ # put_prices = np.array(self._put_prices) # maturity_dt = self._bond._maturity_dt -# tmat = (maturity_dt - settle_dt) / gDaysInYear +# t_mat = (maturity_dt - settle_dt) / gDaysInYear # df_times = discount_curve._times # df_values = discount_curve._values @@ -208,12 +208,12 @@ # more precise we only need to go out the the last option date but # we can do that refinement at a later date. """ -# model.buildTree(tmat, df_times, df_values) +# model.buildTree(t_mat, df_times, df_values) # v1 = model.callableputtable_bond_Tree(cpn_times, cpn_amounts, # call_times, call_prices, # put_times, put_prices, face) # model._num_time_steps += 1 -# model.buildTree(tmat, df_times, df_values) +# model.buildTree(t_mat, df_times, df_values) # v2 = model.callableputtable_bond_Tree(cpn_times, cpn_amounts, # call_times, call_prices, # put_times, put_prices, face) @@ -229,13 +229,13 @@ # """ Because we not have a closed form bond price we need to build # the tree out to the bond maturity which is after option expiry. """ -# model.buildTree(tmat, df_times, df_values) +# model.buildTree(t_mat, df_times, df_values) # v1 = model.callableputtable_bond_Tree(cpn_times, cpn_amounts, # call_times, call_prices, # put_times, put_prices, # face) # model._num_time_steps += 1 -# model.buildTree(tmat, df_times, df_values) +# model.buildTree(t_mat, df_times, df_values) # v2 = model.callableputtable_bond_Tree(cpn_times, cpn_amounts, # call_times, call_prices, # put_times, put_prices, diff --git a/financepy/products/rates/dual_curve.py b/financepy/products/rates/dual_curve.py index f0456b62..9cf52dd3 100644 --- a/financepy/products/rates/dual_curve.py +++ b/financepy/products/rates/dual_curve.py @@ -229,12 +229,12 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDepositMaturityDate = Date(1, 1, 1900) + lastDeposit_maturityDate = Date(1, 1, 1900) firstFRAMaturityDate = Date(1, 1, 1900) lastFRAMaturityDate = Date(1, 1, 1900) if num_depos > 0: - lastDepositMaturityDate = ibor_deposits[-1]._maturity_dt + lastDeposit_maturityDate = ibor_deposits[-1]._maturity_dt if num_fras > 0: firstFRAMaturityDate = ibor_fras[0]._maturity_dt @@ -244,9 +244,9 @@ def _validate_inputs(self, first_swap_maturity_dt = ibor_swaps[0]._maturity_dt if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDepositMaturityDate: + if firstFRAMaturityDate <= lastDeposit_maturityDate: print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDepositMaturityDate) + print("Last Deposit Date:", lastDeposit_maturityDate) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: @@ -296,7 +296,7 @@ def _build_curve_using_1d_solver(self): self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -308,27 +308,27 @@ def _build_curve_using_1d_solver(self): df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) self._interpolator.fit(self._times, self._dfs) - oldtmat = tmat + oldt_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < oldt_mat and t_mat > oldt_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self._discount_curve, self, self._value_dt, fra) @@ -340,9 +340,9 @@ def _build_curve_using_1d_solver(self): # 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] - tmat = (maturity_dt - self._value_dt) / gDaysInYear + t_mat = (maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self._discount_curve, self, self._value_dt, swap) @@ -367,7 +367,7 @@ def _build_curve_using_1d_solver(self): # self._dfs = np.array([]) # # time zero is now. - # tmat = 0.0 + # t_mat = 0.0 # df_mat = 1.0 # self._times = np.append(self._times, 0.0) # self._dfs = np.append(self._dfs, df_mat) @@ -376,28 +376,28 @@ def _build_curve_using_1d_solver(self): # for depo in self._usedDeposits: # df_settle = self.df(depo._effective_dt) # df_mat = depo._maturity_df() * df_settle - # tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - # self._times = np.append(self._times, tmat) + # 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) # self._interpolator.fit(self._times, self._dfs) - # oldtmat = tmat + # oldt_mat = t_mat # for fra in self._usedFRAs: - # tset = (fra._start_dt - self._value_dt) / gDaysInYear - # tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + # t_set = (fra._start_dt - self._value_dt) / gDaysInYear + # t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # # if both dates are after the previous FRA/FUT then need to # # solve for 2 discount factors simultaneously using root search - # if tset < oldtmat and tmat > oldtmat: + # if t_set < oldt_mat and t_mat > oldt_mat: # df_mat = fra.maturity_df(self) - # self._times = np.append(self._times, tmat) + # self._times = np.append(self._times, t_mat) # self._dfs = np.append(self._dfs, df_mat) # self._interpolator.fit(self._times, self._dfs) # else: - # self._times = np.append(self._times, tmat) + # self._times = np.append(self._times, t_mat) # self._dfs = np.append(self._dfs, df_mat) # self._interpolator.fit(self._times, self._dfs) @@ -482,13 +482,13 @@ def _build_curve_using_1d_solver(self): # for i in range(start_index, num_flows): # dt = cpn_dts[i] - # tmat = (dt - self._value_dt) / gDaysInYear + # 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 - # self._times = np.append(self._times, tmat) + # self._times = np.append(self._times, t_mat) # self._dfs = np.append(self._dfs, df_mat) # self._interpolator.fit(self._times, self._dfs) diff --git a/financepy/products/rates/ibor_cap_floor.py b/financepy/products/rates/ibor_cap_floor.py index b3a89cfd..26340017 100644 --- a/financepy/products/rates/ibor_cap_floor.py +++ b/financepy/products/rates/ibor_cap_floor.py @@ -274,7 +274,7 @@ def value_caplet_floor_let(self, elif isinstance(model, HWTree): - tmat = (caplet_end_dt - value_dt) / gDaysInYear + t_mat = (caplet_end_dt - value_dt) / gDaysInYear alpha = self._day_counter.year_frac(caplet_start_dt, caplet_end_dt)[0] strike_price = 1.0/(1.0 + alpha * self._strike_rate) @@ -283,7 +283,7 @@ def value_caplet_floor_let(self, df_times = libor_curve._times df_values = libor_curve._dfs - v = model.option_on_zcb(t_exp, tmat, strike_price, face_amount, + v = model.option_on_zcb(t_exp, t_mat, strike_price, face_amount, df_times, df_values) # we divide by alpha to offset the multiplication above diff --git a/financepy/products/rates/ibor_single_curve.py b/financepy/products/rates/ibor_single_curve.py index f937948b..682261f9 100644 --- a/financepy/products/rates/ibor_single_curve.py +++ b/financepy/products/rates/ibor_single_curve.py @@ -306,12 +306,12 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDepositMaturityDate = Date(1, 1, 1900) + lastDeposit_maturityDate = Date(1, 1, 1900) firstFRAMaturityDate = Date(1, 1, 1900) lastFRAMaturityDate = Date(1, 1, 1900) if num_depos > 0: - lastDepositMaturityDate = ibor_deposits[-1]._maturity_dt + lastDeposit_maturityDate = ibor_deposits[-1]._maturity_dt if num_fras > 0: firstFRAMaturityDate = ibor_fras[0]._maturity_dt @@ -321,9 +321,9 @@ def _validate_inputs(self, first_swap_maturity_dt = ibor_swaps[0]._maturity_dt if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDepositMaturityDate: + if firstFRAMaturityDate <= lastDeposit_maturityDate: print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDepositMaturityDate) + print("Last Deposit Date:", lastDeposit_maturityDate) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: @@ -371,7 +371,7 @@ def _build_curve_using_1d_solver(self): self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -380,27 +380,27 @@ def _build_curve_using_1d_solver(self): for depo in self._usedDeposits: dfSettle = self.df(depo._start_dt) df_mat = depo._maturity_df() * dfSettle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) self._interpolator.fit(self._times, self._dfs) - oldtmat = tmat + oldt_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < oldt_mat and t_mat > oldt_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, @@ -411,9 +411,9 @@ def _build_curve_using_1d_solver(self): # 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] - tmat = (maturity_dt - self._value_dt) / gDaysInYear + t_mat = (maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, swap) @@ -431,24 +431,24 @@ def _build_curve_using_quadratic_minimiser(self): """ Construct the discount curve using a minimisation approach. This is the This enables a more complex interpolation scheme. """ - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 - grid_times = [tmat] + grid_times = [t_mat] gridDfs = [df_mat] for depo in self._usedDeposits: - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - grid_times.append(tmat) + t_mat = (depo._maturity_dt - self._value_dt) / gDaysInYear + grid_times.append(t_mat) for fra in self._usedFRAs: - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear - grid_times.append(tmat) + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear + grid_times.append(t_mat) gridDfs.append(df_mat) for swap in self._usedSwaps: - tmat = (swap._maturity_dt - self._value_dt) / gDaysInYear - grid_times.append(tmat) + t_mat = (swap._maturity_dt - self._value_dt) / gDaysInYear + grid_times.append(t_mat) self._times = np.array(grid_times) self._dfs = np.exp(-self._times * 0.05) @@ -476,7 +476,7 @@ def _build_curve_linear_swap_rate_interpolation(self): self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -485,32 +485,32 @@ def _build_curve_linear_swap_rate_interpolation(self): for depo in self._usedDeposits: dfSettle = self.df(depo._start_dt) df_mat = depo._maturity_df() * dfSettle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) self._interpolator.fit(self._times, self._dfs) - oldtmat = tmat + oldt_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < oldt_mat and t_mat > oldt_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) @@ -596,14 +596,14 @@ def _build_curve_linear_swap_rate_interpolation(self): for i in range(start_index, num_flows): dt = cpn_dts[i] - tmat = (dt - self._value_dt) / gDaysInYear + t_mat = (dt - self._value_dt) / gDaysInYear swap_rate = interpolated_swap_rates[i] acc = accrual_factors[i-1] pv01End = (acc * swap_rate + 1.0) df_mat = (dfSettle - swap_rate * pv01) / pv01End - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) diff --git a/financepy/products/rates/ibor_swaption.py b/financepy/products/rates/ibor_swaption.py index c14f30b7..39240423 100644 --- a/financepy/products/rates/ibor_swaption.py +++ b/financepy/products/rates/ibor_swaption.py @@ -134,7 +134,7 @@ def value(self, s = swap.swap_rate(value_dt, discount_curve) t_exp = (self._exercise_dt - self._settle_dt) / gDaysInYear - tmat = (self._maturity_dt - self._settle_dt) / gDaysInYear + t_mat = (self._maturity_dt - self._settle_dt) / gDaysInYear # Discounting is done via the PV01 annuity so no discounting in Black df = 1.0 @@ -235,9 +235,9 @@ def value(self, elif isinstance(model, BKTree): - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) swaptionPx = model.bermudan_swaption(t_exp, - tmat, + t_mat, strike_price, face_amount, cpn_times, @@ -253,9 +253,9 @@ def value(self, elif isinstance(model, BDTTree): - model.build_tree(tmat, df_times, df_values) + model.build_tree(t_mat, df_times, df_values) swaptionPx = model.bermudan_swaption(t_exp, - tmat, + t_mat, strike_price, face_amount, cpn_times, diff --git a/financepy/products/rates/ois_curve.py b/financepy/products/rates/ois_curve.py index 1ef5bcc0..1678b7d3 100644 --- a/financepy/products/rates/ois_curve.py +++ b/financepy/products/rates/ois_curve.py @@ -254,12 +254,12 @@ def _validate_inputs(self, # Now we have ensure they are in order check for overlaps and the like ####################################################################### - lastDepositMaturityDate = Date(1, 1, 1900) + lastDeposit_maturityDate = Date(1, 1, 1900) firstFRAMaturityDate = Date(1, 1, 1900) lastFRAMaturityDate = Date(1, 1, 1900) if num_depos > 0: - lastDepositMaturityDate = oisDeposits[-1]._maturity_dt + lastDeposit_maturityDate = oisDeposits[-1]._maturity_dt if num_fras > 0: firstFRAMaturityDate = oisFRAs[0]._maturity_dt @@ -273,9 +273,9 @@ def _validate_inputs(self, raise FinError("First Swap must mature after last FRA ends") if num_depos > 0 and num_fras > 0: - if firstFRAMaturityDate <= lastDepositMaturityDate: + if firstFRAMaturityDate <= lastDeposit_maturityDate: print("FRA Maturity Date:", firstFRAMaturityDate) - print("Last Deposit Date:", lastDepositMaturityDate) + print("Last Deposit Date:", lastDeposit_maturityDate) raise FinError("First FRA must end after last Deposit") if num_fras > 0 and num_swaps > 0: @@ -321,7 +321,7 @@ def _build_curve_using_1d_solver(self): self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -330,27 +330,27 @@ def _build_curve_using_1d_solver(self): for depo in self._usedDeposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) self._interpolator.fit(self._times, self._dfs) - oldtmat = tmat + old_t_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < old_t_mat and t_mat > old_t_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, fra) df_mat = optimize.newton(_g, x0=df_mat, fprime=None, @@ -361,9 +361,9 @@ def _build_curve_using_1d_solver(self): # 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] - tmat = (maturity_dt - self._value_dt) / gDaysInYear + t_mat = (maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) argtuple = (self, self._value_dt, swap) @@ -383,12 +383,11 @@ def _build_curve_linear_swap_rate_interpolation(self): require the use of a solver. It is also market standard. """ self._interpolator = Interpolator(self._interp_type) - self._times = np.array([]) self._dfs = np.array([]) # time zero is now. - tmat = 0.0 + t_mat = 0.0 df_mat = 1.0 self._times = np.append(self._times, 0.0) self._dfs = np.append(self._dfs, df_mat) @@ -396,35 +395,35 @@ def _build_curve_linear_swap_rate_interpolation(self): for depo in self._usedDeposits: df_settle = self.df(depo._start_dt) df_mat = depo._maturity_df() * df_settle - tmat = (depo._maturity_dt - self._value_dt) / gDaysInYear - self._times = np.append(self._times, tmat) + 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) self._interpolator.fit(self._times, self._dfs) - oldtmat = tmat + old_t_mat = t_mat for fra in self._usedFRAs: - tset = (fra._start_dt - self._value_dt) / gDaysInYear - tmat = (fra._maturity_dt - self._value_dt) / gDaysInYear + t_set = (fra._start_dt - self._value_dt) / gDaysInYear + t_mat = (fra._maturity_dt - self._value_dt) / gDaysInYear # if both dates are after the previous FRA/FUT then need to # solve for 2 discount factors simultaneously using root search - if tset < oldtmat and tmat > oldtmat: + if t_set < old_t_mat and t_mat > old_t_mat: df_mat = fra.maturity_df(self) - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) else: - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) 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=swaptol, + maxiter=50, fprime2=None) if len(self._usedSwaps) == 0: if self._check_refit is True: @@ -436,13 +435,13 @@ 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 + found_start = False + last_dt = self._value_dt if len(self._usedDeposits) != 0: - lastDate = self._usedDeposits[-1]._maturity_dt + last_dt = self._usedDeposits[-1]._maturity_dt if len(self._usedFRAs) != 0: - lastDate = self._usedFRAs[-1]._maturity_dt + last_dt = self._usedFRAs[-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 @@ -453,12 +452,12 @@ def _build_curve_linear_swap_rate_interpolation(self): # 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 = [] @@ -474,18 +473,17 @@ def _build_curve_linear_swap_rate_interpolation(self): 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 cpn_dts[1:]: - swapTime = (dt - self._value_dt) / gDaysInYear - swap_rate = np.interp(swapTime, swap_times, swap_rates) - interpolatedSwapRates.append(swap_rate) - interpolatedswap_times.append(swapTime) + swap_time = (dt - self._value_dt) / gDaysInYear + swap_rate = np.interp(swap_time, swap_times, swap_rates) + interpolated_swap_rates.append(swap_rate) + interpolated_swap_times.append(swap_time) # Do I need this line ? - interpolatedSwapRates[0] = interpolatedSwapRates[1] - + interpolated_swap_rates[0] = interpolated_swap_rates[1] accrual_factors = longestSwap._fixed_year_fracs acc = 0.0 @@ -502,14 +500,14 @@ def _build_curve_linear_swap_rate_interpolation(self): for i in range(start_index, num_flows): dt = cpn_dts[i] - tmat = (dt - self._value_dt) / gDaysInYear - swap_rate = interpolatedSwapRates[i] + t_mat = (dt - self._value_dt) / gDaysInYear + swap_rate = interpolated_swap_rates[i] acc = accrual_factors[i-1] pv01End = (acc * swap_rate + 1.0) df_mat = (df_settle - swap_rate * pv01) / pv01End - self._times = np.append(self._times, tmat) + self._times = np.append(self._times, t_mat) self._dfs = np.append(self._dfs, df_mat) self._interpolator.fit(self._times, self._dfs) diff --git a/financepy/products/rates/swaps/FinIborIborSwap.py b/financepy/products/rates/swaps/FinIborIborSwap.py index 141d2030..c3ed601f 100644 --- a/financepy/products/rates/swaps/FinIborIborSwap.py +++ b/financepy/products/rates/swaps/FinIborIborSwap.py @@ -38,7 +38,7 @@ def __init__(self, cal_type: CalendarTypes = CalendarTypes.WEEKEND, bd_type: BusDayAdjustTypes = BusDayAdjustTypes.FOLLOWING, dg_type: DateGenRuleTypes = DateGenRuleTypes.BACKWARD): - """ Create a Ibor basis swap contract giving the contract start + """ Create an Ibor basis swap contract giving the contract start date, its maturity, frequency and day counts on the two floating legs and notional. The floating leg parameters have default values that can be overwritten if needed. The start date is contractual diff --git a/financepy/utils/date.py b/financepy/utils/date.py index 138488b2..faba18a2 100644 --- a/financepy/utils/date.py +++ b/financepy/utils/date.py @@ -157,7 +157,7 @@ def calculate_list(): g_date_counter_list.append(-999) ############################################################################### -# The index in these functions is not the excel date index used as the +# The index in these functions is not the Excel date index used as the # internal representation of the date but the index of that date in the # padded date object used to store the dates in a way that allows for a # quick lookup. Do not confuse them as you will find they are out by months @@ -291,7 +291,7 @@ def __init__(self, d, m, y, hh=0, mm=0, ss=0): self._excel_dt = 0 # This is a float as it includes intraday time - # update the excel date used for doing lots of financial calculations + # update the Excel date used for doing lots of financial calculations self._refresh() day_fraction = self._hh/24.0 @@ -393,7 +393,6 @@ def __sub__(self, other): ########################################################################### - @vectorisation_helper def __rsub__(self, other): return self._excel_dt - other._excel_dt @@ -707,16 +706,16 @@ def third_wednesday_of_month(self, """ For a specific month and year this returns the day number of the 3rd Wednesday by scanning through dates in the third week. """ - # Suppose 1st is Weds then 8th is Wed and 15th is 3rd Wed - # Suppose 1st is Thur then 7th is Wed and 14th is 2nd Wed so 21 is 3rd - # so earliest and latest dates are 15th and 21st + # Suppose 1st is Weds then 8th is Wed and 15th is 3rd Wednesday + # Suppose 1st is Thur then 7th is Wed and 14th is 2nd Wednesday so 21 + # is 3rd so earliest and latest dates are 15th and 21st d_start = 15 d_end = 21 for d in range(d_start, d_end+1): - immDate = Date(d, m, y) - if immDate._weekday == self.WED: + imm_date = Date(d, m, y) + if imm_date._weekday == self.WED: return d # Should never reach this line but just to be defensive @@ -756,8 +755,8 @@ def next_imm_date(self): d_imm = self.third_wednesday_of_month(m_imm, y_imm) - immDate = Date(d_imm, m_imm, y_imm) - return immDate + imm_date = Date(d_imm, m_imm, y_imm) + return imm_date ########################################################################### @@ -878,75 +877,75 @@ def __repr__(self): global g_date_type_format - dayNameStr = short_day_names[self._weekday] + day_name_str = short_day_names[self._weekday] if self._d < 10: - dayStr = "0" + str(self._d) + day_str = "0" + str(self._d) else: - dayStr = "" + str(self._d) + day_str = "" + str(self._d) if self._m < 10: - shortMonthStr = "0" + str(self._m) + short_month_str = "0" + str(self._m) else: - shortMonthStr = str(self._m) + short_month_str = str(self._m) - longMonthStr = shortMonthNames[self._m - 1] + long_month_str = shortMonthNames[self._m - 1] - shortYearStr = str(self._y)[2:] - longYearStr = str(self._y) + short_year_str = str(self._y)[2:] + long_year_str = str(self._y) if g_date_type_format == DateFormatTypes.UK_LONGEST: sep = " " - date_str = dayNameStr + " " + dayStr + sep + longMonthStr + sep + longYearStr + date_str = day_name_str + " " + day_str + sep + long_month_str + sep + long_year_str return date_str elif g_date_type_format == DateFormatTypes.UK_LONG: sep = "-" - date_str = dayStr + sep + longMonthStr + sep + longYearStr + date_str = day_str + sep + long_month_str + sep + long_year_str return date_str elif g_date_type_format == DateFormatTypes.UK_MEDIUM: sep = "/" - date_str = dayStr + sep + shortMonthStr + sep + longYearStr + date_str = day_str + sep + short_month_str + sep + long_year_str return date_str elif g_date_type_format == DateFormatTypes.UK_SHORT: sep = "/" - date_str = dayStr + sep + shortMonthStr + sep + shortYearStr + date_str = day_str + sep + short_month_str + sep + short_year_str return date_str elif g_date_type_format == DateFormatTypes.US_LONGEST: sep = " " - date_str = dayNameStr + " " + longMonthStr + sep + dayStr + sep + longYearStr + date_str = day_name_str + " " + long_month_str + sep + day_str + sep + long_year_str return date_str elif g_date_type_format == DateFormatTypes.US_LONG: sep = "-" - date_str = longMonthStr + sep + dayStr + sep + longYearStr + date_str = long_month_str + sep + day_str + sep + long_year_str return date_str elif g_date_type_format == DateFormatTypes.US_MEDIUM: sep = "-" - date_str = shortMonthStr + sep + dayStr + sep + longYearStr + date_str = short_month_str + sep + day_str + sep + long_year_str return date_str elif g_date_type_format == DateFormatTypes.US_SHORT: sep = "-" - date_str = shortMonthStr + sep + dayStr + sep + shortYearStr + date_str = short_month_str + sep + day_str + sep + short_year_str return date_str elif g_date_type_format == DateFormatTypes.BLOOMBERG: sep = "/" - date_str = shortMonthStr + sep + dayStr + sep + shortYearStr + date_str = short_month_str + sep + day_str + sep + short_year_str return date_str elif g_date_type_format == DateFormatTypes.DATETIME: @@ -954,23 +953,23 @@ def __repr__(self): sep = "/" if self._hh < 10: - hourStr = "0" + str(self._hh) + hour_str = "0" + str(self._hh) else: - hourStr = str(self._hh) + hour_str = str(self._hh) if self._mm < 10: - minuteStr = "0" + str(self._mm) + minute_str = "0" + str(self._mm) else: - minuteStr = str(self._mm) + minute_str = str(self._mm) if self._ss < 10: - secondStr = "0" + str(self._ss) + second_str = "0" + str(self._ss) else: - secondStr = str(self._ss) + second_str = str(self._ss) - timeStr = hourStr + ":" + minuteStr + ":" + secondStr - date_str = dayStr + sep + shortMonthStr + sep + longYearStr - date_str = date_str + " " + timeStr + time_str = hour_str + ":" + minute_str + ":" + second_str + date_str = day_str + sep + short_month_str + sep + long_year_str + date_str = date_str + " " + time_str return date_str else: @@ -1022,8 +1021,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. """ - finDate = Date(dt.day, dt.month, dt.year) - return finDate + fin_date = Date(dt.day, dt.month, dt.year) + return fin_date ############################################################################### diff --git a/financepy/utils/day_count.py b/financepy/utils/day_count.py index 36bff92d..fb203ebe 100644 --- a/financepy/utils/day_count.py +++ b/financepy/utils/day_count.py @@ -93,9 +93,9 @@ def year_frac(self, must be set to the next coupon date. You will also need to provide a coupon frequency for some conventions. - Note that if the date is intraday, i.e. hh,mm and ss do not equal zero + Note that if the date is intra-day, i.e. hh,mm and ss do not equal zero then that is used in the calculation of the year frac. This avoids - discontinuities for short dated intra day products. It should not + discontinuities for short-dated intraday products. It should not affect normal dates for which hh=mm=ss=0. This seems like a useful source: @@ -131,7 +131,7 @@ def year_frac(self, num = 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1) den = 360 acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den elif self._type == DayCountTypes.THIRTY_E_360: # This is in section 4.16(g) of ISDA 2006 Definitions @@ -148,7 +148,7 @@ def year_frac(self, num = 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1) den = 360 acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den elif self._type == DayCountTypes.THIRTY_E_360_ISDA: # This is 30E/360 (ISDA 2000), 30E/360 (ISDA) section 4.16(h) @@ -157,15 +157,15 @@ def year_frac(self, if d1 == 31: d1 = 30 - lastDayOfFeb1 = is_last_day_of_feb(dt1) - if lastDayOfFeb1 is True: + last_day_of_feb1 = is_last_day_of_feb(dt1) + if last_day_of_feb1 is True: d1 = 30 if d2 == 31: d2 = 30 - lastDayOfFeb2 = is_last_day_of_feb(dt2) - if lastDayOfFeb2 is True and isTerminationDate is False: + last_day_of_feb2 = is_last_day_of_feb(dt2) + if last_day_of_feb2 is True and isTerminationDate is False: d2 = 30 num = 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1) @@ -203,19 +203,19 @@ def year_frac(self, num = dt2 - dt1 den = denom1 acc_factor = (dt2 - dt1) / denom1 - return (acc_factor, num, den) + return acc_factor, num, den else: day_years_1 = datediff(dt1, Date(1, 1, y1 + 1)) day_years_2 = datediff(Date(1, 1, y2), dt2) acc_factor1 = day_years_1 / denom1 acc_factor2 = day_years_2 / denom2 - yearDiff = y2 - y1 - 1.0 + year_diff = y2 - y1 - 1.0 # Note that num/den does not equal acc_factor # I do need to pass num back num = day_years_1 + day_years_2 den = denom1 + denom2 - acc_factor = acc_factor1 + acc_factor2 + yearDiff - return (acc_factor, num, den) + acc_factor = acc_factor1 + acc_factor2 + year_diff + return acc_factor, num, den elif self._type == DayCountTypes.ACT_ACT_ICMA: @@ -227,21 +227,21 @@ def year_frac(self, num = dt2 - dt1 den = freq * (dt3 - dt1) acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den elif self._type == DayCountTypes.ACT_365F: num = dt2 - dt1 den = 365 acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den elif self._type == DayCountTypes.ACT_360: num = dt2 - dt1 den = 360 acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den elif self._type == DayCountTypes.ACT_365L: @@ -273,14 +273,14 @@ def year_frac(self, den = 366 acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den elif self._type == DayCountTypes.SIMPLE: num = dt2 - dt1 den = gDaysInYear acc_factor = num / den - return (acc_factor, num, den) + return acc_factor, num, den else: diff --git a/financepy/utils/math.py b/financepy/utils/math.py index 246d44f2..ff705e80 100644 --- a/financepy/utils/math.py +++ b/financepy/utils/math.py @@ -21,7 +21,7 @@ @njit(fastmath=True, cache=True) -def accrued_interpolator(tset: float, # Settlement time in years +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 @@ -35,14 +35,14 @@ def accrued_interpolator(tset: float, # Settlement time in years nct = cpn_times[i] denom = (nct-pct) - if tset >= pct and tset < nct: - accdFrac = (tset-pct) / denom + if t_set >= pct and t_set < nct: + accdFrac = (t_set-pct) / denom accdCpn = accdFrac * cpn_amounts[i] return accdCpn # TODO: NEED TO REVISIT THIS TODO return 0.0 - print("t", tset) + print("t", t_set) print("CPN TIMES", cpn_times) print("CPN AMNTS", cpn_amounts) diff --git a/notebooks/products/bonds/FINBONDOPTION_HW_EXAMPLE_MATCH_DERIVA_GEN.ipynb b/notebooks/products/bonds/FINBONDOPTION_HW_EXAMPLE_MATCH_DERIVA_GEN.ipynb index 4c72e548..1de7db00 100644 --- a/notebooks/products/bonds/FINBONDOPTION_HW_EXAMPLE_MATCH_DERIVA_GEN.ipynb +++ b/notebooks/products/bonds/FINBONDOPTION_HW_EXAMPLE_MATCH_DERIVA_GEN.ipynb @@ -424,7 +424,7 @@ "\n", " # Test convergence\n", " t_exp = (expiryDate - settlementDate)/gDaysInYear\n", - " tmat = (maturityDate - settlementDate)/gDaysInYear\n", + " t_mat = (maturityDate - settlementDate)/gDaysInYear\n", "\n", " # Jamshidian approach\n", " vJam = model.european_bond_option_jamshidian(t_exp, strikePrice, face,\n", @@ -432,7 +432,7 @@ " df_times, df_values)\n", "\n", " model._num_time_steps = 200\n", - " model.build_tree(tmat, df_times, df_values)\n", + " model.build_tree(t_mat, df_times, df_values)\n", " exerciseType = FinExerciseTypes.EUROPEAN\n", " vHW = model.bond_option(t_exp, strikePrice, face,\n", " couponTimes, couponFlows, exerciseType)\n" diff --git a/tests/test_FinBondOption.py b/tests/test_FinBondOption.py index 6af4f277..bf848b33 100644 --- a/tests/test_FinBondOption.py +++ b/tests/test_FinBondOption.py @@ -25,8 +25,8 @@ dc_type = DayCountTypes.ACT_ACT_ICMA bond = Bond(issue_dt, maturity_dt, coupon, freq_type, dc_type) -tmat = (maturity_dt - settle_dt) / gDaysInYear -times = np.linspace(0, tmat, 20) +t_mat = (maturity_dt - settle_dt) / gDaysInYear +times = np.linspace(0, t_mat, 20) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) discount_curve = DiscountCurve(settle_dt, dates, dfs) @@ -163,7 +163,7 @@ def test_american_put_bdt(): # Results different from TestFinBondOptionHWModel.py -# because tmat != 10.0 +# because t_mat != 10.0 def test_european_call_hw(): option_type = OptionTypes.EUROPEAN_CALL strike_price = 100 diff --git a/tests/test_FinModelRatesBDT.py b/tests/test_FinModelRatesBDT.py index a775f447..ea1012a0 100644 --- a/tests/test_FinModelRatesBDT.py +++ b/tests/test_FinModelRatesBDT.py @@ -58,9 +58,9 @@ def test_BDTExampleTwo(): strike_price = 105.0 face = 100.0 - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear - times = np.linspace(0, tmat, 11) + times = np.linspace(0, t_mat, 11) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) @@ -76,7 +76,7 @@ def test_BDTExampleTwo(): exercise_type = FinExerciseTypes.AMERICAN model = BDTTree(sigma, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bond_option(t_exp, strike_price, face, cpn_times, cpn_flows, exercise_type) @@ -114,7 +114,7 @@ def test_BDTExampleThree(): expiry_dt = settle_dt.add_years(expiryYears) - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear bond = Bond(issue_dt, maturity_dt, @@ -138,10 +138,10 @@ def test_BDTExampleThree(): settle_dt, curve) model = BDTTree(sigma, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bermudan_swaption(t_exp, - tmat, + t_mat, strike_price, face, cpn_times, @@ -163,7 +163,7 @@ def test_BDTExampleThree(): expiry_dt = settle_dt.add_years(expiryYears) - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear bond = Bond(issue_dt, maturity_dt, @@ -187,10 +187,10 @@ def test_BDTExampleThree(): settle_dt, curve) model = BDTTree(sigma, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bermudan_swaption(t_exp, - tmat, + t_mat, strike_price, face, cpn_times, diff --git a/tests/test_FinModelRatesBK.py b/tests/test_FinModelRatesBK.py index e03a9523..f9f7b399 100644 --- a/tests/test_FinModelRatesBK.py +++ b/tests/test_FinModelRatesBK.py @@ -25,9 +25,9 @@ def test_BKExampleOne(): sigma = 0.25 a = 0.22 num_time_steps = 3 - tmat = (end_dt - start_dt)/gDaysInYear + t_mat = (end_dt - start_dt)/gDaysInYear model = BKTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) assert [round(x, 4) for x in model._Q[2]] == \ [0.0190, 0.2126, 0.5009, 0.2112, 0.0187] @@ -86,9 +86,9 @@ def test_BKExampleTwo(): strike_price = 105.0 face = 100.0 - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear - times = np.linspace(0, tmat, 11) + times = np.linspace(0, t_mat, 11) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) curve = DiscountCurve(settle_dt, dates, dfs) @@ -101,7 +101,7 @@ def test_BKExampleTwo(): num_time_steps = 26 model = BKTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) exercise_type = FinExerciseTypes.AMERICAN v = model.bond_option(t_exp, strike_price, face, cpn_times, cpn_flows, exercise_type) @@ -112,7 +112,7 @@ def test_BKExampleTwo(): treeVector = [] model = BKTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bond_option(t_exp, strike_price, face, cpn_times, cpn_flows, exercise_type) treeVector.append(v) diff --git a/tests/test_FinModelRatesHW.py b/tests/test_FinModelRatesHW.py index e8e0b028..59a14459 100644 --- a/tests/test_FinModelRatesHW.py +++ b/tests/test_FinModelRatesHW.py @@ -38,21 +38,21 @@ def test_HullWhiteExampleTwo(): maturity_dt = start_dt.add_tenor("9Y") t_exp = (expiry_dt - start_dt)/gDaysInYear - tmat = (maturity_dt - start_dt)/gDaysInYear + t_mat = (maturity_dt - start_dt)/gDaysInYear num_time_steps = None model = HWTree(sigma, a, num_time_steps) - vAnal = model.option_on_zcb(t_exp, tmat, strike, face, times, dfs) + vAnal = model.option_on_zcb(t_exp, t_mat, strike, face, times, dfs) num_time_steps = 200 model = HWTree(sigma, a, num_time_steps) model.build_tree(t_exp, times, dfs) - vTree1 = model.option_on_zero_coupon_bond_tree(t_exp, tmat, strike, face) + vTree1 = model.option_on_zero_coupon_bond_tree(t_exp, t_mat, strike, face) model = HWTree(sigma, a, num_time_steps+1) model.build_tree(t_exp, times, dfs) - vTree2 = model.option_on_zero_coupon_bond_tree(t_exp, tmat, strike, face) + vTree2 = model.option_on_zero_coupon_bond_tree(t_exp, t_mat, strike, face) vTreeCall = (vTree1['call'] + vTree2['call']) / 2.0 vTreePut = (vTree1['put'] + vTree2['put']) / 2.0 diff --git a/tests_golden/FinTestCases.py b/tests_golden/FinTestCases.py index d7e1449e..c314dbc0 100644 --- a/tests_golden/FinTestCases.py +++ b/tests_golden/FinTestCases.py @@ -99,7 +99,7 @@ def __init__(self, module_name, mode): print("Looking for:", self._goldenFolder) print("GOLDEN Folder DOES NOT EXIST. You must create it. Exiting") self._foldersExist = False - return None + return self._compare_folder = join(root_folder, "compare") @@ -107,7 +107,7 @@ def __init__(self, module_name, mode): print("Looking for:", self._compare_folder) print("COMPARE Folder DOES NOT EXIST. You must create it. Exiting") self._foldersExist = False - return None + return self._golden_file_name = join(self._goldenFolder, self._module_name + "_GOLDEN.testLog") diff --git a/tests_golden/TestFinBondAnnuity.py b/tests_golden/TestFinBondAnnuity.py index 3d84dc9c..c7e64977 100644 --- a/tests_golden/TestFinBondAnnuity.py +++ b/tests_golden/TestFinBondAnnuity.py @@ -21,6 +21,7 @@ def test_BondAnnuity(): + ''' Test ''' settle_dt = Date(20, 6, 2018) diff --git a/tests_golden/TestFinBondOptionBDTModel.py b/tests_golden/TestFinBondOptionBDTModel.py index b081b8bd..c52ded86 100644 --- a/tests_golden/TestFinBondOptionBDTModel.py +++ b/tests_golden/TestFinBondOptionBDTModel.py @@ -39,8 +39,8 @@ def test_BondOption(): dc_type = DayCountTypes.ACT_ACT_ICMA bond = Bond(issue_dt, maturity_dt, coupon, freq_type, dc_type) - tmat = (maturity_dt - settle_dt) / gDaysInYear - times = np.linspace(0, tmat, 20) + t_mat = (maturity_dt - settle_dt) / gDaysInYear + times = np.linspace(0, t_mat, 20) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) discount_curve = DiscountCurve(settle_dt, dates, dfs) diff --git a/tests_golden/TestFinBondOptionBKModel.py b/tests_golden/TestFinBondOptionBKModel.py index a5406d5e..a902e889 100644 --- a/tests_golden/TestFinBondOptionBKModel.py +++ b/tests_golden/TestFinBondOptionBKModel.py @@ -38,8 +38,8 @@ def test_BondOption(): dc_type = DayCountTypes.ACT_ACT_ICMA bond = Bond(issue_dt, maturity_dt, coupon, freq_type, dc_type) - tmat = (maturity_dt - settle_dt) / gDaysInYear - times = np.linspace(0, tmat, 20) + t_mat = (maturity_dt - settle_dt) / gDaysInYear + times = np.linspace(0, t_mat, 20) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) discount_curve = DiscountCurve(settle_dt, dates, dfs) diff --git a/tests_golden/TestFinBondOptionHWModel.py b/tests_golden/TestFinBondOptionHWModel.py index 035bdcf5..18108402 100644 --- a/tests_golden/TestFinBondOptionHWModel.py +++ b/tests_golden/TestFinBondOptionHWModel.py @@ -527,7 +527,7 @@ def test_BondOptionDerivaGem(): # Test convergence t_exp = (expiry_dt - settle_dt)/gDaysInYear - tmat = (maturity_dt - settle_dt)/gDaysInYear + t_mat = (maturity_dt - settle_dt)/gDaysInYear # Jamshidian approach vjam = model.european_bond_option_jamshidian(t_exp, strike_price, face, @@ -536,7 +536,7 @@ def test_BondOptionDerivaGem(): # print("Jamshidian:", vjam) model._num_time_steps = 100 - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) exerciseType = FinExerciseTypes.EUROPEAN vHW = model.bond_option(t_exp, strike_price, face, diff --git a/tests_golden/TestFinIborLMMProducts.py b/tests_golden/TestFinIborLMMProducts.py index b7cf32bd..227aeac8 100644 --- a/tests_golden/TestFinIborLMMProducts.py +++ b/tests_golden/TestFinIborLMMProducts.py @@ -59,9 +59,9 @@ # dt = 0.5 # t_exp = 3.0 -# tmat = 10.0 +# t_mat = 10.0 # a = int(2*t_exp) -# b = int(2*tmat) +# b = int(2*t_mat) # numFwds = 20 # taus = np.array([dt] * numFwds) diff --git a/tests_golden/TestFinModelRatesBDT.py b/tests_golden/TestFinModelRatesBDT.py index 5565b6cf..e18cd745 100644 --- a/tests_golden/TestFinModelRatesBDT.py +++ b/tests_golden/TestFinModelRatesBDT.py @@ -92,7 +92,7 @@ def test_BDTExampleOne(): yieldVol = 0.16 num_time_steps = 5 - tmat = years[-1] + t_mat = years[-1] dfs = curve.df(zero_dts) test_cases.print("DFS") @@ -102,7 +102,7 @@ def test_BDTExampleOne(): dfs = np.array(dfs) model = BDTTree(yieldVol, num_time_steps) - model.build_tree(tmat, years, dfs) + model.build_tree(t_mat, years, dfs) ############################################################################### @@ -148,9 +148,9 @@ def test_BDTExampleTwo(): strike_price = 105.0 face = 100.0 - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear - times = np.linspace(0, tmat, 11) + times = np.linspace(0, t_mat, 11) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) @@ -172,7 +172,7 @@ def test_BDTExampleTwo(): treeVector = [] for num_time_steps in num_steps_list: model = BDTTree(sigma, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bond_option(t_exp, strike_price, face, cpn_times, cpn_flows, exercise_type) @@ -217,7 +217,7 @@ def test_BDTExampleThree(): # Andersen paper num_time_steps = 200 - test_cases.header("ExerciseType", "Sigma", "NumSteps", "Texp", "Tmat", + test_cases.header("ExerciseType", "Sigma", "NumSteps", "Texp", "t_mat", "V_Fixed", "V_pay", "V_rec") for exercise_type in [FinExerciseTypes.EUROPEAN, @@ -239,7 +239,7 @@ def test_BDTExampleThree(): expiry_dt = settle_dt.add_years(expiryYears) - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear bond = Bond(issue_dt, maturity_dt, @@ -261,10 +261,10 @@ def test_BDTExampleThree(): settle_dt, curve) model = BDTTree(sigma, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bermudan_swaption(t_exp, - tmat, + t_mat, strike_price, face, cpn_times, diff --git a/tests_golden/TestFinModelRatesBK.py b/tests_golden/TestFinModelRatesBK.py index f0345d90..77544558 100644 --- a/tests_golden/TestFinModelRatesBK.py +++ b/tests_golden/TestFinModelRatesBK.py @@ -39,9 +39,9 @@ def test_BKExampleOne(): sigma = 0.25 a = 0.22 num_time_steps = 3 - tmat = (end_dt - start_dt)/gDaysInYear + t_mat = (end_dt - start_dt)/gDaysInYear model = BKTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) # Agrees with Figure 28.10 - Not exact as we have dt not exactly 0.50 if num_time_steps < 5: @@ -95,9 +95,9 @@ def test_BKExampleTwo(): strike_price = 105.0 face = 100.0 - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear t_exp = (expiry_dt - settle_dt) / gDaysInYear - times = np.linspace(0, tmat, 11) + times = np.linspace(0, t_mat, 11) dates = settle_dt.add_years(times) dfs = np.exp(-0.05*times) curve = DiscountCurve(settle_dt, dates, dfs) @@ -111,7 +111,7 @@ def test_BKExampleTwo(): num_time_steps = 26 model = BKTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) exercise_type = FinExerciseTypes.AMERICAN v = model.bond_option(t_exp, strike_price, face, cpn_times, cpn_flows, exercise_type) @@ -125,7 +125,7 @@ def test_BKExampleTwo(): for num_time_steps in num_steps_list: start = time.time() model = BKTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v = model.bond_option(t_exp, strike_price, face, cpn_times, cpn_flows, exercise_type) end = time.time() diff --git a/tests_golden/TestFinModelRatesHW.py b/tests_golden/TestFinModelRatesHW.py index 96da769d..dd79864a 100644 --- a/tests_golden/TestFinModelRatesHW.py +++ b/tests_golden/TestFinModelRatesHW.py @@ -74,11 +74,11 @@ def test_HullWhiteExampleTwo(): maturity_dt = start_dt.add_tenor("9Y") t_exp = (expiry_dt - start_dt)/gDaysInYear - tmat = (maturity_dt - start_dt)/gDaysInYear + t_mat = (maturity_dt - start_dt)/gDaysInYear num_time_steps = None model = HWTree(sigma, a, num_time_steps) - vAnal = model.option_on_zcb(t_exp, tmat, strike, face, times, dfs) + vAnal = model.option_on_zcb(t_exp, t_mat, strike, face, times, dfs) # Test convergence num_steps_list = range(100, 500, 100) @@ -97,12 +97,12 @@ def test_HullWhiteExampleTwo(): model = HWTree(sigma, a, num_time_steps) model.build_tree(t_exp, times, dfs) vTree1 = model.option_on_zero_coupon_bond_tree( - t_exp, tmat, strike, face) + t_exp, t_mat, strike, face) model = HWTree(sigma, a, num_time_steps+1) model.build_tree(t_exp, times, dfs) vTree2 = model.option_on_zero_coupon_bond_tree( - t_exp, tmat, strike, face) + t_exp, t_mat, strike, face) end = time.time() period = end-start @@ -298,7 +298,7 @@ def test_HullWhiteCallableBond(): ########################################################################### - tmat = (maturity_dt - settle_dt) / gDaysInYear + t_mat = (maturity_dt - settle_dt) / gDaysInYear curve = DiscountCurveFlat(settle_dt, 0.05, FrequencyTypes.CONTINUOUS) dfs = [] @@ -323,7 +323,7 @@ def test_HullWhiteCallableBond(): # Test convergence num_steps_list = [100, 200, 500, 1000] - tmat = (maturity_dt - settle_dt)/gDaysInYear + t_mat = (maturity_dt - settle_dt)/gDaysInYear test_cases.header("NUMSTEPS", "TIME", "BOND_ONLY", "CALLABLE_BOND") @@ -331,7 +331,7 @@ def test_HullWhiteCallableBond(): start = time.time() model = HWTree(sigma, a, num_time_steps) - model.build_tree(tmat, times, dfs) + model.build_tree(t_mat, times, dfs) v2 = model.callable_puttable_bond_tree(cpn_times, cpn_flows, call_times, call_prices, diff --git a/tests_golden/TestFinModelRatesLMM.py b/tests_golden/TestFinModelRatesLMM.py index 1662ede5..cc0aa47d 100644 --- a/tests_golden/TestFinModelRatesLMM.py +++ b/tests_golden/TestFinModelRatesLMM.py @@ -105,9 +105,9 @@ def getForwardCurve(numFwds, r): # dt = 0.5 # t_exp = 3.0 -# tmat = 10.0 +# t_mat = 10.0 # a = int(2*t_exp) -# b = int(2*tmat) +# b = int(2*t_mat) # numFwds = 20 # taus = np.array([dt] * numFwds)