Friday, March 21, 2014

Interest Rate Swap - Pricing - Python +Quanlib


In previous note we have understood basic building blocks of an Yield Curve. Now using that Yield Curve we will look into modeling an Interest Rate Swap. Here I am considering a Plain Vanilla style USD 5y interest rate swap with 1,000,000 Notional. This Note pays Fixed rate of 1.57% per annum coupon semi annually and receives 3M Libor quarterly.
Below is the Code used to price up this swap. This code needs to be executed along with the code that has been implemented in the Yield curve note.
swapEngine = DiscountingSwapEngine(discountTermStructure)

nominal = 1000000
length = 5
maturity = calendar.advance(settlementDate,length,Years)
payFixed = True

fixedLegFrequency = Semiannual
fixedLegAdjustment = Unadjusted
fixedLegDayCounter = Thirty360()
fixedRate = 0.0157

floatingLegFrequency = Quarterly
spread = 0.0
fixingDays = 2
index = Euribor6M(forecastTermStructure)
floatingLegAdjustment = ModifiedFollowing
floatingLegDayCounter = index.dayCounter()

fixedSchedule = Schedule(settlementDate, maturity,
                         fixedLegTenor, calendar,
                         fixedLegAdjustment, fixedLegAdjustment,
                         DateGeneration.Forward, False)
floatingSchedule = Schedule(settlementDate, maturity,
                            floatingLegTenor, calendar,
                            floatingLegAdjustment, floatingLegAdjustment,
                            DateGeneration.Forward, False)

spot = VanillaSwap(VanillaSwap.Payer, nominal,
                   fixedSchedule, fixedRate, fixedLegDayCounter,
                   floatingSchedule, index, spread,
                   floatingLegDayCounter)
spot.setPricingEngine(swapEngine)


def formatPrice(p,digits=2):
    format = '%%.%df' % digits
    return format % p

def formatRate(r,digits=2):
    format = '%%.%df %%%%' % digits
    return format % (r*100)

headers = ("term structure", "net present value",
           "fair spread", "fair fixed rate" )
separator = " | "

format = ''
width = 0
for h in headers[:-1]:
    format += '%%%ds' % len(h)
    format += separator
    width += len(h) + len(separator)
format += '%%%ds' % len(headers[-1])
width += len(headers[-1])

rule = "-" * width
dblrule = "=" * width
tab = " " * 8

def report(swap, name):
    print format % (name, formatPrice(swap.NPV(),2),
                    formatRate(swap.fairSpread(),4),
                    formatRate(swap.fairRate(),4))

print dblrule
print "5-year market swap-rate = %s" % formatRate(swaps[(5,Years)].value())
print dblrule
print "Term Structure\t" + "Swap Value\t" + "Swap Spread\t" + "Swap Rate\t"

discountTermStructure.linkTo(depoFuturesSwapCurve)
forecastTermStructure.linkTo(depoFuturesSwapCurve)
report(spot,'depo-fut-swap')

No comments:

Post a Comment