Skip to content

Commit

Permalink
Added logging to test files and some small changes
Browse files Browse the repository at this point in the history
  • Loading branch information
domokane committed Sep 1, 2020
1 parent 2710f82 commit 016c2c1
Show file tree
Hide file tree
Showing 23 changed files with 314 additions and 284 deletions.
22 changes: 19 additions & 3 deletions financepy/finutils/FinHelperFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane
##############################################################################

import sys
import numpy as np
from numba import njit
from typing import Union
Expand All @@ -13,6 +14,15 @@
###############################################################################


def _funcName():
''' Extract calling function name - using a protected method is not that
advisable but calling inspect.stack is so slow it must be avoided. '''
ff = sys._getframe().f_back.f_code.co_name
return ff

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


def betaVectorToCorrMatrix(betas):
''' Convert a one-factor vector of factor weights to a square correlation
matrix. '''
Expand Down Expand Up @@ -57,6 +67,9 @@ def timesFromDates(dt: FinDate,
times from the valuation date. The output is always a numpy vector of times
which has only one element if the input is only one date. '''

if isinstance(valuationDate, FinDate) is False:
raise FinError("Valuation date is not a FinDate")

if dayCountType is None:
dcCounter = None
else:
Expand All @@ -68,17 +81,20 @@ def timesFromDates(dt: FinDate,
if dcCounter is None:
times[0] = (dt - valuationDate) / gDaysInYear
else:
times[0] = dcCounter.yearFrac(valuationDate, dt)
return np.array(times)
times[0] = dcCounter.yearFrac(valuationDate, dt)[0]

return times[0]

elif isinstance(dt, list) and isinstance(dt[0], FinDate):
numDates = len(dt)
times = []
for i in range(0, numDates):
if dcCounter is None:
t = (dt[i] - valuationDate) / gDaysInYear
else:
t = dcCounter.yearFrac(valuationDate, dt)
t = dcCounter.yearFrac(valuationDate, dt[i])[0]
times.append(t)

return np.array(times)

elif isinstance(dt, np.ndarray):
Expand Down
4 changes: 2 additions & 2 deletions financepy/finutils/FinMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def normcdf_integrate(x: float):
fx = exp(-x * x / 2.0)
integral = fx / 2.0

for i in range(0, numSteps - 1):
for _ in range(0, numSteps - 1):
x = x + dx
fx = exp(-x * x / 2.0)
integral += fx
Expand Down Expand Up @@ -445,7 +445,7 @@ def phi3(b1: float,

v = 0.0

for i in range(1, numPoints + 1):
for _ in range(1, numPoints + 1):
dp = N(x + dx) - N(x)
h = (b2 - r12 * x) / r12p
k = (b3 - r13 * x) / r13p
Expand Down
61 changes: 34 additions & 27 deletions tests/TestFinBondOptionBKModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ def test_FinBondOption():

tmat = (maturityDate - settlementDate) / gDaysInYear
times = np.linspace(0, tmat, 20)
dates = settlementDate.addYears(times)
dfs = np.exp(-0.05*times)
discountCurve = FinDiscountCurve(settlementDate, times, dfs)
discountCurve = FinDiscountCurve(settlementDate, dates, dfs)

expiryDate = settlementDate.addTenor("18m")
strikePrice = 105.0
Expand Down Expand Up @@ -183,13 +184,9 @@ def test_FinBondOptionAmericanConvergenceONE():
strikePrice = 100.0
face = 100.0

spotValue = bond.valueBondUsingDiscountCurve(settlementDate,
discountCurve)
spotValue = bond.valueBondUsingDiscountCurve(settlementDate, discountCurve)

texp = (expiryDate - settlementDate) / gDaysInYear
dfExpiry = discountCurve.df(texp)
tmat = (maturityDate - settlementDate) / gDaysInYear
dfMat = discountCurve.df(tmat)
dfExpiry = discountCurve.df(expiryDate)

fwdValue = bond.valueBondUsingDiscountCurve(expiryDate, discountCurve)/dfExpiry

Expand All @@ -199,7 +196,7 @@ def test_FinBondOptionAmericanConvergenceONE():
testCases.header("PERIOD", "N", "PUT_AMER", "PUT_EUR",
"CALL_AME", "CALL_EUR")

timeSteps = range(10, 100, 1)
timeSteps = range(30, 100, 1)

for numTimeSteps in timeSteps:

Expand Down Expand Up @@ -258,7 +255,8 @@ def test_FinBondOptionAmericanConvergenceTWO():
testCases.header("LABEL", "VALUE")
testCases.print("BOND PRICE", spotValue)

testCases.header("PERIOD","N","EUR_CALL","AMER_CALL","EUR_PUT","AMER_PUT")
testCases.header("PERIOD", "N", "EUR_CALL", "AMER_CALL",
"EUR_PUT", "AMER_PUT")

sigma = 0.2
a = 0.1
Expand All @@ -270,32 +268,44 @@ def test_FinBondOptionAmericanConvergenceTWO():
vec_ep = []
vec_ap = []

if 1==1:
if 1 == 1:
K = 100.0
bkModel = FinModelRatesBK(sigma, a, 100)
europeanCallBondOption = FinBondOption(bond, expiryDate, K, face, FinOptionTypes.EUROPEAN_CALL)
v_ec = europeanCallBondOption.value(settlementDate, discountCurve, bkModel)
print("OPTION", v_ec)
europeanCallBondOption = FinBondOption(bond, expiryDate, K, face,
FinOptionTypes.EUROPEAN_CALL)

v_ec = europeanCallBondOption.value(settlementDate, discountCurve,
bkModel)
testCases.header("LABEL", "VALUE")
testCases.print("OPTION", v_ec)

numStepsVector = range(100, 100, 1) # should be 100-400
numStepsVector = range(100, 100, 1) # should be 100-400

for numSteps in numStepsVector:

bkModel = FinModelRatesBK(sigma, a, numSteps)

start = time.time()

europeanCallBondOption = FinBondOption(bond, expiryDate, K, face, FinOptionTypes.EUROPEAN_CALL)
v_ec = europeanCallBondOption.value(settlementDate, discountCurve, bkModel)
europeanCallBondOption = FinBondOption(bond, expiryDate, K, face,
FinOptionTypes.EUROPEAN_CALL)
v_ec = europeanCallBondOption.value(settlementDate, discountCurve,
bkModel)

americanCallBondOption = FinBondOption(bond, expiryDate, K, face, FinOptionTypes.AMERICAN_CALL)
v_ac = americanCallBondOption.value(settlementDate, discountCurve, bkModel)
americanCallBondOption = FinBondOption(bond, expiryDate, K, face,
FinOptionTypes.AMERICAN_CALL)
v_ac = americanCallBondOption.value(settlementDate, discountCurve,
bkModel)

europeanPutBondOption = FinBondOption(bond, expiryDate, K, face, FinOptionTypes.EUROPEAN_PUT)
v_ep = europeanPutBondOption.value(settlementDate, discountCurve, bkModel)
europeanPutBondOption = FinBondOption(bond, expiryDate, K, face,
FinOptionTypes.EUROPEAN_PUT)
v_ep = europeanPutBondOption.value(settlementDate, discountCurve,
bkModel)

americanPutBondOption = FinBondOption(bond, expiryDate, K, face, FinOptionTypes.AMERICAN_PUT)
v_ap = americanPutBondOption.value(settlementDate, discountCurve, bkModel)
americanPutBondOption = FinBondOption(bond, expiryDate, K, face,
FinOptionTypes.AMERICAN_PUT)
v_ap = americanPutBondOption.value(settlementDate, discountCurve,
bkModel)

end = time.time()
period = end - start
Expand Down Expand Up @@ -323,13 +333,10 @@ def test_FinBondOptionAmericanConvergenceTWO():
plt.plot(numStepsVector, vec_ap, label="American Put")
plt.legend()



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


#test_FinBondOption()
#test_FinBondOptionAmericanConvergenceONE()
test_FinBondOption()
# test_FinBondOptionAmericanConvergenceONE()
test_FinBondOptionAmericanConvergenceTWO()
testCases.compareTestCases()

32 changes: 12 additions & 20 deletions tests/TestFinCDS.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def test_CDSCurveRepricing():
valuationDate = FinDate(2018, 6, 20)
recoveryRate = 0.40

cdsContracts, issuerCurve = test_CurveBuild()
cdsContracts, issuerCurve = test_IssuerCurveBuild()
testCases.header("CDS_MATURITY_DATE", "PAR_SPREAD")
for cds in cdsContracts:
spd = cds.parSpread(valuationDate, issuerCurve, recoveryRate)
Expand All @@ -100,30 +100,24 @@ def test_CDSCurveRepricing():

def test_CDSCurveBuildTiming():

numCurves = 10
numCurves = 1000

start = time.time()
for i in range(0, numCurves):
test_CurveBuild()
for _ in range(0, numCurves):
test_IssuerCurveBuild()

end = time.time()

testCases.header("Label", "TIME")
testCases.header("LABEL", "TIME")
duration = (end - start) / numCurves
testCases.print(str(numCurves) + " Libor curves", duration)

start = time.time()
for i in range(0, numCurves):
buildFullIssuerCurve1(0, 0)
end = time.time()

duration = (end - start) / numCurves
testCases.print(str(numCurves) + " Libor + CDS curves:", duration)

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


def test_CurveBuild():
def test_IssuerCurveBuild():
''' Test issuer curve build with simple libor curve to isolate cds
curve building time cost. '''

valuationDate = FinDate(2018, 6, 20)

Expand Down Expand Up @@ -354,9 +348,6 @@ def buildFullIssuerCurve1(mktSpreadBump, irBump):
cds = FinCDS(valuationDate, maturityDate, cdsCoupon)
cdsMarketContracts.append(cds)

# for cds in cdsMarketContracts:
# print("CDS Maturity Date",cds._maturityDate)

recoveryRate = 0.40

issuerCurve = FinCDSCurve(settlementDate,
Expand Down Expand Up @@ -661,7 +652,7 @@ def test_fullPriceCDSModelCheck():

def test_fullPriceCDSConvergence():

liborCurve, issuerCurve = buildFullIssuerCurve1(0.0, 0.0)
_, issuerCurve = buildFullIssuerCurve1(0.0, 0.0)

# This is the 10 year contract at an off market coupon
maturityDate = FinDate(2029, 6, 20)
Expand Down Expand Up @@ -718,12 +709,13 @@ def test_CDSDateGeneration():
##########################################################################


test_fullPriceCDSModelCheck()

test_CDSCurveBuildTiming()
#test_fullPriceCDSModelCheck()
#test_CDSDateGeneration()
#test_fullPriceCDS1()
#test_fullPriceCDSConvergence()
#test_CDSCurveBuildTiming()
#test_CDSCurveRepricing()
#test_CDSFastApproximation()

#testCases.compareTestCases()
2 changes: 2 additions & 0 deletions tests/TestFinCDSCurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane
###############################################################################

import numpy as np

from FinTestCases import FinTestCases, globalTestCaseMode

from financepy.products.credit.FinCDS import FinCDS
Expand Down
7 changes: 4 additions & 3 deletions tests/TestFinCDSIndexAdjustHazards.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
# TO DO
##########################################################################

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


def buildLiborCurve(tradeDate):

Expand Down Expand Up @@ -245,7 +243,8 @@ def test_performCDSIndexHazardRateAdjustment():
import time
start = time.time()

adjustedIssuerCurves = FinCDSIndexPortfolio.hazardRateAdjustIntrinsic(
indexPortfolio = FinCDSIndexPortfolio()
adjustedIssuerCurves = indexPortfolio.hazardRateAdjustIntrinsic(
valuationDate,
issuerCurves,
indexCoupons,
Expand Down Expand Up @@ -295,6 +294,8 @@ def test_performCDSIndexHazardRateAdjustment():
testCases.print("ADJUSTED INTRINSIC SPD 7Y", intrinsicSpd7Y)
testCases.print("ADJUSTED INTRINSIC SPD 10Y", intrinsicSpd10Y)

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


test_performCDSIndexHazardRateAdjustment()
testCases.compareTestCases()
15 changes: 8 additions & 7 deletions tests/TestFinCDSIndexAdjustSpreads.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@
##########################################################################


def buildLiborCurve(tradeDate):
def buildLiborCurve(valuationDate):

valuationDate = tradeDate.addDays(1)
dcType = FinDayCountTypes.ACT_360

depos = []
Expand Down Expand Up @@ -91,9 +90,8 @@ def buildLiborCurve(tradeDate):
##########################################################################


def buildIssuerCurve(tradeDate, liborCurve):
def buildIssuerCurve(valuationDate, liborCurve):

valuationDate = tradeDate.addDays(1)
cdsMarketContracts = []

cdsCoupon = 0.0048375
Expand All @@ -115,9 +113,9 @@ def buildIssuerCurve(tradeDate, liborCurve):

def test_CDSIndexAdjustSpreads():

tradeDate = FinDate(2007, 8, 1)
tradeDate = FinDate(1, 8, 2007)
stepInDate = tradeDate.addDays(1)
valuationDate = stepInDate
valuationDate = tradeDate

liborCurve = buildLiborCurve(tradeDate)

Expand Down Expand Up @@ -240,7 +238,8 @@ def test_CDSIndexAdjustSpreads():
import time
start = time.time()

adjustedIssuerCurves = FinCDSIndexPortfolio.spreadAdjustIntrinsic(
indexPortfolio = FinCDSIndexPortfolio()
adjustedIssuerCurves = indexPortfolio.spreadAdjustIntrinsic(
valuationDate,
issuerCurves,
indexCoupons,
Expand Down Expand Up @@ -282,6 +281,8 @@ def test_CDSIndexAdjustSpreads():
testCases.print("ADJUSTED INTRINSIC SPD 7Y", intrinsicSpd7Y)
testCases.print("ADJUSTED INTRINSIC SPD 10Y", intrinsicSpd10Y)

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


test_CDSIndexAdjustSpreads()
testCases.compareTestCases()
Loading

0 comments on commit 016c2c1

Please sign in to comment.