Skip to content

Commit

Permalink
Pep8 updates
Browse files Browse the repository at this point in the history
  • Loading branch information
domokane committed Dec 9, 2023
1 parent 3cb4be7 commit 11861e5
Show file tree
Hide file tree
Showing 52 changed files with 533 additions and 547 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down
3 changes: 1 addition & 2 deletions financepy/market/curves/discount_curve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions financepy/market/curves/discount_curve_flat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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. """

Expand All @@ -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
Expand All @@ -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
Expand All @@ -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. """

Expand Down
32 changes: 16 additions & 16 deletions financepy/models/bdt_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)

###########################################################################

Expand Down Expand Up @@ -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,
Expand All @@ -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)

###########################################################################

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand All @@ -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]
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -737,17 +737,17 @@ 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
bond maturity and take into account cash flows through time. """

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:
Expand All @@ -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,
Expand Down
46 changes: 23 additions & 23 deletions financepy/models/bk_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

###############################################################################
Expand All @@ -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

###############################################################################
Expand Down Expand Up @@ -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.")
Expand Down Expand Up @@ -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,
Expand All @@ -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.
###########################################################################
Expand Down Expand Up @@ -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,
Expand All @@ -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)

###########################################################################

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -964,17 +964,17 @@ 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
bond maturity and take into account cash flows through time. """

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:
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion financepy/models/black.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion financepy/models/black_scholes_mc_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading

0 comments on commit 11861e5

Please sign in to comment.