Reputation: 495
I followed GB's instructions on this website http://gouthamanbalaraman.com/blog/quantlib-bond-modeling.html
and the codes are below - defined a fixed rate bond, created a bondengine with term structure
import matplotlib
matplotlib.use('macosx')
import matplotlib.pyplot as plt
import QuantLib as ql
import pandas as pd
todaysDate = ql.Date(15, 1, 2015)
ql.Settings.instance().evaluationDate = todaysDate
spotDates = [ql.Date(15, 1, 2015), ql.Date(15, 7, 2015), ql.Date(15, 1, 2016)]
spotRates = [0.0, 0.005, 0.007]
dayCount = ql.Thirty360()
calendar = ql.UnitedStates()
interpolation = ql.Linear()
compounding = ql.Compounded
compoundingFrequency = ql.Annual
spotCurve = ql.ZeroCurve(spotDates, spotRates, dayCount, calendar, interpolation,compounding, compoundingFrequency)
spotCurveHandle = ql.YieldTermStructureHandle(spotCurve)
# define the fixed rate bond.
issueDate = ql.Date(15, 1, 2015)
maturityDate = ql.Date(15, 1, 2016)
tenor = ql.Period(ql.Semiannual)
calendar = ql.UnitedStates()
businessConvention = ql.Unadjusted
dateGeneration = ql.DateGeneration.Backward
monthEnd = False
schedule = ql.Schedule (issueDate, maturityDate, tenor, calendar, businessConvention, businessConvention, dateGeneration, monthEnd)
# coupons
dayCount = ql.Thirty360()
couponRate = .06
coupons = [couponRate]
settlementDays = 0
faceValue = 100
fixedRateBond = ql.FixedRateBond(settlementDays, faceValue, schedule, coupons, dayCount)
# create a bond engine with the term structure as input;
# set the bond to use this bond engine
bondEngine = ql.DiscountingBondEngine(spotCurveHandle)
fixedRateBond.setPricingEngine(bondEngine)
print(fixedRateBond.NPV())
#calculating yields
targetPrice = fixedRateBond.cleanPrice()
day_count = dayCount
compounding = ql.Compounded
frequency = 2
ytm = fixedRateBond.bondYield(targetPrice, day_count, compounding, frequency)
print(ytm)
Now how do I get the mod. duration for the bond? I understand the function to use is ql.BondFunctions.duration(bond,ytm,ql.Duration.Modified)
but that didn't work for me.
Upvotes: 0
Views: 4084
Reputation: 664
The input rate for the duration method has to be an InterestRate object and not a simple float, or you have to pass the conventions.
And the first parameter would be the bond which in your case is fixedRateBond
.
Try this:
rate = ql.InterestRate(ytm, ql.ActualActual(), ql.Compounded, ql.Annual)
ql.BondFunctions.duration(fixedRateBond,rate,ql.Duration.Modified)
or this:
ql.BondFunctions.duration(fixedRateBond,ytm,ql.ActualActual(), ql.Compounded, ql.Annual, ql.Duration.Modified)
Upvotes: 3