예제 #1
0
    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 = \
            code_to_frequency(_params.fixed_leg_period)
        floating_frequency = code_to_frequency(_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(settlement_date, maturity,
                                  Period(fixed_frequency), calendar,
                                  fixed_convention, fixed_convention, Forward,
                                  False)

        float_schedule = Schedule(settlement_date, maturity,
                                  Period(floating_frequency), calendar,
                                  floating_convention, floating_convention,
                                  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,
                                       settlementDate=settlement_date,
                                       npvDate=settlement_date)

        swap.set_pricing_engine(engine)

        return swap
예제 #2
0
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(
        issue_date,
        maturity,
        Period(tenor),
        index.fixing_calendar,
        index.business_day_convention,
        index.business_day_convention,
        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
예제 #3
0
    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)
예제 #4
0
    def test_bond_schedule_anotherday(self):
        '''Test date calculations and role of settings when evaluation date 
        set to arbitrary date. 

        This test is known to fail with boost 1.42.
        
        '''
        
        todays_date = Date(30, August, 2011) 

        settings = Settings()
        settings.evaluation_date =  todays_date

        calendar = TARGET()
        effective_date = Date(10, Jul, 2006)
        termination_date = calendar.advance(
            effective_date, 10, Years, convention=Unadjusted)

        settlement_days = 3
        face_amount = 100.0
        coupon_rate = 0.05
        redemption = 100.0
        
        fixed_bond_schedule = Schedule(
            effective_date,
            termination_date,
            Period(Annual),
            calendar,
            ModifiedFollowing,
            ModifiedFollowing,
            Backward
        )

        issue_date = effective_date

        bond = FixedRateBond(
            settlement_days,
		    face_amount,
		    fixed_bond_schedule,
		    [coupon_rate],
            ActualActual(ISMA), 
		    Following,
            redemption,
            issue_date
        )

        self.assertEqual(
            calendar.advance(todays_date, 3, Days), bond.settlement_date())
예제 #5
0
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))
예제 #6
0
    def setUp(self):
        calendar = TARGET()
        today_date = today()

        Settings().evaluation_date = today_date

        hazard_rate = SimpleQuote(0.01234)
        probability_curve = FlatHazardRate(0, calendar, hazard_rate, Actual360())
        discount_curve = FlatForward(today_date, 0.06, Actual360())
        issue_date  = today_date
        #calendar.advance(today_date, -1, Years)
        maturity = calendar.advance(issue_date, 10, Years)
        self.convention = Following
        self.schedule = Schedule(issue_date, maturity, Period("3M"), calendar,
                self.convention, self.convention, Rule.TwentiethIMM)
        recovery_rate = 0.4
        self.engine = MidPointCdsEngine(probability_curve, recovery_rate, discount_curve, True)
예제 #7
0
파일: test_swap.py 프로젝트: xie3ge/pyql
    def test_swap_QL(self):
        """
        Test that a swap with fixed coupon = fair rate has an NPV=0
        Create from QL objects
        """

        nominal = 100.0
        fixedConvention = Unadjusted
        floatingConvention = ModifiedFollowing
        fixedFrequency = Annual
        floatingFrequency = Semiannual
        fixedDayCount = Thirty360()
        floatDayCount = Thirty360()
        calendar = TARGET()
        settlement_days = 2

        eval_date = Date(2, January, 2014)
        settings = Settings()
        settings.evaluation_date = eval_date

        settlement_date = calendar.advance(eval_date, settlement_days, Days)
        # must be a business day
        settlement_date = calendar.adjust(settlement_date)

        termStructure = YieldTermStructure(relinkable=True)
        termStructure.link_to(
            FlatForward(settlement_date, 0.05, Actual365Fixed()))

        index = Libor('USD Libor', Period(6, Months), settlement_days,
                      USDCurrency(), calendar, Actual360(), termStructure)

        length = 5
        fixedRate = .05
        floatingSpread = 0.0

        maturity = calendar.advance(settlement_date,
                                    length,
                                    Years,
                                    convention=floatingConvention)

        fixedSchedule = Schedule(settlement_date, maturity,
                                 Period(fixedFrequency), calendar,
                                 fixedConvention, fixedConvention,
                                 Rule.Forward, False)

        floatSchedule = Schedule(settlement_date, maturity,
                                 Period(floatingFrequency), calendar,
                                 floatingConvention, floatingConvention,
                                 Rule.Forward, False)
        engine = DiscountingSwapEngine(termStructure, False, settlement_date,
                                       settlement_date)
        for swap_type in [Payer, Receiver]:
            swap = VanillaSwap(swap_type, nominal, fixedSchedule, fixedRate,
                               fixedDayCount, floatSchedule, index,
                               floatingSpread, floatDayCount, fixedConvention)
            swap.set_pricing_engine(engine)
            fixed_leg = swap.fixed_leg
            floating_leg = swap.floating_leg

            f = swap.fair_rate
            print('fair rate: %f' % f)
            p = swap.net_present_value
            print('NPV: %f' % p)

            swap = VanillaSwap(swap_type, nominal, fixedSchedule, f,
                               fixedDayCount, floatSchedule, index,
                               floatingSpread, floatDayCount, fixedConvention)
            swap.set_pricing_engine(engine)

            p = swap.net_present_value
            print('NPV: %f' % p)
            self.assertAlmostEqual(p, 0)
예제 #8
0
    ))
    print("               expected: {:%}".format(0.9704))

    print("2Y survival probability: {:%}".format(
        hazard_rate_structure.survival_probability(todays_date + Period(2, Years))
    ))
    print("               expected: {:%}".format(0.9418))

    # reprice instruments
    nominal = 1000000.0;
    #Handle<DefaultProbabilityTermStructure> probability(hazardRateStructure);
    engine = MidPointCdsEngine(hazard_rate_structure, recovery_rate, ts_curve)

    cds_schedule = Schedule(
        todays_date, maturities[0], Period(Quarterly), calendar,
        termination_date_convention=Unadjusted,
        date_generation_rule=TwentiethIMM
    )

    cds_3m = CreditDefaultSwap(
        SELLER, nominal, quoted_spreads[0], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_schedule = Schedule(
        todays_date, maturities[1], Period(Quarterly), calendar,
        termination_date_convention=Unadjusted,
        date_generation_rule=TwentiethIMM
    )

    cds_6m = CreditDefaultSwap(
예제 #9
0
payFixed = True

fixedLegFrequency = Annual
fixedLegAdjustment = Unadjusted
fixedLegDayCounter = Thirty360()
fixedRate = 0.04

floatingLegFrequency = Semiannual
spread = 0.0
fixingDays = 2
index = Euribor6M(forecastTermStructure)
floatingLegAdjustment = ModifiedFollowing
floatingLegDayCounter = index.day_counter

fixedSchedule = Schedule(settlementDate, maturity, fixedLegTenor, calendar,
                         fixedLegAdjustment, fixedLegAdjustment, Forward,
                         False)
floatingSchedule = Schedule(settlementDate, maturity, floatingLegTenor,
                            calendar, floatingLegAdjustment,
                            floatingLegAdjustment, Forward, False)
swapEngine = DiscountingSwapEngine(discountTermStructure)

spot = VanillaSwap(Payer, nominal, fixedSchedule, fixedRate,
                   fixedLegDayCounter, floatingSchedule, index, spread,
                   floatingLegDayCounter)
spot.set_pricing_engine(swapEngine)

forwardStart = calendar.advance(settlementDate, 1, Years)
forwardEnd = calendar.advance(forwardStart, length, Years)
fixedSchedule = Schedule(forwardStart, forwardEnd, fixedLegTenor, calendar,
                         fixedLegAdjustment, fixedLegAdjustment, Forward,
예제 #10
0
class CreditDefaultSwapTest(unittest.TestCase):
    calendar = TARGET()
    today_date = today()

    Settings().evaluation_date = today_date

    hazard_rate = SimpleQuote(0.01234)
    probability_curve = FlatHazardRate(0, calendar, hazard_rate, Actual360())
    discount_curve = FlatForward(today_date, 0.06, Actual360())
    issue_date  = today_date
    #calendar.advance(today_date, -1, Years)
    maturity = calendar.advance(issue_date, 10, Years)
    convention = Following
    schedule = Schedule(issue_date, maturity, Period("3M"), calendar, convention,
                            convention, TwentiethIMM)
    recovery_rate = 0.4
    engine = MidPointCdsEngine(probability_curve, recovery_rate, discount_curve, True)

    def test_fair_spread(self):
        fixed_rate = 0.001
        day_count = Actual360()
        notional = 10000

        cds = CreditDefaultSwap(SELLER, notional, fixed_rate, self.schedule,
                                self.convention, day_count, True, True)
        cds.set_pricing_engine(self.engine)

        fair_rate = cds.fair_spread
        fair_cds = CreditDefaultSwap(SELLER, notional, fair_rate, self.schedule,
                                     self.convention, day_count, True, True)
        fair_cds.set_pricing_engine(self.engine)

        self.assertAlmostEqual(fair_cds.npv, 0.)

    def test_fair_upfront(self):
        fixed_rate = 0.05
        upfront = 0.001
        day_count = Actual360()
        notional = 10000

        cds = CreditDefaultSwap.from_upfront(SELLER, notional, upfront, fixed_rate,
                                             self.schedule,
                                             self.convention, day_count, True, True)
        cds.set_pricing_engine(self.engine)

        fair_upfront = cds.fair_upfront
        fair_cds = CreditDefaultSwap.from_upfront(SELLER, notional, fair_upfront,
                                                  fixed_rate, self.schedule,
                                                  self.convention, day_count, True, True)
        fair_cds.set_pricing_engine(self.engine)

        self.assertAlmostEqual(fair_cds.npv, 0.)

        # same with null upfront
        upfront = 0.
        cds2 = CreditDefaultSwap.from_upfront(SELLER, notional, upfront,
                                              fixed_rate, self.schedule,
                                              self.convention, day_count, True, True)
        cds2.set_pricing_engine(self.engine)
        fair_upfront2 = cds.fair_upfront
        fair_cds2 = CreditDefaultSwap.from_upfront(SELLER, notional, fair_upfront,
                                                   fixed_rate, self.schedule,
                                                   self.convention, day_count, True, True)
        fair_cds2.set_pricing_engine(self.engine)
        self.assertAlmostEqual(fair_cds2.npv, 0.)