0
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

QuantLib 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()

3347.2767053215985

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()

3347.2767053215985

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.