예제 #1
0
    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_from_quote = SwapRateHelper.from_index(rate, index)
        helper_from_float = SwapRateHelper.from_index(0.005681, index)

        #self.fail(
        #    'Make this pass: create and ask for the .quote property'
        #    ' Test the from_index and from_tenor methods'
        #)

        self.assertIsNotNone(helper_from_quote, helper_from_float)
        self.assertAlmostEqual(rate.value, helper_from_quote.quote.value)
        self.assertAlmostEqual(helper_from_float.quote.value, helper_from_quote.quote.value)

        with self.assertRaises(RuntimeError):
            self.assertAlmostEqual(rate.value, helper_from_quote.implied_quote)
예제 #2
0
    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_from_quote = SwapRateHelper.from_index(rate, index)
        helper_from_float = SwapRateHelper.from_index(0.005681, index)

        #self.fail(
        #    'Make this pass: create and ask for the .quote property'
        #    ' Test the from_index and from_tenor methods'
        #)

        self.assertIsNotNone(helper_from_quote, helper_from_float)
        self.assertAlmostEqual(rate.value, helper_from_quote.quote.value)
        self.assertAlmostEqual(helper_from_float.quote.value, helper_from_quote.quote.value)

        with self.assertRaises(RuntimeError):
            self.assertAlmostEqual(rate.value, helper_from_quote.implied_quote)
예제 #3
0
    def test_create_swap_rate_helper_from_tenor(self):
        calendar = UnitedStates()
        settlement_days = 2

        rate = SimpleQuote(0.005681)

        ibor_index = Libor("USDLibor", Period(3, Months), settlement_days,
                           USDCurrency(), UnitedStates(), Actual360())
        helper_from_quote = SwapRateHelper.from_tenor(rate, Period(12, Months),
                                                      calendar, Annual,
                                                      ModifiedFollowing,
                                                      Actual360(), ibor_index)
        helper_from_float = SwapRateHelper.from_tenor(0.005681,
                                                      Period(12, Months),
                                                      calendar, Annual,
                                                      ModifiedFollowing,
                                                      Actual360(), ibor_index)

        self.assertIsNotNone(helper_from_float, helper_from_quote)
        self.assertEqual(rate.value, helper_from_quote.quote.value)
        self.assertEqual(helper_from_quote.quote.value,
                         helper_from_float.quote.value)

        with self.assertRaises(RuntimeError):
            self.assertAlmostEqual(rate.value, helper_from_quote.implied_quote)
예제 #4
0
    def test_create_swap_rate_helper_from_tenor(self):
        calendar = UnitedStates()
        settlement_days = 2

        rate = SimpleQuote(0.005681)

        ibor_index =  Libor(
            "USDLibor", Period(3,Months), settlement_days, USDCurrency(),
            UnitedStates(), Actual360())
        helper_from_quote = SwapRateHelper.from_tenor(rate, Period(12, Months), calendar,
                                            Annual, ModifiedFollowing, Actual360(),
                                            ibor_index)
        helper_from_float =  SwapRateHelper.from_tenor(0.005681, Period(12, Months), calendar,
                                            Annual, ModifiedFollowing, Actual360(),
                                            ibor_index)

        self.assertIsNotNone(helper_from_float, helper_from_quote)
        self.assertEqual(rate.value, helper_from_quote.quote.value)
        self.assertEqual(helper_from_quote.quote.value, helper_from_float.quote.value)

        with self.assertRaises(RuntimeError):
            self.assertAlmostEqual(rate.value, helper_from_quote.implied_quote)
예제 #5
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)
예제 #6
0
파일: rates.py 프로젝트: ChinaQuants/pyql
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(
            SimpleQuote(rate),
            Period(tenor, Years),
            calendar, Annual,
            Unadjusted, Thirty360(),
            liborIndex, spread, fwdStart)
    elif((rate_type == 'LIBOR') & (period == 'M')):
        helper = DepositRateHelper(SimpleQuote(rate),
                                   Period(tenor, Months),
                                   settlement_days,
                                   calendar,
                                   ModifiedFollowing,
                                   end_of_month,
                                   Actual360())
    else:
        raise Exception("Rate type %s not supported" % label)

    return (helper)
예제 #7
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
예제 #8
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
예제 #9
0
파일: market.py 프로젝트: JohnnyBurst/pyql
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))
    else:
        raise Exception("Rate type %s not supported" % rate_type)

    return (helper)
예제 #10
0
파일: rates.py 프로젝트: stan2133/pyql
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)
예제 #11
0
    def test_create_swap_rate_helper_from_index(self):

        from quantlib.currency import USDCurrency
        from quantlib.indexes.swap_index import SwapIndex
        from quantlib.indexes.libor import Libor
        from quantlib.time.api import Years, UnitedStates, Actual360

        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 = 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, helper.quote)

        with self.assertRaises(RuntimeError):
            self.assertAlmostEquals(rate, helper.implied_quote)
예제 #12
0
    def test_create_swap_rate_helper_from_index(self):

        from quantlib.currency import USDCurrency
        from quantlib.indexes.swap_index import SwapIndex
        from quantlib.indexes.libor import Libor
        from quantlib.time.api import Years, UnitedStates, Actual360

        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 = 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, helper.quote)

        with self.assertRaises(RuntimeError):
            self.assertAlmostEquals(rate, helper.implied_quote)
예제 #13
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)
예제 #14
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(
            'zero', 'linear', settlement_date, instruments, dayCounter,
            tolerance
        )

        self.assertEqual(settlement_date, ts.reference_date)
예제 #15
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(
            'discount', '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)
예제 #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)
예제 #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)
예제 #18
0
    FraRateHelper.from_index(r, p, euribor6M)
    for r, p in zip(fra_rates, fra_periods)
]

# setup swaps

swFixedLegFrequency = Annual
swFixedLegConvention = Unadjusted
swFixedLegDayCounter = Thirty360(European)

swFloatingLegIndex = Euribor6M()
swaps = [
    SwapRateHelper.from_tenor(r,
                              p,
                              calendar,
                              swFixedLegFrequency,
                              swFixedLegConvention,
                              swFixedLegDayCounter,
                              swFloatingLegIndex,
                              discounting_curve=discountingTermStructure)
    for p, r in swap_quotes.items()
]

# // Euribor 6M curve
euribor6MInstruments = [d6M] + fras + swaps
# // If needed, it's possible to change the tolerance; the default is 1.0e-12.
tolerance = 1.0e-15

# // The tolerance is passed in an explicit bootstrap object. Depending on
# // the bootstrap algorithm, it's possible to pass other parameters.
euribor6MTermStructure = PiecewiseYieldCurve[Discount,
                                             Cubic].from_reference_date(
예제 #19
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
예제 #20
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])
예제 #21
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
예제 #22
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
예제 #23
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(relinkable=True)
        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
        )

        bfs=bf.BondFunctions()
        d=bfs.startDate(bond)
        bfs.display()
        zspd=bfs.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(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(
                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(
            'discount', 'loglinear', settlement_date, rate_helpers,
            ts_day_counter, tolerance)   

        pyc_zspd=bfs.zSpread(bond,102.0,ts,ActualActual(ISDA),
        Compounded,Semiannual,settlement_date,1e-6,100,0.5)                     

        pyc_zspd_disco=bfs.zSpread(bond,95.0,ts,ActualActual(ISDA),
        Compounded,Semiannual,settlement_date,1e-6,100,0.5)
                                                          
        # tests
        #self.assertTrue(Date(27, January, 2011), bond.issue_date)
        #self.assertTrue(Date(31, August, 2020), bond.maturity_date)
        #self.assertTrue(settings.evaluation_date, bond.valuation_date)

        print d
        self.assertTrue(Date(27, January, 2011), d)

        print 'Yield: {:.15%}'.format(bond_yield)
        #self.assertTrue(bond_yield,
        print 'Yield: {:.4%}'.format(bond_yield)
        print 'z-spread: {:.4%}'.format(zspd)
        print 'premium  z-spread using pwyc: {:.4%}'.format(pyc_zspd)
        print 'discount z-spread using pwyc: {:.4%}'.format(pyc_zspd_disco)
예제 #24
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()
예제 #25
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
예제 #26
0
    def test_create_swap_rate_helper_no_classmethod(self):

        with self.assertRaises(ValueError):
            SwapRateHelper()
예제 #27
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(relinkable=True)
        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(
            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(),
                            YieldTermStructure(relinkable=False))

        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(
            'discount', 'loglinear', settlement_date, rate_helpers,
            ts_day_counter, tolerance)   

        discounting_term_structure = YieldTermStructure(relinkable=True)
        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])
예제 #28
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(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('discount',
                             'loglinear',
                             settlement_date,
                             rate_helpers,
                             ts_day_counter,
                             tolerance)

    return ts
예제 #29
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()