def test_create_swap_rate_helper_from_index(self): calendar = UnitedStates() settlement_days = 2 currency = USDCurrency() fixed_leg_tenor = Period(12, Months) fixed_leg_convention = ModifiedFollowing fixed_leg_daycounter = Actual360() family_name = currency.name + 'index' ibor_index = Libor( "USDLibor", Period(3,Months), settlement_days, USDCurrency(), UnitedStates(), Actual360() ) rate = SimpleQuote(0.005681) tenor = Period(1, Years) index = SwapIndex ( family_name, tenor, settlement_days, currency, calendar, fixed_leg_tenor, fixed_leg_convention, fixed_leg_daycounter, ibor_index) helper = SwapRateHelper.from_index(rate, index) #self.fail( # 'Make this pass: create and ask for the .quote property' # ' Test the from_index and from_tenor methods' #) self.assertIsNotNone(helper) self.assertAlmostEquals(rate.value, helper.quote) with self.assertRaises(RuntimeError): self.assertAlmostEquals(rate.value, helper.implied_quote)
def test_create_swap_index(self): settings = Settings.instance() # Market information calendar = TARGET() # must be a business day eval_date = calendar.adjust(today()) settings.evaluation_date = eval_date settlement_days = 2 settlement_date = calendar.advance(eval_date, settlement_days, Days) # must be a business day settlement_date = calendar.adjust(settlement_date) term_structure = YieldTermStructure(relinkable=True) term_structure.link_to(FlatForward(settlement_date, 0.05, Actual365Fixed())) ibor_index = Libor('USD Libor', Period(6, Months), settlement_days, USDCurrency(), calendar, Actual360(), term_structure) index = SwapIndex( 'family name', Period(3, Months), 10, USDCurrency(), TARGET(), Period(12, Months), Following, Actual360(), ibor_index) self.assertIsNotNone(index)
def test_create_interpolated_hazard(self): Settings.instance().evaluation_date = self.todays_date dates = [self.todays_date + Period(i, Years) for i in [3, 5, 7]] hazard_rates = [0.01, 0.03, 0.05] interpolation_date = self.todays_date + Period(4, Years) trait = Interpolator.Linear interpolated_curve = InterpolatedHazardRateCurve( trait, dates, hazard_rates, Actual365Fixed()) t0 = interpolated_curve.time_from_reference(dates[0]) t1 = interpolated_curve.time_from_reference(interpolation_date) t2 = interpolated_curve.time_from_reference(dates[1]) interpolated_value = hazard_rates[0] + (t1-t0) /(t2-t0) * \ (hazard_rates[1] - hazard_rates[0]) self.assertAlmostEqual( interpolated_value, interpolated_curve.hazard_rate(interpolation_date)) trait = Interpolator.BackwardFlat interpolated_curve = InterpolatedHazardRateCurve( trait, dates, hazard_rates, Actual365Fixed()) interpolated_value = hazard_rates[1] self.assertAlmostEqual( interpolated_value, interpolated_curve.hazard_rate(interpolation_date)) trait = Interpolator.LogLinear interpolated_curve = InterpolatedHazardRateCurve( trait, dates, hazard_rates, Actual365Fixed()) with self.assertRaisesRegexp( RuntimeError, 'LogInterpolation primitive not implemented'): hazard_rate = interpolated_curve.hazard_rate(interpolation_date)
def make_rate_helper(market, quote, reference_date=None): """ Wrapper for deposit and swaps rate helpers makers TODO: class method of RateHelper? """ rate_type, tenor, quote_value = quote if rate_type == 'SWAP': libor_index = market._floating_rate_index spread = SimpleQuote(0) fwdStart = Period(0, Days) helper = SwapRateHelper.from_tenor( quote_value, Period(tenor), market._floating_rate_index.fixing_calendar, code_to_frequency(market._params.fixed_leg_period), BusinessDayConvention.from_name( market._params.fixed_leg_convention), DayCounter.from_name(market._params.fixed_leg_daycount), libor_index, spread, fwdStart) elif rate_type == 'DEP': end_of_month = True helper = DepositRateHelper( quote_value, Period(tenor), market._params.settlement_days, market._floating_rate_index.fixing_calendar, market._floating_rate_index.business_day_convention, end_of_month, DayCounter.from_name(market._deposit_daycount)) elif rate_type == 'ED': if reference_date is None: raise Exception("Reference date needed with ED Futures data") forward_date = next_imm_date(reference_date, tenor) helper = FuturesRateHelper( rate=SimpleQuote(quote_value), imm_date=qldate_from_pydate(forward_date), length_in_months=3, calendar=market._floating_rate_index.fixing_calendar, convention=market._floating_rate_index.business_day_convention, end_of_month=True, day_counter=DayCounter.from_name( market._params.floating_leg_daycount)) elif rate_type.startswith('ER'): # TODO For Euribor futures, we found it useful to supply the `imm_date` # parameter directly, instead of as a number of periods from the # evaluation date, as for ED futures. To achieve this, we pass the # `imm_date` in the `tenor` field of the quote. helper = FuturesRateHelper( rate=SimpleQuote(quote_value), imm_date=tenor, length_in_months=3, calendar=market._floating_rate_index.fixing_calendar, convention=market._floating_rate_index.business_day_convention, end_of_month=True, day_counter=DayCounter.from_name( market._params.floating_leg_daycount)) else: raise Exception("Rate type %s not supported" % rate_type) return helper
def test_create_libor_index(self): settings = Settings.instance() # Market information calendar = UnitedStates(LiborImpact) # must be a business day eval_date = calendar.adjust(today()) settings.evaluation_date = eval_date settlement_days = 2 settlement_date = calendar.advance(eval_date, settlement_days, Days) # must be a business day settlement_date = calendar.adjust(settlement_date) term_structure = YieldTermStructure(relinkable=True) term_structure.link_to( FlatForward(settlement_date, 0.05, Actual365Fixed())) index = Libor('USDLibor', Period(6, Months), settlement_days, USDCurrency(), calendar, Actual360(), term_structure) default_libor = USDLibor(Period(6, Months)) for attribute in [ "business_day_convention", "end_of_month", "fixing_calendar", "joint_calendar", "tenor", "fixing_days", "day_counter", "family_name", "name" ]: self.assertEqual(getattr(index, attribute), getattr(default_libor, attribute))
def test_makecds(self): cds = (MakeCreditDefaultSwap(Period( 5, Years), 0.01).with_date_generation_rule(CDS2015)()) self.assertEqual(cds.cash_settlement_days, 3) self.assertEqual( cds.protection_end_date, cds_maturity(Settings().evaluation_date, Period(5, Years), CDS2015))
def setUp(self): Settings().evaluation_date = Date(27, 4, 2018) self.yc = FlatForward(forward=0.03, settlement_days=2, daycounter=Actual365Fixed(), calendar=UnitedStates()) self.index = UsdLiborSwapIsdaFixAm(Period(10, Years), self.yc) self.factory = (MakeSwaption(self.index, Period(2, Years), strike=0.0206). with_underlying_type(Receiver). with_settlement_type(Cash). with_settlement_method(ParYieldCurve))
def test_hull_white_calibration(self): """ Adapted from ShortRateModelTest::testCachedHullWhite() """ today = Date(15, February, 2002) settlement = Date(19, February, 2002) self.settings.evaluation_date = today yield_ts = FlatForward(settlement, forward=0.04875825, settlement_days=0, calendar=NullCalendar(), daycounter=Actual365Fixed()) model = HullWhite(yield_ts, a=0.05, sigma=.005) data = [[1, 5, 0.1148 ], [2, 4, 0.1108 ], [3, 3, 0.1070 ], [4, 2, 0.1021 ], [5, 1, 0.1000 ]] index = Euribor6M(yield_ts) engine = JamshidianSwaptionEngine(model) swaptions = [] for start, length, volatility in data: vol = SimpleQuote(volatility) helper = SwaptionHelper(Period(start, Years), Period(length, Years), vol, index, Period(1, Years), Thirty360(), Actual360(), yield_ts) helper.set_pricing_engine(engine) swaptions.append(helper) # Set up the optimization problem om = LevenbergMarquardt(1.0e-8, 1.0e-8, 1.0e-8) endCriteria = EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8) model.calibrate(swaptions, om, endCriteria) print('Hull White calibrated parameters:\na: %f sigma: %f' % (model.a, model.sigma)) cached_a = 0.0464041 cached_sigma = 0.00579912 tolerance = 1.0e-5 self.assertAlmostEqual(cached_a, model.a, delta=tolerance) self.assertAlmostEqual(cached_sigma, model.sigma, delta=tolerance)
def create_fixed_float_swap(self, settlement_date, length, fixed_rate, floating_spread, **kwargs): """ Create a fixed-for-float swap given: - settlement date - length in years - additional arguments to modify market default parameters """ _params = self._params._replace(**kwargs) index = IborIndex.from_name(self._market, self._forecast_term_structure, **kwargs) swap_type = Payer nominal = 100.0 fixed_convention = \ BusinessDayConvention.from_name(_params.fixed_leg_convention) floating_convention = \ BusinessDayConvention.from_name(_params.floating_leg_convention) fixed_frequency = \ Period(_params.fixed_leg_period) floating_frequency = Period(_params.floating_leg_period) fixed_daycount = DayCounter.from_name(_params.fixed_leg_daycount) float_daycount = DayCounter.from_name(_params.floating_leg_daycount) calendar = calendar_from_name(_params.calendar) maturity = calendar.advance(settlement_date, length, Years, convention=floating_convention) fixed_schedule = Schedule.from_rule(settlement_date, maturity, fixed_frequency, calendar, fixed_convention, fixed_convention, Rule.Forward, False) float_schedule = Schedule.from_rule(settlement_date, maturity, floating_frequency, calendar, floating_convention, floating_convention, Rule.Forward, False) swap = VanillaSwap(swap_type, nominal, fixed_schedule, fixed_rate, fixed_daycount, float_schedule, index, floating_spread, float_daycount, fixed_convention) engine = DiscountingSwapEngine(self._discount_term_structure, False, settlement_date=settlement_date, npv_date=settlement_date) swap.set_pricing_engine(engine) return swap
def example03(): print("example 3:\n") todays_date = Date(13, 6, 2011) Settings.instance().evaluation_date = todays_date quotes = [0.00445, 0.00949, 0.01234, 0.01776, 0.01935, 0.02084] tenors = [1, 2, 3, 6, 9, 12] calendar = WeekendsOnly() deps = [ DepositRateHelper(q, Period(t, Months), 2, calendar, ModifiedFollowing, False, Actual360()) for q, t in zip(quotes, tenors) ] quotes = [ 0.01652, 0.02018, 0.02303, 0.02525, 0.0285, 0.02931, 0.03017, 0.03092, 0.03160, 0.03231, 0.03367, 0.03419, 0.03411, 0.03411, 0.03412 ] tenors = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 25, 30] swaps = [ SwapRateHelper.from_tenor(q, Period(t, Years), calendar, Annual, ModifiedFollowing, Thirty360(), Euribor6M(), SimpleQuote(0)) for q, t in zip(quotes, tenors) ] yield_helpers = deps + swaps isda_yts = PiecewiseYieldCurve(BootstrapTrait.Discount, Interpolator.LogLinear, 0, WeekendsOnly(), yield_helpers, Actual365Fixed()) spreads = [0.007927, 0.012239, 0.016979, 0.019271, 0.020860] tenors = [1, 3, 5, 7, 10] spread_helpers = [SpreadCdsHelper(0.007927, Period(6, Months), 1, WeekendsOnly(), Quarterly, Following, Rule.CDS2015, Actual360(), 0.4, isda_yts, True, True, Date(), Actual360(True), True, PricingModel.ISDA)] + \ [SpreadCdsHelper(s, Period(t, Years), 1, WeekendsOnly(), Quarterly, Following, Rule.CDS2015, Actual360(), 0.4, isda_yts, True, True, Date(), Actual360(True), True, PricingModel.ISDA) for s, t in zip(spreads, tenors)] isda_cts = PiecewiseDefaultCurve(ProbabilityTrait.SurvivalProbability, Interpolator.LogLinear, 0, WeekendsOnly(), spread_helpers, Actual365Fixed()) isda_pricer = IsdaCdsEngine(isda_cts, 0.4, isda_yts) print("Isda yield curve:") for h in yield_helpers: d = h.latest_date t = isda_yts.time_from_reference(d) print(d, t, isda_yts.zero_rate(d, Actual365Fixed()).rate) print() print("Isda credit curve:") for h in spread_helpers: d = h.latest_date t = isda_cts.time_from_reference(d) print(d, t, isda_cts.survival_probability(d))
def build_helpers(): calendar = TARGET() settlement_days = 2 depositData = [[1, Months, 'Libor1M', 5.32], [3, Months, 'Libor3M', 5.35], [6, Months, 'Libor6M', 5.35]] swapData = [[1, Years, 'Swap1Y', 5.31], [2, Years, 'Swap2Y', 5.06], [3, Years, 'Swap3Y', 5.00], [4, Years, 'Swap4Y', 5.01], [5, Years, 'Swap5Y', 5.04], [7, Years, 'Swap7Y', 5.12], [10, Years, 'Swap10Y', 5.22], [30, Years, 'Swap30Y', 5.44]] rate_helpers = [] end_of_month = True for m, _, _, rate in depositData: tenor = Period(m, Months) helper = DepositRateHelper(SimpleQuote(rate / 100.0), tenor, settlement_days, calendar, ModifiedFollowing, end_of_month, Actual360()) rate_helpers.append(helper) liborIndex = Libor('USD Libor', Period(3, Months), settlement_days, USDCurrency(), calendar, Actual360()) spread = SimpleQuote(0) fwdStart = Period(0, Days) for m, _, _, rate in swapData: helper = SwapRateHelper.from_tenor( SimpleQuote(rate / 100.0), Period(m, Years), calendar, Semiannual, ModifiedFollowing, Thirty360(), liborIndex, spread, fwdStart) rate_helpers.append(helper) return rate_helpers
def setUp(self): atm_option_tenors = [Period(1, Months), Period(6, Months)] + \ [Period(i, Years) for i in [1, 5, 10, 30]] atm_swap_tenors = [Period(1, Years), Period(5, Years), Period(10, Years), Period(30, Years)] m = np.array([[.1300, .1560, .1390, .1220], [.1440, .1580, .1460, .1260], [.1600, .1590, .1470, .1290], [.1640, .1470, .1370, .1220], [.1400, .1300, .1250, .1100], [.1130, .1090, .1070, .0930]]) M = Matrix.from_ndarray(m) calendar = UnitedStates() self.atm_vol = SwaptionVolatilityMatrix(calendar, Following, atm_option_tenors, atm_swap_tenors, M, Actual365Fixed()) reference_date = calendar.adjust(today()) Settings().evaluation_date = reference_date self.term_structure = FlatForward(reference_date, 0.05, Actual365Fixed()) self.swap_index = EuriborSwapIsdaFixA(Period(10, Years), forwarding=self.term_structure)
class FlatHazardRateTestCase(unittest.TestCase): calendar = TARGET() todays_date = Date(15, May, 2007) todays_date = calendar.adjust(todays_date) d = todays_date + Period(3, Years) def test_create_flat_hazard(self): Settings.instance().evaluation_date = self.todays_date flat_curve = FlatHazardRate(2, self.calendar, 0.05, Actual365Fixed()) flat_curve_from_reference_date = FlatHazardRate.from_reference_date( self.calendar.advance(self.todays_date, 2, Days), 0.05, Actual365Fixed()) self.assertIsNotNone(flat_curve) self.assertIsNotNone(flat_curve_from_reference_date) self.assertEqual( flat_curve.time_from_reference(self.d), flat_curve_from_reference_date.time_from_reference(self.d)) self.assertAlmostEqual(flat_curve.hazard_rate(self.d), 0.05) self.assertAlmostEqual( flat_curve.survival_probability(self.d), math.exp(-0.05 * flat_curve.time_from_reference(self.d))) def test_flat_hazard_with_quote(self): Settings.instance().evaluation_date = self.todays_date hazard_rate = SimpleQuote() flat_curve = FlatHazardRate(2, self.calendar, hazard_rate, Actual365Fixed()) for h in [0.01, 0.02, 0.03]: hazard_rate.value = h self.assertAlmostEqual( flat_curve.survival_probability(self.d), math.exp(-h * flat_curve.time_from_reference(self.d)))
def test_create_fixed_rate_bond_helper(self): issue_date = Date(20, 3, 2014) maturity = Date(20, 3, 2019) schedule = Schedule( issue_date, maturity, Period(Annual), TARGET(), ModifiedFollowing, ModifiedFollowing, Backward, False ) clean_price = 71.23 settlement_days = 3 rates = [0.035] daycounter = DayCounter.from_name("Actual/Actual (Bond)") helper = FixedRateBondHelper( SimpleQuote(clean_price), settlement_days, 100.0, schedule, rates, daycounter, Following, 100.0, issue_date) self.assertEqual(helper.quote, clean_price)
def test_bump_yieldcurve(self): settings = Settings() settings.evaluation_date = Date(6, 10, 2016) # Market information calendar = TARGET() quotes = [SimpleQuote(0.0096), SimpleQuote(0.0145), SimpleQuote(0.0194)] tenors = [3, 6, 12] deposit_day_counter = Actual365Fixed() convention = ModifiedFollowing end_of_month = True fixing_days = 3 rate_helpers = [DepositRateHelper( quote, Period(month, Months), fixing_days, calendar, convention, end_of_month, deposit_day_counter) for quote, month in zip(quotes, tenors)] ts_day_counter = ActualActual(ISDA) tolerance = 1.0e-15 ts = PiecewiseYieldCurve( BootstrapTrait.Discount, Interpolator.LogLinear, 2, calendar, rate_helpers, ts_day_counter, tolerance ) old_discount = ts.discount(ts.max_date) # parallel shift of 1 bps for rh in rate_helpers: rh.quote.value += 1e-4 self.assertEqual([q.value for q in quotes], [rh.quote.value for rh in rate_helpers]) new_discount = ts.discount(ts.max_date) self.assertTrue(new_discount < old_discount)
def test_create_libor_index(self): settings = Settings.instance() # Market information calendar = TARGET() # must be a business day eval_date = calendar.adjust(today()) settings.evaluation_date = eval_date settlement_days = 2 settlement_date = calendar.advance(eval_date, settlement_days, Days) # must be a business day settlement_date = calendar.adjust(settlement_date) term_structure = YieldTermStructure(relinkable=True) term_structure.link_to( FlatForward(settlement_date, 0.05, Actual365Fixed())) index = Libor('USD Libor', Period(6, Months), settlement_days, USDCurrency(), calendar, Actual360(), term_structure) t = index.tenor self.assertEquals(t.length, 6) self.assertEquals(t.units, 2) self.assertEquals('USD Libor6M Actual/360', index.name)
def test_discount_curve(self): settings = Settings() settings.evaluation_date = Date(6, 10, 2016) # Market information calendar = TARGET() quotes = [SimpleQuote(0.0096), SimpleQuote(0.0145), SimpleQuote(0.0194)] tenors = [3, 6, 12] deposit_day_counter = Actual365Fixed() convention = ModifiedFollowing end_of_month = True fixing_days = 3 rate_helpers = [DepositRateHelper( quote, Period(month, Months), fixing_days, calendar, convention, end_of_month, deposit_day_counter) for quote, month in zip(quotes, tenors)] ts_day_counter = ActualActual(ISDA) tolerance = 1.0e-15 ts = PiecewiseYieldCurve( BootstrapTrait.ForwardRate, Interpolator.BackwardFlat, 2, calendar, rate_helpers, ts_day_counter, tolerance ) dates = [rh.latest_date for rh in rate_helpers] dfs = [ts.discount(d) for d in dates] dates.insert(0, ts.reference_date) dfs.insert(0, 1) ts_discount = DiscountCurve(dates, dfs, ts_day_counter, calendar) self.assertTrue(ts.discount(0.75), ts_discount.discount(0.75))
def make_eurobond_helper(market, clean_price, coupons, tenor, issue_date, maturity): """ Wrapper for bond helpers. FIXME: This convenience method has some conventions specifically hardcoded for Eurobonds. These should be moved to the market. """ # Create schedule based on market and bond parameters. index = market._floating_rate_index schedule = Schedule.from_rule( issue_date, maturity, Period(tenor), index.fixing_calendar, index.business_day_convention, index.business_day_convention, Rule.Backward, # Date generation rule index.end_of_month, ) daycounter = DayCounter.from_name("Actual/Actual (Bond)") helper = FixedRateBondHelper( SimpleQuote(clean_price), market._params.settlement_days, 100.0, schedule, coupons, daycounter, Following, # Payment convention 100.0, issue_date) return helper
def create_helper(): calendar = TARGET() todays_date = Date(15, May, 2007) todays_date = calendar.adjust(todays_date) Settings.instance().evaluation_date = todays_date flat_rate = SimpleQuote(0.01) ts_curve = FlatForward(todays_date, flat_rate, Actual365Fixed()) recovery_rate = 0.5 quoted_spreads = 0.0150 tenor = Period(5, Years) helper = SpreadCdsHelper(quoted_spreads, tenor, 0, calendar, Quarterly, Following, Rule.TwentiethIMM, Actual365Fixed(), recovery_rate, ts_curve, model=PricingModel.Midpoint) return todays_date, helper
def make_rate_helper(label, rate, dt_obs, currency='USD'): """ Wrapper for deposit and swaps rate helpers makers For Swaps: assume USD swap fixed rates vs. 6M Libor TODO: make this more general """ if(currency.upper() != 'USD'): raise Exception("Only supported currency is USD.") rate_type, tenor, period = _parse_rate_label(label) if not isinstance(dt_obs, Date): dt_obs = pydate_to_qldate(dt_obs) settings = Settings() calendar = JointCalendar(UnitedStates(), UnitedKingdom()) # must be a business day eval_date = calendar.adjust(dt_obs) settings.evaluation_date = eval_date settlement_days = 2 settlement_date = calendar.advance(eval_date, settlement_days, Days) # must be a business day settlement_date = calendar.adjust(settlement_date) end_of_month = True if((rate_type == 'SWAP') & (period == 'Y')): liborIndex = Libor( 'USD Libor', Period(6, Months), settlement_days, USDCurrency(), calendar, Actual360() ) spread = SimpleQuote(0) fwdStart = Period(0, Days) helper = SwapRateHelper.from_tenor(rate, Period(tenor, Years), calendar, Annual, Unadjusted, Thirty360(), liborIndex, spread, fwdStart) elif((rate_type == 'LIBOR') & (period == 'M')): helper = DepositRateHelper(rate, Period(tenor, Months), settlement_days, calendar, ModifiedFollowing, end_of_month, Actual360()) else: raise Exception("Rate type %s not supported" % label) return (helper)
def example02(): print("example 2:\n") todays_date = Date(25, 9, 2014) Settings.instance().evaluation_date = todays_date calendar = TARGET() term_date = calendar.adjust(todays_date + Period(2, Years), Following) cds_schedule = Schedule(todays_date, term_date, Period(Quarterly), WeekendsOnly(), ModifiedFollowing, ModifiedFollowing, date_generation_rule=Rule.CDS) for date in cds_schedule: print(date) print() todays_date = Date(21, 10, 2014) Settings.instance().evaluation_date = todays_date quotes = [0.00006, 0.00045, 0.00081, 0.001840, 0.00256, 0.00337] tenors = [1, 2, 3, 6, 9, 12] deps = [DepositRateHelper(q, Period(t, Months), 2, calendar, ModifiedFollowing, False, Actual360()) for q, t in zip(quotes, tenors)] tenors = [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 30] quotes = [0.00223, 0.002760, 0.003530, 0.004520, 0.005720, 0.007050, 0.008420, 0.009720, 0.010900, 0.012870, 0.014970, 0.017, 0.01821] swaps = [SwapRateHelper.from_tenor(q, Period(t, Years), calendar, Annual, ModifiedFollowing, Thirty360(), Euribor6M(), SimpleQuote(0)) for q, t in zip(quotes, tenors)] helpers = deps + swaps YC = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.Discount, Interpolator.LogLinear, todays_date, helpers, Actual365Fixed()) YC.extrapolation = True print("ISDA rate curve:") for h in helpers: print("{0}: {1:.6f}\t{2:.6f}".format(h.latest_date, YC.zero_rate(h.latest_date, Actual365Fixed(), 2).rate, YC.discount(h.latest_date))) defaultTs0 = FlatHazardRate(0, WeekendsOnly(), 0.016739207493630, Actual365Fixed()) cds_schedule = Schedule.from_rule(Date(22, 9, 2014), Date(20, 12, 2019), Period(3, Months), WeekendsOnly(), Following, Unadjusted, Rule.CDS, False) nominal = 100000000 trade = CreditDefaultSwap(Side.Buyer, nominal, 0.01, cds_schedule, Following, Actual360(), True, True, Date(22, 10, 2014), Actual360(True), True) engine = IsdaCdsEngine(defaultTs0, 0.4, YC, False) trade.set_pricing_engine(engine) print("reference trade NPV = {0}\n".format(trade.npv))
def test_creation(self): settlement_date = Date(1, January, 2014) term_structure = YieldTermStructure() term_structure.link_to( FlatForward(settlement_date, 0.05, Actual365Fixed())) index = USDLibor(Period(3, Months), term_structure) self.assertEqual(index.name, 'USDLibor3M Actual/360')
def test_creation(self): settings = Settings() # Market information calendar = TARGET() # must be a business day settings.evaluation_date = calendar.adjust(today()) settlement_date = Date(18, September, 2008) # must be a business day settlement_date = calendar.adjust(settlement_date); quotes = [SimpleQuote(0.0096), SimpleQuote(0.0145), SimpleQuote(0.0194)] tenors = [3, 6, 12] rate_helpers = [] calendar = TARGET() deposit_day_counter = Actual365Fixed() convention = ModifiedFollowing end_of_month = True for quote, month in zip(quotes, tenors): tenor = Period(month, Months) fixing_days = 3 helper = DepositRateHelper( quote, tenor, fixing_days, calendar, convention, end_of_month, deposit_day_counter ) rate_helpers.append(helper) ts_day_counter = ActualActual(ISDA) tolerance = 1.0e-15 ts = PiecewiseYieldCurve[BootstrapTrait.Discount, LogLinear].from_reference_date( settlement_date, rate_helpers, ts_day_counter, accuracy=tolerance ) self.assertIsNotNone(ts) self.assertEqual( Date(18, September, 2008), ts.reference_date) # this is not a real test ... self.assertAlmostEqual(0.9975, ts.discount(Date(21, 12, 2008)), 4) self.assertAlmostEqual(0.9944, ts.discount(Date(21, 4, 2009)), 4) self.assertAlmostEqual(0.9904, ts.discount(Date(21, 9, 2009)), 4) dates, dfs = zip(*ts.nodes) self.assertAlmostEqual(list(dates), ts.dates) self.assertAlmostEqual(list(dfs), ts.data)
def test_create_ibor_index(self): euribor6m = IborIndex("Euribor", Period(6, Months), 2, EURCurrency(), TARGET(), ModifiedFollowing, True, Actual360()) default_euribor6m = Euribor6M() for attribute in ["business_day_convention", "end_of_month", "fixing_calendar", "tenor", "fixing_days", "day_counter", "family_name", "name"]: self.assertEqual(getattr(euribor6m, attribute), getattr(default_euribor6m, attribute))
def test_relative_yieldcurve(self): settings = Settings() settings.evaluation_date = Date(6, 10, 2016) # Market information calendar = TARGET() quotes = [0.0096, 0.0145, 0.0194] tenors = [3, 6, 12] deposit_day_counter = Actual365Fixed() convention = ModifiedFollowing end_of_month = True fixing_days = 3 rate_helpers = [ DepositRateHelper(quote, Period(month, Months), fixing_days, calendar, convention, end_of_month, deposit_day_counter) for quote, month in zip(quotes, tenors) ] ts_day_counter = ActualActual(ISDA) tolerance = 1.0e-15 ts_relative = PiecewiseYieldCurve(BootstrapTrait.Discount, Interpolator.LogLinear, 2, calendar, rate_helpers, ts_day_counter, tolerance) self.assertEqual( ts_relative.reference_date, calendar.advance(settings.evaluation_date, period=Period(2, Days))) settings.evaluation_date = Date(10, 10, 2016) settlement_date = calendar.advance(settings.evaluation_date, period=Period(2, Days)) self.assertEqual(ts_relative.reference_date, settlement_date) ts_absolute = PiecewiseYieldCurve.from_reference_date( BootstrapTrait.Discount, Interpolator.LogLinear, settlement_date, rate_helpers, ts_day_counter, tolerance) self.assertEqual(ts_absolute.data, ts_relative.data) self.assertEqual(ts_absolute.dates, ts_relative.dates) self.assertEqual(ts_absolute.times, ts_relative.times)
def setUp(self): self.mean_reversion = SimpleQuote(0.03) self.volatility = SimpleQuote(0.00714) self.index = USDLibor(Period(3, Months)) self.quote = SimpleQuote(99.375) Settings().evaluation_date = Date(13, 10, 2021) self.fut_quote = FuturesConvAdjustmentQuote(self.index, "Z2", self.quote, self.volatility, self.mean_reversion)
def setUp(self): atm_option_tenors = [Period(1, Months), Period(6, Months)] + \ [Period(i, Years) for i in [1, 5, 10, 30]] atm_swap_tenors = [Period(1, Years), Period(5, Years), Period(10, Years), Period(30, Years)] m = np.array([[.1300, .1560, .1390, .1220], [.1440, .1580, .1460, .1260], [.1600, .1590, .1470, .1290], [.1640, .1470, .1370, .1220], [.1400, .1300, .1250, .1100], [.1130, .1090, .1070, .0930]]) M = Matrix.from_ndarray(m) calendar = UnitedStates() self.atm_vol_matrix = SwaptionVolatilityMatrix(calendar, Following, atm_option_tenors, atm_swap_tenors, M, Actual365Fixed()) term_structure = FlatForward(forward=0.05, settlement_days=2, calendar=calendar, daycounter=Actual365Fixed()) self.swap_index_base = EuriborSwapIsdaFixA(Period(2, Years), term_structure) self.short_swap_index_base = EuriborSwapIsdaFixA(Period(1, Years), term_structure) self.vega_weighted_smile_fit = False class Cube: def __init__(self): self.option_tenors = [Period(1, Years), Period(10, Years), Period(30, Years)] self.swap_tenors = [Period(2, Years), Period(10, Years), Period(30, Years)] self.strike_spreads = [-0.02, -0.005, 0, 0.005, 0.02] self.vol_spreads = np.array([[0.0599, 0.0049, 0.0000, -0.0001, 0.0127], [0.0729, 0.0086, 0.0000, -0.0024, 0.0098], [0.0738, 0.0102, 0.0000, -0.0039, 0.0065], [0.0465, 0.0063, 0.0000, -0.0032, -0.0010], [0.0558, 0.0084, 0.0000, -0.0050, -0.0057], [0.0576, 0.0083, 0.0000, -0.0043, -0.0014], [0.0437, 0.0059, 0.0000, -0.0030, -0.0006], [0.0533, 0.0078, 0.0000, -0.0045, -0.0046], [0.0545, 0.0079, 0.0000, -0.0042, -0.0020]]) self.vol_spreads_handle = [] for vs in self.vol_spreads: self.vol_spreads_handle.append([SimpleQuote(v) for v in vs]) self.cube = Cube()
def test_make_swaption(self): swaption = self.factory() self.assertEqual(swaption.settlement_type, Cash) swap = swaption.underlying_swap() self.assertEqual(swap.type, Receiver) exercise_date = self.index.fixing_calendar.advance( Settings().evaluation_date, period=Period(2, Years), convention=ModifiedFollowing) self.assertEqual(swap.start_date, self.index.value_date(exercise_date))
def test_methods(self): Settings.instance().evaluation_date = self.todays_date dates = [self.todays_date + Period(i, Years) for i in [3, 5, 7]] hazard_rates = [0.01, 0.03, 0.05] for trait in [Interpolator.BackwardFlat, Interpolator.Linear]: interpolated_curve = InterpolatedHazardRateCurve( trait, dates, hazard_rates, Actual365Fixed()) self.assertEqual(dates, interpolated_curve.dates) self.assertEqual(interpolated_curve.data, interpolated_curve.hazard_rates)
def test_create_swap_index(self): term_structure = YieldTermStructure() term_structure.link_to( FlatForward(forward=0.05, daycounter=Actual365Fixed(), settlement_days=2, calendar=UnitedStates())) ibor_index = USDLibor(Period(3, Months), term_structure) index = SwapIndex('UsdLiborSwapIsdaFixAm', Period(10, Years), 2, USDCurrency(), UnitedStates(GovernmentBond), Period(6, Months), ModifiedFollowing, Thirty360(), ibor_index) index2 = UsdLiborSwapIsdaFixAm(Period(10, Years), term_structure) for attr in [ 'name', 'family_name', 'fixing_calendar', 'tenor', 'day_counter', 'currency' ]: self.assertEqual(getattr(index, attr), getattr(index2, attr))