Python 中的 QuantLib cpibond 债券示例

2024-05-13

我正在尝试让官方 C++ cpibond 示例在 Python 中运行。原始示例在这里:https://github.com/lballabio/quantlib/blob/master/QuantLib/test-suite/inflationcpibond.cpp https://github.com/lballabio/quantlib/blob/master/QuantLib/test-suite/inflationcpibond.cpp对于这里的scala:https://github.com/lballabio/quantlib/blob/master/QuantLib-SWIG/Scala/examples/CPIBond.scala https://github.com/lballabio/quantlib/blob/master/QuantLib-SWIG/Scala/examples/CPIBond.scala

当我运行我尝试过的操作时,出现此错误:

运行时错误:第一次迭代:第一个活着的仪器失败,成熟度 2010年9月1日,参考日期2009年9月1日:第二站: 缺少 2009 年 9 月 1 日英国零售价格指数 (RPI) 修正值

这是我的尝试:

import QuantLib as ql
calendar = ql.UnitedKingdom()
dayCounter = ql.ActualActual();
convention = ql.ModifiedFollowing

today = ql.Date(20, 11, 2009)
evaluationDate = calendar.adjust(today)
ql.Settings.instance().setEvaluationDate(evaluationDate)        
yTS = ql.YieldTermStructureHandle(ql.FlatForward(evaluationDate, 0.05, dayCounter))

from_date = ql.Date(20, ql.July, 2007);
to_date   = ql.Date(20, ql.November, 2009);
tenor = ql.Period(1, ql.Months)
rpiSchedule = ql.Schedule(from_date, to_date, tenor, calendar, 
                               convention, convention,
                               ql.DateGeneration.Backward, False)
cpiTS = ql.RelinkableZeroInflationTermStructureHandle()
inflationIndex = ql.UKRPI(False, cpiTS)
fixData = [206.1, 207.3, 208.0, 208.9, 209.7, 210.9,
                    209.8, 211.4, 212.1, 214.0, 215.1, 216.8,
                    216.5, 217.2, 218.4, 217.7, 216,
                    212.9, 210.1, 211.4, 211.3, 211.5,
                    212.8, 213.4, 213.4, 213.4, 214.4,213.4, 214.4]
dte_fixings=[dtes for dtes in rpiSchedule]
print len(dte_fixings)
print len(fixData)
#must be the same length
inflationIndex.addFixings(dte_fixings, fixData) 
observationLag = ql.Period(2, ql.Months)
zciisData =[( ql.Date(25, ql.November, 2010), 3.0495 ),
              ( ql.Date(25, ql.November, 2011), 2.93 ),
              ( ql.Date(26, ql.November, 2012), 2.9795 ),
              ( ql.Date(25, ql.November, 2013), 3.029 ),
              ( ql.Date(25, ql.November, 2014), 3.1425 ),
              ( ql.Date(25, ql.November, 2015), 3.211 ),
              ( ql.Date(25, ql.November, 2016), 3.2675 ),
              ( ql.Date(25, ql.November, 2017), 3.3625 ),
              ( ql.Date(25, ql.November, 2018), 3.405 ),
              ( ql.Date(25, ql.November, 2019), 3.48 ),
              ( ql.Date(25, ql.November, 2021), 3.576 ),
              ( ql.Date(25, ql.November, 2024), 3.649 ),
              ( ql.Date(26, ql.November, 2029), 3.751 ),
              ( ql.Date(27, ql.November, 2034), 3.77225),
              ( ql.Date(25, ql.November, 2039), 3.77 ),
              ( ql.Date(25, ql.November, 2049), 3.734 ),
              ( ql.Date(25, ql.November, 2059), 3.714 )]

lRates=[rtes/100.0 for rtes in zip(*zciisData)[1]]
baseZeroRate = lRates[0]

zeroSwapHelpers = [ql.ZeroCouponInflationSwapHelper(a[1]/100,observationLag,
    a[0], calendar, convention, dayCounter, inflationIndex) for a in zciisData]


cpiTS.linkTo(ql.PiecewiseZeroInflation(          
  evaluationDate, calendar, dayCounter, observationLag, 
  inflationIndex.frequency(), inflationIndex.interpolated(), 
  baseZeroRate,
  yTS, zeroSwapHelpers, 1.0e-12, ql.Linear()))


notional = 1000000


fixedRates = [0.1]    

fixedDayCounter = ql.Actual365Fixed()
fixedPaymentConvention = ql.ModifiedFollowing
fixedPaymentCalendar = ql.UnitedKingdom()
contractObservationLag = ql.Period(3, ql.Months)
observationInterpolation = ql.CPI.Flat
settlementDays = 3
growthOnly = True

baseCPI = 206.1
startDate = ql.Date(2, 10, 2007)
endDate = ql.Date(2, 10, 2052)

fixedSchedule = ql.Schedule(startDate, endDate, 
                  ql.Period(6, ql.Months), fixedPaymentCalendar,
                  ql.Unadjusted,
                  ql.Unadjusted,
                  ql.DateGeneration.Backward, False)

bond = ql.CPIBond(settlementDays, notional, growthOnly,
                       baseCPI, contractObservationLag,
                       inflationIndex, observationInterpolation,
                       fixedSchedule, fixedRates, fixedDayCounter, 
                       fixedPaymentConvention)

bondEngine=ql.DiscountingBondEngine(yTS)
bond.setPricingEngine(bondEngine)
print bond.NPV() 
print bond.cleanPrice()

我的大部分问题是我发现很难掌握这些对象如何组合在一起。


让上面的例子工作:

import QuantLib as ql
import datetime as dt
calendar = ql.UnitedKingdom()
dayCounter = ql.ActualActual();
convention = ql.ModifiedFollowing
lag = 3

today = ql.Date(5,3,2008)
evaluationDate = calendar.adjust(today)
issue_date = calendar.advance(evaluationDate,-1, ql.Years)
maturity_date = ql.Date(2,9,2052)
fixing_date = calendar.advance(evaluationDate,-lag, ql.Months)

ql.Settings.instance().setEvaluationDate(evaluationDate)        
yTS = ql.YieldTermStructureHandle(ql.FlatForward(evaluationDate, 0.05, dayCounter))

tenor = ql.Period(1, ql.Months)

from_date = ql.Date(20, ql.July, 2007);
to_date   = ql.Date(20, ql.November, 2009);
rpiSchedule = ql.Schedule(from_date, to_date, tenor, calendar, 
                               convention, convention,
                               ql.DateGeneration.Backward, False)

# this is the going to be holder the inflation curve.
cpiTS = ql.RelinkableZeroInflationTermStructureHandle()
inflationIndex = ql.UKRPI(False, cpiTS)
fixData = [206.1, 207.3, 208.0, 208.9, 209.7, 210.9,
            209.8, 211.4, 212.1, 214.0, 215.1, 216.8,
            216.5, 217.2, 218.4, 217.7, 216,
            212.9, 210.1, 211.4, 211.3, 211.5,
            212.8, 213.4, 213.4, 213.4, 214.4]
dte_fixings=[dtes for dtes in rpiSchedule]
print len(fixData)
print len(dte_fixings[:len(fixData)])
#must be the same length
#inflationIndex.addFixings(dte_fixings[:len(fixData)], fixData) 
#Current CPI level
#last observed rate
fixing_rate = 214.4


inflationIndex.addFixing(fixing_date, fixing_rate)

observationLag = ql.Period(lag, ql.Months)
zciisData =[( ql.Date(25, ql.November, 2010), 3.0495 ),
              ( ql.Date(25, ql.November, 2011), 2.93 ),
              ( ql.Date(26, ql.November, 2012), 2.9795 ),
              ( ql.Date(25, ql.November, 2013), 3.029 ),
              ( ql.Date(25, ql.November, 2014), 3.1425 ),
              ( ql.Date(25, ql.November, 2015), 3.211 ),
              ( ql.Date(25, ql.November, 2016), 3.2675 ),
              ( ql.Date(25, ql.November, 2017), 3.3625 ),
              ( ql.Date(25, ql.November, 2018), 3.405 ),
              ( ql.Date(25, ql.November, 2019), 3.48 ),
              ( ql.Date(25, ql.November, 2021), 3.576 ),
              ( ql.Date(25, ql.November, 2024), 3.649 ),
              ( ql.Date(26, ql.November, 2029), 3.751 ),
              ( ql.Date(27, ql.November, 2034), 3.77225),
              ( ql.Date(25, ql.November, 2039), 3.77 ),
              ( ql.Date(25, ql.November, 2049), 3.734 ),
              ( ql.Date(25, ql.November, 2059), 3.714 )]

#lRates=[rtes/100.0 for rtes in zip(*zciisData)[1]]
#baseZeroRate = lRates[0]

zeroSwapHelpers = [ql.ZeroCouponInflationSwapHelper(rate/100,observationLag,
    date, calendar, convention, dayCounter, inflationIndex) for date,rate in zciisData]


# the derived inflation curve
jj=ql.PiecewiseZeroInflation(          
                              evaluationDate, calendar, dayCounter, observationLag, 
                              inflationIndex.frequency(), inflationIndex.interpolated(), 
                              zciisData[0][1],#baseZeroRate,
                              yTS, zeroSwapHelpers, 1.0e-12, ql.Linear())

cpiTS.linkTo(jj)

notional = 1000000

fixedRates = [0.1]    

fixedDayCounter = ql.Actual365Fixed()
fixedPaymentConvention = ql.ModifiedFollowing
fixedPaymentCalendar = ql.UnitedKingdom()
contractObservationLag = ql.Period(3, ql.Months)
observationInterpolation = ql.CPI.Flat
settlementDays = 3
growthOnly = False

baseCPI = 206.1


fixedSchedule = ql.Schedule(issue_date,
                  maturity_date, 
                  ql.Period(ql.Semiannual),
                  fixedPaymentCalendar,
                  ql.Unadjusted,
                  ql.Unadjusted,
                  ql.DateGeneration.Backward,
                  False)

bond = ql.CPIBond(settlementDays,
                    notional,
                    growthOnly,
                    baseCPI,
                    contractObservationLag,
                    inflationIndex,
                    observationInterpolation,
                    fixedSchedule,
                    fixedRates,
                    fixedDayCounter, 
                    fixedPaymentConvention)

#bond2= ql.QuantLib.C

bondEngine=ql.DiscountingBondEngine(yTS)
bond.setPricingEngine(bondEngine)
print bond.NPV() 
print bond.cleanPrice()
compounding = ql.Compounded
yield_rate = bond.bondYield(fixedDayCounter,compounding,ql.Semiannual)
y_curve = ql.InterestRate(yield_rate,fixedDayCounter,compounding,ql.Semiannual)
##Collate results
print "Clean Price:", bond.cleanPrice()
print "Dirty Price:", bond.dirtyPrice()
print "Notional:", bond.notional()
print "Yield:", yield_rate
print "Accrued Amount:", bond.accruedAmount()
print "Settlement Value:", bond.settlementValue()

#suspect there's more to this for TIPS
print "Duration:", ql.BondFunctions.duration(bond,y_curve)
print "Convexity:", ql.BondFunctions.convexity(bond,y_curve)
print "Bps:", ql.BondFunctions.bps(bond,y_curve)
print "Basis Point Value:", ql.BondFunctions.basisPointValue(bond,y_curve)
print "Yield Value Basis Point:", ql.BondFunctions.yieldValueBasisPoint(bond,y_curve)

print "NPV:", bond.NPV()

# get the cash flows:
#cf_list=[(cf.amount(),cf.date()) for cf in bond.cashflows()]

def to_datetime(d):
    return dt.datetime(d.year(),d.month(), d.dayOfMonth())

for cf in bond.cashflows():
    try:
        amt=cf.amount()
        rte=jj.zeroRate(cf.date())
        zc=yTS.zeroRate(cf.date(),fixedDayCounter,compounding,ql.Semiannual).rate()
    except:
        amt=0
        rte=0
        zc=0
    print to_datetime(cf.date()),amt,rte,zc

问题似乎在于,flationIndex 对象需要一个日期而不是多个索引点。我的假设是它会得出最新的有效点。

定价器的工作方式是通过通货膨胀率曲线期限结构 zciisData 增加实际息票。因此,结果成为名义未来现金流量。为了定价,债券定价者只需按名义期限结构对这些进行贴现即可。我添加了一些额外的代码来打印确定的现金流量和“增长因子”,然后打印贴现率。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的 QuantLib cpibond 债券示例 的相关文章

随机推荐

  • 使用 Ruby on Rails 进行设计 - 强制用户在首次登录时更改密码

    我有一个运行 Devise 的 RoR 应用程序 Rails 4 2 Ruby 2 2 0 我已经进行了设置 以便管理员用户 标识了我添加到用户模型中的 is admin 布尔值 能够创建新的用户帐户 为他们提供生成的密码和确认电子邮件 这
  • 构建 makefile 依赖/继承树

    如果我解释得不好或者问了一些明显的问题 我很抱歉 但我是 Linux 内核的新手 而且有点深入 我们有一个嵌入式 Linux 系统 它附带一个 文档非常糟糕的 SDK 其中包含数百个文件夹stuff 大多数文件夹包含rules make m
  • Vuex存储数据总是驻留在内存中?

    首先 我希望您能理解我蹩脚的英语 我想知道Vuex的存储数据是否总是驻留在内存中 让我用一个例子来解释一下 当进入页面A时 我们从服务器收到一个列表 并实现将其存储在商店中 这是否意味着当我进入页面A并移动到页面B时 A的列表将保留在内存中
  • gentoo crontab:为什么这个简单的 crontab 不起作用?

    我使用 GENTOO 发行版 crontab e 35 12 root php5 home www cron php 当我手动运行时 php5 php5 home www cron php 这有效 它向我发送了一封电子邮件 然后我检查日期
  • 如何强制 BundleCollection 刷新 MVC4 中缓存的脚本包

    or 我如何学会停止担忧 只针对 Microsoft 完全未记录的 API 编写代码 有没有官方的实际文档System Web Optimization发布 因为我确实找不到任何内容 没有 XML 文档 而且所有博客文章都引用了 RC AP
  • Git:如何使外部存储库和嵌入式存储库作为通用/独立存储库工作?

    我有一个大项目 比方说A repo 其中有一个子文件夹来自B repo 当我提交时 我会遇到如下警告A repo warning adding embedded git repository extractor annotator serv
  • 如何在单元测试中比较列表

    这个测试怎么会失败呢 TestMethod public void Get Code var expected new List
  • 在 Kotlin 中创建 Spring 的 ParameterizedTypeReference 实例

    我正在尝试学习 Kotlin 并测试它如何与 Spring Boot 配合使用 我的应用程序使用 mongo 数据库来存储数据 并且我有用于检索数据的 Jersey 资源 我正在使用它进行测试spring boot test and Res
  • 如何在不使用 Invoke-WebRequest 的情况下在 Powershell 中 POST .json 文件?

    我目前正在做的事情 Invoke WebRequest Uri https coolWebsite com ext ext ContentType application json Method POST Body someJSONFile
  • TestFlight iOS 应用程序 get-task-allow 问题

    我在 ios 的 testflight 中有一个名为 MapItTrackIt 的应用程序 一切都进展顺利 我刚刚更新到 xcode 5 1 我按照以往的方式构建了该应用程序 相同的配置文件和临时证书 这次 当我尝试上传 IPA 文件时 我
  • 从字符串中修剪/删除制表符 ( "\t" )

    任何人都可以建议一种从字符串中删除制表符 t 的方法吗 CString 或 std string 例如 1E10 变为 1E10 hackingwords 的回答 https stackoverflow com questions 5562
  • 如何使用 Scikit-Learn 和 Python 找到最佳簇数

    我正在学习聚类Pythons scikit learnlib 但我找不到找到最佳簇数的方法 我试图制作一个集群数量列表并将其传递进去for loop 并看到elbow但我想找到更好的解决方案 只有当我这样做时 这种方法才有效range 1
  • Microsoft 报表查看器对象

    我正在 Microsoft Visual studio 2013 Express 上为 Windows 桌面开发一个 C Windows 窗体应用程序 我还使用 SQL Server 2012 Express 以及包括报告服务在内的高级功能
  • 使用 XML 时引用未声明的实体异常

    我正在尝试设置 xmldoc 的 innerxml 但出现异常 Reference to undeclaredEntity XmlDocument xmldoc new XmlDocument string text Hello I am
  • 具有依赖项的自定义 MSBuild 任务

    我编写了一个使用第三方程序集的 MSBuild 任务 当我在项目中使用该任务时 MSBuild 抱怨它无法加载第三方程序集 毫不奇怪 我应该将第三方程序集放在哪里 以便 MSBuild 可以使用它们 我尝试向它们添加项目引用但没有成功 我不
  • Kubernetes 通过基于时间的触发器扩展 Pod

    我有一台在 Kubernetes 上运行的服务器来处理每小时的处理作业 考虑使用服务来公开 pod 并使用 外部 cron 作业来访问负载均衡器 以便 kubernetes 可以根据需要自动缩放以处理更高的负载 然而在实现中 如果 cron
  • 我测量运行时间的方法有缺陷吗?

    抱歉 这篇文章很长 但我只是在分析这个问题时解释一下我的思路 问题在最后 我了解测量代码运行时间的原理 它运行多次以获得平均运行时间 以考虑每次运行的差异 并获得更好地利用缓存的时间 为了测量某人的跑步时间 我想出了this https s
  • count 和 groupby 在一个查询中一起使用

    以下查询正在获取页面上的一些产品信息 这很好 但我也想以文本形式显示它出现的产品编号 但是 我使用了groupby但我也想用count on pro id SELECT FROM cart WHERE session id SESSION
  • 创建正则表达式来检查强密码

    假设我有一个检查字母数字的正则表达式 我现在想创建另一个正则表达式来检查密码中至少有 1 个数字 我想检查它是否至少有 1 个非字母数字字符 字母或数字以外的字符 我应该单独调用每个函数 如果一个函数失败返回 false 还是有办法将它们合
  • Python 中的 QuantLib cpibond 债券示例

    我正在尝试让官方 C cpibond 示例在 Python 中运行 原始示例在这里 https github com lballabio quantlib blob master QuantLib test suite inflationc