aboutsummaryrefslogtreecommitdiffstats
path: root/python/tests
diff options
context:
space:
mode:
Diffstat (limited to 'python/tests')
-rw-r--r--python/tests/test_cds.py7
-rw-r--r--python/tests/test_cms_spread.py128
-rw-r--r--python/tests/test_dates.py12
-rw-r--r--python/tests/test_index.py15
-rw-r--r--python/tests/test_scenarios.py51
-rw-r--r--python/tests/test_swap_index.py12
-rw-r--r--python/tests/test_swaption.py7
-rw-r--r--python/tests/test_tranche_basket.py2
-rw-r--r--python/tests/test_upfront_cds.py189
-rw-r--r--python/tests/test_yieldcurve.py63
10 files changed, 326 insertions, 160 deletions
diff --git a/python/tests/test_cds.py b/python/tests/test_cds.py
index bdaf6db6..3cab9211 100644
--- a/python/tests/test_cds.py
+++ b/python/tests/test_cds.py
@@ -8,11 +8,8 @@ import numpy as np
from quantlib.settings import Settings
from quantlib.time.api import Date
-import sys
-
-sys.path.append("..")
-from analytics import CreditIndex
-from yieldcurve import YC, ql_to_jp, get_curve
+from serenitas.analytics import CreditIndex
+from serenitas.analytics.yieldcurve import YC, ql_to_jp, get_curve
class TestUpfront(unittest.TestCase):
diff --git a/python/tests/test_cms_spread.py b/python/tests/test_cms_spread.py
index dbf3f218..777aee86 100644
--- a/python/tests/test_cms_spread.py
+++ b/python/tests/test_cms_spread.py
@@ -2,37 +2,46 @@ import datetime
import math
import numpy as np
import unittest
-from analytics.cms_spread import (
- build_spread_index, VolatilityType,
- get_swaption_vol_data, get_swaption_vol_matrix, get_cms_coupons,
- get_params, _call_integrand, h_call, h_put, CmsSpread)
+from serenitas.analytics.cms_spread import (
+ build_spread_index,
+ VolatilityType,
+ get_swaption_vol_data,
+ get_swaption_vol_matrix,
+ get_cms_coupons,
+ get_params,
+ _call_integrand,
+ h_call,
+ h_put,
+ CmsSpread,
+)
from quantlib.quotes import SimpleQuote
-from quantlib.time.api import (Actual365Fixed, Days, Date, ModifiedFollowing,
- Period, Years)
-from yieldcurve import YC
-from quantlib.cashflows.conundrum_pricer import (
- AnalyticHaganPricer, YieldCurveModel)
-from quantlib.experimental.coupons.cms_spread_coupon import (
- CappedFlooredCmsSpreadCoupon)
+from quantlib.time.api import (
+ Actual365Fixed,
+ Days,
+ Date,
+ ModifiedFollowing,
+ Period,
+ Years,
+)
+from serenitas.analytics.yieldcurve import YC
+from quantlib.cashflows.conundrum_pricer import AnalyticHaganPricer, YieldCurveModel
+from quantlib.experimental.coupons.cms_spread_coupon import CappedFlooredCmsSpreadCoupon
from quantlib.experimental.coupons.lognormal_cmsspread_pricer import (
- LognormalCmsSpreadPricer)
+ LognormalCmsSpreadPricer,
+)
from scipy.special import roots_hermitenorm
from scipy.integrate import quad
import ctypes
-class TestCmsSpread(unittest.TestCase):
+class TestCmsSpread(unittest.TestCase):
def setUp(self):
self.trade_date = datetime.date(2018, 1, 19)
option_tenor = Period(2, Years)
maturity = Date.from_datetime(self.trade_date) + Period(2, Years)
spread_index, self.yc = build_spread_index(30, 2)
- fixing_date = (spread_index.
- fixing_calendar.
- adjust(maturity, ModifiedFollowing))
- payment_date = (spread_index.
- fixing_calendar.
- advance(fixing_date, 2, Days))
+ fixing_date = spread_index.fixing_calendar.adjust(maturity, ModifiedFollowing)
+ payment_date = spread_index.fixing_calendar.advance(fixing_date, 2, Days)
accrued_end_date = payment_date
accrued_start_date = accrued_end_date - Period(1, Years)
@@ -46,21 +55,22 @@ class TestCmsSpread(unittest.TestCase):
end_date=accrued_end_date,
fixing_days=spread_index.fixing_days,
index=spread_index,
- gearing=1.,
+ gearing=1.0,
spread=-self.cap,
- floor=0.,
+ floor=0.0,
day_counter=Actual365Fixed(),
- is_in_arrears=True)
+ is_in_arrears=True,
+ )
- self.cms2y, self.cms30y = get_cms_coupons(self.trade_date,
- self.notional,
- option_tenor,
- spread_index)
+ self.cms2y, self.cms30y = get_cms_coupons(
+ self.trade_date, self.notional, option_tenor, spread_index
+ )
evaluation_date = datetime.date(2018, 8, 23)
self.yc.link_to(YC(evaluation_date=evaluation_date, extrapolation=True))
self.yc.extrapolation = True
- date, surf = get_swaption_vol_data(date=evaluation_date,
- vol_type=VolatilityType.ShiftedLognormal)
+ date, surf = get_swaption_vol_data(
+ date=evaluation_date, vol_type=VolatilityType.ShiftedLognormal
+ )
atm_vol = get_swaption_vol_matrix(evaluation_date, surf)
μ = SimpleQuote(0.1)
self.ρ = SimpleQuote(0.8)
@@ -69,55 +79,77 @@ class TestCmsSpread(unittest.TestCase):
self.cms30y.set_pricer(self.cms_pricer)
self.params = get_params(self.cms2y, self.cms30y, atm_vol)
cms_spread_pricer = LognormalCmsSpreadPricer(
- self.cms_pricer,
- self.ρ,
- integration_points=20)
+ self.cms_pricer, self.ρ, integration_points=20
+ )
self.cms30y2y_cap.set_pricer(cms_spread_pricer)
def test_black_model(self):
x, w = roots_hermitenorm(16)
- val_call = 1 / math.sqrt(2 * math.pi) * np.dot(w,
- h_call(x, self.cap, *self.params, self.ρ.value))
- val_put = 1 / math.sqrt(2 * math.pi) * np.dot(w,
- h_put(x, self.cap, *self.params, self.ρ.value))
- self.assertAlmostEqual(self.cms30y2y_cap.rate,
- val_call)
+ val_call = (
+ 1
+ / math.sqrt(2 * math.pi)
+ * np.dot(w, h_call(x, self.cap, *self.params, self.ρ.value))
+ )
+ val_put = (
+ 1
+ / math.sqrt(2 * math.pi)
+ * np.dot(w, h_put(x, self.cap, *self.params, self.ρ.value))
+ )
+ self.assertAlmostEqual(self.cms30y2y_cap.rate, val_call)
self.assertAlmostEqual(-self.cms30y2y_cap.underlying.rate, val_put - val_call)
- self.assertAlmostEqual(self.cms30y.rate - self.cms2y.rate - self.cap,
- self.cms30y2y_cap.underlying.rate)
+ self.assertAlmostEqual(
+ self.cms30y.rate - self.cms2y.rate - self.cap,
+ self.cms30y2y_cap.underlying.rate,
+ )
def test_h1_hcall(self):
args = (self.cap, *self.params, self.ρ.value)
h1_capsule = _call_integrand.function
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
- ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
- ptr_type = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_int, ctypes.POINTER(ctypes.c_double))
+ ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [
+ ctypes.py_object,
+ ctypes.c_char_p,
+ ]
+ ptr_type = ctypes.CFUNCTYPE(
+ ctypes.c_double, ctypes.c_int, ctypes.POINTER(ctypes.c_double)
+ )
# Get the function pointer from the capsule "capsule_mul"
- h1_fun = ptr_type(ctypes.pythonapi.PyCapsule_GetPointer(h1_capsule, b"double (int, double *)"))
+ h1_fun = ptr_type(
+ ctypes.pythonapi.PyCapsule_GetPointer(h1_capsule, b"double (int, double *)")
+ )
x = np.linspace(-5, 5, 11)
- b = h_call(x, *args) * np.exp(-0.5* x * x)
+ b = h_call(x, *args) * np.exp(-0.5 * x * x)
i = 0
for x in np.linspace(-5, 5, 11):
full_args = np.array((x, *args))
a = h1_fun(9, full_args.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
self.assertAlmostEqual(a, b[i])
- i+= 1
+ i += 1
def test_scipy_integrate(self):
x, w = roots_hermitenorm(20)
val_call = np.dot(w, h_call(x, self.cap, *self.params, self.ρ.value))
args = (self.cap, *self.params, self.ρ.value)
- val, _ = quad(_call_integrand, -np.inf, np.inf, args=(self.cap, *self.params, self.ρ.value))
+ val, _ = quad(
+ _call_integrand,
+ -np.inf,
+ np.inf,
+ args=(self.cap, *self.params, self.ρ.value),
+ )
self.assertAlmostEqual(val, val_call)
def test_CmsSpread(self):
- trade = CmsSpread(None, 2, 30, 0.0075835, Period(2, Years), value_date=self.trade_date)
+ trade = CmsSpread(
+ None, 2, 30, 0.0075835, Period(2, Years), value_date=self.trade_date
+ )
trade1 = CmsSpread.from_tradeid(1)
trade.value_date = datetime.date(2018, 8, 23)
trade1.value_date = datetime.date(2018, 8, 23)
- self.assertAlmostEqual(self.cms30y2y_cap.rate * 1e8 * self.yc.discount(self.cms2y.fixing_date),
- trade.pv)
+ self.assertAlmostEqual(
+ self.cms30y2y_cap.rate * 1e8 * self.yc.discount(self.cms2y.fixing_date),
+ trade.pv,
+ )
self.assertAlmostEqual(trade.pv, trade1.pv)
diff --git a/python/tests/test_dates.py b/python/tests/test_dates.py
index 1437bba4..f9054700 100644
--- a/python/tests/test_dates.py
+++ b/python/tests/test_dates.py
@@ -2,20 +2,14 @@ import unittest
import datetime
import pandas as pd
-import sys
-
-sys.path.append("..")
-from analytics.utils import roll_date
-from analytics.tranche_functions import cds_accrued, credit_schedule
+from serenitas.analytics.utils import roll_date, days_accrued
+from serenitas.analytics.tranche_functions import cds_accrued, credit_schedule
from pyisda.date import (
roll_date as roll_date_c,
cds_accrued as cds_accrued_c,
previous_twentieth,
- pydate_to_TDate,
- TDate_to_pydate,
)
-from dates import days_accrued
-from yieldcurve import get_curve
+from serenitas.analytics.yieldcurve import get_curve
class TestStartDate(unittest.TestCase):
diff --git a/python/tests/test_index.py b/python/tests/test_index.py
index a4ef886a..89677bbe 100644
--- a/python/tests/test_index.py
+++ b/python/tests/test_index.py
@@ -1,12 +1,9 @@
import unittest
import datetime
-import numpy as np
-from pyisda.cdsone import upfront_charge
-
-from analytics import CreditIndex, ForwardIndex
-from analytics.basket_index import BasketIndex
-from analytics.index import g
+from serenitas.analytics.index import CreditIndex, ForwardIndex
+from serenitas.analytics.basket_index import BasketIndex
+from serenitas.analytics.index import g
import pickle
@@ -65,13 +62,15 @@ class TestForwardIndex(unittest.TestCase):
exercise_date = datetime.date(2016, 8, 19)
fi = ForwardIndex(index, exercise_date)
- def test_forward_pv(self):
+ def test_forward_annuity(self):
"""default adjusted forward spread and forward annuity match"""
+ # TODO: check what's going on
self.assertAlmostEqual(
self.fi.forward_pv,
self.fi.forward_annuity
- * (self.fi.index.fixed_rate - self.forward_spread)
+ * (self.fi.forward_spread - self.fi.index.fixed_rate)
* 1e-4,
+ 4,
)
def test_forward_pv(self):
diff --git a/python/tests/test_scenarios.py b/python/tests/test_scenarios.py
index 1f1f6bf3..0bcce027 100644
--- a/python/tests/test_scenarios.py
+++ b/python/tests/test_scenarios.py
@@ -2,20 +2,30 @@ import unittest
import numpy as np
import pandas as pd
-from analytics import (CreditIndex, BlackSwaption, Portfolio,
- BlackSwaptionVolSurface)
+from serenitas.analytics import (
+ CreditIndex,
+ BlackSwaption,
+ Portfolio,
+ BlackSwaptionVolSurface,
+)
from pandas.tseries.offsets import BDay
-from analytics.scenarios import (run_portfolio_scenarios,
- run_swaption_scenarios, run_index_scenarios)
+from serenitas.analytics.scenarios import (
+ run_portfolio_scenarios,
+ run_swaption_scenarios,
+ run_index_scenarios,
+)
class TestSenarios(unittest.TestCase):
option_delta = CreditIndex.from_tradeid(874)
option1 = BlackSwaption.from_tradeid(7, option_delta)
option2 = BlackSwaption.from_tradeid(8, option_delta)
- portf = Portfolio([option1, option2, option_delta], trade_ids=['opt1', 'opt2', 'delta'])
- date_range = pd.bdate_range(option_delta.value_date,
- pd.Timestamp('2017-05-17') - BDay(), freq='5B')
+ portf = Portfolio(
+ [option1, option2, option_delta], trade_ids=["opt1", "opt2", "delta"]
+ )
+ date_range = pd.bdate_range(
+ option_delta.value_date, pd.Timestamp("2017-05-17") - BDay(), freq="5B"
+ )
def test_portfolio(self):
""" check that run_portfolio_scenarios match the sum of the individual pieces"""
@@ -23,20 +33,25 @@ class TestSenarios(unittest.TestCase):
spread_shock = np.arange(-0.2, 0.3, 0.01)
vs = BlackSwaptionVolSurface("IG", 28, value_date=self.option_delta.value_date)
vol_surface = vs[vs.list(source="BAML")[-1]]
- df = run_portfolio_scenarios(self.portf, self.date_range,
- spread_shock=spread_shock,
- vol_shock=vol_shock,
- vol_surface=vol_surface)
- df1 = run_swaption_scenarios(self.option1, self.date_range,
- spread_shock, vol_shock, vol_surface, ["pnl"])
- df2 = run_swaption_scenarios(self.option2, self.date_range,
- spread_shock, vol_shock, vol_surface, ["pnl"])
+ df = run_portfolio_scenarios(
+ self.portf,
+ self.date_range,
+ spread_shock=spread_shock,
+ vol_shock=vol_shock,
+ vol_surface=vol_surface,
+ )
+ df1 = run_swaption_scenarios(
+ self.option1, self.date_range, spread_shock, vol_shock, vol_surface, ["pnl"]
+ )
+ df2 = run_swaption_scenarios(
+ self.option2, self.date_range, spread_shock, vol_shock, vol_surface, ["pnl"]
+ )
df_index = run_index_scenarios(self.option_delta, self.date_range, spread_shock)
df_swaptions = df1 + df2
- df_swaptions = df_swaptions.reset_index(level='vol_shock')
+ df_swaptions = df_swaptions.reset_index(level="vol_shock")
df_orig = df_index.add(df_swaptions, fill_value=0)
- df_orig = df_orig.set_index('vol_shock', append=True)
- self.assertFalse(np.any((df.sum(axis=1).values-df_orig['pnl'].values)))
+ df_orig = df_orig.set_index("vol_shock", append=True)
+ self.assertFalse(np.any((df.sum(axis=1).values - df_orig["pnl"].values)))
if __name__ == "__main__":
diff --git a/python/tests/test_swap_index.py b/python/tests/test_swap_index.py
index f2816bac..c197559a 100644
--- a/python/tests/test_swap_index.py
+++ b/python/tests/test_swap_index.py
@@ -1,17 +1,21 @@
import unittest
-import sys
from quantlib.indexes.swap.usd_libor_swap import UsdLiborSwapIsdaFixAm
from quantlib.time.api import Date, Period, Years
-from yieldcurve import YC
+from serenitas.analytics.yieldcurve import YC
+
class UsdLiborSwap(unittest.TestCase):
def test_creation(self):
yc = YC()
yc.extrapolation = True
- USISDA30 = UsdLiborSwapIsdaFixAm(Period(30, Years), forwarding=yc, discounting=yc)
+ USISDA30 = UsdLiborSwapIsdaFixAm(
+ Period(30, Years), forwarding=yc, discounting=yc
+ )
USISDA30.add_fixing(Date(25, 1, 2018), 0.02781)
- USISDA02 = UsdLiborSwapIsdaFixAm(Period(2, Years), forwarding=yc, discounting=yc)
+ USISDA02 = UsdLiborSwapIsdaFixAm(
+ Period(2, Years), forwarding=yc, discounting=yc
+ )
USISDA02.add_fixing(Date(25, 1, 2018), 0.02283)
USFS022 = USISDA02.underlying_swap(Date(27, 1, 2020))
USFS0230 = USISDA30.underlying_swap(Date(27, 1, 2020))
diff --git a/python/tests/test_swaption.py b/python/tests/test_swaption.py
index 64b7e71c..ee777603 100644
--- a/python/tests/test_swaption.py
+++ b/python/tests/test_swaption.py
@@ -1,11 +1,8 @@
import unittest
import datetime
-import sys
-
-sys.path.append("..")
-from analytics.index import g
-from analytics import CreditIndex, Swaption, BlackSwaption
+from serenitas.analytics.index import g
+from serenitas.analytics import CreditIndex, Swaption, BlackSwaption
class TestPutCallParity(unittest.TestCase):
diff --git a/python/tests/test_tranche_basket.py b/python/tests/test_tranche_basket.py
index 34be0af2..63fe2347 100644
--- a/python/tests/test_tranche_basket.py
+++ b/python/tests/test_tranche_basket.py
@@ -1,6 +1,6 @@
import unittest
import datetime
-from analytics import DualCorrTranche, TrancheBasket
+from serenitas.analytics import DualCorrTranche, TrancheBasket
import numpy as np
import pickle
diff --git a/python/tests/test_upfront_cds.py b/python/tests/test_upfront_cds.py
index b9fd4beb..66a2f122 100644
--- a/python/tests/test_upfront_cds.py
+++ b/python/tests/test_upfront_cds.py
@@ -1,15 +1,37 @@
-from quantlib.time.api import (WeekendsOnly, today, Years, Months,
- Period, Date, Actual365Fixed, Actual360,
- Quarterly, Following, Unadjusted, Schedule,
- pydate_from_qldate, Rule)
+from quantlib.time.api import (
+ WeekendsOnly,
+ today,
+ Years,
+ Months,
+ Period,
+ Date,
+ Actual365Fixed,
+ Actual360,
+ Quarterly,
+ Following,
+ Unadjusted,
+ Schedule,
+ pydate_from_qldate,
+ Rule,
+)
from quantlib.instruments.api import CreditDefaultSwap, Side
from quantlib.pricingengines.credit.isda_cds_engine import (
- IsdaCdsEngine, ForwardsInCouponPeriod, NumericalFix, AccrualBias)
-from quantlib.termstructures.default_term_structure import DefaultProbabilityTermStructure
+ IsdaCdsEngine,
+ ForwardsInCouponPeriod,
+ NumericalFix,
+ AccrualBias,
+)
+from quantlib.termstructures.default_term_structure import (
+ DefaultProbabilityTermStructure,
+)
from quantlib.termstructures.credit.api import (
- UpfrontCdsHelper, SpreadCdsHelper, PiecewiseDefaultCurve, FlatHazardRate)
+ UpfrontCdsHelper,
+ SpreadCdsHelper,
+ PiecewiseDefaultCurve,
+ FlatHazardRate,
+)
from quantlib.settings import Settings
-from yieldcurve import YC, rate_helpers, getMarkitIRData
+from serenitas.analytics.yieldcurve import YC, rate_helpers, getMarkitIRData
import pandas as pd
from pyisda.curve import YieldCurve, SpreadCurve
from pyisda.utils import build_yc
@@ -20,42 +42,91 @@ import array
import math
import numpy as np
+
def snac_pv(spread, term_date, fixed_coupon=0.01, recovery=0.4, ts=YC()):
settings = Settings()
calendar = WeekendsOnly()
- cds_helper = SpreadCdsHelper(spread, Period(57, Months), 1, calendar,
- Quarterly, Following, Rule.CDS, Actual360(), recovery, ts,
- lastperiod = Actual360(True))
- cds_helper.set_isda_engine_parameters(int(NumericalFix.Taylor), int(AccrualBias.HalfDayBias),
- int(ForwardsInCouponPeriod.Flat))
- pdc = PiecewiseDefaultCurve("SurvivalProbability", "LogLinear",
- settings.evaluation_date, [cds_helper], Actual365Fixed())
- isda_pricer = IsdaCdsEngine(pdc, recovery, ts, False,
- forwards_in_coupon_period=ForwardsInCouponPeriod.Piecewise,
- accrual_bias=AccrualBias.HalfDayBias)
+ cds_helper = SpreadCdsHelper(
+ spread,
+ Period(57, Months),
+ 1,
+ calendar,
+ Quarterly,
+ Following,
+ Rule.CDS,
+ Actual360(),
+ recovery,
+ ts,
+ lastperiod=Actual360(True),
+ )
+ cds_helper.set_isda_engine_parameters(
+ int(NumericalFix.Taylor),
+ int(AccrualBias.HalfDayBias),
+ int(ForwardsInCouponPeriod.Flat),
+ )
+ pdc = PiecewiseDefaultCurve(
+ "SurvivalProbability",
+ "LogLinear",
+ settings.evaluation_date,
+ [cds_helper],
+ Actual365Fixed(),
+ )
+ isda_pricer = IsdaCdsEngine(
+ pdc,
+ recovery,
+ ts,
+ False,
+ forwards_in_coupon_period=ForwardsInCouponPeriod.Piecewise,
+ accrual_bias=AccrualBias.HalfDayBias,
+ )
protect_start = settings.evaluation_date + 1
- cds_schedule = Schedule(protect_start, term_date, Period(Quarterly), calendar,
- Following, Unadjusted, Rule.CDS)
- cds_trade = CreditDefaultSwap(BUYER, 100, fixed_coupon, cds_schedule, Following, Actual360(),
- protection_start = protect_start,
- last_period_day_counter = Actual360(True))
+ cds_schedule = Schedule(
+ protect_start,
+ term_date,
+ Period(Quarterly),
+ calendar,
+ Following,
+ Unadjusted,
+ Rule.CDS,
+ )
+ cds_trade = CreditDefaultSwap(
+ BUYER,
+ 100,
+ fixed_coupon,
+ cds_schedule,
+ Following,
+ Actual360(),
+ protection_start=protect_start,
+ last_period_day_counter=Actual360(True),
+ )
cds_trade.set_pricing_engine(isda_pricer)
return cds_trade, cds_helper, isda_pricer
+
def jpmorgan_curves(trade_date, value_date, start_date, end_date, spread, recovery=0.4):
yc = build_yc(trade_date, True)
step_in_date = trade_date + datetime.timedelta(days=1)
- spread = array.array('d', [spread])
- recovery = array.array('d', [recovery])
- sc = SpreadCurve(trade_date, yc, start_date, step_in_date,
- value_date, [end_date], spread, recovery, True)
+ spread = array.array("d", [spread])
+ recovery = array.array("d", [recovery])
+ sc = SpreadCurve(
+ trade_date,
+ yc,
+ start_date,
+ step_in_date,
+ value_date,
+ [end_date],
+ spread,
+ recovery,
+ True,
+ )
return yc, sc
-if __name__=="__main__":
+
+if __name__ == "__main__":
settings = Settings()
settings.evaluation_date = Date(21, 5, 2009)
yield_helpers = rate_helpers()
- ts = YC(helpers = yield_helpers)
+ ts = YC(helpers=yield_helpers)
tenor = Period(5, Years)
trade_date = datetime.date(2009, 5, 21)
stepin_date = trade_date + datetime.timedelta(days=1)
@@ -63,34 +134,62 @@ if __name__=="__main__":
term_date = datetime.date(2019, 6, 20)
start_date = datetime.date(2009, 3, 20)
spread = 0.001
- yc, sc = jpmorgan_curves(trade_date, value_date, start_date, term_date, spread, recovery = 0.4)
- sc_data = sc.inspect()['data']
+ yc, sc = jpmorgan_curves(
+ trade_date, value_date, start_date, term_date, spread, recovery=0.4
+ )
+ sc_data = sc.inspect()["data"]
hazard_rate = math.log(1 + sc_data[0][1])
contingent_leg = ContingentLeg(start_date, term_date, 10000000)
fee_leg = FeeLeg(start_date, term_date, True, 10000000, 0.01)
flat_curve = FlatHazardRate(0, WeekendsOnly(), hazard_rate, Actual365Fixed())
- cds_schedule = Schedule(Date.from_datetime(trade_date), Date.from_datetime(term_date),
- Period(Quarterly), WeekendsOnly(),
- Following, Unadjusted, CDS)
- cds_trade = CreditDefaultSwap.from_upfront(BUYER, 10000000, 0., 0.01, cds_schedule, Following, Actual360(),
- protection_start = Date.from_datetime(trade_date) + 1,
- last_period_day_counter = Actual360(True))
- isda_pricer = IsdaCdsEngine(flat_curve, 0.4, ts, accrual_bias=AccrualBias.HalfDayBias,
- forwards_in_coupon_period = ForwardsInCouponPeriod.Piecewise)
- #795915.9787
+ cds_schedule = Schedule(
+ Date.from_datetime(trade_date),
+ Date.from_datetime(term_date),
+ Period(Quarterly),
+ WeekendsOnly(),
+ Following,
+ Unadjusted,
+ CDS,
+ )
+ cds_trade = CreditDefaultSwap.from_upfront(
+ BUYER,
+ 10000000,
+ 0.0,
+ 0.01,
+ cds_schedule,
+ Following,
+ Actual360(),
+ protection_start=Date.from_datetime(trade_date) + 1,
+ last_period_day_counter=Actual360(True),
+ )
+ isda_pricer = IsdaCdsEngine(
+ flat_curve,
+ 0.4,
+ ts,
+ accrual_bias=AccrualBias.HalfDayBias,
+ forwards_in_coupon_period=ForwardsInCouponPeriod.Piecewise,
+ )
+ # 795915.9787
cds_trade.set_pricing_engine(isda_pricer)
- cds_trade2 = CreditDefaultSwap(BUYER, 10000000, spread, cds_schedule, Following, Actual360(),
- protection_start = Date.from_datetime(trade_date) + 1,
- last_period_day_counter = Actual360(True))
- #h = cds_trade2.implied_hazard_rate(0., ts)
+ cds_trade2 = CreditDefaultSwap(
+ BUYER,
+ 10000000,
+ spread,
+ cds_schedule,
+ Following,
+ Actual360(),
+ protection_start=Date.from_datetime(trade_date) + 1,
+ last_period_day_counter=Actual360(True),
+ )
+ # h = cds_trade2.implied_hazard_rate(0., ts)
h = 0.00168276528775
flat_curve2 = FlatHazardRate(0, WeekendsOnly(), h, Actual365Fixed())
isda_pricer2 = IsdaCdsEngine(flat_curve2, 0.4, ts)
cds_trade.set_pricing_engine(isda_pricer2)
print(cds_trade.fair_upfront)
- #hazard_rate = 0.12649393489974806
+ # hazard_rate = 0.12649393489974806
# cds_trade.set_pricing_engine(isda_pricer)
# cds_trade2 = CreditDefaultSwap.from_upfront(BUYER, 10000000, 0., 0.01, cds_schedule,
diff --git a/python/tests/test_yieldcurve.py b/python/tests/test_yieldcurve.py
index 21693b77..8a684fda 100644
--- a/python/tests/test_yieldcurve.py
+++ b/python/tests/test_yieldcurve.py
@@ -1,36 +1,65 @@
import unittest
from quantlib.time.api import (
- Date, Period, Quarterly, Schedule, Rule, WeekendsOnly,
- Following, Unadjusted)
+ Date,
+ Period,
+ Quarterly,
+ Schedule,
+ Rule,
+ WeekendsOnly,
+ Following,
+ Unadjusted,
+)
from quantlib.settings import Settings
-import sys
-sys.path.append('..')
-from yieldcurve import YC
+from serenitas.analytics.yieldcurve import YC
-class TestYieldCurve(unittest.TestCase):
- def assertListAlmostEqual(self, list1, list2, places = 7):
+class TestYieldCurve(unittest.TestCase):
+ def assertListAlmostEqual(self, list1, list2, places=7):
self.assertEqual(len(list1), len(list2))
for a, b in zip(list1, list2):
self.assertAlmostEqual(a, b, places)
def test_bloomberg(self):
- discounts = [0.99848606, 0.99548212, 0.99167201, 0.98772518,
- 0.98629694, 0.98509013, 0.98389804, 0.98268094,
- 0.97993369, 0.97709955, 0.97430462, 0.97145583,
- 0.96827211, 0.9651054, 0.96194904, 0.95869946,
- 0.95499459, 0.95125679, 0.94753361, 0.94382501]
+ discounts = [
+ 0.99848606,
+ 0.99548212,
+ 0.99167201,
+ 0.98772518,
+ 0.98629694,
+ 0.98509013,
+ 0.98389804,
+ 0.98268094,
+ 0.97993369,
+ 0.97709955,
+ 0.97430462,
+ 0.97145583,
+ 0.96827211,
+ 0.9651054,
+ 0.96194904,
+ 0.95869946,
+ 0.95499459,
+ 0.95125679,
+ 0.94753361,
+ 0.94382501,
+ ]
settings = Settings()
settings.evaluation_date = Date(23, 6, 2016)
curve = YC()
term_date = Date(20, 6, 2021)
cds_schedule = Schedule.from_rule(
- settings.evaluation_date, term_date, Period(Quarterly),
- WeekendsOnly(), Following, Unadjusted, Rule.CDS2015)
+ settings.evaluation_date,
+ term_date,
+ Period(Quarterly),
+ WeekendsOnly(),
+ Following,
+ Unadjusted,
+ Rule.CDS2015,
+ )
curve_df = [curve.discount(d) for d in cds_schedule[1:-1]]
- #last date is term_date+1
- curve_df.append(curve.discount(term_date+1))
+ # last date is term_date+1
+ curve_df.append(curve.discount(term_date + 1))
self.assertListAlmostEqual(discounts, curve_df)
-if __name__=="__main__":
+
+if __name__ == "__main__":
unittest.main()