Skip to content

Commit

Permalink
PEP8 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
domokane committed Feb 19, 2024
1 parent 7e30d6f commit 928b0ab
Show file tree
Hide file tree
Showing 32 changed files with 737 additions and 742 deletions.
5 changes: 5 additions & 0 deletions financepy/market/curves/discount_curve.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ def __init__(self,

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

def value_dt(self):
return self._value_dt

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

def _zero_to_df(self,
value_dt: Date, # TODO: why is value_date not used ?
rates: (float, np.ndarray),
Expand Down
9 changes: 4 additions & 5 deletions financepy/market/curves/interpolator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,19 @@
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane
##############################################################################

from enum import Enum
from numba import njit, float64, int64
import numpy as np
from ...utils.error import FinError
from ...utils.global_vars import gSmall

from scipy.interpolate import PchipInterpolator
from scipy.interpolate import CubicSpline
from ...utils.error import FinError
from ...utils.global_vars import gSmall

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

from enum import Enum


class InterpTypes(Enum):
''' Types of interpolation '''
FLAT_FWD_RATES = 1
LINEAR_FWD_RATES = 2
LINEAR_ZERO_RATES = 4
Expand Down
2 changes: 1 addition & 1 deletion financepy/market/volatility/equity_vol_curve.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,6 @@ def calculate_pdf(self):
""" calculate the probability density function of the underlying using
the volatility smile or skew curve following the approach set out in
Breedon and Litzenberger. """
pass
return

###############################################################################
94 changes: 47 additions & 47 deletions financepy/market/volatility/equity_vol_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def _solve_to_horizon(s, t, r, q,
volatility_grid,
vol_type_value,
x_inits,
finSolverType):
fin_solver_type):

###########################################################################
# Determine parameters of vol surface using minimisation
Expand All @@ -104,20 +104,20 @@ def _solve_to_horizon(s, t, r, q,
# to converge, so for those cases try again with CG
# Numba version is quicker, but can be slightly away from CG output
try:
if finSolverType == FinSolverTypes.NELDER_MEAD_NUMBA:
if fin_solver_type == FinSolverTypes.NELDER_MEAD_NUMBA:
xopt = nelder_mead(_obj, np.array(x_inits),
bounds=np.array([[], []]).T,
args=args, tol_f=tol,
tol_x=tol, max_iter=1000)
elif finSolverType == FinSolverTypes.NELDER_MEAD:
elif fin_solver_type == FinSolverTypes.NELDER_MEAD:
opt = minimize(_obj, x_inits, args, method="Nelder-Mead", tol=tol)
xopt = opt.x
elif finSolverType == FinSolverTypes.CONJUGATE_GRADIENT:
elif fin_solver_type == FinSolverTypes.CONJUGATE_GRADIENT:
opt = minimize(_obj, x_inits, args, method="CG", tol=tol)
xopt = opt.x
except Exception:
# If convergence fails try again with CG if necessary
if finSolverType != FinSolverTypes.CONJUGATE_GRADIENT:
if fin_solver_type != FinSolverTypes.CONJUGATE_GRADIENT:
print('Failed to converge, will try CG')
opt = minimize(_obj, x_inits, args, method="CG", tol=tol)
xopt = opt.x
Expand All @@ -137,29 +137,29 @@ def vol_function(vol_function_type_value, params, f, k, t):
if vol_function_type_value == VolFuncTypes.CLARK.value:
vol = vol_function_clark(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.SABR_BETA_ONE.value:
if vol_function_type_value == VolFuncTypes.SABR_BETA_ONE.value:
vol = vol_function_sabr_beta_one(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.SABR_BETA_HALF.value:
if vol_function_type_value == VolFuncTypes.SABR_BETA_HALF.value:
vol = vol_function_sabr_beta_half(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.BBG.value:
if vol_function_type_value == VolFuncTypes.BBG.value:
vol = vol_function_bloomberg(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.SABR.value:
if vol_function_type_value == VolFuncTypes.SABR.value:
vol = vol_function_sabr(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.CLARK5.value:
if vol_function_type_value == VolFuncTypes.CLARK5.value:
vol = vol_function_clark(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.SVI.value:
if vol_function_type_value == VolFuncTypes.SVI.value:
vol = vol_function_svi(params, f, k, t)
return vol
elif vol_function_type_value == VolFuncTypes.SSVI.value:
if vol_function_type_value == VolFuncTypes.SSVI.value:
vol = vol_function_ssvi(params, f, k, t)
return vol
else:
return 0.0

return 0.0

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

Expand Down Expand Up @@ -198,7 +198,7 @@ def _delta_fit(k, *args):
# float64, float64[:]), fastmath=True)
def _solver_for_smile_strike(s, t, r, q,
option_type_value,
volatilityTypeValue,
vol_type_value,
delta_target,
initial_guess,
parameters):
Expand All @@ -208,7 +208,7 @@ def _solver_for_smile_strike(s, t, r, q,

inverse_delta_target = norminvcdf(np.abs(delta_target))

argtuple = (volatilityTypeValue, s, t, r, q,
argtuple = (vol_type_value, s, t, r, q,
option_type_value,
inverse_delta_target,
parameters)
Expand Down Expand Up @@ -238,8 +238,8 @@ def __init__(self,
expiry_dts: (list),
strikes: (list, np.ndarray),
volatility_grid: (list, np.ndarray),
volatility_function_type: VolFuncTypes = VolFuncTypes.CLARK,
finSolverType: FinSolverTypes = FinSolverTypes.NELDER_MEAD):
volatility_function_type = VolFuncTypes.CLARK,
fin_solver_type = FinSolverTypes.NELDER_MEAD):
""" Create the EquitySurface object by passing in market vol data
for a list of strikes and expiry dates. """

Expand All @@ -266,12 +266,12 @@ def __init__(self,
self._num_strikes = len(strikes)

self._expiry_dts = expiry_dts
self._numExpiryDates = len(expiry_dts)
self._num_expiry_dates = len(expiry_dts)

self._volatility_grid = volatility_grid
self._volatility_function_type = volatility_function_type

self._build_vol_surface(finSolverType=finSolverType)
self._build_vol_surface(fin_solver_type=fin_solver_type)

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

Expand All @@ -293,7 +293,7 @@ def vol_from_strike_dt(self, K, expiry_dt):
index0 = 0 # lower index in bracket
index1 = 0 # upper index in bracket

num_curves = self._numExpiryDates
num_curves = self._num_expiry_dates

if num_curves == 1:

Expand Down Expand Up @@ -473,7 +473,7 @@ def vol_from_delta_dt(self, call_delta, expiry_dt, delta_method=None):
index0 = 0 # lower index in bracket
index1 = 0 # upper index in bracket

num_curves = self._numExpiryDates
num_curves = self._num_expiry_dates

# If there is only one time horizon then assume flat vol to this time
if num_curves == 1:
Expand Down Expand Up @@ -562,59 +562,59 @@ def vol_from_delta_dt(self, call_delta, expiry_dt, delta_method=None):

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

def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD):
def _build_vol_surface(self, fin_solver_type=fin_solver_types.NELDER_MEAD):
""" Main function to construct the vol surface. """

s = self._stock_price

numExpiryDates = self._numExpiryDates
num_expiry_dates = self._num_expiry_dates

if self._volatility_function_type == VolFuncTypes.CLARK:
num_parameters = 3
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.SABR_BETA_ONE:
num_parameters = 3
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.SABR_BETA_HALF:
num_parameters = 3
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.BBG:
num_parameters = 3
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.SABR:
num_parameters = 4
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.CLARK5:
num_parameters = 5
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.SVI:
num_parameters = 5
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
elif self._volatility_function_type == VolFuncTypes.SSVI:
num_parameters = 5
self._parameters = np.zeros([numExpiryDates, num_parameters])
self._parameters = np.zeros([num_expiry_dates, num_parameters])
self._parameters[:, 0] = 0.2 # sigma
self._parameters[:, 1] = 0.8 # gamma
self._parameters[:, 2] = -0.7 # rho
self._parameters[:, 3] = 0.3
self._parameters[:, 4] = 0.048
else:
print(self._volatilityFunctionType)
print(self._volatility_function_type)
raise FinError("Unknown Model Type")

self._t_exp = np.zeros(numExpiryDates)
self._t_exp = np.zeros(num_expiry_dates)

self._F0T = np.zeros(numExpiryDates)
self._r = np.zeros(numExpiryDates)
self._q = np.zeros(numExpiryDates)
self._F0T = np.zeros(num_expiry_dates)
self._r = np.zeros(num_expiry_dates)
self._q = np.zeros(num_expiry_dates)

#######################################################################
# TODO: ADD SPOT DAYS
#######################################################################

spot_dt = self._value_dt

for i in range(0, numExpiryDates):
for i in range(0, num_expiry_dates):

expiry_dt = self._expiry_dts[i]
t_exp = (expiry_dt - spot_dt) / gDaysInYear
Expand All @@ -638,7 +638,7 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD):
x_init = np.zeros(num_parameters)
x_inits.append(x_init)

for i in range(0, numExpiryDates):
for i in range(0, num_expiry_dates):

t = self._t_exp[i]
r = self._r[i]
Expand All @@ -650,7 +650,7 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD):
self._volatility_grid,
vol_type_value,
x_inits[i],
finSolverType)
fin_solver_type)

self._parameters[i, :] = res

Expand All @@ -659,7 +659,7 @@ def _build_vol_surface(self, finSolverType=FinSolverTypes.NELDER_MEAD):

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

def check_calibration(self, verbose: bool, tol: float = 1e-6):
def check_calibration(self, verbose: bool):
""" Compare calibrated vol surface with market and output a report
which sets out the quality of fit to the ATM and 10 and 25 delta market
strangles and risk reversals. """
Expand All @@ -671,7 +671,7 @@ def check_calibration(self, verbose: bool, tol: float = 1e-6):
print("STOCK PRICE:", self._stock_price)
print("==========================================================")

for i in range(0, self._numExpiryDates):
for i in range(0, self._num_expiry_dates):

expiry_dt = self._expiry_dts[i]
print("==========================================================")
Expand Down Expand Up @@ -701,9 +701,9 @@ def implied_dbns(self, lowS, highS, num_intervals):

dbns = []

for iTenor in range(0, self._numExpiryDates):
for iTenor in range(0, self._num_expiry_dates):

f = self._F_0T[iTenor]
f = self._F0T[iTenor]
t = self._t_exp[iTenor]

dS = (highS - lowS) / num_intervals
Expand Down Expand Up @@ -747,7 +747,7 @@ def plot_vol_curves(self):
lowK = self._strikes[0] * 0.9
highK = self._strikes[-1] * 1.1

for tenor_index in range(0, self._numExpiryDates):
for tenor_index in range(0, self._num_expiry_dates):

expiry_dt = self._expiry_dts[tenor_index]
plt.figure()
Expand All @@ -759,7 +759,7 @@ def plot_vol_curves(self):
K = lowK
dK = (highK - lowK)/num_intervals

for i in range(0, num_intervals):
for _ in range(0, num_intervals):

ks.append(K)
fitted_vol = self.vol_from_strike_dt(K, expiry_dt) * 100.
Expand Down Expand Up @@ -788,7 +788,7 @@ def __repr__(self):
s += label_to_string("STOCK PRICE", self._stock_price)
s += label_to_string("VOL FUNCTION", self._volatility_function_type)

for i in range(0, self._numExpiryDates):
for i in range(0, self._num_expiry_dates):
s += label_to_string("EXPIRY DATE", self._expiry_dts[i])

for i in range(0, self._num_strikes):
Expand Down
20 changes: 10 additions & 10 deletions financepy/market/volatility/fx_vol_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,14 +257,14 @@ def delta_fit(K, *args):
r_d = args[3]
r_f = args[4]
option_type_value = args[5]
deltaTypeValue = args[6]
delta_type_value = args[6]
inverse_delta_target = args[7]
params = args[8]

f = s*np.exp((r_d-r_f)*t)
v = vol_function(vol_type_value, params, f, K, t)
delta_out = fast_delta(
s, t, K, r_d, r_f, v, deltaTypeValue, option_type_value)
s, t, K, r_d, r_f, v, delta_type_value, option_type_value)
inverse_delta_out = norminvcdf(np.abs(delta_out))
inv_obj_fn = inverse_delta_target - inverse_delta_out

Expand All @@ -278,7 +278,7 @@ def delta_fit(K, *args):
int64, float64, float64[:]), fastmath=True, cache=False)
def solver_for_smile_strike_fast(s, t, rd, rf,
option_type_value,
volatilityTypeValue,
volatility_type_value,
delta_target,
delta_method_value,
initial_guess,
Expand All @@ -289,7 +289,7 @@ def solver_for_smile_strike_fast(s, t, rd, rf,

inverse_delta_target = norminvcdf(np.abs(delta_target))

argtuple = (volatilityTypeValue, s, t, rd, rf, option_type_value,
argtuple = (volatility_type_value, s, t, rd, rf, option_type_value,
delta_method_value, inverse_delta_target, parameters)

K = newton_secant(delta_fit, x0=initial_guess, args=argtuple,
Expand Down Expand Up @@ -401,8 +401,8 @@ def __init__(self,
for_discount_curve: DiscountCurve,
tenors: (list),
atm_vols: (list, np.ndarray),
mktStrangle25DeltaVols: (list, np.ndarray),
riskReversal25DeltaVols: (list, np.ndarray),
ms25DeltaVols: (list, np.ndarray),
rr25DeltaVols: (list, np.ndarray),
atmMethod: FinFXATMMethod = FinFXATMMethod.FWD_DELTA_NEUTRAL,
delta_method: FinFXDeltaMethod = FinFXDeltaMethod.SPOT_DELTA,
volatility_function_type: VolFuncTypes = VolFuncTypes.CLARK):
Expand Down Expand Up @@ -432,16 +432,16 @@ def __init__(self,
if len(atm_vols) != self._num_vol_curves:
raise FinError("Number ATM vols must equal number of tenors")

if len(mktStrangle25DeltaVols) != self._num_vol_curves:
if len(ms25DeltaVols) != self._num_vol_curves:
raise FinError("Number MS25D vols must equal number of tenors")

if len(riskReversal25DeltaVols) != self._num_vol_curves:
if len(rr25DeltaVols) != self._num_vol_curves:
raise FinError("Number RR25D vols must equal number of tenors")

self._tenors = tenors
self._atm_vols = np.array(atm_vols)/100.0
self._mktStrangle25DeltaVols = np.array(mktStrangle25DeltaVols)/100.0
self._riskReversal25DeltaVols = np.array(riskReversal25DeltaVols)/100.0
self._ms25DeltaVols = np.array(ms25DeltaVols)/100.0
self._rr25DeltaVols = np.array(rr25DeltaVols)/100.0

self._atmMethod = atmMethod
self._delta_method = delta_method
Expand Down
Loading

0 comments on commit 928b0ab

Please sign in to comment.