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
예제 #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
파일: test_cms.py 프로젝트: xie3ge/pyql
    def setUp(self):
        atm_option_tenors = [Period(1, Months), Period(6, Months)] + \
                            [Period(i, Years) for i in [1, 5, 10, 30]]
        atm_swap_tenors = [Period(1, Years), Period(5, Years), Period(10, Years),
                           Period(30, Years)]

        m = np.array([[.1300, .1560, .1390, .1220],
                      [.1440, .1580, .1460, .1260],
                      [.1600, .1590, .1470, .1290],
                      [.1640, .1470, .1370, .1220],
                      [.1400, .1300, .1250, .1100],
                      [.1130, .1090, .1070, .0930]])

        M = Matrix.from_ndarray(m)

        calendar = UnitedStates()
        self.atm_vol = SwaptionVolatilityMatrix(calendar,
                                                Following,
                                                atm_option_tenors,
                                                atm_swap_tenors,
                                                M,
                                                Actual365Fixed())

        reference_date = calendar.adjust(today())
        Settings().evaluation_date = reference_date
        self.term_structure = FlatForward(reference_date, 0.05, Actual365Fixed())
        self.swap_index = EuriborSwapIsdaFixA(Period(10, Years),
                                              forwarding=self.term_structure)
예제 #4
0
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))
 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)))
예제 #6
0
    def setUp(self):
        atm_option_tenors = [Period(1, Months), Period(6, Months)] + \
                            [Period(i, Years) for i in [1, 5, 10, 30]]
        atm_swap_tenors = [Period(1, Years), Period(5, Years),
                           Period(10, Years), Period(30, Years)]

        m = np.array([[.1300, .1560, .1390, .1220],
                      [.1440, .1580, .1460, .1260],
                      [.1600, .1590, .1470, .1290],
                      [.1640, .1470, .1370, .1220],
                      [.1400, .1300, .1250, .1100],
                      [.1130, .1090, .1070, .0930]])

        M = Matrix.from_ndarray(m)

        calendar = UnitedStates()
        self.atm_vol_matrix = SwaptionVolatilityMatrix(calendar,
                                                       Following,
                                                       atm_option_tenors,
                                                       atm_swap_tenors,
                                                       M,
                                                       Actual365Fixed())
        term_structure = FlatForward(forward=0.05, settlement_days=2, calendar=calendar,
            daycounter=Actual365Fixed())
        self.swap_index_base = EuriborSwapIsdaFixA(Period(2, Years),
                                                   term_structure)
        self.short_swap_index_base = EuriborSwapIsdaFixA(Period(1, Years),
                                                         term_structure)
        self.vega_weighted_smile_fit = False

        class Cube:
            def __init__(self):
                self.option_tenors = [Period(1, Years), Period(10, Years), Period(30, Years)]
                self.swap_tenors = [Period(2, Years), Period(10, Years), Period(30, Years)]
                self.strike_spreads = [-0.02, -0.005, 0, 0.005, 0.02]
                self.vol_spreads = np.array([[0.0599, 0.0049, 0.0000, -0.0001, 0.0127],
                                             [0.0729, 0.0086, 0.0000, -0.0024, 0.0098],
                                             [0.0738, 0.0102, 0.0000, -0.0039, 0.0065],
                                             [0.0465, 0.0063, 0.0000, -0.0032, -0.0010],
                                             [0.0558, 0.0084, 0.0000, -0.0050, -0.0057],
                                             [0.0576, 0.0083, 0.0000, -0.0043, -0.0014],
                                             [0.0437, 0.0059, 0.0000, -0.0030, -0.0006],
                                             [0.0533, 0.0078, 0.0000, -0.0045, -0.0046],
                                             [0.0545, 0.0079, 0.0000, -0.0042, -0.0020]])
                self.vol_spreads_handle = []
                for vs in self.vol_spreads:
                    self.vol_spreads_handle.append([SimpleQuote(v) for v in vs])
        self.cube = Cube()
예제 #7
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))
예제 #8
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))
예제 #9
0
    def test_piecewise_methods(self):

        for trait in ProbabilityTrait:
            for interpolator in Interpolator:
                curve = PiecewiseDefaultCurve.from_reference_date(
                    trait,
                    interpolator,
                    reference_date=self.todays_date,
                    helpers=[self.helper],
                    daycounter=Actual365Fixed())

                if interpolator == Interpolator.LogLinear and \
                   trait in [ProbabilityTrait.HazardRate, ProbabilityTrait.DefaultDensity]:
                    with self.assertRaisesRegexp(
                            RuntimeError,
                            'LogInterpolation primitive not implemented'):
                        curve.survival_probability(self.d)
                else:
                    self.assertEqual(
                        curve.survival_probability(self.d),
                        curve.survival_probability(
                            curve.time_from_reference(self.d)))
                    self.assertEqual(
                        curve.hazard_rate(self.d),
                        curve.hazard_rate(curve.time_from_reference(self.d)))
예제 #10
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)
예제 #11
0
 def setUp(self):
     """"""
     self.today = today()
     self.settings = Settings()
     self.settings.evaluation_date = self.today
     self.dc = Actual365Fixed()
     self.spot = SimpleQuote(0.0)
     self.q_rate = SimpleQuote(0.0)
     self.q_ts = FlatForward(self.today, self.q_rate, self.dc)
     self.r_rate = SimpleQuote(0.0)
     self.r_ts = FlatForward(self.today, self.r_rate, self.dc)
     self.values = {
         'type': SwapType.Long,
         'strike': 0.04,
         'nominal': 50000,
         's': 100.0,
         'q': 0.00,
         'r': 0.05,
         't': 0.246575,
         'v': 0.20,
         'result': 0.04189,
         'tol': 1.0e-4,
     }
     self.spot.value = self.values['s']
     self.q_rate.value = self.values['q']
     self.r_rate.value = self.values['r']
     self.ex_date = self.today + int(self.values['t'] * 365 + 0.5)
예제 #12
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)
예제 #13
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))
예제 #14
0
    def test_clean_price(self):
        notional = 1000000.0
        fixed_rates = [0.1]
        fixed_day_count = Actual365Fixed()
        fixed_calendar = self.calendar
        fixed_index = self.ii
        contractObservationLag = Period(3, Months)
        observationInterpolation = InterpolationType.Flat
        settlement_days = 3
        growth_only = True

        baseCPI = 206.1

        fixed_schedule = Schedule.from_rule(Date(2, 10,
                                                 2007), Date(2, 10, 2052),
                                            Period(6, Months), fixed_calendar,
                                            Unadjusted, Rule.Backward)

        cpi_bond = CPIBond(settlement_days, notional, growth_only, baseCPI,
                           contractObservationLag, fixed_index,
                           observationInterpolation, fixed_schedule,
                           fixed_rates, fixed_day_count, ModifiedFollowing)

        engine = DiscountingBondEngine(self.yts)
        cpi_bond.set_pricing_engine(engine)
        set_coupon_pricer(cpi_bond.cashflows, CPICouponPricer(self.yts))
        storedPrice = 383.01816406
        calculated = cpi_bond.clean_price
        self.assertAlmostEqual(storedPrice, calculated)
예제 #15
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)
예제 #16
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))
 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)))
예제 #18
0
파일: utilities.py 프로젝트: gregKiely/pyql
def flat_rate(rate, dc=Actual365Fixed(), reference_date=None):
    if reference_date is None:
        return FlatForward(settlement_days=0,
                           calendar=NullCalendar(),
                           forward=rate,
                           daycounter=dc)
    else:
        return FlatForward(reference_date, rate, dc)
예제 #19
0
    def test_creation(self):

        settings = Settings()

        # Market information
        calendar = TARGET()

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

        settlement_date = Date(18, September, 2008)
        # must be a business day
        settlement_date = calendar.adjust(settlement_date);

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

        rate_helpers = []

        calendar =  TARGET()
        deposit_day_counter = Actual365Fixed()
        convention = ModifiedFollowing
        end_of_month = True

        for quote, month in zip(quotes, tenors):
            tenor = Period(month, Months)
            fixing_days = 3

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

            rate_helpers.append(helper)


        ts_day_counter = ActualActual(ISDA)

        tolerance = 1.0e-15

        ts = PiecewiseYieldCurve[BootstrapTrait.Discount, LogLinear].from_reference_date(
            settlement_date, rate_helpers,
            ts_day_counter, accuracy=tolerance
        )

        self.assertIsNotNone(ts)

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

        # this is not a real test ...
        self.assertAlmostEqual(0.9975, ts.discount(Date(21, 12, 2008)), 4)
        self.assertAlmostEqual(0.9944, ts.discount(Date(21, 4, 2009)), 4)
        self.assertAlmostEqual(0.9904, ts.discount(Date(21, 9, 2009)), 4)

        dates, dfs = zip(*ts.nodes)
        self.assertAlmostEqual(list(dates), ts.dates)
        self.assertAlmostEqual(list(dfs), ts.data)
예제 #20
0
    def test_creation(self):

        settlement_date = Date(1, January, 2014)
        term_structure = YieldTermStructure()
        term_structure.link_to(
            FlatForward(settlement_date, 0.05, Actual365Fixed()))
        index = USDLibor(Period(3, Months), term_structure)

        self.assertEqual(index.name, 'USDLibor3M Actual/360')
예제 #21
0
 def setUp(self):
     Settings().evaluation_date = Date(27, 4, 2018)
     self.yc = FlatForward(forward=0.03, settlement_days=2,
                           daycounter=Actual365Fixed(),
                           calendar=UnitedStates())
     self.index = UsdLiborSwapIsdaFixAm(Period(10, Years), self.yc)
     self.factory = (MakeSwaption(self.index, Period(2, Years), strike=0.0206).
                     with_underlying_type(Receiver).
                     with_settlement_type(Cash).
                     with_settlement_method(ParYieldCurve))
예제 #22
0
    def test_creation(self):

        settlement_date = Date(1, January, 2014)
        term_structure = YieldTermStructure(relinkable=True)
        term_structure.link_to(
            FlatForward(settlement_date, 0.05, Actual365Fixed()))
        # Makes sure the constructor does not segfault anymore ;-)
        index = Euribor6M(term_structure)

        self.assertEquals(index.name, 'Euribor6M Actual/360')
    def test_hull_white_calibration(self):
        """
        Adapted from ShortRateModelTest::testCachedHullWhite()
        """

        today = Date(15, February, 2002)
        settlement = Date(19, February, 2002)
        self.settings.evaluation_date = today
        yield_ts = FlatForward(settlement,
                               forward=0.04875825,
                               settlement_days=0,
                               calendar=NullCalendar(),
                               daycounter=Actual365Fixed())

        model = HullWhite(yield_ts, a=0.05, sigma=.005)

        data = [[1, 5, 0.1148 ],
                [2, 4, 0.1108 ],
                [3, 3, 0.1070 ],
                [4, 2, 0.1021 ],
                [5, 1, 0.1000 ]]

        index = Euribor6M(yield_ts)

        engine = JamshidianSwaptionEngine(model)

        swaptions = []
        for start, length, volatility in data:
            vol = SimpleQuote(volatility)
            helper = SwaptionHelper(Period(start, Years),
                                    Period(length, Years),
                                    vol,
                                    index,
                                    Period(1, Years), Thirty360(),
                                    Actual360(), yield_ts)

            helper.set_pricing_engine(engine)
            swaptions.append(helper)

        # Set up the optimization problem
        om = LevenbergMarquardt(1.0e-8, 1.0e-8, 1.0e-8)
        endCriteria = EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8)

        model.calibrate(swaptions, om, endCriteria)

        print('Hull White calibrated parameters:\na: %f sigma: %f' %
              (model.a, model.sigma))

        cached_a = 0.0464041
        cached_sigma = 0.00579912

        tolerance = 1.0e-5

        self.assertAlmostEqual(cached_a, model.a, delta=tolerance)
        self.assertAlmostEqual(cached_sigma, model.sigma, delta=tolerance)
예제 #24
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
예제 #25
0
    def test_create_piecewise(self):

        for trait in ProbabilityTrait:
            for interpolator in Interpolator:
                curve = PiecewiseDefaultCurve.from_reference_date(
                    trait,
                    interpolator,
                    reference_date=self.todays_date,
                    helpers=[self.helper],
                    daycounter=Actual365Fixed())
                self.assertIsNotNone(curve)
예제 #26
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)
예제 #27
0
def dfToZeroCurve(df_rates, dtSettlement, daycounter=Actual365Fixed()):
    """
    Convert a panda data frame into a QL zero curve
    """

    dates = [dateToQLDate(dt) for dt in df_rates.index]
    dates.insert(0, dateToQLDate(dtSettlement))
    dates.append(dates[-1] + 365 * 2)
    vx = list(df_rates.values)
    vx.insert(0, vx[0])
    vx.append(vx[-1])
    return ZeroCurve(dates, vx, daycounter)
예제 #28
0
    def test_creation(self):

        settings = Settings()

        # Market information
        calendar = TARGET()

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

        settlement_date = Date(18, September, 2008)
        # must be a business day
        settlement_date = calendar.adjust(settlement_date);

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

        rate_helpers = []

        calendar =  TARGET()
        deposit_day_counter = Actual365Fixed()
        convention = ModifiedFollowing
        end_of_month = True

        for quote, month in zip(quotes, tenors):
            tenor = Period(month, Months)
            fixing_days = 3

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

            rate_helpers.append(helper)


        ts_day_counter = ActualActual(ISDA)

        tolerance = 1.0e-15

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

        self.assertIsNotNone(ts)

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

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

        helper = DepositRateHelper(0.005, tenor, fixing_days, calendar,
                                   convention, end_of_month,
                                   deposit_day_counter)
        Settings.instance().evaluation_date = Date(8, 6, 2016)
        self.assertEqual(helper.latest_date, Date(13, 9, 2016))
예제 #30
0
    def test_bucket_analysis_option(self):

        settings = Settings()

        calendar = TARGET()

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

        settings.evaluation_date = todays_date

        option_type = Put
        underlying = 40
        strike = 40
        dividend_yield = 0.00
        risk_free_rate = 0.001
        volatility = 0.20
        maturity = Date(17, May, 1999)
        daycounter = Actual365Fixed()

        underlyingH = SimpleQuote(underlying)

        payoff = PlainVanillaPayoff(option_type, strike)

        flat_term_structure = FlatForward(reference_date=settlement_date,
                                          forward=risk_free_rate,
                                          daycounter=daycounter)
        flat_dividend_ts = FlatForward(reference_date=settlement_date,
                                       forward=dividend_yield,
                                       daycounter=daycounter)

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

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

        european_exercise = EuropeanExercise(maturity)
        european_option = VanillaOption(payoff, european_exercise)
        analytic_european_engine = AnalyticEuropeanEngine(
            black_scholes_merton_process)

        european_option.set_pricing_engine(analytic_european_engine)

        ba_eo = bucket_analysis([[underlyingH]], [european_option], [1], 0.50,
                                1)

        self.assertTrue(2, ba_eo)
        self.assertTrue(type(tuple), ba_eo)
        self.assertEqual(1, len(ba_eo[0][0]))
        self.assertAlmostEqual(-0.4582666150152517, ba_eo[0][0][0])