定义一个互换,本金为1e7,7年后到期
固定端:利率2.5%,每年付息一次
浮动端:Libor6M,每半年付息一次
import QuantLib as ql
from prettytable import PrettyTable# 定义全局时间:当前日期,下一个结算日,到期日
calendar = ql.UnitedStates(ql.UnitedStates.NYSE) # 定义整体日历格式
todaysDate = ql.Date(20, 10, 2015) # 定义估值日
settlementDate = calendar.advance(todaysDate, 5, ql.Days) #定义生效日
maturityDate = calendar.advance(settlementDate, 10, ql.Years) # 定义到期日
ql.Settings.instance().evaluationDate = todaysDate# 定义利率的期限结构:
# 1.根据无风险利率确定利率期限结构,定义为:discount_curve
# 2.根据libor计算浮动利率端利率结构,定义为:libor_curve
risk_free_rate = 0.01
libor_rate = 0.02
day_count = ql.Actual365Fixed()
discount_curve = ql.YieldTermStructureHandle(ql.FlatForward(todaysDate, risk_free_rate, day_count))
libor_curve = ql.YieldTermStructureHandle(ql.FlatForward(todaysDate, libor_rate, day_count))# 定义固定端基本参数
fixedLegFrequency = ql.Period(12, ql.Months)
fixedSchedule = ql.Schedule(settlementDate, maturityDate, fixedLegFrequency, calendar,ql.ModifiedFollowing, ql.ModifiedFollowing, ql.DateGeneration.Forward, False)# 定义浮动端基本参数
floatingLegFrequency = ql.Period(6, ql.Months)
floatSchedule = ql.Schedule(settlementDate, maturityDate, floatingLegFrequency, calendar,ql.ModifiedFollowing, ql.ModifiedFollowing, ql.DateGeneration.Forward, False)# 定义一个互换,本金为1e7,7年后到期
# 固定端:利率2.5%,每年付息一次
# 浮动端:Libor6M,每半年付息一次
swapType = ql.VanillaSwap.Payer
nominal = 10000000
fixedRate = 0.025
float_spread = 0.004
fixedLegDayCounter = ql.Actual360() # 固定端计息方式
floatingLegDayCounter = ql.Actual360() # 浮动端计息方式
libor3M_index = ql.USDLibor(ql.Period(6, ql.Months), libor_curve)# 对swap进行估值
spot7YearSwap = ql.VanillaSwap(swapType, nominal, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule,libor3M_index, float_spread, floatingLegDayCounter)
swapEngine = ql.DiscountingSwapEngine(discount_curve) # 根据当前的利率结构折现求互换定价
spot7YearSwap.setPricingEngine(swapEngine)# 打印固定端和浮动端的现金流
fixedTable = PrettyTable(['Date', 'cashflow'])
floatTable = PrettyTable(['Date', 'cashflow'])for i, cf in enumerate(spot7YearSwap.leg(0)):fixedTable.add_row([str(cf.date()), cf.amount()])for i, cf in enumerate(spot7YearSwap.leg(1)):floatTable.add_row([str(cf.date()), cf.amount()])print(fixedTable.get_string(title="fixed leg cashflow"))
print(floatTable.get_string(title="float leg cashflow"))# 打印swap整体情况
print("%-20s: %20.3f" % ("Net Present Value", spot7YearSwap.NPV()))
print("%-20s: %20.3f" % ("Fair Spread", spot7YearSwap.fairSpread()))
print("%-20s: %20.3f" % ("Fair Rate", spot7YearSwap.fairRate()))
print("%-20s: %20.3f" % ("Fixed Leg BPS", spot7YearSwap.fixedLegBPS()))
print("%-20s: %20.3f" % ("Floating Leg BPS", spot7YearSwap.floatingLegBPS()))
结果输出: