コード例 #1
0
ファイル: test_settings.py プロジェクト: enthought/pyql
    def test_settings_instance_method(self):

        Settings.instance().evaluation_date = today()

        self.assertEqual(
                today(),
                Settings.instance().evaluation_date
        )
コード例 #2
0
    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)
コード例 #3
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)
コード例 #4
0
ファイル: test_mlab.py プロジェクト: cottrell/pyql
    def test_blsprice(self):

        from quantlib.settings import Settings
        from quantlib.time.api import today
        Settings.instance().evaluation_date = today()
        call_value = blsprice(100.0, 97.0, 0.1, 0.25, 0.5)
        self.assertAlmostEquals(call_value, 12.61, 2)
コード例 #5
0
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
コード例 #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.assertEquals(t.length, 6)
        self.assertEquals(t.units, 2)
        self.assertEquals('USD Libor6M Actual/360', index.name)
コード例 #7
0
ファイル: test_indexes.py プロジェクト: GuidoE/pyql
    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)
コード例 #8
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)
コード例 #9
0
ファイル: test_cds.py プロジェクト: ChinaQuants/pyql
    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)
コード例 #10
0
ファイル: test_indexes.py プロジェクト: phenaff/pyql
    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)
コード例 #11
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
コード例 #12
0
ファイル: test_indexes.py プロジェクト: enthought/pyql
    def test_create_libor_index(self):

        settings = Settings.instance()

        # Market information
        calendar = UnitedStates(LiborImpact)

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

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

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

        index = Libor('USDLibor', Period(6, Months), settlement_days,
                      USDCurrency(), calendar, Actual360(),
                      term_structure)
        default_libor = USDLibor(Period(6, Months))
        for attribute in ["business_day_convention", "end_of_month",
                          "fixing_calendar", "joint_calendar", "tenor",
                          "fixing_days", "day_counter", "family_name", "name"]:
            self.assertEqual(getattr(index, attribute),
                             getattr(default_libor, attribute))
コード例 #13
0
    def test_create_libor_index(self):

        settings = Settings.instance()

        # Market information
        calendar = UnitedStates(LiborImpact)

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

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

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

        index = Libor('USDLibor', Period(6, Months), settlement_days,
                      USDCurrency(), calendar, Actual360(), term_structure)
        default_libor = USDLibor(Period(6, Months))
        for attribute in [
                "business_day_convention", "end_of_month", "fixing_calendar",
                "joint_calendar", "tenor", "fixing_days", "day_counter",
                "family_name", "name"
        ]:
            self.assertEqual(getattr(index, attribute),
                             getattr(default_libor, attribute))
コード例 #14
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))
コード例 #15
0
ファイル: test_mlab.py プロジェクト: surfmaverick/pyql
    def test_blsprice(self):

        from quantlib.settings import Settings
        from quantlib.time.api import today
        Settings.instance().evaluation_date = today()
        call_value = blsprice(100.0, 97.0, 0.1, 0.25, 0.5)
        self.assertAlmostEquals(call_value, 12.61, 2)
コード例 #16
0
ファイル: test_cds.py プロジェクト: ChinaQuants/pyql
 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)))
コード例 #17
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))
コード例 #18
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))
コード例 #19
0
 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)))
コード例 #20
0
    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)
コード例 #21
0
ファイル: test_cds.py プロジェクト: ChinaQuants/pyql
    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)
コード例 #22
0
ファイル: test_cds.py プロジェクト: ChinaQuants/pyql
 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)))
コード例 #23
0
 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)))
コード例 #24
0
ファイル: cds.py プロジェクト: pmnyc/Source_Codes_Collected
def example03():
    print("example 3:\n")
    todays_date = Date(13, 6, 2011)
    Settings.instance().evaluation_date = todays_date
    quotes = [0.00445, 0.00949, 0.01234, 0.01776, 0.01935, 0.02084]
    tenors = [1, 2, 3, 6, 9, 12]
    calendar = WeekendsOnly()
    deps = [
        DepositRateHelper(q, Period(t, Months), 2, calendar, ModifiedFollowing,
                          False, Actual360()) for q, t in zip(quotes, tenors)
    ]
    quotes = [
        0.01652, 0.02018, 0.02303, 0.02525, 0.0285, 0.02931, 0.03017, 0.03092,
        0.03160, 0.03231, 0.03367, 0.03419, 0.03411, 0.03411, 0.03412
    ]
    tenors = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 25, 30]
    swaps = [
        SwapRateHelper.from_tenor(q, Period(t, Years), calendar, Annual,
                                  ModifiedFollowing, Thirty360(), Euribor6M(),
                                  SimpleQuote(0))
        for q, t in zip(quotes, tenors)
    ]
    yield_helpers = deps + swaps
    isda_yts = PiecewiseYieldCurve(BootstrapTrait.Discount,
                                   Interpolator.LogLinear, 0, WeekendsOnly(),
                                   yield_helpers, Actual365Fixed())

    spreads = [0.007927, 0.012239, 0.016979, 0.019271, 0.020860]
    tenors = [1, 3, 5, 7, 10]
    spread_helpers = [SpreadCdsHelper(0.007927, Period(6, Months), 1,
                                      WeekendsOnly(), Quarterly, Following, Rule.CDS2015,
                                      Actual360(), 0.4, isda_yts, True, True,
                                      Date(), Actual360(True), True, PricingModel.ISDA)] + \
    [SpreadCdsHelper(s, Period(t, Years), 1, WeekendsOnly(), Quarterly, Following, Rule.CDS2015,
                     Actual360(), 0.4, isda_yts, True, True, Date(), Actual360(True), True,
                     PricingModel.ISDA)
     for s, t in zip(spreads, tenors)]
    isda_cts = PiecewiseDefaultCurve(ProbabilityTrait.SurvivalProbability,
                                     Interpolator.LogLinear, 0, WeekendsOnly(),
                                     spread_helpers, Actual365Fixed())
    isda_pricer = IsdaCdsEngine(isda_cts, 0.4, isda_yts)
    print("Isda yield curve:")
    for h in yield_helpers:
        d = h.latest_date
        t = isda_yts.time_from_reference(d)
        print(d, t, isda_yts.zero_rate(d, Actual365Fixed()).rate)

    print()
    print("Isda credit curve:")
    for h in spread_helpers:
        d = h.latest_date
        t = isda_cts.time_from_reference(d)
        print(d, t, isda_cts.survival_probability(d))
コード例 #25
0
    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))
コード例 #26
0
ファイル: test_rate_helpers.py プロジェクト: enthought/pyql
    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))
コード例 #27
0
    def build_pln_fx_swap_curve(self, base_ccy_yts, fx_swaps, fx_spot):
        """
        Build curve implied from fx swap curve.
        :param base_ccy_yts:
            Relinkable yield term structure handle to curve in base currency.
        :param fx_swaps:
            Dictionary with swap points, already divided by 10,000
        :param fx_spot:
            Float value of fx spot exchange rate.
        :return: tuple consisting of objects related to fx swap implied curve:
                PiecewiseFlatForward,
                YieldTermStructureHandle
                RelinkableYieldTermStructureHandle
                list of FxSwapRateHelper
        """
        todaysDate = base_ccy_yts.reference_date
        # I am not sure if that is required, but I guss it is worth setting
        # up just in case somewhere another thread updates this setting.
        Settings.instance().evaluation_date = todaysDate

        calendar = JointCalendar(TARGET(), Poland())
        spot_date_lag = 2
        trading_calendar = UnitedStates()

        # build rate helpers
        spotFx = SimpleQuote(fx_spot)

        fxSwapHelpers = [
            FxSwapRateHelper(
                SimpleQuote(fx_swaps[(n, unit)]),
                spotFx,
                Period(n, unit),
                spot_date_lag,
                calendar,
                ModifiedFollowing,
                True,
                True,
                base_ccy_yts,
                trading_calendar,
            )
            for n, unit in fx_swaps
        ]

        # term-structure construction
        fxSwapCurve = PiecewiseYieldCurve[ForwardRate, BackwardFlat].from_reference_date(todaysDate, fxSwapHelpers,
                                           Actual365Fixed())
        fxSwapCurve.extrapolation = True
        return fxSwapCurve, fxSwapHelpers
コード例 #28
0
    def test_deposit_end_of_month(self):
        tenor = Period(3, Months)
        fixing_days = 0
        calendar = TARGET()
        convention = ModifiedFollowing
        end_of_month = True
        deposit_day_counter = Actual365Fixed()

        helper_end_of_month = DepositRateHelper(0.005, tenor, fixing_days,
                                                calendar, convention, True,
                                                deposit_day_counter)
        helper_no_end_of_month = DepositRateHelper(0.005, tenor, fixing_days,
                                                   calendar, convention, False,
                                                   deposit_day_counter)
        Settings.instance().evaluation_date = Date(29, 2, 2016)
        self.assertEqual(helper_end_of_month.latest_date, Date(31, 5, 2016))
        self.assertEqual(helper_no_end_of_month.latest_date, Date(30, 5, 2016))
コード例 #29
0
ファイル: cds.py プロジェクト: enthought/pyql
def example03():
    print("example 3:\n")
    todays_date = Date(13, 6, 2011)
    Settings.instance().evaluation_date = todays_date
    quotes = [0.00445, 0.00949, 0.01234, 0.01776, 0.01935, 0.02084]
    tenors = [1, 2, 3, 6, 9, 12]
    calendar = WeekendsOnly()
    deps = [DepositRateHelper(q, Period(t, Months), 2, calendar, ModifiedFollowing, False, Actual360())
            for q, t in zip(quotes, tenors)]
    quotes = [0.01652, 0.02018, 0.02303, 0.02525, 0.0285, 0.02931, 0.03017, 0.03092, 0.03160, 0.03231,
              0.03367, 0.03419, 0.03411, 0.03411, 0.03412]
    tenors = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 25, 30]
    swaps =  [SwapRateHelper.from_tenor(q, Period(t, Years),
                                        calendar, Annual, ModifiedFollowing,
                                        Thirty360(), Euribor6M(), SimpleQuote(0)) for q, t
              in zip(quotes, tenors)]
    yield_helpers = deps + swaps
    isda_yts = PiecewiseYieldCurve(BootstrapTrait.Discount, Interpolator.LogLinear, 0,
                                   WeekendsOnly(), yield_helpers, Actual365Fixed())

    spreads = [0.007927, 0.012239, 0.016979, 0.019271, 0.020860]
    tenors = [1, 3, 5, 7, 10]
    spread_helpers = [SpreadCdsHelper(0.007927, Period(6, Months), 1,
                                      WeekendsOnly(), Quarterly, Following, Rule.CDS2015,
                                      Actual360(), 0.4, isda_yts, True, True,
                                      Date(), Actual360(True), True, PricingModel.ISDA)] + \
    [SpreadCdsHelper(s, Period(t, Years), 1, WeekendsOnly(), Quarterly, Following, Rule.CDS2015,
                     Actual360(), 0.4, isda_yts, True, True, Date(), Actual360(True), True,
                     PricingModel.ISDA)
     for s, t in zip(spreads, tenors)]
    isda_cts = PiecewiseDefaultCurve(ProbabilityTrait.SurvivalProbability,
                                     Interpolator.LogLinear, 0, WeekendsOnly(), spread_helpers,
                                     Actual365Fixed())
    isda_pricer = IsdaCdsEngine(isda_cts, 0.4, isda_yts)
    print("Isda yield curve:")
    for h in yield_helpers:
        d = h.latest_date
        t = isda_yts.time_from_reference(d)
        print(d, t, isda_yts.zero_rate(d, Actual365Fixed()).rate)

    print()
    print("Isda credit curve:")
    for h in spread_helpers:
        d = h.latest_date
        t = isda_cts.time_from_reference(d)
        print(d, t, isda_cts.survival_probability(d))
コード例 #30
0
ファイル: test_rate_helpers.py プロジェクト: enthought/pyql
    def test_deposit_end_of_month(self):
        tenor = Period(3, Months)
        fixing_days = 0
        calendar =  TARGET()
        convention = ModifiedFollowing
        end_of_month = True
        deposit_day_counter = Actual365Fixed()

        helper_end_of_month = DepositRateHelper(
            0.005, tenor, fixing_days, calendar, convention, True,
            deposit_day_counter
        )
        helper_no_end_of_month = DepositRateHelper(
            0.005, tenor, fixing_days, calendar, convention, False,
            deposit_day_counter
        )
        Settings.instance().evaluation_date = Date(29, 2, 2016)
        self.assertEqual(helper_end_of_month.latest_date, Date(31, 5, 2016))
        self.assertEqual(helper_no_end_of_month.latest_date, Date(30, 5, 2016))
コード例 #31
0
ファイル: test_indexes.py プロジェクト: harpone/pyql
    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)
コード例 #32
0
ファイル: test_indexes.py プロジェクト: adriancdperu/pyql
    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)
コード例 #33
0
    def testFxMarketConventionsForDatesInEURUSD_ShortEnd(self):
        """
        Testing if FxSwapRateHelper obeys the fx spot market
        conventions for EURUSD settlement dates on the 3M tenor.
        """
        today = Date(1, 7, 2016)
        Settings.instance().evaluation_date = today

        expected_3M_date = Date(5, 10, 2016)
        fwd_points = 4.0
        # critical for ON rate helper
        period = Period("3M")
        fixing_days = 2

        # empty RelinkableYieldTermStructureHandle is sufficient for testing
        # dates
        base_ccy_yts = YieldTermStructure()

        # In EURUSD, there must be two days to spot date in Target calendar
        # and one day in US, therefore it is sufficient to pass only Target
        # as a base calendar. Passing joint calendar would result in wrong
        # spot date of the trade
        calendar = TARGET()
        trading_calendar = UnitedStates()

        rate_helper = FxSwapRateHelper(
            SimpleQuote(fwd_points),
            SimpleQuote(self.fx_spot_quote_EURUSD),
            period,
            fixing_days,
            calendar,
            ModifiedFollowing,
            True,
            True,
            base_ccy_yts,
            trading_calendar,
        )

        self.assertEqual(expected_3M_date, rate_helper.latest_date)
コード例 #34
0
    def testFxMarketConventionsForDatesInEURUSD_ON_Period(self):
        """
        Testing if FxSwapRateHelper obeys the fx spot market
        conventions for EURUSD settlement dates on the ON Period.
        """
        today = Date(1, 7, 2016)
        Settings.instance().evaluation_date = today

        spot_date = Date(5, 7, 2016)
        fwd_points = 4.0
        # critical for ON rate helper
        on_period = Period("1d")
        fixing_days = 0

        # empty RelinkableYieldTermStructureHandle is sufficient for testing
        # dates
        base_ccy_yts = YieldTermStructure()

        # In EURUSD, there must be two days to spot date in Target calendar
        # and one day in US, therefore it is sufficient to pass only Target
        # as a base calendar
        calendar = TARGET()
        trading_calendar = UnitedStates()

        on_rate_helper = FxSwapRateHelper(
            SimpleQuote(fwd_points),
            SimpleQuote(self.fx_spot_quote_EURUSD),
            on_period,
            fixing_days,
            calendar,
            ModifiedFollowing,
            False,
            True,
            base_ccy_yts,
            trading_calendar,
        )

        self.assertEqual(spot_date, on_rate_helper.latest_date)
コード例 #35
0
    def testFxMarketConventionsForCrossRateONPeriod(self):
        """
        Testing if FxSwapRateHelper obeys the fx spot market
        conventions for cross rates' ON Period.
        """
        today = Date(1, 7, 2016)
        Settings.instance().evaluation_date = today

        spot_date = Date(5, 7, 2016)
        fwd_points = 4.0
        # critical for ON rate helper
        on_period = Period("1d")
        fixing_days = 0

        # empty RelinkableYieldTermStructureHandle is sufficient for testing
        # dates
        base_ccy_yts = YieldTermStructure()

        us_calendar = UnitedStates()

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

        # Settlement should be on a day where all three centers are operating
        #  and follow EndOfMonth rule
        on_rate_helper = FxSwapRateHelper(
            SimpleQuote(fwd_points),
            SimpleQuote(self.fx_spot_quote_EURPLN),
            on_period,
            fixing_days,
            joint_calendar,
            ModifiedFollowing,
            False,
            True,
            base_ccy_yts,
            us_calendar,
        )

        self.assertEqual(spot_date, on_rate_helper.latest_date)
コード例 #36
0
ファイル: cds.py プロジェクト: enthought/pyql
def example01():
    #*********************
    #***  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%

    # market
    recovery_rate = 0.5
    quoted_spreads = [0.0150, 0.0150, 0.0150, 0.0150 ]
    tenors = [Period(i, Months) for i in [3, 6, 12, 24]]
    maturities = [
        calendar.adjust(todays_date + tenors[i], Following) for i in range(4)
    ]
    instruments = []
    for i in range(4):
        helper = SpreadCdsHelper(
            quoted_spreads[i], tenors[i], 0, calendar, Quarterly,
            Following, Rule.TwentiethIMM, Actual365Fixed(), recovery_rate, ts_curve
        )

        instruments.append(helper)

    # Bootstrap hazard rates
    hazard_rate_structure = PiecewiseDefaultCurve.from_reference_date(
            ProbabilityTrait.HazardRate, Interpolator.BackwardFlat, todays_date, instruments, Actual365Fixed()
    )

    #vector<pair<Date, Real> > hr_curve_data = hazardRateStructure->nodes();

    #cout << "Calibrated hazard rate values: " << endl ;
    #for (Size i=0; i<hr_curve_data.size(); i++) {
    #    cout << "hazard rate on " << hr_curve_data[i].first << " is "
    #         << hr_curve_data[i].second << endl;
    #}
    #cout << endl;

    target = todays_date + Period(1, Years)
    print(target)
    print("Some survival probability values: ")
    print("1Y survival probability: {:%}".format(
            hazard_rate_structure.survival_probability(target)
    ))
    print("               expected: {:%}".format(0.9704))

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

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

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

    cds_3m = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[0], cds_schedule, Following,
        Actual365Fixed()
    )

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

    cds_6m = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[1], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_schedule = Schedule.from_rule(
        todays_date, maturities[2], Period(Quarterly), calendar,
        termination_date_convention=Unadjusted,
        date_generation_rule=Rule.TwentiethIMM
    )

    cds_1y = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[2], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_schedule = Schedule.from_rule(
        todays_date, maturities[3], Period(Quarterly), calendar,
        termination_date_convention=Unadjusted,
        date_generation_rule=Rule.TwentiethIMM
    )

    cds_2y = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[3], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_3m.set_pricing_engine(engine);
    cds_6m.set_pricing_engine(engine);
    cds_1y.set_pricing_engine(engine);
    cds_2y.set_pricing_engine(engine);

    print("Repricing of quoted CDSs employed for calibration: ")
    print("3M fair spread: {}".format(cds_3m.fair_spread))
    print("   NPV:         ", cds_3m.net_present_value)
    print("   default leg: ", cds_3m.default_leg_npv)
    print("   coupon leg:  ", cds_3m.coupon_leg_npv)

    print("6M fair spread: {}".format(cds_6m.fair_spread))
    print("   NPV:         ", cds_6m.net_present_value)
    print("   default leg: ", cds_6m.default_leg_npv)
    print("   coupon leg:  ", cds_6m.coupon_leg_npv)

    print("1Y fair spread: {}".format(cds_1y.fair_spread))
    print("   NPV:         ", cds_1y.net_present_value)
    print("   default leg: ", cds_1y.default_leg_npv)
    print("   coupon leg:  ", cds_1y.coupon_leg_npv)

    print("2Y fair spread: {}".format(cds_2y.fair_spread))
    print("   NPV:         ", cds_2y.net_present_value)
    print("   default leg: ", cds_2y.default_leg_npv)
    print("   coupon leg:  ", cds_2y.coupon_leg_npv)
    print()
コード例 #37
0
 def tearDown(self):
     Settings.instance().evaluation_date = Date()
コード例 #38
0
def example01():
    #*********************
    #***  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%

    # market
    recovery_rate = 0.5
    quoted_spreads = [0.0150, 0.0150, 0.0150, 0.0150 ]
    tenors = [Period(i, Months) for i in [3, 6, 12, 24]]
    maturities = [
        calendar.adjust(todays_date + tenors[i], Following) for i in range(4)
    ]
    instruments = []
    for i in range(4):
        helper = SpreadCdsHelper(
            quoted_spreads[i], tenors[i], 0, calendar, Quarterly,
            Following, Rule.TwentiethIMM, Actual365Fixed(), recovery_rate, ts_curve
        )

        instruments.append(helper)

    # Bootstrap hazard rates
    hazard_rate_structure = PiecewiseDefaultCurve.from_reference_date(
            ProbabilityTrait.HazardRate, Interpolator.BackwardFlat, todays_date, instruments, Actual365Fixed()
    )

    #vector<pair<Date, Real> > hr_curve_data = hazardRateStructure->nodes();

    #cout << "Calibrated hazard rate values: " << endl ;
    #for (Size i=0; i<hr_curve_data.size(); i++) {
    #    cout << "hazard rate on " << hr_curve_data[i].first << " is "
    #         << hr_curve_data[i].second << endl;
    #}
    #cout << endl;

    target = todays_date + Period(1, Years)
    print(target)
    print("Some survival probability values: ")
    print("1Y survival probability: {:%}".format(
            hazard_rate_structure.survival_probability(target)
    ))
    print("               expected: {:%}".format(0.9704))

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

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

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

    cds_3m = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[0], cds_schedule, Following,
        Actual365Fixed()
    )

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

    cds_6m = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[1], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_schedule = Schedule.from_rule(
        todays_date, maturities[2], Period(Quarterly), calendar,
        termination_date_convention=Unadjusted,
        date_generation_rule=Rule.TwentiethIMM
    )

    cds_1y = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[2], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_schedule = Schedule.from_rule(
        todays_date, maturities[3], Period(Quarterly), calendar,
        termination_date_convention=Unadjusted,
        date_generation_rule=Rule.TwentiethIMM
    )

    cds_2y = CreditDefaultSwap(
        Side.Seller, nominal, quoted_spreads[3], cds_schedule, Following,
        Actual365Fixed()
    )

    cds_3m.set_pricing_engine(engine);
    cds_6m.set_pricing_engine(engine);
    cds_1y.set_pricing_engine(engine);
    cds_2y.set_pricing_engine(engine);

    print("Repricing of quoted CDSs employed for calibration: ")
    print("3M fair spread: {}".format(cds_3m.fair_spread))
    print("   NPV:         ", cds_3m.net_present_value)
    print("   default leg: ", cds_3m.default_leg_npv)
    print("   coupon leg:  ", cds_3m.coupon_leg_npv)

    print("6M fair spread: {}".format(cds_6m.fair_spread))
    print("   NPV:         ", cds_6m.net_present_value)
    print("   default leg: ", cds_6m.default_leg_npv)
    print("   coupon leg:  ", cds_6m.coupon_leg_npv)

    print("1Y fair spread: {}".format(cds_1y.fair_spread))
    print("   NPV:         ", cds_1y.net_present_value)
    print("   default leg: ", cds_1y.default_leg_npv)
    print("   coupon leg:  ", cds_1y.coupon_leg_npv)

    print("2Y fair spread: {}".format(cds_2y.fair_spread))
    print("   NPV:         ", cds_2y.net_present_value)
    print("   default leg: ", cds_2y.default_leg_npv)
    print("   coupon leg:  ", cds_2y.coupon_leg_npv)
    print()
コード例 #39
0
ファイル: test_mlab.py プロジェクト: PythonCharmers/pyql
    def test_blsprice(self):

        Settings.instance().evaluation_date = today()
        call_value = blsprice(100.0, 97.0, 0.1, 0.25, 0.5)
        self.assertAlmostEquals(call_value, 12.61, 2)
コード例 #40
0
ファイル: american_option.py プロジェクト: phista/pyql
def main():
    # global data
    todays_date = Date(15, May, 1998)
    Settings.instance().evaluation_date = todays_date
    settlement_date = Date(17, May ,1998)

    risk_free_rate = FlatForward(
        reference_date = settlement_date,
        forward        = 0.06,
        daycounter     = Actual365Fixed()
    )

    # option parameters
    exercise = AmericanExercise(
        earliest_exercise_date = settlement_date,
        latest_exercise_date   = Date(17, May, 1999)
    )
    payoff = PlainVanillaPayoff(Put, 40.0)

    # market data
    underlying = SimpleQuote(36.0)
    volatility = BlackConstantVol(todays_date, TARGET(), 0.20, Actual365Fixed())
    dividend_yield = FlatForward(
        reference_date = settlement_date,
        forward        = 0.00,
        daycounter     = Actual365Fixed()
    )

    # report
    header = '%19s' % 'method' + ' |' + \
            ' |'.join(['%17s' % tag for tag in ['value',
                                                'estimated error',
                                                'actual error' ] ])
    print
    print header
    print '-'*len(header)

    refValue = None
    def report(method, x, dx = None):
        e = '%.4f' % abs(x-refValue)
        x = '%.5f' % x
        if dx:
            dx = '%.4f' % dx
        else:
            dx = 'n/a'
        print '%19s' % method + ' |' + \
            ' |'.join(['%17s' % y for y in [x, dx, e] ])

    # good to go

    process = BlackScholesMertonProcess(
        underlying, dividend_yield, risk_free_rate, volatility
    )

    option = VanillaOption(payoff, exercise)

    refValue = 4.48667344
    report('reference value',refValue)

    # method: analytic

    option.set_pricing_engine(BaroneAdesiWhaleyApproximationEngine(process))
    report('Barone-Adesi-Whaley',option.net_present_value)

    # method: finite differences
    time_steps = 801
    grid_points = 800

    option.set_pricing_engine(FDAmericanEngine('CrankNicolson', process,time_steps,grid_points))
    report('finite differences',option.net_present_value)


    print 'This is work in progress.'
    print 'Some pricing engines are not yet interfaced.'

    return

    option.set_pricing_engine(BjerksundStenslandEngine(process))
    report('Bjerksund-Stensland',option.NPV())

    # method: binomial
    timeSteps = 801

    option.setPricingEngine(BinomialVanillaEngine(process,'jr',timeSteps))
    report('binomial (JR)',option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process,'crr',timeSteps))
    report('binomial (CRR)',option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process,'eqp',timeSteps))
    report('binomial (EQP)',option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process,'trigeorgis',timeSteps))
    report('bin. (Trigeorgis)',option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process,'tian',timeSteps))
    report('binomial (Tian)',option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process,'lr',timeSteps))
    report('binomial (LR)',option.NPV())
コード例 #41
0
    def build_eur_curve(self, quotes_date):
        """
        Builds the EUR OIS curve as the collateral currency discount curve
        :param quotes_date: date fro which it is assumed all market data are
            valid
        :return: tuple consisting of objects related to EUR OIS discounting
            curve: PiecewiseFlatForward,
                   YieldTermStructureHandle
                   RelinkableYieldTermStructureHandle
        """
        calendar = TARGET()
        settlementDays = 2

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

        todays_Eonia_quote = -0.00341

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

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

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

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

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

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

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

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

        rateHelpers = depositHelpers + oisHelpers

        # term-structure construction
        oisSwapCurve = PiecewiseYieldCurve[ForwardRate, BackwardFlat].from_reference_date(todaysDate, rateHelpers,
                                                                                    Actual360())
        oisSwapCurve.extrapolation = True
        return oisSwapCurve
コード例 #42
0
ファイル: option_valuation.py プロジェクト: enthought/pyql
def dividendOption():
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ General Parameter for all the computation +++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    # declaration of the today's date (date where the records are done)
    todaysDate = Date(24 , Jan ,2012)	# INPUT
    Settings.instance().evaluation_date = todaysDate #!\ IMPORTANT COMMAND REQUIRED FOR ALL VALUATIONS
    calendar = UnitedStates() # INPUT
    settlement_days	= 2	# INPUT
    # Calcul of the settlement date : need to add a period of 2 days to the todays date
    settlementDate =  calendar.advance(
        todaysDate, period=Period(settlement_days, Days)
    )
    dayCounter = Actual360() # INPUT
    currency = USDCurrency() # INPUT	

    print("Date of the evaluation:			", todaysDate)
    print("Calendar used:         			", calendar.name)
    print("Number of settlement Days:		", settlement_days)
    print("Date of settlement:       		", settlementDate)
    print("Convention of day counter:		", dayCounter.name)
    print("Currency of the actual context:\t\t", currency.name)

    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ Description of the underlying +++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    underlying_name		= "IBM"
    underlying_price	= 191.75	# INPUT
    underlying_vol		= 0.2094	# INPUT

    print("**********************************")
    print("Name of the underlying:			", underlying_name)
    print("Price of the underlying at t0:	", underlying_price)
    print("Volatility of the underlying:		", underlying_vol)

    # For a great managing of price and vol objects --> Handle
    underlying_priceH  = SimpleQuote(underlying_price)

    # We suppose the vol constant : his term structure is flat --> BlackConstantVol object
    flatVolTS = BlackConstantVol(settlementDate, calendar, underlying_vol, dayCounter)
    
    # ++++++++++++++++++++ Description of Yield Term Structure
    
    #  Libor data record 
    print("**********************************")
    print("Description of the Libor used for the Yield Curve construction") 
    
    Libor_dayCounter = Actual360();

    liborRates = []
    liborRatesTenor = []
    # INPUT : all the following data are input : the rate and the corresponding tenor
    #		You could make the choice of more or less data
    #		--> However you have tho choice the instruments with different maturities
    liborRates = [ 0.002763, 0.004082, 0.005601, 0.006390, 0.007125, 0.007928, 0.009446, 
            0.01110]
    liborRatesTenor = [Period(tenor, Months) for tenor in [1,2,3,4,5,6,9,12]]
    
    for tenor, rate in zip(liborRatesTenor, liborRates):
        print(tenor, "\t\t\t", rate)

    # Swap data record 

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

    print("Description of the Swap used for the Yield Curve construction")
    print("Tenor of the fixed leg:			", Swap_fixedLegTenor)
    print("Index of the floated leg: 		", Swap_iborIndex.name)
    print("Maturity		Rate				")

    swapRates = []
    swapRatesTenor = []
    # INPUT : all the following data are input : the rate and the corresponding tenor
    #		You could make the choice of more or less data
    #		--> However you have tho choice the instruments with different maturities
    swapRates = [0.005681, 0.006970, 0.009310, 0.012010, 0.014628, 0.016881, 0.018745,
                 0.020260, 0.021545]
    swapRatesTenor = [Period(i, Years) for i in range(2, 11)]
    
    for tenor, rate in zip(swapRatesTenor, swapRates):
        print(tenor, "\t\t\t", rate)
    
    # ++++++++++++++++++++ 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))

    # +++++++++++++++++++++ Swap
    SwapFamilyName = currency.name + "swapIndex";
    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

    riskFreeTS = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.ZeroYield,
            Interpolator.Linear, settlementDate, instruments, dayCounter)


    # ++++++++++++++++++  build of the underlying process : with a Black-Scholes model 

    print('Creating process')

    bsProcess = BlackScholesProcess(underlying_priceH, riskFreeTS, flatVolTS)


    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ Description of the option +++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    Option_name = "IBM Option"
    maturity = Date(26, Jan, 2013)
    strike = 190
    option_type = Call 

    # Here, as an implementation exemple, we make the test with borth american and european exercise
    europeanExercise = EuropeanExercise(maturity)
    # The emericanExercise need also the settlement date, as his right to exerce the buy or call start at the settlement date!
    #americanExercise = AmericanExercise(settlementDate, maturity)
    americanExercise = AmericanExercise(maturity, settlementDate)
    
    print("**********************************")
    print("Description of the option:		", Option_name)
    print("Date of maturity:     			", maturity)
    print("Type of the option:   			", option_type)
    print("Strike of the option:		    ", strike)



    # ++++++++++++++++++ Description of the discrete dividends
    # INPUT You have to determine the frequece and rates of the discrete dividend. Here is a sollution, but she's not the only one.
    # Last know dividend:
    dividend			= 0.75 #//0.75
    next_dividend_date	= Date(10,Feb,2012)
    # HERE we have make the assumption that the dividend will grow with the quarterly croissance:
    dividendCroissance	= 1.03
    dividendfrequence	= Period(3, Months)
    dividendDates = []
    dividends = []


    d = next_dividend_date
    while d <= maturity:
        dividendDates.append(d)
        dividends.append(dividend)
        d = d + dividendfrequence
        dividend *= dividendCroissance

    print("Discrete dividends				")
    print("Dates				Dividends		")
    for date, div in zip(dividendDates, dividends):
        print(date, "		", div)

    # ++++++++++++++++++ Description of the final payoff 
    payoff = PlainVanillaPayoff(option_type, strike)

    # ++++++++++++++++++ The OPTIONS : (American and European) with their dividends description:
    dividendEuropeanOption = DividendVanillaOption(
        payoff, europeanExercise, dividendDates, dividends
    )
    dividendAmericanOption = DividendVanillaOption(
        payoff, americanExercise, dividendDates, dividends
    )


    # just too test
    europeanOption = VanillaOption(payoff, europeanExercise)
    americanOption =  VanillaOption(payoff, americanExercise)

    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ Description of the pricing  +++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    # For the european options we have a closed analytic formula: The Black Scholes:
    dividendEuropeanEngine = AnalyticDividendEuropeanEngine(bsProcess)

    # For the american option we have make the choice of the finite difference model with the CrankNicolson scheme
    #		this model need to precise the time and space step
    #		More they are greater, more the calul will be precise.
    americanGirdPoints = 600
    americanTimeSteps	= 600
    dividendAmericanEngine = FDDividendAmericanEngine('CrankNicolson', bsProcess,americanTimeSteps, americanGirdPoints)

    # just to test
    europeanEngine = AnalyticEuropeanEngine(bsProcess)
    americanEngine = FDAmericanEngine('CrankNicolson', bsProcess,americanTimeSteps, americanGirdPoints)


    # ++++++++++++++++++++ Valorisation ++++++++++++++++++++++++++++++++++++++++
        
    # Link the pricing Engine to the option
    dividendEuropeanOption.set_pricing_engine(dividendEuropeanEngine)
    dividendAmericanOption.set_pricing_engine(dividendAmericanEngine)
    
    # just	to test
    europeanOption.set_pricing_engine(europeanEngine)
    americanOption.set_pricing_engine(americanEngine)

    # Now we make all the needing calcul	
    # ... and final results
    print("NPV of the European Option with discrete dividends=0:	{:.4f}".format(dividendEuropeanOption.npv))
    print("NPV of the European Option without dividend:		{:.4f}".format(europeanOption.npv))
    print("NPV of the American Option with discrete dividends=0:	{:.4f}".format(dividendAmericanOption.npv))
    print("NPV of the American Option without dividend:		{:.4f}".format(americanOption.npv))
    # just a single test
    print("ZeroRate with a maturity at ", maturity, ": ", \
            riskFreeTS.zero_rate(maturity, dayCounter, Simple))
コード例 #43
0
ファイル: test_settings.py プロジェクト: surfmaverick/pyql
    def test_settings_instance_method(self):

        Settings.instance().evaluation_date = today()

        self.assertEquals(today(), Settings.instance().evaluation_date)
コード例 #44
0
)
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%
    # corresponds to a flat 3% hazard rate. The implied 1-year
    # survival probability is 97.04% and the 2-years is 94.18%

    # market
    recovery_rate = 0.5
    quoted_spreads = [0.0150, 0.0150, 0.0150, 0.0150 ]
コード例 #45
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)
コード例 #46
0
ファイル: bonds.py プロジェクト: stan2133/pyql
from quantlib.instruments.bonds import FixedRateBond
from quantlib.time.api import (TARGET, Unadjusted, ModifiedFollowing,
                               Following, NullCalendar)
from quantlib.compounding import Continuous
from quantlib.pricingengines.bond import DiscountingBondEngine
from quantlib.time.date import Date, August, Period, Jul, Annual, Years
from quantlib.time.daycounter 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(effective_date, termination_date,
コード例 #47
0
ファイル: option_valuation.py プロジェクト: systemtrader/pyql
def dividendOption():
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ General Parameter for all the computation +++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    # declaration of the today's date (date where the records are done)
    todaysDate = Date(24, Jan, 2012)  # INPUT
    Settings.instance(
    ).evaluation_date = todaysDate  #!\ IMPORTANT COMMAND REQUIRED FOR ALL VALUATIONS
    calendar = UnitedStates()  # INPUT
    settlement_days = 2  # INPUT
    # Calcul of the settlement date : need to add a period of 2 days to the todays date
    settlementDate = calendar.advance(todaysDate,
                                      period=Period(settlement_days, Days))
    dayCounter = Actual360()  # INPUT
    currency = USDCurrency()  # INPUT

    print("Date of the evaluation:			", todaysDate)
    print("Calendar used:         			", calendar.name)
    print("Number of settlement Days:		", settlement_days)
    print("Date of settlement:       		", settlementDate)
    print("Convention of day counter:		", dayCounter.name())
    print("Currency of the actual context:\t\t", currency.name)

    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ Description of the underlying +++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    underlying_name = "IBM"
    underlying_price = 191.75  # INPUT
    underlying_vol = 0.2094  # INPUT

    print("**********************************")
    print("Name of the underlying:			", underlying_name)
    print("Price of the underlying at t0:	", underlying_price)
    print("Volatility of the underlying:		", underlying_vol)

    # For a great managing of price and vol objects --> Handle
    underlying_priceH = SimpleQuote(underlying_price)

    # We suppose the vol constant : his term structure is flat --> BlackConstantVol object
    flatVolTS = BlackConstantVol(settlementDate, calendar, underlying_vol,
                                 dayCounter)

    # ++++++++++++++++++++ Description of Yield Term Structure

    #  Libor data record
    print("**********************************")
    print("Description of the Libor used for the Yield Curve construction")

    Libor_dayCounter = Actual360()

    liborRates = []
    liborRatesTenor = []
    # INPUT : all the following data are input : the rate and the corresponding tenor
    #		You could make the choice of more or less data
    #		--> However you have tho choice the instruments with different maturities
    liborRates = [
        0.002763, 0.004082, 0.005601, 0.006390, 0.007125, 0.007928, 0.009446,
        0.01110
    ]
    liborRatesTenor = [
        Period(tenor, Months) for tenor in [1, 2, 3, 4, 5, 6, 9, 12]
    ]

    for tenor, rate in zip(liborRatesTenor, liborRates):
        print(tenor, "\t\t\t", rate)

    # Swap data record

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

    print("Description of the Swap used for the Yield Curve construction")
    print("Tenor of the fixed leg:			", Swap_fixedLegTenor)
    print("Index of the floated leg: 		", Swap_iborIndex.name)
    print("Maturity		Rate				")

    swapRates = []
    swapRatesTenor = []
    # INPUT : all the following data are input : the rate and the corresponding tenor
    #		You could make the choice of more or less data
    #		--> However you have tho choice the instruments with different maturities
    swapRates = [
        0.005681, 0.006970, 0.009310, 0.012010, 0.014628, 0.016881, 0.018745,
        0.020260, 0.021545
    ]
    swapRatesTenor = [Period(i, Years) for i in range(2, 11)]

    for tenor, rate in zip(swapRatesTenor, swapRates):
        print(tenor, "\t\t\t", rate)

    # ++++++++++++++++++++ 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))

    # +++++++++++++++++++++ Swap
    SwapFamilyName = currency.name + "swapIndex"
    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

    riskFreeTS = PiecewiseYieldCurve.from_reference_date(
        BootstrapTrait.ZeroYield, Interpolator.Linear, settlementDate,
        instruments, dayCounter)

    # ++++++++++++++++++  build of the underlying process : with a Black-Scholes model

    print('Creating process')

    bsProcess = BlackScholesProcess(underlying_priceH, riskFreeTS, flatVolTS)

    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ Description of the option +++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    Option_name = "IBM Option"
    maturity = Date(26, Jan, 2013)
    strike = 190
    option_type = 'call'

    # Here, as an implementation exemple, we make the test with borth american and european exercise
    europeanExercise = EuropeanExercise(maturity)
    # The emericanExercise need also the settlement date, as his right to exerce the buy or call start at the settlement date!
    #americanExercise = AmericanExercise(settlementDate, maturity)
    americanExercise = AmericanExercise(maturity, settlementDate)

    print("**********************************")
    print("Description of the option:		", Option_name)
    print("Date of maturity:     			", maturity)
    print("Type of the option:   			", option_type)
    print("Strike of the option:		    ", strike)

    # ++++++++++++++++++ Description of the discrete dividends
    # INPUT You have to determine the frequece and rates of the discrete dividend. Here is a sollution, but she's not the only one.
    # Last know dividend:
    dividend = 0.75  #//0.75
    next_dividend_date = Date(10, Feb, 2012)
    # HERE we have make the assumption that the dividend will grow with the quarterly croissance:
    dividendCroissance = 1.03
    dividendfrequence = Period(3, Months)
    dividendDates = []
    dividends = []

    d = next_dividend_date
    while d <= maturity:
        dividendDates.append(d)
        dividends.append(dividend)
        d = d + dividendfrequence
        dividend *= dividendCroissance

    print("Discrete dividends				")
    print("Dates				Dividends		")
    for date, div in zip(dividendDates, dividends):
        print(date, "		", div)

    # ++++++++++++++++++ Description of the final payoff
    payoff = PlainVanillaPayoff(option_type, strike)

    # ++++++++++++++++++ The OPTIONS : (American and European) with their dividends description:
    dividendEuropeanOption = DividendVanillaOption(payoff, europeanExercise,
                                                   dividendDates, dividends)
    dividendAmericanOption = DividendVanillaOption(payoff, americanExercise,
                                                   dividendDates, dividends)

    # just too test
    europeanOption = VanillaOption(payoff, europeanExercise)
    americanOption = VanillaOption(payoff, americanExercise)

    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++ Description of the pricing  +++++++++++++++++++++++++++++++++++++
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    # For the european options we have a closed analytic formula: The Black Scholes:
    dividendEuropeanEngine = AnalyticDividendEuropeanEngine(bsProcess)

    # For the american option we have make the choice of the finite difference model with the CrankNicolson scheme
    #		this model need to precise the time and space step
    #		More they are greater, more the calul will be precise.
    americanGirdPoints = 600
    americanTimeSteps = 600
    dividendAmericanEngine = FDDividendAmericanEngine('CrankNicolson',
                                                      bsProcess,
                                                      americanTimeSteps,
                                                      americanGirdPoints)

    # just to test
    europeanEngine = AnalyticEuropeanEngine(bsProcess)
    americanEngine = FDAmericanEngine('CrankNicolson', bsProcess,
                                      americanTimeSteps, americanGirdPoints)

    # ++++++++++++++++++++ Valorisation ++++++++++++++++++++++++++++++++++++++++

    # Link the pricing Engine to the option
    dividendEuropeanOption.set_pricing_engine(dividendEuropeanEngine)
    dividendAmericanOption.set_pricing_engine(dividendAmericanEngine)

    # just	to test
    europeanOption.set_pricing_engine(europeanEngine)
    americanOption.set_pricing_engine(americanEngine)

    # Now we make all the needing calcul
    # ... and final results
    print(
        "NPV of the European Option with discrete dividends=0:	{:.4f}".format(
            dividendEuropeanOption.npv))
    print("NPV of the European Option without dividend:		{:.4f}".format(
        europeanOption.npv))
    print(
        "NPV of the American Option with discrete dividends=0:	{:.4f}".format(
            dividendAmericanOption.npv))
    print("NPV of the American Option without dividend:		{:.4f}".format(
        americanOption.npv))
    # just a single test
    print("ZeroRate with a maturity at ", maturity, ": ", \
            riskFreeTS.zero_rate(maturity, dayCounter, Simple))
コード例 #48
0
def main():
    # global data
    todays_date = Date(15, May, 1998)
    Settings.instance().evaluation_date = todays_date
    settlement_date = Date(17, May, 1998)

    risk_free_rate = FlatForward(reference_date=settlement_date,
                                 forward=0.06,
                                 daycounter=Actual365Fixed())

    # option parameters
    exercise = AmericanExercise(earliest_exercise_date=settlement_date,
                                latest_exercise_date=Date(17, May, 1999))
    payoff = PlainVanillaPayoff(Put, 40.0)

    # market data
    underlying = SimpleQuote(36.0)
    volatility = BlackConstantVol(todays_date, TARGET(), 0.20,
                                  Actual365Fixed())
    dividend_yield = FlatForward(reference_date=settlement_date,
                                 forward=0.00,
                                 daycounter=Actual365Fixed())

    # report
    header = '%19s' % 'method' + ' |' + \
        ' |'.join(['%17s' % tag for tag in ['value',
                                            'estimated error',
                                            'actual error']])
    print()
    print(header)
    print('-' * len(header))

    refValue = None

    def report(method, x, dx=None):
        e = '%.4f' % abs(x - refValue)
        x = '%.5f' % x
        if dx:
            dx = '%.4f' % dx
        else:
            dx = 'n/a'
        print('%19s' % method + ' |' +
              ' |'.join(['%17s' % y for y in [x, dx, e]]))

    # good to go

    process = BlackScholesMertonProcess(underlying, dividend_yield,
                                        risk_free_rate, volatility)

    option = VanillaOption(payoff, exercise)

    refValue = 4.48667344
    report('reference value', refValue)

    # method: analytic

    option.set_pricing_engine(BaroneAdesiWhaleyApproximationEngine(process))
    report('Barone-Adesi-Whaley', option.net_present_value)

    # method: finite differences
    time_steps = 801
    grid_points = 800

    option.set_pricing_engine(
        FDAmericanEngine('CrankNicolson', process, time_steps, grid_points))
    report('finite differences', option.net_present_value)

    print('This is work in progress.')
    print('Some pricing engines are not yet interfaced.')

    return

    option.set_pricing_engine(BjerksundStenslandEngine(process))
    report('Bjerksund-Stensland', option.NPV())

    # method: binomial
    timeSteps = 801

    option.setPricingEngine(BinomialVanillaEngine(process, 'jr', timeSteps))
    report('binomial (JR)', option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process, 'crr', timeSteps))
    report('binomial (CRR)', option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process, 'eqp', timeSteps))
    report('binomial (EQP)', option.NPV())

    option.setPricingEngine(
        BinomialVanillaEngine(process, 'trigeorgis', timeSteps))
    report('bin. (Trigeorgis)', option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process, 'tian', timeSteps))
    report('binomial (Tian)', option.NPV())

    option.setPricingEngine(BinomialVanillaEngine(process, 'lr', timeSteps))
    report('binomial (LR)', option.NPV())
コード例 #49
0
ファイル: HestonSimulation.py プロジェクト: fish2000/pyql
# The Heston Process
# ------------------

# <codecell>


def flat_rate(forward, daycounter):
    return FlatForward(
        quote           = SimpleQuote(forward),
        settlement_days = 0,
        calendar        = NullCalendar(),
        daycounter      = daycounter
    )

settings = Settings.instance()
settlement_date = today()
settings.evaluation_date = settlement_date

daycounter = ActualActual()
calendar = NullCalendar()

interest_rate = .1
dividend_yield = .04

risk_free_ts = flat_rate(interest_rate, daycounter)
dividend_ts = flat_rate(dividend_yield, daycounter)

s0 = SimpleQuote(100.0)

# Heston model
コード例 #50
0
ファイル: cds.py プロジェクト: enthought/pyql
)
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%

    # market
    recovery_rate = 0.5
    quoted_spreads = [0.0150, 0.0150, 0.0150, 0.0150]
    tenors = [Period(i, Months) for i in [3, 6, 12, 24]]
    maturities = [calendar.adjust(todays_date + tenors[i], Following) for i in range(4)]
コード例 #51
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)
コード例 #52
0
ファイル: plot.py プロジェクト: kevingivens/Blog
from quantlib.quotes import SimpleQuote
from quantlib.settings import Settings
from quantlib.time.api import (TARGET, Actual365Fixed, Date, UnitedStates,
                               NullCalendar)
from quantlib.math.matrix import Matrix
from quantlib.termstructures.yields.flat_forward import FlatForward
from quantlib.termstructures.volatility.equityfx.black_variance_surface import BlackVarianceSurface
from quantlib.termstructures.volatility.equityfx.local_vol_surface import LocalVolSurface

dc = Actual365Fixed()
calendar = UnitedStates()

calculation_date = Date(6, 11, 2015)

spot = 659.37
Settings.instance().evaluation_date = calculation_date

dividend_yield = SimpleQuote(0.0)
risk_free_rate = 0.01
dividend_rate = 0.0
# bootstrap the yield/dividend/vol curves
flat_term_structure = FlatForward(reference_date=calculation_date,
                                  forward=risk_free_rate,
                                  daycounter=dc)

flat_dividend_ts = FlatForward(reference_date=calculation_date,
                               forward=dividend_yield,
                               daycounter=dc)

dates = [
    Date(6, 12, 2015),