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)
def test_fair_rate(self): start_date = self.term_structure.reference_date + Period(20, Years) payment_date = start_date + Period(1, Years) end_date = payment_date nominal = 1.0 gearing = 1.0 spread = 0.0 coupon = CappedFlooredCmsCoupon(payment_date, nominal, start_date, end_date, self.swap_index.fixing_days, self.swap_index, gearing, spread, ref_period_start=start_date, ref_period_end=end_date, day_counter=self.swap_index.day_counter) for model in YieldCurveModel: pricer = NumericHaganPricer(self.atm_vol, model, SimpleQuote(0.)) coupon.set_pricer(pricer) rate_numeric = coupon.rate pricer = AnalyticHaganPricer(self.atm_vol, model, SimpleQuote(0.)) coupon.set_pricer(pricer) rate_analytic = coupon.rate pricer = LinearTsrPricer(self.atm_vol, SimpleQuote(0.)) coupon.set_pricer(pricer) rate_lineartsr = coupon.rate self.assertAlmostEqual(rate_lineartsr, rate_analytic, 3)
def make_rate_helper(market, quote, reference_date=None): """ Wrapper for deposit and swaps rate helpers makers TODO: class method of RateHelper? """ rate_type, tenor, quote_value = quote if rate_type == 'SWAP': libor_index = market._floating_rate_index spread = SimpleQuote(0) fwdStart = Period(0, Days) helper = SwapRateHelper.from_tenor( quote_value, Period(tenor), market._floating_rate_index.fixing_calendar, Period(market._params.fixed_leg_period).frequency, BusinessDayConvention.from_name( market._params.fixed_leg_convention), DayCounter.from_name(market._params.fixed_leg_daycount), libor_index, spread, fwdStart) elif rate_type == 'DEP': end_of_month = True helper = DepositRateHelper( quote_value, Period(tenor), market._params.settlement_days, market._floating_rate_index.fixing_calendar, market._floating_rate_index.business_day_convention, end_of_month, DayCounter.from_name(market._deposit_daycount)) elif rate_type == 'ED': if reference_date is None: raise Exception("Reference date needed with ED Futures data") forward_date = next_imm_date(reference_date, tenor) helper = FuturesRateHelper( price=SimpleQuote(quote_value), imm_date=qldate_from_pydate(forward_date), length_in_months=3, calendar=market._floating_rate_index.fixing_calendar, convention=market._floating_rate_index.business_day_convention, end_of_month=True, day_counter=DayCounter.from_name( market._params.floating_leg_daycount)) elif rate_type.startswith('ER'): # TODO For Euribor futures, we found it useful to supply the `imm_date` # parameter directly, instead of as a number of periods from the # evaluation date, as for ED futures. To achieve this, we pass the # `imm_date` in the `tenor` field of the quote. helper = FuturesRateHelper( price=SimpleQuote(quote_value), imm_date=tenor, length_in_months=3, calendar=market._floating_rate_index.fixing_calendar, convention=market._floating_rate_index.business_day_convention, end_of_month=True, day_counter=DayCounter.from_name( market._params.floating_leg_daycount)) else: raise Exception("Rate type %s not supported" % rate_type) return helper
def test_spreaded_cube(self): parameters_guess = [] for i in range(len(self.cube.option_tenors) * len(self.cube.swap_tenors)): parameters_guess.append([SimpleQuote(0.2), SimpleQuote(0.5), SimpleQuote(0.4), SimpleQuote(0.)]) is_parameter_fixed = [False] * 4 spread = SimpleQuote(0.0001) vol_cube = SwaptionVolCube1(self.atm_vol_matrix, self.cube.option_tenors, self.cube.swap_tenors, self.cube.strike_spreads, self.cube.vol_spreads_handle, self.swap_index_base, self.short_swap_index_base, self.vega_weighted_smile_fit, parameters_guess, is_parameter_fixed, True) spreaded_vol_cube = SpreadedSwaptionVolatility(vol_cube, spread) strikes = np.linspace(0.01, 0.99, 99) for t1 in self.cube.option_tenors: for t2 in self.cube.swap_tenors: smile_section_by_cube = vol_cube.smile_section( t1, t2) smile_section_by_spreaded_cube = (spreaded_vol_cube. smile_section(t1, t2)) for k in strikes: diff = spreaded_vol_cube.volatility(t1, t2, k) - \ vol_cube.volatility(t1, t2, k) self.assertAlmostEqual(diff, spread.value) diff = smile_section_by_spreaded_cube.volatility(k) - \ smile_section_by_cube.volatility(k) self.assertAlmostEqual(diff, spread.value)
def test_reference_evaluation_data_changed(self): """Testing term structure against evaluation date change... """ quote = SimpleQuote() term_structure = FlatForward(settlement_days=self.settlement_days, forward=quote, calendar=NullCalendar(), daycounter=Actual360()) quote.value = 0.03 expected = [] for days in [10, 30, 60, 120, 360, 720]: expected.append( term_structure.discount(self.adjusted_today + days) ) Settings().evaluation_date = self.adjusted_today + 30 calculated = [] for days in [10, 30, 60, 120, 360, 720]: calculated.append( term_structure.discount(self.adjusted_today+ 30 + days) ) for i, val in enumerate(expected): self.assertAlmostEqual(val, calculated[i])
def test_yield(self): rates_data = [('Libor1M',SimpleQuote(.01)), ('Libor3M', SimpleQuote(.015)), ('Libor6M', SimpleQuote(.017)), ('Swap1Y', SimpleQuote(.02)), ('Swap2Y', SimpleQuote(.03)), ('Swap3Y', SimpleQuote(.04)), ('Swap5Y', SimpleQuote(.05)), ('Swap7Y', SimpleQuote(.06)), ('Swap10Y', SimpleQuote(.07)), ('Swap20Y', SimpleQuote(.08))] settlement_date = pydate_to_qldate('01-Dec-2013') rate_helpers = [] for label, rate in rates_data: h = make_rate_helper(label, rate, settlement_date) rate_helpers.append(h) ts_day_counter = ActualActual(ISDA) tolerance = 1.0e-15 ts = PiecewiseYieldCurve( 'discount', 'loglinear', settlement_date, rate_helpers, ts_day_counter, tolerance ) zc = zero_rate(ts, (200, 300), settlement_date) # not a real test - just verify execution self.assertAlmostEqual(zc[1][0], 0.0189, 2)
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)
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))
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)))
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)
def setUp(self): self.mean_reversion = SimpleQuote(0.03) self.volatility = SimpleQuote(0.00714) self.index = USDLibor(Period(3, Months)) self.quote = SimpleQuote(99.375) Settings().evaluation_date = Date(13, 10, 2021) self.fut_quote = FuturesConvAdjustmentQuote(self.index, "Z2", self.quote, self.volatility, self.mean_reversion)
def test_using_simple_quote(self): quote = SimpleQuote(10) self.assertEquals(10, quote.value) quote.value = 15 self.assertEquals(15, quote.value) self.assertTrue(quote.is_valid)
def test_using_simple_quote(self): quote = SimpleQuote(10) self.assertEqual(10, quote.value) quote.value = 15 self.assertEqual(15, quote.value) self.assertTrue(quote.is_valid)
def test_zero_rate(self): """ Not a real test - just verifies that it runs """ instruments = ['Libor1M', 'Libor3M', 'Libor6M', 'Swap1Y', 'Swap2Y', 'Swap3Y', 'Swap5Y', 'Swap7Y', 'Swap10Y', 'Swap20Y', 'Swap30Y'] yields = [SimpleQuote(.01), SimpleQuote(.015), SimpleQuote(.02), SimpleQuote(.03), SimpleQuote(.04), SimpleQuote(.05), SimpleQuote(.06), SimpleQuote(.07), SimpleQuote(.08), SimpleQuote(.09), SimpleQuote(.1)] pricing_date = '01-dec-2013' dt, rates = zbt_libor_yield(instruments, yields, pricing_date, compounding_freq='Continuous', maturity_dates=None) self.assertAlmostEqual(rates[0], .01, 3)
def test_empty_constructor(self): quote = SimpleQuote() self.assertFalse(quote.is_valid) with self.assertRaisesRegexp(RuntimeError, 'invalid SimpleQuote'): x = quote.value # test quote reset quote.value = 1. quote.reset() self.assertFalse(quote.is_valid) with self.assertRaisesRegexp(RuntimeError, 'invalid SimpleQuote'): x = quote.value
def setUp(self): option_date = Date(20, 9, 2017) Settings().evaluation_date = Date(4, 8, 2017) self.strikes = (np.array([50, 55, 57.5, 60, 62.5, 65, 67.5, 70, 75, 80, 85, 90, 95, 100]) * 1e-4).tolist() vol = np.array([28.5, 31.6, 33.7, 36.1, 38.7, 41.5, 44.1, 46.5, 50.8, 54.4, 57.3, 59.8, 61.8, 63.6]) * 1e-2 vol_quotes = [SimpleQuote(q) for q in vol] self.forward = SimpleQuote(58.71e-4) atm_vol = (60-58.71)/1.5*33.7 + (58.71-57.5)/1.5*36.1 self.sabr_smile = SabrInterpolatedSmileSection(option_date, self.forward, self.strikes, False, SimpleQuote(0.4), vol_quotes, 0.1, 1, 0.1, 0.5, is_beta_fixed=True)
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 = SimpleQuote(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) delta, gamma = bucket_analysis([underlyingH, volatility], [european_option], shift=1e-4, type=Centered) self.assertAlmostEqual(delta[0], european_option.delta) self.assertAlmostEqual(delta[1], european_option.vega) self.assertAlmostEqual(gamma[0], european_option.gamma, 5)
def setUp(self): self.calendar = TARGET() self.settlement_days = 1 settlement_date = self.calendar.adjust(Date(28, January, 2011)) todays_date = self.calendar.advance( settlement_date, -self.settlement_days, Days ) Settings().evaluation_date = todays_date depositData = [[ 1, Months, 4.581 ], [ 2, Months, 4.573 ], [ 3, Months, 4.557 ], [ 6, Months, 4.496 ], [ 9, Months, 4.490 ]] swapData = [[ 1, Years, 4.54 ], [ 5, Years, 4.99 ], [ 10, Years, 5.47 ], [ 20, Years, 5.89 ], [ 30, Years, 5.96 ]] self.rate_helpers = [] end_of_month = True for m, period, rate in depositData: tenor = Period(m, Months) helper = DepositRateHelper(SimpleQuote(rate / 100), tenor, self.settlement_days, self.calendar, ModifiedFollowing, end_of_month, Actual360()) self.rate_helpers.append(helper) liborIndex = USDLibor(Period(6, Months)) for m, period, rate in swapData: sq_rate = SimpleQuote(rate/100) helper = SwapRateHelper.from_tenor( sq_rate, Period(m, Years), self.calendar, Annual, Unadjusted, Thirty360(), liborIndex ) self.rate_helpers.append(helper) ts_day_counter = ActualActual(ISDA) tolerance = 1.0e-15 self.ts = PiecewiseYieldCurve( BootstrapTrait.Discount, Interpolator.LogLinear, self.settlement_days, self.calendar, self.rate_helpers, ts_day_counter, tolerance)
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
def heston_helpers(spot, df_option, dtTrade, df_rates): """ Create array of heston options helpers """ DtSettlement = dateToQLDate(dtTrade) settings = Settings() settings.evaluation_date = DtSettlement calendar = TARGET() # convert data frame (date/value) into zero curve # expect the index to be a date, and 1 column of values risk_free_ts = dfToZeroCurve(df_rates['iRate'], dtTrade) dividend_ts = dfToZeroCurve(df_rates['iDiv'], dtTrade) # loop through rows in option data frame, construct # helpers for bid/ask oneDay = datetime.timedelta(days=1) dtExpiry = [dtTrade + int(t*365)*oneDay for t in df_option['TTM']] df_option['dtExpiry'] = dtExpiry options = [] for index, row in df_option.T.iteritems(): strike = row['Strike'] if (strike/spot.value > 1.3) | (strike/spot.value < .7): continue days = int(365*row['TTM']) maturity = Period(days, Days) options.append( HestonModelHelper( maturity, calendar, spot.value, strike, SimpleQuote(row['IVBid']), risk_free_ts, dividend_ts, ImpliedVolError)) options.append( HestonModelHelper( maturity, calendar, spot.value, strike, SimpleQuote(row['IVAsk']), risk_free_ts, dividend_ts, ImpliedVolError)) return {'options':options, 'spot': spot}
def test_all_types_of_piecewise_curves(self): settings = Settings() # Market information calendar = TARGET() todays_date = Date(12, September, 2008) # must be a business day settings.evaluation_date = calendar.adjust(todays_date) settlement_date = Date(18, September, 2008) # must be a business day settlement_date = calendar.adjust(settlement_date) quotes = [ SimpleQuote(0.0096), SimpleQuote(0.0145), SimpleQuote(0.0194) ] tenors = [3, 6, 12] rate_helpers = [] deposit_day_counter = Actual365Fixed() convention = ModifiedFollowing end_of_month = True for quote, month in zip(quotes, tenors): tenor = Period(month, Months) fixing_days = 3 helper = DepositRateHelper(quote, tenor, fixing_days, calendar, convention, end_of_month, deposit_day_counter) rate_helpers.append(helper) tolerance = 1.0e-15 for trait in BootstrapTrait: for interpolation in Interpolator: ts = PiecewiseYieldCurve.from_reference_date( trait, interpolation, settlement_date, rate_helpers, deposit_day_counter, tolerance) self.assertIsNotNone(ts) self.assertEqual(Date(18, September, 2008), ts.reference_date)
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
def setUp(self): self.settings = Settings() daycounter = ActualActual() interest_rate = .1 dividend_yield = .04 self.risk_free_ts = flat_rate(interest_rate, daycounter) self.dividend_ts = flat_rate(dividend_yield, daycounter) s0 = SimpleQuote(32.0) # Heston model v0 = 0.05 kappa = 5.0 theta = 0.05 sigma = 1.0e-4 rho = -0.5 self.heston_process = HestonProcess(self.risk_free_ts, self.dividend_ts, s0, v0, kappa, theta, sigma, rho, PartialTruncation) v0 = 0.05 ival = { 'v0': v0, 'kappa': 3.7, 'theta': v0, 'sigma': 1.0, 'rho': -.6, 'lambda': .1, 'nu': -.5, 'delta': 0.3 } spot = SimpleQuote(1200) self.bates_process = BatesProcess(self.risk_free_ts, self.dividend_ts, spot, ival['v0'], ival['kappa'], ival['theta'], ival['sigma'], ival['rho'], ival['lambda'], ival['nu'], ival['delta']) a = 0.376739 sigma = 0.0209 self.hullwhite_process = HullWhiteProcess(self.risk_free_ts, a, sigma)
def make_eurobond_helper(market, clean_price, coupons, tenor, issue_date, maturity): """ Wrapper for bond helpers. FIXME: This convenience method has some conventions specifically hardcoded for Eurobonds. These should be moved to the market. """ # Create schedule based on market and bond parameters. index = market._floating_rate_index schedule = Schedule.from_rule( issue_date, maturity, Period(tenor), index.fixing_calendar, index.business_day_convention, index.business_day_convention, Rule.Backward, # Date generation rule index.end_of_month, ) daycounter = DayCounter.from_name("Actual/Actual (Bond)") helper = FixedRateBondHelper( SimpleQuote(clean_price), market._params.settlement_days, 100.0, schedule, coupons, daycounter, Following, # Payment convention 100.0, issue_date) return helper
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)
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
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)
def setUp(self): settlement_date = today() settings = Settings() settings.evaluation_date = settlement_date daycounter = ActualActual() self.calendar = NullCalendar() i_rate = .1 i_div = .04 self.risk_free_ts = flat_rate(i_rate, daycounter) self.dividend_ts = flat_rate(i_div, daycounter) self.s0 = SimpleQuote(32.0) # Bates model self.v0 = 0.05 self.kappa = 5.0 self.theta = 0.05 self.sigma = 1.0e-4 self.rho = 0.0 self.Lambda = .1 self.nu = .01 self.delta = .001
def flat_rate(forward, daycounter): return FlatForward( forward=SimpleQuote(forward), settlement_days=0, calendar=NullCalendar(), daycounter=daycounter )
def test_create_fixed_rate_bond_helper(self): issue_date = Date(20, 3, 2014) maturity = Date(20, 3, 2019) schedule = Schedule( issue_date, maturity, Period(Annual), TARGET(), ModifiedFollowing, ModifiedFollowing, Backward, False ) clean_price = 71.23 settlement_days = 3 rates = [0.035] daycounter = DayCounter.from_name("Actual/Actual (Bond)") helper = FixedRateBondHelper( SimpleQuote(clean_price), settlement_days, 100.0, schedule, rates, daycounter, Following, 100.0, issue_date) self.assertEqual(helper.quote, clean_price)
def _blsimpv(price, spot, strike, risk_free_rate, time, option_type, dividend): spot = SimpleQuote(spot) daycounter = ActualActual(ISMA) risk_free_ts = FlatForward(today(), risk_free_rate, daycounter) dividend_ts = FlatForward(today(), dividend, daycounter) volatility_ts = BlackConstantVol(today(), NullCalendar(), .3, daycounter) process = BlackScholesMertonProcess(spot, dividend_ts, risk_free_ts, volatility_ts) exercise_date = today() + Period(time * 365, Days) exercise = EuropeanExercise(exercise_date) payoff = PlainVanillaPayoff(option_type, strike) option = EuropeanOption(payoff, exercise) engine = AnalyticEuropeanEngine(process) option.set_pricing_engine(engine) accuracy = 0.001 max_evaluations = 1000 min_vol = 0.01 max_vol = 2 vol = option.implied_volatility(price, process, accuracy, max_evaluations, min_vol, max_vol) return vol
from quantlib.quotes import SimpleQuote from quantlib.settings import Settings from quantlib.termstructures.yields.api import FlatForward from quantlib.time.api import Actual360, Date, NullCalendar, TARGET calendar = TARGET() settings = Settings() date_today = Date(6,9,2011) date_payment = Date(6,10,2011) settlement_days = 2 settings.evaluation_date = date_today quote = SimpleQuote(value=0.03) term_structure = FlatForward( settlement_days = settlement_days, quote = quote, calendar = NullCalendar(), daycounter = Actual360() ) df_1 = term_structure.discount(date_payment) date_today = Date(19,9,2011) settings.evaluation_date = date_today date_payment = Date(19,10,2011) df_2 = term_structure.discount(date_payment)