Vanilla Swap
[1]:
import QuantLib as ql
Create a relinkable yield term structure handle and build a curve
[3]:
yts = ql.RelinkableYieldTermStructureHandle()
instruments = [
('depo', '6M', 0.025),
('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.Actual365Fixed())
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.205%
Swap NPV: -343,527.872
[7]:
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 | January 19th, 2024 | 128,288.65 |
1 | July 19th, 2024 | 180,166.24 |
2 | January 20th, 2025 | 166,690.49 |
3 | July 21st, 2025 | 162,876.45 |
[8]:
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 | 2023-07-19 | 2024-01-19 | 0.03 | 128,288.65 |
1 | 10,000,000.00 | 2024-01-19 | 2024-07-19 | 0.04 | 180,166.24 |
2 | 10,000,000.00 | 2024-07-19 | 2025-01-20 | 0.03 | 166,690.49 |
3 | 10,000,000.00 | 2025-01-20 | 2025-07-21 | 0.03 | 162,876.45 |
[ ]: