程式
QuantLib 在回測時返回的債券收益率略有不同
我剛剛開始熟悉 QuantLib(特別是固定利率債券定價功能)。我閱讀了一些例子,從中我可以計算出債券價格和債券收益率。
以下腳本使用輸入收益率 (0.057154825761367800000) 計算債券價格 (96.9073930899788536),使用 bond.cleanPrice。
然後,我將計算出的債券價格回饋給 bond.bondYield 計算(其他輸入不變),期望能取回我原來的輸入收益率。
我發現反向計算的收益率很接近,但沒有我天真期望的那麼接近(它匹配到小數點後 8 位)。我做錯什麼了嗎?這是基於數值求解器最大迭代的可接受精度嗎?還有什麼?
import QuantLib as ql def calculate_bond_price(): settlementDays = 0 faceValue = 100 issueDate = ql.Date(11, 2, 2020) maturityDate = ql.Date(11, 2, 2025) tenor = ql.Period(ql.Quarterly) calendar = ql.NullCalendar() businessConvention = ql.Following dateGeneration = ql.DateGeneration.Backward monthEnd = False schedule = ql.Schedule (issueDate, maturityDate, tenor, calendar, businessConvention, businessConvention, dateGeneration, monthEnd) coupon_rate = 0.05 coupons = [coupon_rate] dayCount = ql.Thirty360() bond = ql.FixedRateBond(settlementDays, faceValue, schedule, coupons, dayCount) ## manually specify a yield rate to 16 decimal places ## this is the value I expect to get back from bond.bondYield calculation yield_rate = 0.057154825761367800000 bond_price = bond.cleanPrice(yield_rate, dayCount, ql.Simple, ql.Quarterly) print(f'PRICE >> calculated={bond_price:20,.16f}') # OUTPUTS: PRICE >> calculated= 96.9073930899788536 # feed the calculated bond price back into a bond.bondYield calculation with exact same (dayCount, Simple, Quarterly) inputs # expect to get back the yield_rate (16 decimal); but only match to 8 decimals back_calculate_bond_yield = bond.bondYield(bond_price, dayCount, ql.Simple, ql.Quarterly) print(f'YIELD >> calculated={back_calculate_bond_yield:20,.16f} | expected={yield_rate:20,.16f} | diff={back_calculate_bond_yield-yield_rate:20,.16f}') # OUTPUTS: YIELD >> calculated= 0.0571548314094543 | expected= 0.0571548257613678 | diff= 0.0000000056480865 if __name__ == '__main__': calculate_bond_price()
我會首先說是的,這是一個可以接受的精度。
但是,您沒有得到相同結果的原因是,預設情況下,QuantLib 具有
accuracy=1.0e-8
和maxEvaluations=100
.您可以像這樣設置這些參數:
bond.bondYield(bond_price, dayCount, ql.Simple, ql.Quarterly, ql.Date(), 1.0e-16, 100)
這會讓你更接近…
產量 >> 計算 = 0.0571548257613679 | 預期= 0.0571548257613678 | 差異= 0.0000000000000001