I have a table of bonds which I imported into python using pandas.
Is there a way I can simultaneously price all of them in python using the Quantlib library. I know how to price one bond but not in a table.
Quantitative Finance Stack Exchange is a question and answer site for finance professionals and academics. It only takes a minute to sign up.
Sign up to join this communityQuantLib doesn't really have the concept of portfolio but since you're using pandas, you can play around with that to price your bonds at once. Here is an example:
data = [
[ "15-06-2018", "15-06-2022", 4.75, 500 ],
[ "21-07-2017", "21-07-2027", 0.25, 100 ],
[ "17-02-2015", "17-02-2045", 1.50, 250 ],
]
bonds = pd.DataFrame(data, columns=["start", "maturity", "coupon", "notional"])
def makeBond(row):
start, maturity, coupon, notional = row
startDate = ql.Date(start, "%d-%m-%Y")
maturityDate = ql.Date(maturity, "%d-%m-%Y")
return ql.FixedRateBond(2, ql.TARGET(), 100, startDate, maturityDate, ql.Period("1Y"), [coupon], ql.ActualActual())
yts = ql.YieldTermStructureHandle(
ql.FlatForward(2, ql.TARGET(), 0.05, ql.Actual360())
)
engine = ql.DiscountingBondEngine(yts)
bonds['bond'] = bonds.apply(makeBond, axis=1)
bonds['bond'].apply(lambda x: x.setPricingEngine(engine))
bonds['bond'].apply(lambda x: x.NPV()).sum()
Or you could even make a bond portfolio object from a pandas DataFrame:
class BondPortfolio(pd.DataFrame):
def makeBond(self, row):
start, maturity, coupon, notional = row
startDate = ql.Date(start, "%d-%m-%Y")
maturityDate = ql.Date(maturity, "%d-%m-%Y")
return ql.FixedRateBond(2, ql.TARGET(), 100, startDate, maturityDate, ql.Period("1Y"), [coupon], ql.ActualActual())
def makeBonds(self):
self['bond'] = self.apply(self.makeBond, axis=1)
def setPricingEngine(self, engine):
self['bond'].apply(lambda x: x.setPricingEngine(engine))
def NPV(self):
return self['bond'].apply(lambda x: x.NPV()).sum()
portfolio = BondPortfolio(data, columns=["start", "maturity", "coupon", "notional"])
portfolio.makeBonds()
portfolio.setPricingEngine(engine)
portfolio.NPV()