Exemple #1
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)
Exemple #2
0
    def test_create_swap_rate_helper_from_index(self):
        calendar = UnitedStates()
        settlement_days = 2
        currency = USDCurrency()
        fixed_leg_tenor	= Period(12, Months)
        fixed_leg_convention = ModifiedFollowing
        fixed_leg_daycounter = Actual360()
        family_name = currency.name + 'index'
        ibor_index =  Libor(
            "USDLibor", Period(3,Months), settlement_days, USDCurrency(),
            UnitedStates(), Actual360()
        )

        rate = SimpleQuote(0.005681)
        tenor = Period(1, Years)

        index = SwapIndex (
            family_name, tenor, settlement_days, currency, calendar,
            fixed_leg_tenor, fixed_leg_convention,
            fixed_leg_daycounter, ibor_index)

        helper_from_quote = SwapRateHelper.from_index(rate, index)
        helper_from_float = SwapRateHelper.from_index(0.005681, index)

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

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

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

        rate = SimpleQuote(0.005681)

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

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

        with self.assertRaises(RuntimeError):
            self.assertAlmostEqual(rate.value, helper_from_quote.implied_quote)
Exemple #4
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)
Exemple #5
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))
def build_helpers():
        calendar = TARGET()
        settlement_days = 2

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

        swapData = [[1, Years, 'Swap1Y', 5.31],
                    [2, Years, 'Swap2Y', 5.06],
                    [3, Years, 'Swap3Y', 5.00],
                    [4, Years, 'Swap4Y', 5.01],
                    [5, Years, 'Swap5Y', 5.04],
                    [7, Years, 'Swap7Y', 5.12],
                    [10, Years, 'Swap10Y', 5.22],
                    [30, Years, 'Swap30Y', 5.44]]

        rate_helpers = []

        end_of_month = True

        for m, _, _, rate in depositData:
            tenor = Period(m, Months)
            helper = DepositRateHelper(SimpleQuote(rate / 100.0), tenor,
                                       settlement_days,
                                       calendar, ModifiedFollowing,
                                       end_of_month,
                                       Actual360())

        rate_helpers.append(helper)

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

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

        for m, _, _, rate in swapData:
            helper = SwapRateHelper.from_tenor(
                SimpleQuote(rate / 100.0),
                Period(m, Years),
                calendar, Semiannual,
                ModifiedFollowing, Thirty360(),
                liborIndex, spread, fwdStart)

        rate_helpers.append(helper)

        return rate_helpers
Exemple #7
0
def make_rate_helper(label, rate, dt_obs, currency='USD'):
    """
    Wrapper for deposit and swaps rate helpers makers
    For Swaps: assume USD swap fixed rates vs. 6M Libor
    TODO: make this more general
    """

    if(currency.upper() != 'USD'):
        raise Exception("Only supported currency is USD.")

    rate_type, tenor, period = _parse_rate_label(label)

    if not isinstance(dt_obs, Date):
        dt_obs = pydate_to_qldate(dt_obs)
    settings = Settings()
    calendar = JointCalendar(UnitedStates(), UnitedKingdom())
    # must be a business day
    eval_date = calendar.adjust(dt_obs)
    settings.evaluation_date = eval_date
    settlement_days = 2
    settlement_date = calendar.advance(eval_date, settlement_days, Days)
    # must be a business day
    settlement_date = calendar.adjust(settlement_date)
    end_of_month = True

    if((rate_type == 'SWAP') & (period == 'Y')):
        liborIndex = Libor(
            'USD Libor', Period(6, Months), settlement_days,
            USDCurrency(), calendar, Actual360()
        )
        spread = SimpleQuote(0)
        fwdStart = Period(0, Days)
        helper = SwapRateHelper.from_tenor(rate,
                 Period(tenor, Years),
                 calendar, Annual,
                 Unadjusted, Thirty360(),
                 liborIndex, spread, fwdStart)
    elif((rate_type == 'LIBOR') & (period == 'M')):
        helper = DepositRateHelper(rate, Period(tenor, Months),
                 settlement_days,
                 calendar, ModifiedFollowing,
                 end_of_month,
                 Actual360())
    else:
        raise Exception("Rate type %s not supported" % label)

    return (helper)
Exemple #8
0
    def test_create_swap_index(self):

        term_structure = YieldTermStructure()
        term_structure.link_to(
            FlatForward(forward=0.05,
                        daycounter=Actual365Fixed(),
                        settlement_days=2,
                        calendar=UnitedStates()))

        ibor_index = USDLibor(Period(3, Months), term_structure)

        index = SwapIndex('UsdLiborSwapIsdaFixAm', Period(10, Years), 2,
                          USDCurrency(), UnitedStates(GovernmentBond),
                          Period(6, Months), ModifiedFollowing, Thirty360(),
                          ibor_index)
        index2 = UsdLiborSwapIsdaFixAm(Period(10, Years), term_structure)
        for attr in [
                'name', 'family_name', 'fixing_calendar', 'tenor',
                'day_counter', 'currency'
        ]:
            self.assertEqual(getattr(index, attr), getattr(index2, attr))
Exemple #9
0
 def test_from_name(self):
     cu_1 = Currency.from_name('USD')
     cu_2 = USDCurrency()
     self.assertEquals(cu_1.name, cu_2.name)
     self.assertIsInstance(cu_1, USDCurrency)
Exemple #10
0
    def test_zero_curve(self):

        try:

            settings = Settings()

            calendar = TARGET()

            # must be a business Days
            dtObs = date(2007, 4, 27)
            eval_date = calendar.adjust(pydate_to_qldate(dtObs))
            settings.evaluation_date = eval_date

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

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

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

            swapData = [[1, Years, 'Swap1Y', 5.31], [2, Years, 'Swap2Y', 5.06],
                        [3, Years, 'Swap3Y', 5.00], [4, Years, 'Swap4Y', 5.01],
                        [5, Years, 'Swap5Y', 5.04], [7, Years, 'Swap7Y', 5.12],
                        [10, Years, 'Swap10Y', 5.22],
                        [30, Years, 'Swap30Y', 5.44]]

            rate_helpers = []

            end_of_month = True

            for m, period, label, rate in depositData:
                tenor = Period(m, Months)
                helper = DepositRateHelper(SimpleQuote(rate / 100.0), tenor,
                                           settlement_days, calendar,
                                           ModifiedFollowing, end_of_month,
                                           Actual360())

                rate_helpers.append(helper)

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

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

            for m, period, label, rate in swapData:
                helper = SwapRateHelper.from_tenor(SimpleQuote(rate / 100.0),
                                                   Period(m, Years), calendar,
                                                   Semiannual,
                                                   ModifiedFollowing,
                                                   Thirty360(), liborIndex,
                                                   spread, fwdStart)

                rate_helpers.append(helper)

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

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

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

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

            self.assertTrue(True)

        except Exception:
            self.assertFalse()
    def test_display(self):

        settings = Settings()

        # Date setup
        calendar = TARGET()

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

        # Evaluation date
        fixing_days = 1
        settlement_days = 1

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

        settings.evaluation_date = todays_date

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

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


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


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



        d=bf.startDate(bond)

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


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

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

        rate_helpers = []

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

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

            rate_helpers.append(helper)

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

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

        for m, period, rate in swapData:

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

            rate_helpers.append(helper)

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

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

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

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


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

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

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

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

        self.assertEqual(round(dur, 4), 8.0655)
        self.assertEqual(round(dur_disco, 4), 7.9702)
Exemple #12
0
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))
Exemple #13
0
    def test_swap_QL(self):
        """
        Test that a swap with fixed coupon = fair rate has an NPV=0
        Create from QL objects
        """

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

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

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

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

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

        length = 5
        fixedRate = .05
        floatingSpread = 0.0

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

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

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

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

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

            p = swap.net_present_value
            print('NPV: %f' % p)
            self.assertAlmostEqual(p, 0)
Exemple #14
0
    def test_zero_curve_on_swap_index(self):

        todays_date = today()

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

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

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

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


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

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

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

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


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

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

        tolerance = 1.0e-15

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

        self.assertEqual(settlement_date, ts.reference_date)
Exemple #15
0
    def test_deposit_swap(self):

        settings = Settings()

        # Market information
        calendar = TARGET()

        todays_date = Date(1, Mar, 2012)

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

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

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

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

        rate_helpers = []

        end_of_month = True

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


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

            rate_helpers.append(helper)

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

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

        for m, period, rate in swapData:

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

            rate_helpers.append(helper)

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

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

        self.assertEqual(settlement_date, ts.reference_date)

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

    settings = Settings()

    # Market information
    calendar = TARGET()

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

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

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

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

    rate_helpers = []

    end_of_month = True

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

        rate_helpers.append(helper)

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

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

    for m, period, label in swapData:
        rate = df_libor.get_value(dtObs, label)
        helper = SwapRateHelper.from_tenor(
            SimpleQuote(rate / 100.0),
            Period(m, Years),
            calendar, Semiannual,
            ModifiedFollowing, Thirty360(),
            liborIndex, spread, fwdStart)

        rate_helpers.append(helper)

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

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

    return ts
Exemple #17
0
    def test_bucketanalysis_bond(self):

        settings = Settings()

        calendar = TARGET()

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

        fixing_days = 1
        settlement_days = 1

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

        settings.evaluation_date = todays_date

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

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

        flat_discounting_term_structure.link_to(flat_term_structure)

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

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

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

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

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

        rate_helpers = []

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

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

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

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

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

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

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

        self.assertAlmostEqual(bond.npv, 100.83702940160767)

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

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