Vanilla SwapΒΆ

[2]:
import QuantLib as ql

Create a relinkable yield term structure handle and build a curve

[3]:
yts = ql.RelinkableYieldTermStructureHandle()

instruments = [
    ('depo', '6M', 0.025),
    ('fra', '6M', 0.03),
    ('swap', '1Y', 0.031),
    ('swap', '2Y', 0.032),
    ('swap', '3Y', 0.035)
]

helpers = ql.RateHelperVector()
index = ql.Euribor6M(yts)
for instrument, tenor, rate in instruments:
    if instrument == 'depo':
        helpers.append( ql.DepositRateHelper(rate, index) )
    if instrument == 'fra':
        monthsToStart = ql.Period(tenor).length()
        helpers.append( ql.FraRateHelper(rate, monthsToStart, index) )
    if instrument == 'swap':
        swapIndex = ql.EuriborSwapIsdaFixA(ql.Period(tenor))
        helpers.append( ql.SwapRateHelper(rate, swapIndex))
curve = ql.PiecewiseLogCubicDiscount(2, ql.TARGET(), helpers, ql.ActualActual())

Link the built curve to the relinkable yield term structure handle and build a swap pricing engine

[4]:
yts.linkTo(curve)
engine = ql.DiscountingSwapEngine(yts)

Build a vanilla swap and provide a pricing engine

[5]:
tenor = ql.Period('2y')
fixedRate = 0.05
forwardStart = ql.Period("2D")

swap = ql.MakeVanillaSwap(tenor, index, fixedRate, forwardStart, Nominal=10e6, pricingEngine=engine)

Get the fair rate and NPV

[6]:
fairRate = swap.fairRate()
npv = swap.NPV()

print(f"Fair swap rate: {fairRate:.3%}")
print(f"Swap NPV: {npv:,.3f}")
Fair swap rate: 3.232%
Swap NPV: -337,608.498
[10]:
import pandas as pd
pd.options.display.float_format = "{:,.2f}".format

cashflows = pd.DataFrame({
    'date': cf.date(),
    'amount': cf.amount()
    } for cf in swap.leg(1))
display(cashflows)
date amount
0 April 6th, 2021 129,166.12
1 October 5th, 2021 166,342.17
2 April 5th, 2022 -100,976.64
3 October 5th, 2022 455,178.07
[23]:
cashflows = pd.DataFrame({
    'nominal': cf.nominal(),
    'accrualStartDate': cf.accrualStartDate().ISO(),
    'accrualEndDate': cf.accrualEndDate().ISO(),
    'rate': cf.rate(),
    'amount': cf.amount()
    } for cf in map(ql.as_coupon, swap.leg(1)))
display(cashflows)
nominal accrualStartDate accrualEndDate rate amount
0 10,000,000.00 2020-10-05 2021-04-06 0.03 129,166.12
1 10,000,000.00 2021-04-06 2021-10-05 0.03 166,342.17
2 10,000,000.00 2021-10-05 2022-04-05 -0.02 -100,976.64
3 10,000,000.00 2022-04-05 2022-10-05 0.09 455,178.07