Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
    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 test_deposit_end_of_month(self):
        tenor = Period(3, Months)
        fixing_days = 0
        calendar = TARGET()
        convention = ModifiedFollowing
        end_of_month = True
        deposit_day_counter = Actual365Fixed()

        helper_end_of_month = DepositRateHelper(0.005, tenor, fixing_days,
                                                calendar, convention, True,
                                                deposit_day_counter)
        helper_no_end_of_month = DepositRateHelper(0.005, tenor, fixing_days,
                                                   calendar, convention, False,
                                                   deposit_day_counter)
        Settings.instance().evaluation_date = Date(29, 2, 2016)
        self.assertEqual(helper_end_of_month.latest_date, Date(31, 5, 2016))
        self.assertEqual(helper_no_end_of_month.latest_date, Date(30, 5, 2016))
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    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 = [0.0096, 0.0145, 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 = term_structure_factory(
            'discount', 'loglinear', settlement_date, rate_helpers,
            ts_day_counter, tolerance
        )

        self.assertIsNotNone(ts)

        self.assertEquals( Date(18, September, 2008), ts.reference_date)

        # this is not a real test ...
        self.assertAlmostEquals(0.9975, ts.discount(Date(21, 12, 2008)), 4)
        self.assertAlmostEquals(0.9944, ts.discount(Date(21, 4, 2009)), 4)
        self.assertAlmostEquals(0.9904, ts.discount(Date(21, 9, 2009)), 4)
    def test_relativedate_rate_helper(self):
        tenor = Period(3, Months)
        fixing_days = 3
        calendar = TARGET()
        convention = ModifiedFollowing
        end_of_month = True
        deposit_day_counter = Actual365Fixed()

        helper = DepositRateHelper(0.005, tenor, fixing_days, calendar,
                                   convention, end_of_month,
                                   deposit_day_counter)
        Settings.instance().evaluation_date = Date(8, 6, 2016)
        self.assertEqual(helper.latest_date, Date(13, 9, 2016))
Ejemplo n.º 7
0
    def setUp(self):
        self.calendar = TARGET()
        self.settlement_days = 1
        settlement_date = self.calendar.adjust(Date(28, January, 2011))
        todays_date = self.calendar.advance(
            settlement_date, -self.settlement_days, Days
        )
        Settings().evaluation_date = todays_date

        depositData = [[ 1, Months, 4.581 ],
                       [ 2, Months, 4.573 ],
                       [ 3, Months, 4.557 ],
                       [ 6, Months, 4.496 ],
                       [ 9, Months, 4.490 ]]

        swapData = [[ 1, Years, 4.54 ],
                    [ 5, Years, 4.99 ],
                    [ 10, Years, 5.47 ],
                    [ 20, Years, 5.89 ],
                    [ 30, Years, 5.96 ]]

        self.rate_helpers = []

        end_of_month = True
        for m, period, rate in depositData:
            tenor = Period(m, Months)
            helper = DepositRateHelper(SimpleQuote(rate / 100),
                                       tenor,
                                       self.settlement_days,
                                       self.calendar,
                                       ModifiedFollowing,
                                       end_of_month,
                                       Actual360())
            self.rate_helpers.append(helper)

        liborIndex = USDLibor(Period(6, Months))

        for m, period, rate in swapData:
            sq_rate = SimpleQuote(rate/100)
            helper = SwapRateHelper.from_tenor(
                sq_rate, Period(m, Years), self.calendar, Annual, Unadjusted,
                Thirty360(), liborIndex
            )
            self.rate_helpers.append(helper)

        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-15

        self.ts = PiecewiseYieldCurve(
            BootstrapTrait.Discount, Interpolator.LogLinear, self.settlement_days,
            self.calendar, self.rate_helpers, ts_day_counter, tolerance)
    def test_create_deposit_rate_helper(self):

        quote = SimpleQuote(0.0096)
        tenor = Period(3, Months)
        fixing_days = 3
        calendar = TARGET()
        convention = ModifiedFollowing
        end_of_month = True
        deposit_day_counter = Actual365Fixed()

        helper_from_quote = DepositRateHelper(quote, tenor, fixing_days,
                                              calendar, convention,
                                              end_of_month,
                                              deposit_day_counter)

        ## create helper from float directly
        helper_from_float = DepositRateHelper(0.0096, tenor, fixing_days,
                                              calendar, convention,
                                              end_of_month,
                                              deposit_day_counter)
        self.assertIsNotNone(helper_from_quote, helper_from_float)
        self.assertEqual(quote.value, helper_from_quote.quote)
        self.assertEqual(helper_from_quote.quote, helper_from_float.quote)
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
    def test_all_types_of_piecewise_curves(self):

        settings = Settings()

        # Market information
        calendar = TARGET()

        todays_date = Date(12, September, 2008)
        # must be a business day
        settings.evaluation_date = calendar.adjust(todays_date)

        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 = []

        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)

        tolerance = 1.0e-15

        for trait in BootstrapTrait:
            for interpolation in Interpolator:
                ts = PiecewiseYieldCurve.from_reference_date(
                    trait, interpolation, settlement_date, rate_helpers,
                    deposit_day_counter, tolerance)

                self.assertIsNotNone(ts)
                self.assertEqual(Date(18, September, 2008), ts.reference_date)
Ejemplo n.º 11
0
    def test_create_deposit_rate_helper(self):

        quote = 0.0096
        tenor = Period(3, Months)
        fixing_days = 3
        calendar = TARGET()
        convention = ModifiedFollowing
        end_of_month = True
        deposit_day_counter = Actual365Fixed()

        helper = DepositRateHelper(quote, tenor, fixing_days, calendar,
                                   convention, end_of_month,
                                   deposit_day_counter)

        self.assertIsNotNone(helper)
        self.assertEquals(quote, helper.quote)
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
def get_term_structure(df_libor, dtObs):
    
    settings = Settings()

    # Market information
    calendar = TARGET()

    # must be a business day
    eval_date = calendar.adjust(dateToDate(dtObs))
    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);

    depositData =[[1, Months, 'Libor1M'],
                  [3, Months, 'Libor3M'],
                  [6, Months, 'Libor6M']]

    swapData = [[ 1, Years, 'Swap1Y'],
                [ 2, Years, 'Swap2Y'],
                [ 3, Years, 'Swap3Y'],
                [ 4, Years, 'Swap4Y'],
                [ 5, Years, 'Swap5Y'],
                [ 7, Years, 'Swap7Y'],
                [ 10, Years,'Swap10Y'],
                [ 30, Years,'Swap30Y']]

    rate_helpers = []

    end_of_month = True

    for m, period, label in depositData:
        tenor = Period(m, Months)
        rate = df_libor.get_value(dtObs, label)
        helper = DepositRateHelper(float(rate/100), tenor,
                 settlement_days,
                 calendar, ModifiedFollowing,
                 end_of_month,
                 Actual360())

        rate_helpers.append(helper)

    endOfMonth = True

    liborIndex = Libor('USD Libor', Period(6, Months),
                       settlement_days,
                       USDCurrency(), calendar,
                       ModifiedFollowing,
                       endOfMonth, Actual360())

    spread = SimpleQuote(0)
    fwdStart = Period(0, Days)

    for m, period, label in swapData:
        rate = df_libor.get_value(dtObs, label)
        helper = SwapRateHelper(SimpleQuote(rate/100),
                 Period(m, Years), 
            calendar, Annual,
            Unadjusted, Thirty360(),
            liborIndex, spread, fwdStart)

        rate_helpers.append(helper)

    ts_day_counter = ActualActual(ISDA)
    tolerance = 1.0e-15

    ts = term_structure_factory('discount', 'loglinear',
         settlement_date, rate_helpers,
         ts_day_counter, tolerance)

    return ts
Ejemplo n.º 15
0
    def test_display(self):

        settings = Settings()

        # Date setup
        calendar = TARGET()

        # Settlement date
        settlement_date = calendar.adjust(Date(28, January, 2011))

        # Evaluation date
        fixing_days = 1
        settlement_days = 1

        todays_date = calendar.advance(
            settlement_date, -fixing_days, Days
        )

        settings.evaluation_date = todays_date

        # Bound attributes
        face_amount = 100.0
        redemption = 100.0
        issue_date = Date(27, January, 2011)
        maturity_date = Date(31, August, 2020)
        coupon_rate = 0.03625
        bond_yield = 0.034921

        flat_discounting_term_structure = YieldTermStructure()
        flat_term_structure = FlatForward(
            reference_date = settlement_date,
            forward        = bond_yield,
            daycounter     = Actual365Fixed(), #actual_actual.ActualActual(actual_actual.Bond),
            compounding    = Compounded,
            frequency      = Semiannual)
        # have a look at the FixedRateBondHelper to simplify this
        # construction
        flat_discounting_term_structure.link_to(flat_term_structure)


	#Rate
        fixed_bond_schedule = Schedule(
            issue_date,
            maturity_date,
            Period(Semiannual),
            UnitedStates(market=GOVERNMENTBOND),
            Unadjusted,
            Unadjusted,
            Backward,
            False);


        bond = FixedRateBond(
            settlement_days,
		    face_amount,
		    fixed_bond_schedule,
		    [coupon_rate],
            ActualActual(Bond),
		    Unadjusted,
            redemption,
            issue_date
        )



        d=bf.startDate(bond)

        zspd=bf.zSpread(bond, 100.0, flat_term_structure, Actual365Fixed(),
        Compounded, Semiannual, settlement_date, 1e-6, 100, 0.5)


        #Also need a test case for a PiecewiseTermStructure...
        depositData = [[ 1, Months, 4.581 ],
                       [ 2, Months, 4.573 ],
                       [ 3, Months, 4.557 ],
                       [ 6, Months, 4.496 ],
                       [ 9, Months, 4.490 ]]

        swapData = [[ 1, Years, 4.54 ],
                    [ 5, Years, 4.99 ],
                    [ 10, Years, 5.47 ],
                    [ 20, Years, 5.89 ],
                    [ 30, Years, 5.96 ]]

        rate_helpers = []

        end_of_month = True
        for m, period, rate in depositData:
            tenor = Period(m, Months)

            helper = DepositRateHelper(SimpleQuote(rate/100), tenor, settlement_days,
                     calendar, ModifiedFollowing, end_of_month,
                     Actual360())

            rate_helpers.append(helper)

        liborIndex = Libor('USD Libor', Period(6, Months), settlement_days,
                           USDCurrency(), calendar, Actual360(),
                           YieldTermStructure(relinkable=False))

        spread = SimpleQuote(0)
        fwdStart = Period(0, Days)

        for m, period, rate in swapData:

            helper = SwapRateHelper.from_tenor(
                SimpleQuote(rate/100), Period(m, Years), calendar, Annual, Unadjusted, Thirty360(), liborIndex,
                spread, fwdStart
            )

            rate_helpers.append(helper)

        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-15

        ts = PiecewiseYieldCurve.from_reference_date(
            BootstrapTrait.Discount, Interpolator.LogLinear, settlement_date, rate_helpers,
            ts_day_counter, tolerance)

        pyc_zspd=bf.zSpread(bond, 102.0, ts, ActualActual(ISDA),
        Compounded, Semiannual, Date(1, April, 2015), 1e-6, 100, 0.5)

        pyc_zspd_disco=bf.zSpread(bond, 95.0, ts, ActualActual(ISDA),
        Compounded, Semiannual, settlement_date, 1e-6, 100, 0.5)


        yld  = bf.yld(bond, 102.0, ActualActual(ISDA), Compounded, Semiannual, settlement_date, 1e-6, 100, 0.5)
        dur  = bf.duration(bond, yld, ActualActual(ISDA), Compounded, Semiannual, 2, settlement_date)

        yld_disco  = bf.yld(bond, 95.0, ActualActual(ISDA), Compounded, Semiannual, settlement_date, 1e-6, 100, 0.5)
        dur_disco  = bf.duration(bond, yld_disco, ActualActual(ISDA), Compounded, Semiannual, 2, settlement_date)

        self.assertEqual(round(zspd, 6), 0.001281)
        self.assertEqual(round(pyc_zspd, 4), -0.0264)
        self.assertEqual(round(pyc_zspd_disco, 4), -0.0114)

        self.assertEqual(round(yld, 4), 0.0338)
        self.assertEqual(round(yld_disco, 4), 0.0426)

        self.assertEqual(round(dur, 4), 8.0655)
        self.assertEqual(round(dur_disco, 4), 7.9702)
Ejemplo n.º 16
0
    def test_zero_curve_on_swap_index(self):

        todays_date = today()

        calendar = UnitedStates() # INPUT
        dayCounter = Actual360() # INPUT
        currency = USDCurrency() # INPUT

        Settings.instance().evaluation_date = todays_date
        settlement_days	= 2

        settlement_date =  calendar.advance(
            todays_date, period=Period(settlement_days, Days)
        )

        liborRates = [ SimpleQuote(0.002763), SimpleQuote(0.004082), SimpleQuote(0.005601), SimpleQuote(0.006390), SimpleQuote(0.007125),
            SimpleQuote(0.007928), SimpleQuote(0.009446), SimpleQuote(0.01110)]
        liborRatesTenor = [Period(tenor, Months) for tenor in [1,2,3,4,5,6,9,12]]
        Libor_dayCounter = Actual360();


        swapRates = [SimpleQuote(0.005681), SimpleQuote(0.006970), SimpleQuote(0.009310), SimpleQuote(0.012010), SimpleQuote(0.014628),
                 SimpleQuote(0.016881), SimpleQuote(0.018745), SimpleQuote(0.020260), SimpleQuote(0.021545)]
        swapRatesTenor = [Period(i, Years) for i in range(2, 11)]
        # description of the fixed leg of the swap
        Swap_fixedLegTenor = Period(12, Months)      # INPUT
        Swap_fixedLegConvention = ModifiedFollowing  # INPUT
        Swap_fixedLegDayCounter = Actual360()        # INPUT
        # description of the float leg of the swap
        Swap_iborIndex = Libor(
            "USDLibor", Period(3, Months), settlement_days, USDCurrency(),
            UnitedStates(), Actual360()
        )

        SwapFamilyName = currency.name + "swapIndex"
        instruments = []

        # ++++++++++++++++++++ Creation of the vector of RateHelper (need for the Yield Curve construction)
        # ++++++++++++++++++++ Libor
        LiborFamilyName = currency.name + "Libor"
        instruments = []
        for rate, tenor in zip(liborRates, liborRatesTenor):
            # Index description ___ creation of a Libor index
            liborIndex =  Libor(
                LiborFamilyName, tenor, settlement_days, currency, calendar,
                Libor_dayCounter
            )
            # Initialize rate helper
            # the DepositRateHelper link the recording rate with the Libor
            # index

            instruments.append(DepositRateHelper(rate, index=liborIndex))


        for tenor, rate in zip(swapRatesTenor, swapRates):
            # swap description ___ creation of a swap index. The floating leg is described in the index 'Swap_iborIndex'
            swapIndex = SwapIndex (
                SwapFamilyName, tenor, settlement_days, currency, calendar,
                Swap_fixedLegTenor, Swap_fixedLegConvention,
                Swap_fixedLegDayCounter, Swap_iborIndex
            )
            # Initialize rate helper __ the SwapRateHelper links the swap index width his rate
            instruments.append(SwapRateHelper.from_index(rate,swapIndex))

        # ++++++++++++++++++  Now the creation of the yield curve

        tolerance = 1.0e-15

        ts = PiecewiseYieldCurve.from_reference_date(
            BootstrapTrait.ZeroYield, Interpolator.Linear, settlement_date, instruments, dayCounter,
            tolerance
        )

        self.assertEqual(settlement_date, ts.reference_date)
Ejemplo n.º 17
0
    def test_deposit_swap(self):

        settings = Settings()

        # Market information
        calendar = TARGET()

        todays_date = Date(1, Mar, 2012)

        # must be a business day
        eval_date = calendar.adjust(todays_date)
        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);

        depositData = [[ 1, Months, 4.581 ],
                       [ 2, Months, 4.573 ],
                       [ 3, Months, 4.557 ],
                       [ 6, Months, 4.496 ],
                       [ 9, Months, 4.490 ]]

        swapData = [[ 1, Years, 4.54 ],
                    [ 5, Years, 4.99 ],
                    [ 10, Years, 5.47 ],
                    [ 20, Years, 5.89 ],
                    [ 30, Years, 5.96 ]]

        rate_helpers = []

        end_of_month = True

        for m, period, rate in depositData:
            tenor = Period(m, Months)


            helper = DepositRateHelper(SimpleQuote(rate/100), tenor, settlement_days,
                     calendar, ModifiedFollowing, end_of_month,
                     Actual360())

            rate_helpers.append(helper)

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

        spread = SimpleQuote(0)
        fwdStart = Period(0, Days)

        for m, period, rate in swapData:

            helper = SwapRateHelper.from_tenor(
                SimpleQuote(rate/100), Period(m, Years), calendar, Annual, Unadjusted, Thirty360(), liborIndex,
                spread, fwdStart
            )

            rate_helpers.append(helper)

        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-15

        ts = PiecewiseYieldCurve.from_reference_date(
            BootstrapTrait.Discount, Interpolator.LogLinear, settlement_date, rate_helpers,
            ts_day_counter, tolerance
        )

        self.assertEqual(settlement_date, ts.reference_date)

        # this is not a real test ...
        self.assertAlmostEqual(0.9103,
             ts.discount(calendar.advance(todays_date, 2, Years)),3)
        self.assertAlmostEqual(0.7836,
             ts.discount(calendar.advance(todays_date, 5, Years)),3)
        self.assertAlmostEqual(0.5827,
             ts.discount(calendar.advance(todays_date, 10, Years)),3)
        self.assertAlmostEqual(0.4223,
             ts.discount(calendar.advance(todays_date, 15, Years)),3)
Ejemplo n.º 18
0
def get_term_structure(df_libor, dtObs):

    settings = Settings()

    # Market information
    calendar = TARGET()

    # must be a business day
    eval_date = calendar.adjust(Date.from_datetime(dtObs))
    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)

    depositData = [[1, Months, 'Libor1M'], [3, Months, 'Libor3M'],
                   [6, Months, 'Libor6M']]

    swapData = [[1, Years, 'Swap1Y'], [2, Years,
                                       'Swap2Y'], [3, Years, 'Swap3Y'],
                [4, Years, 'Swap4Y'], [5, Years, 'Swap5Y'],
                [7, Years, 'Swap7Y'], [10, Years, 'Swap10Y'],
                [30, Years, 'Swap30Y']]

    rate_helpers = []

    end_of_month = True

    for m, period, label in depositData:
        tenor = Period(m, Months)
        rate = df_libor.get_value(dtObs, label)
        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, period, label in swapData:
        rate = df_libor.get_value(dtObs, label)
        helper = SwapRateHelper.from_tenor(SimpleQuote(rate / 100.0),
                                           Period(m, Years), calendar,
                                           Semiannual, ModifiedFollowing,
                                           Thirty360(), liborIndex, spread,
                                           fwdStart)

        rate_helpers.append(helper)

    ts_day_counter = ActualActual(ISDA)
    tolerance = 1.0e-15

    ts = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.Discount,
                                                 Interpolator.LogLinear,
                                                 settlement_date, rate_helpers,
                                                 ts_day_counter, tolerance)
    ts.extrapolation = True
    return ts
Ejemplo n.º 19
0
ois25YRate = SimpleQuote(0.02003)
ois30YRate = SimpleQuote(0.02038)

#/*********************
# ***  RATE HELPERS ***
# *********************/

# RateHelpers are built from the above quotes together with
# other instrument dependant infos.  Quotes are passed in
# relinkable handles which could be relinked to some other
# data source later.

# deposits
depositDayCounter = Actual360()

dON = DepositRateHelper(dONRate, 1 * Days, 0, calendar, Following, False,
                        depositDayCounter)
dTN = DepositRateHelper(dTNRate, 1 * Days, 1, calendar, Following, False,
                        depositDayCounter)
dSN = DepositRateHelper(dSNRate, 1 * Days, 2, calendar, Following, False,
                        depositDayCounter)

# OIS
eonia = Eonia()

ois1W = OISRateHelper(2, 1 * Weeks, ois1WRate, eonia)
ois2W = OISRateHelper(2, 2 * Weeks, ois2WRate, eonia)
ois3W = OISRateHelper(2, 3 * Weeks, ois3WRate, eonia)
ois1M = OISRateHelper(2, 1 * Months, ois1MRate, eonia)

# Dated OIS
oisDated1 = DatedOISRateHelper(Date(16, 1, 2013), Date(13, 2, 2013),
Ejemplo n.º 20
0
def get_term_structure(df_libor, dtObs):

    settings = Settings()

    # libor as fixed in London, but cash-flows are determined according to
    # US calendar, hence the need to combine both holidays lists
    calendar = JointCalendar(UnitedStates(), UnitedKingdom())

    # must be a business day
    eval_date = calendar.adjust(dateToDate(dtObs))
    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)

    depositData = [[1, Months, 'Libor1M'], [3, Months, 'Libor3M'],
                   [6, Months, 'Libor6M']]

    swapData = [[1, Years, 'Swap1Y'], [2, Years,
                                       'Swap2Y'], [3, Years, 'Swap3Y'],
                [4, Years, 'Swap4Y'], [5, Years, 'Swap5Y'],
                [7, Years, 'Swap7Y'], [10, Years, 'Swap10Y'],
                [30, Years, 'Swap30Y']]

    rate_helpers = []

    end_of_month = True

    for m, period, label in depositData:
        tenor = Period(m, Months)
        rate = df_libor.get_value(dtObs, label)
        helper = DepositRateHelper(float(rate / 100), tenor, settlement_days,
                                   calendar, ModifiedFollowing, end_of_month,
                                   Actual360())

        rate_helpers.append(helper)

    endOfMonth = True

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

    spread = SimpleQuote(0)
    fwdStart = Period(0, Days)

    for m, period, label in swapData:
        rate = df_libor.get_value(dtObs, label)
        helper = SwapRateHelper.from_tenor(rate / 100., Period(m, Years),
                                           calendar, Annual, Unadjusted,
                                           Thirty360(), liborIndex, spread,
                                           fwdStart)

        rate_helpers.append(helper)

    ts_day_counter = ActualActual(ISDA)
    tolerance = 1.0e-15

    ts = term_structure_factory('discount', 'loglinear', settlement_date,
                                rate_helpers, ts_day_counter, tolerance)

    return ts
Ejemplo n.º 21
0
    def test_zero_curve(self):

        try:

            settings = Settings()

            calendar = TARGET()

            # must be a business Days
            dtObs = date(2007, 4, 27)
            eval_date = calendar.adjust(pydate_to_qldate(dtObs))
            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)

            print('dt Obs: %s\ndt Eval: %s\ndt Settle: %s' %
                  (dtObs, eval_date, settlement_date))

            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, period, label, 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, period, label, 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)

            ts_day_counter = ActualActual(ISDA)
            tolerance = 1.0e-2

            ts = PiecewiseYieldCurve('discount', 'loglinear', settlement_date,
                                     rate_helpers, ts_day_counter, tolerance)

            # max_date raises an exception...
            dtMax = ts.max_date
            print('max date: %s' % dtMax)

        except RuntimeError as e:
            print('Exception (expected):\n%s' % e)

            self.assertTrue(True)

        except Exception:
            self.assertFalse()
Ejemplo n.º 22
0
    def build_eur_curve(self, quotes_date):
        """
        Builds the EUR OIS curve as the collateral currency discount curve
        :param quotes_date: date fro which it is assumed all market data are
            valid
        :return: tuple consisting of objects related to EUR OIS discounting
            curve: PiecewiseFlatForward,
                   YieldTermStructureHandle
                   RelinkableYieldTermStructureHandle
        """
        calendar = TARGET()
        settlementDays = 2

        todaysDate = quotes_date
        Settings.instance().evaluation_date = todaysDate

        todays_Eonia_quote = -0.00341

        # market quotes
        # deposits, key structure as (settlement_days_number, number_of_units_
        # for_maturity, unit)
        deposits = {(0, 1, Days): todays_Eonia_quote}

        discounting_yts_handle = YieldTermStructure()
        on_index = Eonia(discounting_yts_handle)
        on_index.add_fixing(todaysDate, todays_Eonia_quote / 100.0)

        ois = {
            (1, Weeks): -0.342,
            (1, Months): -0.344,
            (3, Months): -0.349,
            (6, Months): -0.363,
            (1, Years): -0.389,
        }

        # convert them to Quote objects
        for k, v in deposits.items():
            deposits[k] = SimpleQuote(v / 100.0)

        for k, v in ois.items():
            ois[k] = SimpleQuote(v / 100.0)

        # build rate helpers
        dayCounter = Actual360()
        # looping left if somone wants two add more deposits to tests, e.g. T/N

        depositHelpers = [
            DepositRateHelper(
                q,
                Period(n, unit),
                sett_num,
                calendar,
                ModifiedFollowing,
                True,
                dayCounter,
            )
            for (sett_num, n, unit), q in deposits.items()
        ]

        oisHelpers = [
            OISRateHelper(
                settlementDays, Period(n, unit),
                q, on_index, discounting_yts_handle
            )
            for (n, unit), q in ois.items()
        ]

        rateHelpers = depositHelpers + oisHelpers

        # term-structure construction
        oisSwapCurve = PiecewiseYieldCurve[ForwardRate, BackwardFlat].from_reference_date(todaysDate, rateHelpers,
                                                                                    Actual360())
        oisSwapCurve.extrapolation = True
        return oisSwapCurve
Ejemplo n.º 23
0
    def test_bucketanalysis_bond(self):

        settings = Settings()

        calendar = TARGET()

        settlement_date = calendar.adjust(Date(28, January, 2011))
        simple_quotes = []

        fixing_days = 1
        settlement_days = 1

        todays_date = calendar.advance(settlement_date, -fixing_days, Days)

        settings.evaluation_date = todays_date

        face_amount = 100.0
        redemption = 100.0
        issue_date = Date(27, January, 2011)
        maturity_date = Date(1, January, 2021)
        coupon_rate = 0.055
        bond_yield = 0.034921

        flat_discounting_term_structure = YieldTermStructure()
        flat_term_structure = FlatForward(reference_date=settlement_date,
                                          forward=bond_yield,
                                          daycounter=Actual365Fixed(),
                                          compounding=Compounded,
                                          frequency=Semiannual)

        flat_discounting_term_structure.link_to(flat_term_structure)

        fixed_bond_schedule = Schedule.from_rule(
            issue_date, maturity_date, Period(Semiannual),
            UnitedStates(market=GovernmentBond), Unadjusted, Unadjusted,
            Backward, False)

        bond = FixedRateBond(settlement_days, face_amount,
                             fixed_bond_schedule, [coupon_rate],
                             ActualActual(Bond), Unadjusted, redemption,
                             issue_date)

        zspd = bf.zSpread(bond, 100.0, flat_term_structure, Actual365Fixed(),
                          Compounded, Semiannual, settlement_date, 1e-6, 100,
                          0.5)

        depositData = [[1, Months, 4.581], [2, Months, 4.573],
                       [3, Months, 4.557], [6, Months, 4.496],
                       [9, Months, 4.490]]

        swapData = [[1, Years, 4.54], [5, Years, 4.99], [10, Years, 5.47],
                    [20, Years, 5.89], [30, Years, 5.96]]

        rate_helpers = []

        end_of_month = True
        for m, period, rate in depositData:
            tenor = Period(m, Months)
            sq_rate = SimpleQuote(rate / 100)
            helper = DepositRateHelper(sq_rate, tenor, settlement_days,
                                       calendar, ModifiedFollowing,
                                       end_of_month, Actual360())
            simple_quotes.append(sq_rate)
            rate_helpers.append(helper)

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

        spread = SimpleQuote(0)
        fwdStart = Period(0, Days)

        for m, period, rate in swapData:
            sq_rate = SimpleQuote(rate / 100)
            helper = SwapRateHelper.from_tenor(sq_rate, Period(m, Years),
                                               calendar, Annual, Unadjusted,
                                               Thirty360(), liborIndex, spread,
                                               fwdStart)
            simple_quotes.append(sq_rate)
            rate_helpers.append(helper)

        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-15

        ts = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.Discount,
                                                     Interpolator.LogLinear,
                                                     settlement_date,
                                                     rate_helpers,
                                                     ts_day_counter, tolerance)

        discounting_term_structure = YieldTermStructure()
        discounting_term_structure.link_to(ts)
        pricing_engine = DiscountingBondEngine(discounting_term_structure)
        bond.set_pricing_engine(pricing_engine)

        self.assertAlmostEqual(bond.npv, 100.83702940160767)

        ba = bucket_analysis([simple_quotes], [bond], [1], 0.0001, 1)

        self.assertTrue(2, ba)
        self.assertTrue(type(tuple), ba)
        self.assertEqual(len(simple_quotes), len(ba[0][0]))
        self.assertEqual(0, ba[0][0][8])