示例#1
0
    def test_zero_curve(self):
        rate_helpers = build_helpers()
        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)

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

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

        # max_date raises an exception...
        ts.extrapolation = True
        zr = ts.zero_rate(Date(10, 5, 2027), ts_day_counter, 2)
        self.assertAlmostEqual(zr.rate, 0.0539332, 6)
示例#2
0
    def test_extrapolation(self):
        rate_helpers = build_helpers()
        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))
        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 without extrapolaiton...
        self.assertFalse(ts.extrapolation)
        with self.assertRaisesRegexp(
                RuntimeError, "1st iteration: failed at 2nd alive instrument"):
            dtMax = ts.max_date
示例#3
0
    def test_zero_curve(self):
        rate_helpers = build_helpers()
        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)

        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...
        ts.extrapolation = True
        zr = ts.zero_rate(Date(10, 5, 2027), ts_day_counter, 2)
        self.assertAlmostEqual(zr.rate, 0.0539332)
示例#4
0
class FlatHazardRateTestCase(unittest.TestCase):
    def setUp(self):
        self.calendar = TARGET()

        todays_date = Date(15, May, 2007)
        self.todays_date = self.calendar.adjust(todays_date)
        self.d = self.todays_date + Period(3, Years)

    def test_create_flat_hazard(self):
        Settings.instance().evaluation_date = self.todays_date
        flat_curve = FlatHazardRate(2, self.calendar, 0.05, Actual365Fixed())
        flat_curve_from_reference_date = FlatHazardRate.from_reference_date(
            self.calendar.advance(self.todays_date, 2, Days), 0.05,
            Actual365Fixed())
        self.assertIsNotNone(flat_curve)
        self.assertIsNotNone(flat_curve_from_reference_date)
        self.assertEqual(
            flat_curve.time_from_reference(self.d),
            flat_curve_from_reference_date.time_from_reference(self.d))
        self.assertAlmostEqual(flat_curve.hazard_rate(self.d), 0.05)
        self.assertAlmostEqual(
            flat_curve.survival_probability(self.d),
            math.exp(-0.05 * flat_curve.time_from_reference(self.d)))

    def test_flat_hazard_with_quote(self):
        Settings.instance().evaluation_date = self.todays_date
        hazard_rate = SimpleQuote()
        flat_curve = FlatHazardRate(2, self.calendar, hazard_rate,
                                    Actual365Fixed())
        for h in [0.01, 0.02, 0.03]:
            hazard_rate.value = h
            self.assertAlmostEqual(
                flat_curve.survival_probability(self.d),
                math.exp(-h * flat_curve.time_from_reference(self.d)))
示例#5
0
    def test_extrapolation(self):
        rate_helpers = build_helpers()
        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))
        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-2

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

        # max_date raises an exception without extrapolaiton...
        self.assertFalse(ts.extrapolation)
示例#6
0
    def test_create_libor_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

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

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

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

        t = index.tenor
        self.assertEqual(t.length, 6)
        self.assertEqual(t.units, 2)
        self.assertEqual('USD Libor6M Actual/360', index.name)
示例#7
0
    def test_extrapolation(self):
        rate_helpers = build_helpers()
        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))
        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-2

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

        # max_date raises an exception without extrapolaiton...
        self.assertFalse(ts.extrapolation)
        with self.assertRaises(RuntimeError) as ctx:
            ts.discount(ts.max_date + 1)
        self.assertTrue(
            str(ctx.exception) in (
                "time (30.011) is past max curve time (30.0082)",
                "1st iteration: failed at 2nd alive instrument"))
class FlatHazardRateTestCase(unittest.TestCase):

    def setUp(self):
        self.calendar = TARGET()

        todays_date = Date(15, May, 2007)
        self.todays_date = self.calendar.adjust(todays_date)
        self.d = self.todays_date + Period(3, Years)

    def test_create_flat_hazard(self):
        Settings.instance().evaluation_date = self.todays_date
        flat_curve = FlatHazardRate(2, self.calendar, 0.05, Actual365Fixed())
        flat_curve_from_reference_date = FlatHazardRate.from_reference_date(
            self.calendar.advance(self.todays_date, 2, Days), 0.05, Actual365Fixed())
        self.assertIsNotNone(flat_curve)
        self.assertIsNotNone(flat_curve_from_reference_date)
        self.assertEqual(flat_curve.time_from_reference(self.d),
                         flat_curve_from_reference_date.time_from_reference(self.d))
        self.assertAlmostEqual(flat_curve.hazard_rate(self.d), 0.05)
        self.assertAlmostEqual(flat_curve.survival_probability(self.d),
                               math.exp(-0.05*flat_curve.time_from_reference(self.d)))

    def test_flat_hazard_with_quote(self):
        Settings.instance().evaluation_date = self.todays_date
        hazard_rate = SimpleQuote()
        flat_curve = FlatHazardRate(2, self.calendar, hazard_rate, Actual365Fixed())
        for h in [0.01, 0.02, 0.03]:
            hazard_rate.value =  h
            self.assertAlmostEqual(flat_curve.survival_probability(self.d),
                                   math.exp(-h * flat_curve.time_from_reference(self.d)))
示例#9
0
    def test_create_libor_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

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

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

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

        t = index.tenor
        self.assertEquals(t.length, 6)
        self.assertEquals(t.units, 2)
        self.assertEquals('USD Libor6M Actual/360', index.name)
示例#10
0
    def test_extrapolation(self):
        rate_helpers = build_helpers()
        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))
        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 without extrapolaiton...
        self.assertFalse(ts.extrapolation)
        with self.assertRaisesRegexp(RuntimeError,
                                     "1st iteration: failed at 2nd alive instrument"):
            dtMax = ts.max_date
def create_helper():

    calendar = TARGET()

    todays_date = Date(15, May, 2007)
    todays_date = calendar.adjust(todays_date)

    Settings.instance().evaluation_date = todays_date

    flat_rate = SimpleQuote(0.01)
    ts_curve = FlatForward(todays_date, flat_rate, Actual365Fixed())

    recovery_rate = 0.5
    quoted_spreads = 0.0150
    tenor = Period(5, Years)

    helper = SpreadCdsHelper(quoted_spreads,
                             tenor,
                             0,
                             calendar,
                             Quarterly,
                             Following,
                             Rule.TwentiethIMM,
                             Actual365Fixed(),
                             recovery_rate,
                             ts_curve,
                             model=PricingModel.Midpoint)

    return todays_date, helper
示例#12
0
    def test_extrapolation(self):
        rate_helpers = build_helpers()
        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))
        ts_day_counter = ActualActual(ISDA)
        tolerance = 1.0e-2

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

        # max_date raises an exception without extrapolaiton...
        self.assertFalse(ts.extrapolation)
        with self.assertRaises(RuntimeError) as ctx:
            ts.discount(ts.max_date + 1)
        self.assertTrue(str(ctx.exception) in (
            "time (30.011) is past max curve time (30.0082)",
            "1st iteration: failed at 2nd alive instrument"))
示例#13
0
    def test_create_swap_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

        settlement_days = 2
        settlement_date = calendar.advance(eval_date, settlement_days, Days)
        # must be a business day
        settlement_date = calendar.adjust(settlement_date)
        term_structure = YieldTermStructure(relinkable=True)
        term_structure.link_to(FlatForward(settlement_date, 0.05,
                                          Actual365Fixed()))

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

        index = SwapIndex(
            'family name', Period(3, Months), 10, USDCurrency(), TARGET(),
            Period(12, Months), Following, Actual360(), ibor_index)

        self.assertIsNotNone(index)
示例#14
0
文件: test_cds.py 项目: ducky427/pyql
def create_helper():

    calendar = TARGET()

    todays_date = Date(15, May, 2007)
    todays_date = calendar.adjust(todays_date)

    Settings.instance().evaluation_date = todays_date

    flat_rate = SimpleQuote(0.01)
    ts_curve = FlatForward(todays_date, flat_rate, Actual365Fixed())

    recovery_rate = 0.5
    quoted_spreads = 0.0150
    tenor = Period(3, Months)

    helper = SpreadCdsHelper(
        quoted_spreads,
        tenor,
        0,
        calendar,
        Quarterly,
        Following,
        TwentiethIMM,
        Actual365Fixed(),
        recovery_rate,
        ts_curve,
    )

    return todays_date, helper
示例#15
0
def zero_curve(ts, days, dtObs):
    calendar = TARGET()
    dtMat = [calendar.advance(dateToDate(dtObs), d, Days) for d in days]
    df = np.array([ts.discount(dt) for dt in dtMat])
    dtMat = [QLDateTodate(dt) for dt in dtMat]
    dtToday = QLDateTodate(dtObs)
    dt = np.array([(d - dtToday).days / 365.0 for d in dtMat])
    zc = -np.log(df) / dt
    return (dtMat, zc)
示例#16
0
def zero_curve(ts, days, dtObs):
    calendar = TARGET()
    dtMat = [calendar.advance(dateToDate(dtObs), d, Days) for d in days]
    df = np.array([ts.discount(dt) for dt in dtMat])
    dtMat = [QLDateTodate(dt) for dt in dtMat]
    dtToday = QLDateTodate(dtObs)
    dt = np.array([(d-dtToday).days/365.0 for d in dtMat])
    zc = -np.log(df) / dt
    return (dtMat, zc)
    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.from_reference_date(
            BootstrapTrait.Discount, Interpolator.LogLinear, settlement_date, rate_helpers,
            ts_day_counter, 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)
示例#18
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_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)
示例#20
0
def zero_curve(ts, dtObs):
    dtMax = ts.max_date

    calendar = TARGET()
    days = range(10, 365 * 20, 30)
    dtMat = [min(dtMax, calendar.advance(dateToDate(dtObs), d, Days))
             for d in days]
    # largest dtMat < dtMax, yet QL run time error

    df = np.array([ts.discount(dt, extrapolate=True) for dt in dtMat])
    dtMat = [QLDateTodate(dt) for dt in dtMat]
    dtToday = QLDateTodate(dtObs)
    dt = np.array([(d - dtToday).days / 365.0 for d in dtMat])
    zc = -np.log(df) / dt
    return (dtMat, zc)
示例#21
0
def zero_curve(ts, dtObs):
    dtMax = ts.max_date

    calendar = TARGET()
    days = range(10, 365 * 20, 30)
    dtMat = [min(dtMax, calendar.advance(dateToDate(dtObs), d, Days))
             for d in days]
    # largest dtMat < dtMax, yet QL run time error

    df = np.array([ts.discount(dt, extrapolate=True) for dt in dtMat])
    dtMat = [QLDateTodate(dt) for dt in dtMat]
    dtToday = QLDateTodate(dtObs)
    dt = np.array([(d - dtToday).days / 365.0 for d in dtMat])
    zc = -np.log(df) / dt
    return (dtMat, zc)
示例#22
0
    def test_bond_schedule_anotherday(self):
        '''Test date calculations and role of settings when evaluation date
        set to arbitrary date.

        This test is known to fail with boost 1.42.

        '''

        todays_date = Date(30, August, 2011)

        settings = Settings()
        settings.evaluation_date =  todays_date

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

        settlement_days = 3
        face_amount = 100.0
        coupon_rate = 0.05
        redemption = 100.0

        fixed_bond_schedule = Schedule.from_rule(
            effective_date,
            termination_date,
            Period(Annual),
            calendar,
            ModifiedFollowing,
            ModifiedFollowing,
            Rule.Backward
        )

        issue_date = effective_date

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

        self.assertEqual(
            calendar.advance(todays_date, 3, Days), bond.settlement_date())
示例#23
0
    def test_bond_schedule_anotherday(self):
        '''Test date calculations and role of settings when evaluation date
        set to arbitrary date.

        This test is known to fail with boost 1.42.

        '''

        todays_date = Date(30, August, 2011)

        settings = Settings()
        settings.evaluation_date =  todays_date

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

        settlement_days = 3
        face_amount = 100.0
        coupon_rate = 0.05
        redemption = 100.0

        fixed_bond_schedule = Schedule.from_rule(
            effective_date,
            termination_date,
            Period(Annual),
            calendar,
            ModifiedFollowing,
            ModifiedFollowing,
            Rule.Backward
        )

        issue_date = effective_date

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

        self.assertEqual(
            calendar.advance(todays_date, 3, Days), bond.settlement_date())
    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 VALID_TRAITS:
            for interpolation in VALID_INTERPOLATORS:
                ts = PiecewiseYieldCurve(
                    trait, interpolation, settlement_date, rate_helpers,
                    deposit_day_counter, tolerance
                )

                self.assertIsNotNone(ts)
                self.assertEqual( Date(18, September, 2008), ts.reference_date)
示例#25
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))
示例#26
0
    def setUp(self):
        Settings.instance().evaluation_date = Date(26, 5, 2021)

        self.basis_point = 1.0e-4
        self.settlement_days = 2
        self.business_day_convention = Following
        self.calendar = TARGET()
        self.day_count = Actual365Fixed()
        self.end_of_month = False
        base_ccy_idx_handle = flat_rate(0.007)
        quoted_ccy_idx_handle = flat_rate(0.015)
        self.base_ccy_idx = Euribor3M(base_ccy_idx_handle)
        self.quote_ccy_idx = USDLibor(
            Period(3, Months), quoted_ccy_idx_handle)
        self.collateral_ccy_handle = flat_rate(0.009)
        # Cross currency basis swaps data source:
        #   N. Moreni, A. Pallavicini (2015)
        #   FX Modelling in Collateralized Markets: foreign measures, basis curves
        #   and pricing formulae.
        #   section 4.2.1, Table 2.
        self.cross_currency_basis_quotes = ((Period(1, Years), -14.5),
                                            (Period(18, Months), -18.5),
                                            (Period(2, Years), -20.5),
                                            (Period(3, Years), -23.75),
                                            (Period(4, Years), -25.5),
                                            (Period(5, Years), -26.5),
                                            (Period(7, Years), -26.75),
                                            (Period(10, Years), -26.25),
                                            (Period(15, Years), -24.75),
                                            (Period(20, Years), -23.25),
                                            (Period(30, Years), -20.50))
示例#27
0
    def test_create_fixed_rate_bond_helper(self):

        issue_date = Date(20, 3, 2014)
        maturity = Date(20, 3, 2019)

        schedule = Schedule(
            issue_date,
            maturity,
            Period(Annual),
            TARGET(),
            ModifiedFollowing,
            ModifiedFollowing,
            Backward,
            False
        )

        clean_price = 71.23
        settlement_days = 3
        rates = [0.035]

        daycounter = DayCounter.from_name("Actual/Actual (Bond)")
        helper = FixedRateBondHelper(
            SimpleQuote(clean_price),
            settlement_days,
            100.0,
            schedule,
            rates,
            daycounter,
            Following,
            100.0,
            issue_date)

        self.assertEqual(helper.quote, clean_price)
示例#28
0
    def testFxMarketConventionsForCrossRate(self):
        """
        Testing if FxSwapRateHelper obeys the fx spot market
        conventions for cross rates.
        """
        today = Date(1, 7, 2016)
        spot_date = Date(5, 7, 2016)
        self.build_curves(today)

        us_calendar = UnitedStates()

        joint_calendar = JointCalendar(TARGET(), Poland())

        settlement_calendar = JointCalendar(joint_calendar, us_calendar)

        # Settlement should be on a day where all three centers are operating
        #  and follow EndOfMonth rule
        maturities = [
            settlement_calendar.advance(spot_date, n, unit,
                                        convention=ModifiedFollowing, end_of_month=True)
            for n, unit in self.fx_swap_quotes
        ]

        for m, helper in zip(maturities, self.eur_pln_fx_swap_helpers):
            self.assertEqual(m, helper.latest_date)
示例#29
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)
示例#30
0
    def test_bond_schedule_today(self):
        '''Test date calculations and role of settings when evaluation date 
        set to current date. 

        
        '''
        
        todays_date = today()

        settings = Settings()
        settings.evaluation_date =  todays_date

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

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

        issue_date = effective_date

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

        self.assertEquals(
            calendar.advance(todays_date, 3, Days), bond.settlement_date())
示例#31
0
文件: cds.py 项目: enthought/pyql
def example02():
    print("example 2:\n")
    todays_date = Date(25, 9, 2014)
    Settings.instance().evaluation_date = todays_date

    calendar = TARGET()
    term_date = calendar.adjust(todays_date + Period(2, Years), Following)
    cds_schedule =  Schedule(todays_date, term_date, Period(Quarterly),
                             WeekendsOnly(), ModifiedFollowing,
                             ModifiedFollowing,
                             date_generation_rule=Rule.CDS)
    for date in cds_schedule:
        print(date)
    print()

    todays_date = Date(21, 10, 2014)
    Settings.instance().evaluation_date = todays_date
    quotes = [0.00006, 0.00045, 0.00081, 0.001840, 0.00256, 0.00337]
    tenors = [1, 2, 3, 6, 9, 12]
    deps = [DepositRateHelper(q, Period(t, Months), 2, calendar, ModifiedFollowing, False, Actual360())
           for q, t in zip(quotes, tenors)]
    tenors = [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 30]
    quotes = [0.00223, 0.002760, 0.003530, 0.004520, 0.005720, 0.007050, 0.008420, 0.009720, 0.010900,
              0.012870, 0.014970, 0.017, 0.01821]
    swaps = [SwapRateHelper.from_tenor(q, Period(t, Years),
                                       calendar, Annual, ModifiedFollowing,
                                       Thirty360(), Euribor6M(), SimpleQuote(0))
             for q, t in zip(quotes, tenors)]
    helpers = deps + swaps
    YC = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.Discount, Interpolator.LogLinear,
            todays_date, helpers, Actual365Fixed())
    YC.extrapolation = True
    print("ISDA rate curve:")
    for h in helpers:
        print("{0}: {1:.6f}\t{2:.6f}".format(h.latest_date,
                                             YC.zero_rate(h.latest_date, Actual365Fixed(), 2).rate,
                                             YC.discount(h.latest_date)))
    defaultTs0 = FlatHazardRate(0, WeekendsOnly(), 0.016739207493630, Actual365Fixed())
    cds_schedule = Schedule.from_rule(Date(22, 9, 2014), Date(20, 12, 2019), Period(3, Months),
                            WeekendsOnly(), Following, Unadjusted, Rule.CDS, False)
    nominal = 100000000
    trade = CreditDefaultSwap(Side.Buyer, nominal, 0.01, cds_schedule, Following,
                            Actual360(), True, True, Date(22, 10, 2014), Actual360(True), True)
    engine = IsdaCdsEngine(defaultTs0, 0.4, YC, False)
    trade.set_pricing_engine(engine)
    print("reference trade NPV = {0}\n".format(trade.npv))
示例#32
0
    def setUp(self):
        calendar = TARGET()
        today_date = today()

        Settings().evaluation_date = today_date

        hazard_rate = SimpleQuote(0.01234)
        probability_curve = FlatHazardRate(0, calendar, hazard_rate, Actual360())
        discount_curve = FlatForward(today_date, 0.06, Actual360())
        issue_date  = today_date
        #calendar.advance(today_date, -1, Years)
        maturity = calendar.advance(issue_date, 10, Years)
        self.convention = Following
        self.schedule = Schedule(issue_date, maturity, Period("3M"), calendar,
                self.convention, self.convention, Rule.TwentiethIMM)
        recovery_rate = 0.4
        self.engine = MidPointCdsEngine(probability_curve, recovery_rate, discount_curve, True)
示例#33
0
def example02():
    print("example 2:\n")
    todays_date = Date(25, 9, 2014)
    Settings.instance().evaluation_date = todays_date

    calendar = TARGET()
    term_date = calendar.adjust(todays_date + Period(2, Years), Following)
    cds_schedule =  Schedule(todays_date, term_date, Period(Quarterly),
                             WeekendsOnly(), ModifiedFollowing,
                             ModifiedFollowing,
                             date_generation_rule=Rule.CDS)
    for date in cds_schedule:
        print(date)
    print()

    todays_date = Date(21, 10, 2014)
    Settings.instance().evaluation_date = todays_date
    quotes = [0.00006, 0.00045, 0.00081, 0.001840, 0.00256, 0.00337]
    tenors = [1, 2, 3, 6, 9, 12]
    deps = [DepositRateHelper(q, Period(t, Months), 2, calendar, ModifiedFollowing, False, Actual360())
           for q, t in zip(quotes, tenors)]
    tenors = [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 30]
    quotes = [0.00223, 0.002760, 0.003530, 0.004520, 0.005720, 0.007050, 0.008420, 0.009720, 0.010900,
              0.012870, 0.014970, 0.017, 0.01821]
    swaps = [SwapRateHelper.from_tenor(q, Period(t, Years),
                                       calendar, Annual, ModifiedFollowing,
                                       Thirty360(), Euribor6M(), SimpleQuote(0))
             for q, t in zip(quotes, tenors)]
    helpers = deps + swaps
    YC = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.Discount, Interpolator.LogLinear,
            todays_date, helpers, Actual365Fixed())
    YC.extrapolation = True
    print("ISDA rate curve:")
    for h in helpers:
        print("{0}: {1:.6f}\t{2:.6f}".format(h.latest_date,
                                             YC.zero_rate(h.latest_date, Actual365Fixed(), 2).rate,
                                             YC.discount(h.latest_date)))
    defaultTs0 = FlatHazardRate(0, WeekendsOnly(), 0.016739207493630, Actual365Fixed())
    cds_schedule = Schedule.from_rule(Date(22, 9, 2014), Date(20, 12, 2019), Period(3, Months),
                            WeekendsOnly(), Following, Unadjusted, Rule.CDS, False)
    nominal = 100000000
    trade = CreditDefaultSwap(Side.Buyer, nominal, 0.01, cds_schedule, Following,
                            Actual360(), True, True, Date(22, 10, 2014), Actual360(True), True)
    engine = IsdaCdsEngine(defaultTs0, 0.4, YC, False)
    trade.set_pricing_engine(engine)
    print("reference trade NPV = {0}\n".format(trade.npv))
示例#34
0
 def test_create_ibor_index(self):
     euribor6m = IborIndex("Euribor", Period(6, Months), 2, EURCurrency(), TARGET(),
                           ModifiedFollowing, True, Actual360())
     default_euribor6m = Euribor6M()
     for attribute in ["business_day_convention", "end_of_month",
                        "fixing_calendar", "tenor", "fixing_days",
                        "day_counter", "family_name", "name"]:
         self.assertEqual(getattr(euribor6m, attribute),
                          getattr(default_euribor6m, attribute))
    def test_relative_yieldcurve(self):
        settings = Settings()
        settings.evaluation_date = Date(6, 10, 2016)

        # Market information
        calendar = TARGET()

        quotes = [0.0096, 0.0145, 0.0194]
        tenors = [3, 6, 12]

        deposit_day_counter = Actual365Fixed()
        convention = ModifiedFollowing
        end_of_month = True
        fixing_days = 3
        rate_helpers = [
            DepositRateHelper(quote, Period(month,
                                            Months), fixing_days, calendar,
                              convention, end_of_month, deposit_day_counter)
            for quote, month in zip(quotes, tenors)
        ]

        ts_day_counter = ActualActual(ISDA)

        tolerance = 1.0e-15

        ts_relative = PiecewiseYieldCurve(BootstrapTrait.Discount,
                                          Interpolator.LogLinear, 2, calendar,
                                          rate_helpers, ts_day_counter,
                                          tolerance)
        self.assertEqual(
            ts_relative.reference_date,
            calendar.advance(settings.evaluation_date, period=Period(2, Days)))

        settings.evaluation_date = Date(10, 10, 2016)
        settlement_date = calendar.advance(settings.evaluation_date,
                                           period=Period(2, Days))
        self.assertEqual(ts_relative.reference_date, settlement_date)

        ts_absolute = PiecewiseYieldCurve.from_reference_date(
            BootstrapTrait.Discount, Interpolator.LogLinear, settlement_date,
            rate_helpers, ts_day_counter, tolerance)
        self.assertEqual(ts_absolute.data, ts_relative.data)
        self.assertEqual(ts_absolute.dates, ts_relative.dates)
        self.assertEqual(ts_absolute.times, ts_relative.times)
示例#36
0
    def test_create_libor_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

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

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

        self.assertEquals("USD Libor6M Actual/360", index.name)
示例#37
0
    def setUp(self):
        self.calendar = TARGET()
        self.today = Date(9, 6, 2009)
        settlement_date = self.calendar.advance(self.today, 2, Days)
        Settings().evaluation_date = self.today
        rates = [0.035, 0.035, 0.033, 0.034, 0.034, 0.036, 0.037, 0.039, 0.04]
        ts = [13, 41, 75, 165, 256, 345, 524, 703]
        dates = [settlement_date] + [self.calendar.advance(self.today, d, Days) for d in ts]
        self.day_counter = Actual360()
        self.term_structure = ZeroCurve(dates, rates, self.day_counter)
        self.spreads = [SimpleQuote(0.02), SimpleQuote(0.03)]
        self.spread_dates = [self.calendar.advance(self.today, 8, Months),
                             self.calendar.advance(self.today, 15, Months)]

        self.spreaded_term_structure = PiecewiseZeroSpreadedTermStructure(
            self.term_structure,
            self.spreads,
            self.spread_dates)
        self.spreaded_term_structure.extrapolation = True
示例#38
0
    def setUp(self):

        self.settings = Settings()

        self.calendar = TARGET()

        self.todays_date = Date(15, May, 1998)
        self.settlement_date = Date(17, May, 1998)

        self.settings.evaluation_date = self.todays_date

        # options parameters
        self.option_type = Put
        self.underlying = 36
        self.strike = 40
        self.dividend_yield = 0.00
        self.risk_free_rate = 0.06
        self.volatility = 0.20
        self.maturity = Date(17, May, 1999)
        self.daycounter = Actual365Fixed()

        self.underlyingH = SimpleQuote(self.underlying)

        # bootstrap the yield/dividend/vol curves
        self.flat_term_structure = FlatForward(
            reference_date=self.settlement_date,
            forward=self.risk_free_rate,
            daycounter=self.daycounter)
        self.flat_dividend_ts = FlatForward(
            reference_date=self.settlement_date,
            forward=self.dividend_yield,
            daycounter=self.daycounter)

        self.flat_vol_ts = BlackConstantVol(self.settlement_date,
                                            self.calendar, self.volatility,
                                            self.daycounter)

        self.black_scholes_merton_process = BlackScholesMertonProcess(
            self.underlyingH, self.flat_dividend_ts, self.flat_term_structure,
            self.flat_vol_ts)

        self.payoff = PlainVanillaPayoff(self.option_type, self.strike)

        #Additional parameters for testing DividendVanillaOption
        self.dividend_dates = []
        self.dividends = []
        self.american_time_steps = 600
        self.american_grid_points = 600

        #Parameters for implied volatility:
        self.accuracy = 0.001
        self.max_evaluations = 1000
        self.min_vol = 0.001
        self.max_vol = 4
        self.target_price = 4.485992
示例#39
0
    def test_create_libor_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

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

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

        self.assertEquals('USD Libor6M Actual/360', index.name)
class InterpolatedHazardRateTestCase(unittest.TestCase):

    calendar = TARGET()

    todays_date = Date(15, May, 2007)
    todays_date = calendar.adjust(todays_date)

    def test_create_interpolated_hazard(self):
        Settings.instance().evaluation_date = self.todays_date

        dates = [self.todays_date + Period(i, Years) for i in [3, 5, 7]]
        hazard_rates =  [0.01, 0.03, 0.05]

        interpolation_date = self.todays_date + Period(4, Years)

        trait = Interpolator.Linear
        interpolated_curve = InterpolatedHazardRateCurve(trait, dates,
                                                         hazard_rates,
                                                         Actual365Fixed())
        t0 = interpolated_curve.time_from_reference(dates[0])
        t1 = interpolated_curve.time_from_reference(interpolation_date)
        t2 = interpolated_curve.time_from_reference(dates[1])
        interpolated_value = hazard_rates[0] + (t1-t0) /(t2-t0) * \
                             (hazard_rates[1] - hazard_rates[0])

        self.assertAlmostEqual(interpolated_value,
                               interpolated_curve.hazard_rate(interpolation_date))
        trait = Interpolator.BackwardFlat
        interpolated_curve = InterpolatedHazardRateCurve(trait, dates,
                                                         hazard_rates,
                                                         Actual365Fixed())
        interpolated_value = hazard_rates[1]
        self.assertAlmostEqual(interpolated_value,
                               interpolated_curve.hazard_rate(interpolation_date))
        trait = Interpolator.LogLinear
        interpolated_curve = InterpolatedHazardRateCurve(trait, dates,
                                                         hazard_rates,
                                                         Actual365Fixed())
        with self.assertRaisesRegexp(RuntimeError,
                                     'LogInterpolation primitive not implemented'):
            hazard_rate = interpolated_curve.hazard_rate(interpolation_date)

    def test_methods(self):
        Settings.instance().evaluation_date = self.todays_date

        dates = [self.todays_date + Period(i, Years) for i in [3, 5, 7]]
        hazard_rates =  [0.01, 0.03, 0.05]
        for trait in [Interpolator.BackwardFlat, Interpolator.Linear]:
            interpolated_curve = InterpolatedHazardRateCurve(trait, dates,
                                                             hazard_rates,
                                                             Actual365Fixed())
            self.assertEqual(dates, interpolated_curve.dates)
            self.assertEqual(interpolated_curve.data, interpolated_curve.hazard_rates)
    def test_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)
示例#42
0
    def test_create_swap_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date


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

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


        index = SwapIndex(
            'family name', Period(3, Months), 10, USDCurrency(), TARGET(),
            Period(12, Months), Following, Actual360(), ibor_index)

        self.assertIsNotNone(index)
示例#43
0
    def test_create_swap_index(self):

        settings = Settings.instance()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

        settlement_days = 2
        settlement_date = calendar.advance(eval_date, settlement_days, Days)
        # must be a business day
        settlement_date = calendar.adjust(settlement_date)
        term_structure = YieldTermStructure(relinkable=True)
        term_structure.link_to(
            FlatForward(settlement_date, 0.05, Actual365Fixed()))

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

        index = SwapIndex('family name', Period(3, Months), 10, USDCurrency(),
                          TARGET(), Period(12, Months), Following, Actual360(),
                          ibor_index)

        self.assertIsNotNone(index)
    def test_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))
示例#45
0
    def test_bond_schedule_today(self):
        '''Test date calculations and role of settings when evaluation date 
        set to current date. 

        
        '''

        todays_date = today()

        settings = Settings()
        settings.evaluation_date = todays_date

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

        settlement_days = 3
        face_amount = 100.0
        coupon_rate = 0.05
        redemption = 100.0

        fixed_bond_schedule = Schedule(effective_date, termination_date,
                                       Period(Annual), calendar,
                                       ModifiedFollowing, ModifiedFollowing,
                                       Backward)

        issue_date = effective_date

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

        self.assertEquals(calendar.advance(todays_date, 3, Days),
                          bond.settlement_date())
示例#46
0
    def setUp(self):

        self.settings = Settings()

        self.calendar = TARGET()

        self.todays_date = Date(15, May, 1998)
        self.settlement_date = Date(17, May, 1998)

        self.settings.evaluation_date = self.todays_date

        # options parameters
        self.option_type = Put
        self.underlying = 36
        self.strike = 40
        self.dividend_yield = 0.00
        self.risk_free_rate = 0.06
        self.volatility = 0.20
        self.maturity = Date(17, May, 1999)
        self.daycounter = Actual365Fixed()

        self.underlyingH = SimpleQuote(self.underlying)

        # bootstrap the yield/dividend/vol curves
        self.flat_term_structure = FlatForward(
            reference_date = self.settlement_date,
            forward        = self.risk_free_rate,
            daycounter     = self.daycounter
        )
        self.flat_dividend_ts = FlatForward(
            reference_date = self.settlement_date,
            forward        = self.dividend_yield,
            daycounter     = self.daycounter
        )

        self.flat_vol_ts = BlackConstantVol(
            self.settlement_date,
            self.calendar,
            self.volatility,
            self.daycounter
        )

        self.black_scholes_merton_process = BlackScholesMertonProcess(
            self.underlyingH,
            self.flat_dividend_ts,
            self.flat_term_structure,
            self.flat_vol_ts
        )

        self.payoff = PlainVanillaPayoff(self.option_type, self.strike)
示例#47
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
示例#48
0
    def test_swap_from_market(self):
        """
        Test that a swap with fixed coupon = fair rate has an NPV=0
        Create from market
        """

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

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

        length = 5
        fixed_rate = .05
        floating_spread = 0.0

        m = libor_market('USD(NY)')

        quotes = [('DEP', '1W', SimpleQuote(0.0382)),
                  ('DEP', '1M', SimpleQuote(0.0372)),
                  ('DEP', '3M', SimpleQuote(0.0363)),
                  ('DEP', '6M', SimpleQuote(0.0353)),
                  ('DEP', '9M', SimpleQuote(0.0348)),
                  ('DEP', '1Y', SimpleQuote(0.0345)),
                  ('SWAP', '2Y', SimpleQuote(0.037125)),
                  ('SWAP', '3Y', SimpleQuote(0.0398)),
                  ('SWAP', '5Y', SimpleQuote(0.0443)),
                  ('SWAP', '10Y', SimpleQuote(0.05165)),
                  ('SWAP', '15Y', SimpleQuote(0.055175))]

        m.set_quotes(eval_date, quotes)

        m.bootstrap_term_structure()

        dt = Date(2, January, 2015)
        df = m.discount(dt)
        print('discount factor for %s (USD Libor): %f' % (dt, df))

        swap = m.create_fixed_float_swap(settlement_date, length, fixed_rate,
                                         floating_spread)

        fixed_l = swap.fixed_leg

        float_l = swap.floating_leg

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

        fixed_npv = swap.fixed_leg_npv
        float_npv = swap.floating_leg_npv

        # verify calculation by discounting both legs
        tot = 0.0
        for frc in fixed_l:
            df = m.discount(frc.date)
            tot += frc.amount * df
        print('fixed npv: %f discounted cf: %f' % (fixed_npv, tot))
        self.assertAlmostEqual(fixed_npv, -tot)

        tot = 0.0
        for ic in float_l:
            df = m.discount(ic.date)
            tot += ic.amount * df
        print('float npv: %f discounted cf: %f' % (float_npv, tot))
        self.assertAlmostEqual(float_npv, tot)
示例#49
0
    def test_swap_QL(self):
        """
        Test that a swap with fixed coupon = fair rate has an NPV=0
        Create from QL objects
        """

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

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

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

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

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

        length = 5
        fixedRate = .05
        floatingSpread = 0.0

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

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

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

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

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

            p = swap.net_present_value
            print('NPV: %f' % p)
            self.assertAlmostEqual(p, 0)
示例#50
0
文件: bonds.py 项目: enthought/pyql
from quantlib.time.date import Date, August, Period, Jul, Annual, Years
from quantlib.time.daycounters.simple import Actual365Fixed
from quantlib.time.daycounters.actual_actual import ActualActual, ISMA
from quantlib.time.schedule import Schedule, Backward
from quantlib.settings import Settings
from quantlib.termstructures.yields.api import (
    FlatForward, YieldTermStructure
)

todays_date = Date(25, August, 2011)


settings = Settings.instance()
settings.evaluation_date = todays_date

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


settlement_days = 3
face_amount = 100.0
coupon_rate = 0.05
redemption = 100.0

fixed_bond_schedule = Schedule.from_rule(
    effective_date,
    termination_date,
    Period(Annual),
示例#51
0
文件: cds.py 项目: enthought/pyql
    Months,
    Quarterly,
    TwentiethIMM,
    Years,
    Schedule,
    Unadjusted,
)
from quantlib.termstructures.credit.api import SpreadCdsHelper, PiecewiseDefaultCurve, ProbabilityTrait, Interpolator
from quantlib.termstructures.yields.api import FlatForward

if __name__ == "__main__":

    # *********************
    # ***  MARKET DATA  ***
    # *********************
    calendar = TARGET()

    todays_date = Date(15, May, 2007)
    # must be a business day
    todays_date = calendar.adjust(todays_date)

    Settings.instance().evaluation_date = todays_date

    # dummy curve
    ts_curve = FlatForward(reference_date=todays_date, forward=0.01, daycounter=Actual365Fixed())

    # In Lehmans Brothers "guide to exotic credit derivatives"
    # p. 32 there's a simple case, zero flat curve with a flat CDS
    # curve with constant market spreads of 150 bp and RR = 50%
    # corresponds to a flat 3% hazard rate. The implied 1-year
    # survival probability is 97.04% and the 2-years is 94.18%
示例#52
0
文件: cds.py 项目: JohnnyBurst/pyql
from quantlib.instruments.credit_default_swap import CreditDefaultSwap, SELLER
from quantlib.pricingengines.credit import MidPointCdsEngine
from quantlib.settings import Settings
from quantlib.time.api import (
    Date, May, Actual365Fixed, Following, TARGET, Period, Months,
    Quarterly, TwentiethIMM, Years, Schedule, Unadjusted
)
from quantlib.termstructures.credit.api import SpreadCdsHelper, PiecewiseDefaultCurve
from quantlib.termstructures.yields.api import FlatForward

if __name__ == '__main__':

    #*********************
    #***  MARKET DATA  ***
    #*********************/
    calendar = TARGET()

    todays_date = Date(15, May, 2007)
    # must be a business day
    todays_date = calendar.adjust(todays_date)

    Settings.instance().evaluation_date = todays_date

    # dummy curve
    ts_curve = FlatForward(
        reference_date=todays_date, forward=0.01, daycounter=Actual365Fixed()
    )

    # In Lehmans Brothers "guide to exotic credit derivatives"
    # p. 32 there's a simple case, zero flat curve with a flat CDS
    # curve with constant market spreads of 150 bp and RR = 50%
示例#53
0
    def test_deposit_swap(self):

        settings = Settings()

        # Market information
        calendar = TARGET()

        # must be a business day
        eval_date = calendar.adjust(today())
        settings.evaluation_date = eval_date

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

        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())

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

        for m, period, rate in swapData:
            rate = SimpleQuote(rate/100)

            helper = SwapRateHelper(rate, 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)

        # this is not a real test ...
        self.assertAlmostEquals(0.9103,
             ts.discount(calendar.advance(today(), 2, Years)),3)
        self.assertAlmostEquals(0.7836,
             ts.discount(calendar.advance(today(), 5, Years)),3)
        self.assertAlmostEquals(0.5827,
             ts.discount(calendar.advance(today(), 10, Years)),3)
        self.assertAlmostEquals(0.4223,
             ts.discount(calendar.advance(today(), 15, Years)),3)
示例#54
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
    def setUp(self):
        calendar = TARGET()

        todays_date = Date(15, May, 2007)
        self.todays_date = calendar.adjust(todays_date)
    def setUp(self):
        self.calendar = TARGET()

        todays_date = Date(15, May, 2007)
        self.todays_date = self.calendar.adjust(todays_date)
        self.d = self.todays_date + Period(3, Years)
示例#57
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)