hasquant 0.8.0.0 → 0.9.0.0
raw patch · 70 files changed
+2347/−783 lines, 70 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
- QuantLib.Commodity: paymentTermGetPaymentDate :: PaymentTerm -> Day -> IO Day
- QuantLib.Credit: basketDefaultCorrelation :: DigitalBasket -> Day -> Word -> Word -> IO Double
- QuantLib.Credit: basketExpectedShortfall :: TrancheBasket -> Day -> Double -> IO Double
- QuantLib.Credit: basketExpectedTrancheLoss :: TrancheBasket -> Day -> IO Double
- QuantLib.Credit: basketNotional :: Basket -> IO Double
- QuantLib.Credit: basketPercentile :: TrancheBasket -> Day -> Double -> IO Double
- QuantLib.Credit: basketProbAtLeastNEvents :: DigitalBasket -> Word -> Day -> IO Double
- QuantLib.Credit: basketProbOverLoss :: TrancheBasket -> Day -> Double -> IO Double
- QuantLib.Credit: basketRecoveryRate :: Basket -> Day -> Word -> IO Double
- QuantLib.Credit: basketRemainingNotional :: Basket -> Day -> IO Double
- QuantLib.Index.Inflation: fixing :: GenZeroInflationIndex zidx -> Day -> IO Double
- QuantLib.Index.Inflation: yoyFixing :: GenYoYInflationIndex yidx -> Day -> IO Double
- QuantLib.Index.Inflation: yoyNeedsForecast :: GenYoYInflationIndex yidx -> Day -> IO Bool
- QuantLib.Instrument.Credit: cdoRemainingNotional :: SyntheticCDO -> IO Double
- QuantLib.Instrument.Swap: nonstandardSwapFixedRate :: NonstandardSwap -> IO [Double]
- QuantLib.TermStructure.Credit: factorSpreadedHazardRateCurve :: GenDefaultProbabilityTermStructure d -> GenQuote q -> IO DefaultProbabilityTermStructure
- QuantLib.TermStructure.Credit: spreadedHazardRateCurve :: GenDefaultProbabilityTermStructure d -> GenQuote q -> IO DefaultProbabilityTermStructure
- QuantLib.TermStructure.Inflation: yearOnYearInflationSwapImpliedQuoteOn :: YearOnYearInflationSwapHelper -> YoYInflationTermStructure -> IO Double
- QuantLib.TermStructure.Inflation: zeroCouponInflationSwapImpliedQuoteOn :: ZeroCouponInflationSwapHelper -> ZeroInflationTermStructure -> IO Double
- QuantLib.TermStructure.InflationVolatility: kInterpolatedYoyOptionletVolatilitySurfaceBachelier :: Word -> Calendar -> BusinessDayConvention -> DayCounter -> YoYCapFloorTermPriceSurface -> GenYoYInflationIndex yidx -> GenYieldTermStructure y -> Double -> Interpolation -> IO YoYOptionletVolatilitySurface
- QuantLib.TermStructure.InflationVolatility: kInterpolatedYoyOptionletVolatilitySurfaceBlack :: Word -> Calendar -> BusinessDayConvention -> DayCounter -> YoYCapFloorTermPriceSurface -> GenYoYInflationIndex yidx -> GenYieldTermStructure y -> Double -> Interpolation -> IO YoYOptionletVolatilitySurface
- QuantLib.TermStructure.InflationVolatility: kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack :: Word -> Calendar -> BusinessDayConvention -> DayCounter -> YoYCapFloorTermPriceSurface -> GenYoYInflationIndex yidx -> GenYieldTermStructure y -> Double -> Interpolation -> IO YoYOptionletVolatilitySurface
- QuantLib.TermStructure.Volatility: abcdAtmVolCurveOptionTenors :: AbcdAtmVolCurve -> IO [(Word, TimeUnit)]
- QuantLib.TermStructure.Volatility: blackVolVariance :: GenBlackVolTermStructure bv -> TermPoint -> Double -> Bool -> IO Double
- QuantLib.TermStructure.Volatility: denseSabrParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix
- QuantLib.TermStructure.Volatility: marketVolCube :: SabrSwaptionVolatilityCube -> IO RealMatrix
- QuantLib.TermStructure.Volatility: noArbSabrDenseSabrParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix
- QuantLib.TermStructure.Volatility: noArbSabrSparseSabrParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix
- QuantLib.TermStructure.Volatility: sabrVolatilitySpreads :: SabrVolSurface -> SabrVolatilitySpreadsMaturity -> IO [Double]
- QuantLib.TermStructure.Volatility: sparseSabrParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix
- QuantLib.TermStructure.Volatility: swapLengthBetweenDates :: GenSwaptionVolatilityStructure sv -> Day -> Day -> IO Double
- QuantLib.TermStructure.Volatility: volCubeAtmCalibrated :: SabrSwaptionVolatilityCube -> IO RealMatrix
- QuantLib.TermStructure.Yield: forwardRateBetweenTimes :: GenYieldTermStructure y -> Double -> Double -> Compounding -> Frequency -> Bool -> IO InterestRate
- QuantLib.TermStructure.Yield: futuresRateHelperConvexityAdjustment :: FuturesRateHelper -> IO Double
- QuantLib.TermStructure.Yield: overnightIndexFutureRateHelperConvexityAdjustment :: OvernightIndexFutureRateHelper -> IO Double
+ QuantLib.CashFlow: class HasFixingAccrualFractions coupon
+ QuantLib.CashFlow: fixingAccrualFractions :: HasFixingAccrualFractions coupon => coupon -> IO [Double]
+ QuantLib.CashFlow: instance QuantLib.CashFlow.HasFixingAccrualFractions QuantLib.Internal.Type.MultipleResetsCoupon
+ QuantLib.CashFlow: instance QuantLib.CashFlow.HasFixingAccrualFractions QuantLib.Internal.Type.OvernightIndexedCoupon
+ QuantLib.Commodity: paymentTermPaymentDate :: PaymentTerm -> Day -> IO Day
+ QuantLib.Credit: defaultCorrelation :: DigitalBasket -> Day -> Word -> Word -> IO Double
+ QuantLib.Credit: expectedShortfall :: TrancheBasket -> Day -> Double -> IO Double
+ QuantLib.Credit: expectedTrancheLoss :: TrancheBasket -> Day -> IO Double
+ QuantLib.Credit: notional :: Basket -> IO Double
+ QuantLib.Credit: percentile :: TrancheBasket -> Day -> Double -> IO Double
+ QuantLib.Credit: probAtLeastNEvents :: DigitalBasket -> Word -> Day -> IO Double
+ QuantLib.Credit: probOverLoss :: TrancheBasket -> Day -> Double -> IO Double
+ QuantLib.Credit: recoveryRate :: Basket -> Day -> Word -> IO Double
+ QuantLib.Credit: remainingNotional :: Basket -> Day -> IO Double
+ QuantLib.Index.Inflation: class HasNeedsForecast idx
+ QuantLib.Index.Inflation: instance QuantLib.Index.Inflation.HasNeedsForecast (QuantLib.Internal.Type.GenYoYInflationIndex yidx)
+ QuantLib.Index.Inflation: instance QuantLib.Index.Inflation.HasNeedsForecast (QuantLib.Internal.Type.GenZeroInflationIndex zidx)
+ QuantLib.Instrument.Credit: remainingNotional :: SyntheticCDO -> IO Double
+ QuantLib.Instrument.Swap: fixedRates :: NonstandardSwap -> IO [Double]
+ QuantLib.InterestRate: instance GHC.Classes.Eq QuantLib.InterestRate.EquivalentPeriod
+ QuantLib.InterestRate: instance GHC.Internal.Show.Show QuantLib.InterestRate.EquivalentPeriod
+ QuantLib.Quote: fxCashSpotQuote :: GenQuote q -> GenYieldTermStructure y1 -> GenYieldTermStructure y2 -> Calendar -> Word -> IO Quote
+ QuantLib.TermStructure: RateBetweenDates :: !Day -> !Day -> !DayCounter -> RateInterval
+ QuantLib.TermStructure: RateBetweenTimes :: !Double -> !Double -> RateInterval
+ QuantLib.TermStructure: bootstrappedNodes :: HasNodes c => c -> IO [(Day, Double)]
+ QuantLib.TermStructure: class HasNodes c
+ QuantLib.TermStructure: data RateInterval
+ QuantLib.TermStructure: instance GHC.Classes.Eq QuantLib.TermStructure.RateInterval
+ QuantLib.TermStructure: instance GHC.Internal.Show.Show QuantLib.TermStructure.RateInterval
+ QuantLib.TermStructure: instance QuantLib.TermStructure.HasNodes QuantLib.Internal.Type.PiecewiseDefaultCurve
+ QuantLib.TermStructure: instance QuantLib.TermStructure.HasNodes QuantLib.Internal.Type.PiecewiseYieldCurve
+ QuantLib.TermStructure: instance QuantLib.TermStructure.HasNodes QuantLib.Internal.Type.PiecewiseYoYInflationCurve
+ QuantLib.TermStructure: instance QuantLib.TermStructure.HasNodes QuantLib.Internal.Type.PiecewiseZeroInflationCurve
+ QuantLib.TermStructure.Credit: BucketHazardShifts :: NonEmpty (Day, GenQuote q) -> HazardRateShift q
+ QuantLib.TermStructure.Credit: KeyRateHazardShifts :: NonEmpty (Day, GenQuote q) -> HazardRateShift q
+ QuantLib.TermStructure.Credit: ParallelHazardShift :: GenQuote q -> HazardRateShift q
+ QuantLib.TermStructure.Credit: RelativeHazardShift :: GenQuote q -> HazardRateShift q
+ QuantLib.TermStructure.Credit: asDefaultProbabilityTermStructure :: GenDefaultProbabilityTermStructure d -> IO DefaultProbabilityTermStructure
+ QuantLib.TermStructure.Credit: bootstrappedNodes :: HasNodes c => c -> IO [(Day, Double)]
+ QuantLib.TermStructure.Credit: class HasNodes c
+ QuantLib.TermStructure.Credit: conditionalSurvivalCurve :: GenDefaultProbabilityTermStructure d -> Day -> IO DefaultProbabilityTermStructure
+ QuantLib.TermStructure.Credit: data HazardRateShift q
+ QuantLib.TermStructure.Credit: shiftedHazardRateCurve :: GenDefaultProbabilityTermStructure d -> HazardRateShift q -> IO DefaultProbabilityTermStructure
+ QuantLib.TermStructure.Credit: type PiecewiseDefaultCurve = GenDefaultProbabilityTermStructure CPiecewiseDefaultCurve
+ QuantLib.TermStructure.Inflation: asYoyInflationTermStructure :: GenYoYInflationTermStructure yoy -> IO YoYInflationTermStructure
+ QuantLib.TermStructure.Inflation: asZeroInflationTermStructure :: GenZeroInflationTermStructure z -> IO ZeroInflationTermStructure
+ QuantLib.TermStructure.Inflation: bootstrappedNodes :: HasNodes c => c -> IO [(Day, Double)]
+ QuantLib.TermStructure.Inflation: class HasImpliedQuoteOn helper curve
+ QuantLib.TermStructure.Inflation: class HasNodes c
+ QuantLib.TermStructure.Inflation: impliedQuoteOn :: HasImpliedQuoteOn helper curve => helper -> curve -> IO Double
+ QuantLib.TermStructure.Inflation: instance QuantLib.TermStructure.Inflation.HasImpliedQuoteOn QuantLib.Internal.Type.YearOnYearInflationSwapHelper (QuantLib.Internal.Type.GenYoYInflationTermStructure yoy)
+ QuantLib.TermStructure.Inflation: instance QuantLib.TermStructure.Inflation.HasImpliedQuoteOn QuantLib.Internal.Type.ZeroCouponInflationSwapHelper (QuantLib.Internal.Type.GenZeroInflationTermStructure z)
+ QuantLib.TermStructure.Inflation: type GenYoYInflationTermStructure yoy = GenTermStructure AnyOf CYoYInflationTermStructure' yoy
+ QuantLib.TermStructure.Inflation: type GenZeroInflationTermStructure z = GenTermStructure AnyOf CZeroInflationTermStructure' z
+ QuantLib.TermStructure.Inflation: type PiecewiseYoYInflationCurve = GenYoYInflationTermStructure CPiecewiseYoYInflationCurve
+ QuantLib.TermStructure.Inflation: type PiecewiseZeroInflationCurve = GenZeroInflationTermStructure CPiecewiseZeroInflationCurve
+ QuantLib.TermStructure.InflationVolatility: BookedAtEvaluationDate :: YoyPriceSurfaceStart
+ QuantLib.TermStructure.InflationVolatility: MovingStart :: YoyPriceSurfaceStart
+ QuantLib.TermStructure.InflationVolatility: YoyBachelier :: YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: YoyBlack :: YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: YoyUnitDisplacedBlack :: YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: data YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: data YoyPriceSurfaceStart
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Classes.Eq QuantLib.TermStructure.InflationVolatility.YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Classes.Eq QuantLib.TermStructure.InflationVolatility.YoyPriceSurfaceStart
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Internal.Enum.Enum QuantLib.TermStructure.InflationVolatility.YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Internal.Read.Read QuantLib.TermStructure.InflationVolatility.YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Internal.Read.Read QuantLib.TermStructure.InflationVolatility.YoyPriceSurfaceStart
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Internal.Show.Show QuantLib.TermStructure.InflationVolatility.YoyOptionletModel
+ QuantLib.TermStructure.InflationVolatility: instance GHC.Internal.Show.Show QuantLib.TermStructure.InflationVolatility.YoyPriceSurfaceStart
+ QuantLib.TermStructure.InflationVolatility: kInterpolatedYoyOptionletVolatilitySurface :: YoyOptionletModel -> Word -> Calendar -> BusinessDayConvention -> DayCounter -> YoYCapFloorTermPriceSurface -> GenYoYInflationIndex yidx -> GenYieldTermStructure y -> Double -> Maybe (Double, Double) -> Interpolation -> IO YoYOptionletVolatilitySurface
+ QuantLib.TermStructure.Volatility: SwapSpanDates :: !Day -> !Day -> SwapSpan
+ QuantLib.TermStructure.Volatility: SwapSpanTenor :: !(Word, TimeUnit) -> SwapSpan
+ QuantLib.TermStructure.Volatility: VarianceGrid :: [Day] -> [Double] -> RealMatrix -> PiecewiseVarianceNodes
+ QuantLib.TermStructure.Volatility: VarianceSlices :: NonEmpty (Day, NonEmpty (Double, Double)) -> PiecewiseVarianceNodes
+ QuantLib.TermStructure.Volatility: abcdOptionTenors :: AbcdAtmVolCurve -> IO [(Word, TimeUnit)]
+ QuantLib.TermStructure.Volatility: blackVariance :: GenBlackVolTermStructure bv -> TermPoint -> Double -> Bool -> IO Double
+ QuantLib.TermStructure.Volatility: data PiecewiseVarianceNodes
+ QuantLib.TermStructure.Volatility: data SwapSpan
+ QuantLib.TermStructure.Volatility: instance GHC.Classes.Eq QuantLib.TermStructure.Volatility.PiecewiseVarianceNodes
+ QuantLib.TermStructure.Volatility: instance GHC.Classes.Eq QuantLib.TermStructure.Volatility.SwapSpan
+ QuantLib.TermStructure.Volatility: instance GHC.Internal.Show.Show QuantLib.TermStructure.Volatility.PiecewiseVarianceNodes
+ QuantLib.TermStructure.Volatility: instance GHC.Internal.Show.Show QuantLib.TermStructure.Volatility.SwapSpan
+ QuantLib.TermStructure.Volatility: noArbSabrDenseParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix
+ QuantLib.TermStructure.Volatility: noArbSabrSparseParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix
+ QuantLib.TermStructure.Volatility: sabrDenseParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix
+ QuantLib.TermStructure.Volatility: sabrMarketVolCube :: SabrSwaptionVolatilityCube -> IO RealMatrix
+ QuantLib.TermStructure.Volatility: sabrSparseParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix
+ QuantLib.TermStructure.Volatility: sabrVolCubeAtmCalibrated :: SabrSwaptionVolatilityCube -> IO RealMatrix
+ QuantLib.TermStructure.Volatility: sabrVolSurfaceVolatilitySpreads :: SabrVolSurface -> SabrVolatilitySpreadsMaturity -> IO [Double]
+ QuantLib.TermStructure.Yield: RateBetweenDates :: !Day -> !Day -> !DayCounter -> RateInterval
+ QuantLib.TermStructure.Yield: RateBetweenTimes :: !Double -> !Double -> RateInterval
+ QuantLib.TermStructure.Yield: bootstrappedNodes :: HasNodes c => c -> IO [(Day, Double)]
+ QuantLib.TermStructure.Yield: class HasConvexityAdjustment h
+ QuantLib.TermStructure.Yield: class HasNodes c
+ QuantLib.TermStructure.Yield: convexityAdjustment :: HasConvexityAdjustment h => h -> IO Double
+ QuantLib.TermStructure.Yield: data RateInterval
+ QuantLib.TermStructure.Yield: instance QuantLib.TermStructure.Yield.HasConvexityAdjustment QuantLib.Internal.Type.FuturesRateHelper
+ QuantLib.TermStructure.Yield: instance QuantLib.TermStructure.Yield.HasConvexityAdjustment QuantLib.Internal.Type.OvernightIndexFutureRateHelper
+ QuantLib.TermStructure.Yield: rateHelperPillarDate :: GenRateHelper rh -> IO Day
+ QuantLib.TermStructure.Yield: type PiecewiseYieldCurve = GenYieldTermStructure CPiecewiseYieldCurve
- QuantLib.CashFlow: capRate :: StrippedCappedFlooredCoupon -> Double
+ QuantLib.CashFlow: capRate :: StrippedCappedFlooredCoupon -> IO Double
- QuantLib.CashFlow: date :: GenCashFlow cf -> Day
+ QuantLib.CashFlow: date :: GenCashFlow cf -> IO Day
- QuantLib.CashFlow: effectiveCap :: StrippedCappedFlooredCoupon -> Double
+ QuantLib.CashFlow: effectiveCap :: StrippedCappedFlooredCoupon -> IO Double
- QuantLib.CashFlow: effectiveFloor :: StrippedCappedFlooredCoupon -> Double
+ QuantLib.CashFlow: effectiveFloor :: StrippedCappedFlooredCoupon -> IO Double
- QuantLib.CashFlow: floorRate :: StrippedCappedFlooredCoupon -> Double
+ QuantLib.CashFlow: floorRate :: StrippedCappedFlooredCoupon -> IO Double
- QuantLib.CashFlow: isCap :: StrippedCappedFlooredCoupon -> Bool
+ QuantLib.CashFlow: isCap :: StrippedCappedFlooredCoupon -> IO Bool
- QuantLib.CashFlow: isCollar :: StrippedCappedFlooredCoupon -> Bool
+ QuantLib.CashFlow: isCollar :: StrippedCappedFlooredCoupon -> IO Bool
- QuantLib.CashFlow: isFloor :: StrippedCappedFlooredCoupon -> Bool
+ QuantLib.CashFlow: isFloor :: StrippedCappedFlooredCoupon -> IO Bool
- QuantLib.Index.Commodity: isEmpty :: CommodityIndex -> Bool
+ QuantLib.Index.Commodity: isEmpty :: CommodityIndex -> IO Bool
- QuantLib.Index.Inflation: customYoyInflationIndex :: String -> Region -> Bool -> Frequency -> (Int, TimeUnit) -> Currency -> Maybe YoYInflationTermStructure -> IO YoYInflationIndex
+ QuantLib.Index.Inflation: customYoyInflationIndex :: String -> Region -> Bool -> Frequency -> (Int, TimeUnit) -> Currency -> Maybe (GenYoYInflationTermStructure yoy) -> IO YoYInflationIndex
- QuantLib.Index.Inflation: customZeroInflationIndex :: String -> Region -> Bool -> Frequency -> (Int, TimeUnit) -> Currency -> Maybe ZeroInflationTermStructure -> IO ZeroInflationIndex
+ QuantLib.Index.Inflation: customZeroInflationIndex :: String -> Region -> Bool -> Frequency -> (Int, TimeUnit) -> Currency -> Maybe (GenZeroInflationTermStructure z) -> IO ZeroInflationIndex
- QuantLib.Index.Inflation: needsForecast :: GenZeroInflationIndex zidx -> Day -> IO Bool
+ QuantLib.Index.Inflation: needsForecast :: HasNeedsForecast idx => idx -> Day -> IO Bool
- QuantLib.Index.Inflation: yoyInflationIndexFromZero :: GenZeroInflationIndex zidx -> Maybe YoYInflationTermStructure -> IO YoYInflationIndex
+ QuantLib.Index.Inflation: yoyInflationIndexFromZero :: GenZeroInflationIndex zidx -> Maybe (GenYoYInflationTermStructure yoy) -> IO YoYInflationIndex
- QuantLib.Index.InterestRate: businessDayConvention :: GenIborIndex ibor -> BusinessDayConvention
+ QuantLib.Index.InterestRate: businessDayConvention :: GenIborIndex ibor -> IO BusinessDayConvention
- QuantLib.Index.InterestRate: endOfMonth :: GenIborIndex ibor -> Bool
+ QuantLib.Index.InterestRate: endOfMonth :: GenIborIndex ibor -> IO Bool
- QuantLib.Index.InterestRate: fixingDays :: GenInterestRateIndex ridx -> Word
+ QuantLib.Index.InterestRate: fixingDays :: GenInterestRateIndex ridx -> IO Word
- QuantLib.Instrument.Bond: maturityDate :: GenBond b -> IO (Maybe Day)
+ QuantLib.Instrument.Bond: maturityDate :: GenBond b -> IO Day
- QuantLib.Instrument.Energy: discountFactor :: CommodityCashFlow -> Double
+ QuantLib.Instrument.Energy: discountFactor :: CommodityCashFlow -> IO Double
- QuantLib.Instrument.Energy: finalized :: CommodityCashFlow -> Bool
+ QuantLib.Instrument.Energy: finalized :: CommodityCashFlow -> IO Bool
- QuantLib.Instrument.Energy: paymentDiscountFactor :: CommodityCashFlow -> Double
+ QuantLib.Instrument.Energy: paymentDiscountFactor :: CommodityCashFlow -> IO Double
- QuantLib.Instrument.Forward: fxForwardRate :: FxForward -> Double
+ QuantLib.Instrument.Forward: fxForwardRate :: FxForward -> IO Double
- QuantLib.Instrument.Option: twoAssetBarrierOption :: BarrierType -> Double -> StrikedPayoff -> Exercise -> IO Instrument
+ QuantLib.Instrument.Option: twoAssetBarrierOption :: BarrierType -> Double -> StrikedPayoff -> Exercise -> IO Option
- QuantLib.Instrument.Swap: fxResetNotionals :: MtMCrossCurrencyBasisSwap -> IO RealVector
+ QuantLib.Instrument.Swap: fxResetNotionals :: MtMCrossCurrencyBasisSwap -> IO [Double]
- QuantLib.Instrument.Swap: fxResetRates :: MtMCrossCurrencyBasisSwap -> IO RealVector
+ QuantLib.Instrument.Swap: fxResetRates :: MtMCrossCurrencyBasisSwap -> IO [Double]
- QuantLib.Instrument.Swap: maturityDate :: GenSwap s -> IO (Maybe Day)
+ QuantLib.Instrument.Swap: maturityDate :: GenSwap s -> IO Day
- QuantLib.Instrument.Swap: startDate :: GenSwap s -> IO (Maybe Day)
+ QuantLib.Instrument.Swap: startDate :: GenSwap s -> IO Day
- QuantLib.Quote: setValue :: SimpleQuote -> Double -> IO Double
+ QuantLib.Quote: setValue :: SimpleQuote -> Double -> IO ()
- QuantLib.TermStructure.Commodity: isEmpty :: CommodityCurve -> Bool
+ QuantLib.TermStructure.Commodity: isEmpty :: CommodityCurve -> IO Bool
- QuantLib.TermStructure.Credit: piecewiseDefaultCurve :: Reference -> NonEmpty DefaultProbabilityHelper -> DayCounter -> [(Day, GenQuote q)] -> ProbabilityTrait -> Interpolation -> IterativeBootstrapOpts -> Bool -> IO DefaultProbabilityTermStructure
+ QuantLib.TermStructure.Credit: piecewiseDefaultCurve :: Reference -> NonEmpty DefaultProbabilityHelper -> DayCounter -> [(Day, GenQuote q)] -> ProbabilityTrait -> Interpolation -> IterativeBootstrapOpts -> Bool -> IO PiecewiseDefaultCurve
- QuantLib.TermStructure.Inflation: piecewiseYoyInflationCurve :: Day -> Day -> Double -> Frequency -> DayCounter -> NonEmpty YearOnYearInflationSwapHelper -> Maybe Seasonality -> Interpolation -> IO YoYInflationTermStructure
+ QuantLib.TermStructure.Inflation: piecewiseYoyInflationCurve :: Day -> Day -> Double -> Frequency -> DayCounter -> NonEmpty YearOnYearInflationSwapHelper -> Maybe Seasonality -> Interpolation -> IO PiecewiseYoYInflationCurve
- QuantLib.TermStructure.Inflation: piecewiseZeroInflationCurve :: Day -> Day -> Frequency -> DayCounter -> NonEmpty ZeroCouponInflationSwapHelper -> Maybe Seasonality -> Interpolation -> IO ZeroInflationTermStructure
+ QuantLib.TermStructure.Inflation: piecewiseZeroInflationCurve :: Day -> Day -> Frequency -> DayCounter -> NonEmpty ZeroCouponInflationSwapHelper -> Maybe Seasonality -> Interpolation -> IO PiecewiseZeroInflationCurve
- QuantLib.TermStructure.Inflation: type YoYInflationTermStructure = GenTermStructure CYoYInflationTermStructure
+ QuantLib.TermStructure.Inflation: type YoYInflationTermStructure = GenYoYInflationTermStructure CYoYInflationTermStructure
- QuantLib.TermStructure.Inflation: type ZeroInflationTermStructure = GenTermStructure CZeroInflationTermStructure
+ QuantLib.TermStructure.Inflation: type ZeroInflationTermStructure = GenZeroInflationTermStructure CZeroInflationTermStructure
- QuantLib.TermStructure.Inflation: yoyRate :: YoYInflationTermStructure -> Day -> Bool -> IO Double
+ QuantLib.TermStructure.Inflation: yoyRate :: GenYoYInflationTermStructure yoy -> Day -> Bool -> IO Double
- QuantLib.TermStructure.Inflation: zeroRate :: ZeroInflationTermStructure -> Day -> Bool -> IO Double
+ QuantLib.TermStructure.Inflation: zeroRate :: GenZeroInflationTermStructure z -> Day -> Bool -> IO Double
- QuantLib.TermStructure.InflationVolatility: yoyCapFloorTermPriceSurface :: Word -> (Word, TimeUnit) -> GenYoYInflationIndex yidx -> CPIInterpolationType -> GenYieldTermStructure y -> DayCounter -> Calendar -> BusinessDayConvention -> [Double] -> [Double] -> [(Word, TimeUnit)] -> RealMatrix -> RealMatrix -> Interpolation2D -> Interpolation -> IO YoYCapFloorTermPriceSurface
+ QuantLib.TermStructure.InflationVolatility: yoyCapFloorTermPriceSurface :: YoyPriceSurfaceStart -> Word -> (Word, TimeUnit) -> GenYoYInflationIndex yidx -> CPIInterpolationType -> GenYieldTermStructure y -> DayCounter -> Calendar -> BusinessDayConvention -> [Double] -> [Double] -> [(Word, TimeUnit)] -> RealMatrix -> RealMatrix -> Interpolation2D -> Interpolation -> IO YoYCapFloorTermPriceSurface
- QuantLib.TermStructure.Volatility: capFloorTermVolCurve :: CalendarReference -> Calendar -> BusinessDayConvention -> NonEmpty (Word, TimeUnit, GenQuote q) -> DayCounter -> IO CapFloorTermVolCurve
+ QuantLib.TermStructure.Volatility: capFloorTermVolCurve :: CalendarReference -> Calendar -> BusinessDayConvention -> NonEmpty ((Word, TimeUnit), GenQuote q) -> DayCounter -> IO CapFloorTermVolCurve
- QuantLib.TermStructure.Volatility: capletVarianceCurve :: Day -> NonEmpty (Day, Double) -> DayCounter -> VolatilityType -> Double -> IO OptionletVolatilityStructure
+ QuantLib.TermStructure.Volatility: capletVarianceCurve :: Day -> NonEmpty (Day, Double) -> DayCounter -> VolatilityType -> Double -> Bool -> IO OptionletVolatilityStructure
- QuantLib.TermStructure.Volatility: piecewiseBlackVarianceSurface :: Day -> [Day] -> [Double] -> RealMatrix -> DayCounter -> IO BlackVolTermStructure
+ QuantLib.TermStructure.Volatility: piecewiseBlackVarianceSurface :: Day -> PiecewiseVarianceNodes -> DayCounter -> Bool -> IO BlackVolTermStructure
- QuantLib.TermStructure.Volatility: swapLength :: GenSwaptionVolatilityStructure sv -> (Word, TimeUnit) -> IO Double
+ QuantLib.TermStructure.Volatility: swapLength :: GenSwaptionVolatilityStructure sv -> SwapSpan -> IO Double
- QuantLib.TermStructure.Yield: addBootstrappedCurve :: MultiCurve -> RelinkableYieldTermStructure -> GenYieldTermStructure y -> IO YieldTermStructure
+ QuantLib.TermStructure.Yield: addBootstrappedCurve :: MultiCurve -> RelinkableYieldTermStructure -> PiecewiseYieldCurve -> IO YieldTermStructure
- QuantLib.TermStructure.Yield: forwardRate :: GenYieldTermStructure y -> Day -> Day -> DayCounter -> Compounding -> Frequency -> Bool -> IO InterestRate
+ QuantLib.TermStructure.Yield: forwardRate :: GenYieldTermStructure y -> RateInterval -> Compounding -> Frequency -> Bool -> IO InterestRate
- QuantLib.TermStructure.Yield: piecewiseSpreadYieldCurve :: GenYieldTermStructure y -> NonEmpty (GenRateHelper rh) -> SpreadBootstrap -> Bool -> IO YieldTermStructure
+ QuantLib.TermStructure.Yield: piecewiseSpreadYieldCurve :: GenYieldTermStructure y -> NonEmpty (GenRateHelper rh) -> SpreadBootstrap -> Bool -> IO PiecewiseYieldCurve
- QuantLib.TermStructure.Yield: piecewiseYieldCurve :: Reference -> NonEmpty (GenRateHelper rh) -> DayCounter -> [(Day, GenQuote q)] -> Bootstrap rh2 -> Bool -> IO YieldTermStructure
+ QuantLib.TermStructure.Yield: piecewiseYieldCurve :: Reference -> NonEmpty (GenRateHelper rh) -> DayCounter -> [(Day, GenQuote q)] -> Bootstrap rh2 -> Bool -> IO PiecewiseYieldCurve
Files
- CHANGELOG.md +24/−1
- QuantLib/CashFlow.chs +28/−8
- QuantLib/Commodity.chs +2/−2
- QuantLib/Credit.chs +18/−18
- QuantLib/Index/Commodity.chs +1/−1
- QuantLib/Index/Inflation.chs +19/−24
- QuantLib/Index/InterestRate.chs +3/−3
- QuantLib/Instrument/Bond.chs +1/−1
- QuantLib/Instrument/Credit.chs +2/−2
- QuantLib/Instrument/Energy.chs +3/−3
- QuantLib/Instrument/Forward.chs +1/−1
- QuantLib/Instrument/Option.chs +2/−1
- QuantLib/Instrument/Swap.chs +12/−12
- QuantLib/InterestRate.chs +1/−0
- QuantLib/Internal.hs +45/−8
- QuantLib/Internal/Type.hs +86/−12
- QuantLib/Quote.chs +27/−3
- QuantLib/TermStructure.chs +42/−0
- QuantLib/TermStructure/Commodity.chs +1/−1
- QuantLib/TermStructure/Credit.chs +106/−11
- QuantLib/TermStructure/Inflation.chs +34/−18
- QuantLib/TermStructure/InflationVolatility.chs +54/−78
- QuantLib/TermStructure/Volatility.chs +117/−61
- QuantLib/TermStructure/Yield.chs +59/−36
- README.md +6/−4
- cbits/qlConditionalSurvivalCurve.h +69/−0
- cbits/qlEnumObjects.h +2/−0
- cbits/qlInstrument.cpp +12/−6
- cbits/qlInstrument.h +3/−1
- cbits/qlMisc.cpp +37/−1
- cbits/qlMisc.h +2/−1
- cbits/qlShapedHazardCurve.h +119/−0
- cbits/qlTermStructure.cpp +188/−116
- cbits/qlTermStructure.h +44/−40
- cbits/qlTermStructureAux.cpp +257/−50
- cbits/qlTermStructureAux.h +44/−15
- cbits/qlTypesC2HS.h +4/−0
- cbits/qlaux.h +33/−0
- hasquant.cabal +3/−1
- test/example/QuantLib/Example/Bond.hs +2/−1
- test/example/QuantLib/Example/FRA.hs +3/−3
- test/example/QuantLib/Example/FittedBondCurve.hs +4/−2
- test/example/QuantLib/Example/Gaussian1dModels.hs +1/−1
- test/example/QuantLib/Example/InflationInstruments.hs +2/−2
- test/example/QuantLib/Example/LiborMarketModelMC.hs +3/−2
- test/example/QuantLib/Example/Replication.hs +2/−2
- test/example/QuantLib/Example/Repo.hs +2/−2
- test/example/QuantLib/Example/ShortRateModels.hs +2/−2
- test/example/QuantLib/Example/Swap.hs +2/−2
- test/hspec/QuantLib/Spec/CashFlow/FxReset.hs +1/−1
- test/hspec/QuantLib/Spec/Commodity.hs +1/−1
- test/hspec/QuantLib/Spec/Credit.hs +230/−21
- test/hspec/QuantLib/Spec/Examples.hs +1/−1
- test/hspec/QuantLib/Spec/Index/Commodity.hs +2/−2
- test/hspec/QuantLib/Spec/Index/Inflation.hs +2/−2
- test/hspec/QuantLib/Spec/Instrument/Forward.hs +1/−1
- test/hspec/QuantLib/Spec/Instrument/InflationCapFloor.hs +1/−1
- test/hspec/QuantLib/Spec/Instrument/MtmCrossCurrency.hs +9/−9
- test/hspec/QuantLib/Spec/InterestRateAndCashFlow.hs +34/−25
- test/hspec/QuantLib/Spec/Model.hs +2/−1
- test/hspec/QuantLib/Spec/Model/RoughHeston.hs +1/−1
- test/hspec/QuantLib/Spec/PricingEngine.hs +64/−64
- test/hspec/QuantLib/Spec/Process.hs +14/−9
- test/hspec/QuantLib/Spec/Quote.hs +105/−18
- test/hspec/QuantLib/Spec/TermStructure.hs +236/−40
- test/hspec/QuantLib/Spec/TermStructure/Commodity.hs +1/−1
- test/hspec/QuantLib/Spec/TermStructure/Inflation.hs +53/−2
- test/hspec/QuantLib/Spec/TermStructure/InflationVolatility.hs +39/−8
- tools/ql-methods-1.43.txt +8/−8
- tools/ql-methods-1.44.txt +8/−8
CHANGELOG.md view
@@ -1,8 +1,31 @@+## 0.9.0.0 (2026)++Supports QuantLib 1.43 and 1.44; 1.44 is now the default for development, documentation and+release builds. Most changes below are breaking.++- Bootstrapped curves keep their calibration. The piecewise yield, spread, default and+ inflation curve constructors return typed piecewise leaves whose calibrated nodes+ `bootstrappedNodes` reads; `addBootstrappedCurve` accepts only such a leaf, and+ `rateHelperPillarDate` inspects helper pillars before bootstrapping.+- Credit-curve scenarios: `shiftedHazardRateCurve` replaces the spreaded hazard curves and adds+ live key-rate and bucket shifts; `conditionalSurvivalCurve` conditions an existing curve on+ survival to a later date.+- Volatility: piecewise Black variance surfaces accept per-expiry strike slices, caplet variance+ curves and variance surfaces can extrapolate, YoY optionlet stripping uses one model-selected+ constructor with an optional root bracket, and YoY price surfaces can be booked at the+ evaluation date.+- Added a curve-observing FX cash spot quote (`fxCashSpotQuote`) and the accrual fractions of+ compounded coupons (`fixingAccrualFractions`).+- `QuantLib.Math` exports `Matrix` abstractly, with checked constructors and plain inspector+ functions.+- API consistency pass: uniform naming, `IO` getters on live objects, more precise return+ types, coordinate ADTs instead of per-coordinate query variants, and capability classes+ instead of per-type names (`QuantLib.Index.fixing` now reads every index).+ ## 0.8.0.0 (2026) - Added value-based Settings snapshots with checked restoration, preserving floating dates and observer settings, and native fixing-history name normalization for context owners.- - Added QuantLib 1.44 support, while retaining compatibility with 1.43. New bindings include Rough Heston pricing, mark-to-market cross-currency basis swaps, FX reset cash flows, and Gaussian1d (GSR) swaptions on overnight-indexed swaps. Calls requiring 1.44, and non-default
QuantLib/CashFlow.chs view
@@ -188,6 +188,7 @@ , HasFixingDates(..) , fixingDependencies , HasIndexFixings(..)+ , HasFixingAccrualFractions(..) , baseFixing , indexFixing , adjustedFixing@@ -429,7 +430,7 @@ ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |The payment date of a cash flow.-{#fun pure qlCashFlowDate as date{withCashFlow*`GenCashFlow cf' -- ^cashFlow+{#fun qlCashFlowDate as date{withCashFlow*`GenCashFlow cf' -- ^cashFlow }->`Day'toDay#} -- |A payment of @notional * i(fixingDate) \/ i(baseDate)@, or the same ratio minus one when@@ -545,34 +546,34 @@ -- |The cap actually in effect for this coupon, accounting for the sign of /gearing/; -- QuantLib's null-rate sentinel means no cap applies.-{#fun pure qlStrippedCappedFlooredCouponCap as capRate{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponCap as capRate{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Double'#} -- |The floor actually in effect for this coupon, accounting for the sign of /gearing/; -- QuantLib's null-rate sentinel means no floor applies.-{#fun pure qlStrippedCappedFlooredCouponFloor as floorRate{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponFloor as floorRate{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Double'#} -- |The cap rate translated back to the underlying index rate (before gearing\/spread); -- QuantLib's null-rate sentinel means the coupon is not capped.-{#fun pure qlStrippedCappedFlooredCouponEffectiveCap as effectiveCap{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponEffectiveCap as effectiveCap{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Double'#} -- |The floor rate translated back to the underlying index rate (before gearing\/spread); -- QuantLib's null-rate sentinel means the coupon is not floored.-{#fun pure qlStrippedCappedFlooredCouponEffectiveFloor as effectiveFloor{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponEffectiveFloor as effectiveFloor{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Double'#} -- |Whether this coupon has a cap in effect.-{#fun pure qlStrippedCappedFlooredCouponIsCap as isCap{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponIsCap as isCap{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Bool'#} -- |Whether this coupon has a floor in effect.-{#fun pure qlStrippedCappedFlooredCouponIsFloor as isFloor{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponIsFloor as isFloor{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Bool'#} -- |Whether this coupon is both capped and floored (a collar).-{#fun pure qlStrippedCappedFlooredCouponIsCollar as isCollar{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon+{#fun qlStrippedCappedFlooredCouponIsCollar as isCollar{withStrippedCappedFlooredCoupon*`StrippedCappedFlooredCoupon' -- ^coupon }->`Bool'#} -- |Ibor coupon with optional cap and floor rates.@@ -1695,6 +1696,12 @@ instance HasFixingDates OvernightIndexedCoupon where fixingDates = overnightIndexedCouponFixingDatesRaw +{#fun qlOvernightIndexedCouponAccrualFractions as overnightIndexedCouponAccrualFractionsRaw{withOvernightIndexedCoupon*`OvernightIndexedCoupon' -- ^Coupon whose native sub-period weights are read.+ ,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}++{#fun qlMultipleResetsCouponAccrualFractions as multipleResetsCouponAccrualFractionsRaw{withMultipleResetsCoupon*`MultipleResetsCoupon' -- ^Coupon whose native sub-period weights are read.+ ,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}+ -- |Coupon types that expose their component index fixings. class HasIndexFixings coupon where indexFixings :: coupon -> IO [Double]@@ -1703,6 +1710,19 @@ indexFixings = averageBmaCouponIndexFixingsRaw instance HasIndexFixings OvernightIndexedCoupon where indexFixings = overnightIndexedCouponIndexFixingsRaw++-- |Coupons exposing the year fractions applied to their component index fixings.+-- Entries align with 'fixingDates' and use the underlying index's day counter, independently+-- of the coupon's overall day counter. Overnight weights include native observation-shift+-- conventions; a telescopic coupon exposes only its retained sub-periods.+class HasFixingAccrualFractions coupon where+ fixingAccrualFractions :: coupon -- ^Coupon whose computed accrual sub-periods are read.+ -> IO [Double]++instance HasFixingAccrualFractions OvernightIndexedCoupon where+ fixingAccrualFractions = overnightIndexedCouponAccrualFractionsRaw+instance HasFixingAccrualFractions MultipleResetsCoupon where+ fixingAccrualFractions = multipleResetsCouponAccrualFractionsRaw -- |FX observation as fixing date and associated settlement/value date. data FxReset = FxReset { fxResetFixingDate :: Day, fxResetSettlementDate :: Day } deriving (Eq, Show, Read)
QuantLib/Commodity.chs view
@@ -67,7 +67,7 @@ , paymentTermOffsetDays , paymentTermCalendar , paymentTermEmpty- , paymentTermGetPaymentDate+ , paymentTermPaymentDate -- ** Pricing periods and conversions , pricingPeriodStartDate , pricingPeriodEndDate@@ -204,7 +204,7 @@ -- |Applies the term's offset (and calendar adjustment) to a trade or pricing-period-end date to -- get the actual payment date.-{#fun qlPaymentTermGetPaymentDate as paymentTermGetPaymentDate+{#fun qlPaymentTermGetPaymentDate as paymentTermPaymentDate {withPaymentTerm*`PaymentTerm',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Day'toDay#} -- |A commodity type, unit of measure, and amount. Its FFI arguments are flat because c2hs's
QuantLib/Credit.chs view
@@ -29,15 +29,15 @@ , constantLossModel -- * Inspectors- , basketExpectedTrancheLoss- , basketProbOverLoss- , basketPercentile- , basketExpectedShortfall- , basketDefaultCorrelation- , basketProbAtLeastNEvents- , basketNotional- , basketRemainingNotional- , basketRecoveryRate+ , expectedTrancheLoss+ , probOverLoss+ , percentile+ , expectedShortfall+ , defaultCorrelation+ , probAtLeastNEvents+ , notional+ , remainingNotional+ , recoveryRate ) where import Data.List.NonEmpty(NonEmpty, toList) @@ -116,46 +116,46 @@ ,preErrorCheck-`String'errorCheck*-}->`TrancheBasket'peekTrancheBasket*#} -- |Basket total notional at inception, before losses.-{#fun qlBasketNotional as basketNotional{withBasket*`Basket',preErrorCheck-`String'errorCheck*-}->`Double'#}+{#fun qlBasketNotional as notional{withBasket*`Basket',preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Live (undefaulted) notional remaining at date @d@. Loss-model-agnostic.-{#fun qlBasketRemainingNotional as basketRemainingNotional{withBasket*`Basket',withDay*`Day' -- ^d+{#fun qlBasketRemainingNotional as remainingNotional{withBasket*`Basket',withDay*`Day' -- ^d ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Expected recovery rate of the @iName@-th pool name (0-based, in basket-construction order), -- conditional on default by date @d@. Loss-model-agnostic.-{#fun qlBasketRecoveryRate as basketRecoveryRate{withBasket*`Basket',withDay*`Day' -- ^d+{#fun qlBasketRecoveryRate as recoveryRate{withBasket*`Basket',withDay*`Day' -- ^d ,fromIntegral`Word' -- ^iName ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Expected tranche loss on date @d@; requires a tranche-loss model.-{#fun qlBasketExpectedTrancheLoss as basketExpectedTrancheLoss{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d+{#fun qlBasketExpectedTrancheLoss as expectedTrancheLoss{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Probability the tranche loses at least @lossFraction@ of the tranche notional by date @d@.-{#fun qlBasketProbOverLoss as basketProbOverLoss{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d+{#fun qlBasketProbOverLoss as probOverLoss{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d ,`Double' -- ^lossFraction ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Tranche loss fraction at the given percentile of the loss distribution on date @d@ (VaR).-{#fun qlBasketPercentile as basketPercentile{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d+{#fun qlBasketPercentile as percentile{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d ,`Double' -- ^prob ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Expected tranche loss given loss exceeds the given percentile on date @d@.-{#fun qlBasketExpectedShortfall as basketExpectedShortfall{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d+{#fun qlBasketExpectedShortfall as expectedShortfall{withTrancheBasket*`TrancheBasket',withDay*`Day' -- ^d ,`Double' -- ^prob ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Pearson default-probability correlation between pool names @iName@ and @jName@ (0-based) by -- date @d@.-{#fun qlBasketDefaultCorrelation as basketDefaultCorrelation{withDigitalBasket*`DigitalBasket',withDay*`Day' -- ^d+{#fun qlBasketDefaultCorrelation as defaultCorrelation{withDigitalBasket*`DigitalBasket',withDay*`Day' -- ^d ,fromIntegral`Word' -- ^iName ,fromIntegral`Word' -- ^jName ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Probability of at least @n@ defaults in the basket by date @d@.-{#fun qlBasketProbAtLeastNEvents as basketProbAtLeastNEvents{withDigitalBasket*`DigitalBasket'+{#fun qlBasketProbAtLeastNEvents as probAtLeastNEvents{withDigitalBasket*`DigitalBasket' ,fromIntegral`Word' -- ^n ,withDay*`Day' -- ^d ,preErrorCheck-`String'errorCheck*-}->`Double'#}
QuantLib/Index/Commodity.chs view
@@ -53,6 +53,6 @@ {#fun qlCommodityIndexLastQuoteDate as lastQuoteDate{withCommodityIndex*`CommodityIndex',preErrorCheck-`String'errorCheck*-}->`Day'toDay#} -- |Whether this index has any stored historical fixings.-{#fun pure qlCommodityIndexEmpty as isEmpty{withCommodityIndex*`CommodityIndex'}->`Bool'#}+{#fun qlCommodityIndexEmpty as isEmpty{withCommodityIndex*`CommodityIndex'}->`Bool'#} -- vim: set ff=unix ts=8 sts=2 sw=2 et:
QuantLib/Index/Inflation.chs view
@@ -1,3 +1,4 @@+{-# LANGUAGE FlexibleInstances #-} module QuantLib.Index.Inflation ( -- * Types@@ -30,10 +31,7 @@ , yoyInflationIndexFromZero -- * Inspectors- , fixing- , yoyFixing- , needsForecast- , yoyNeedsForecast+ , HasNeedsForecast(..) ) where import QuantLib.Internal import QuantLib.Internal.Type@@ -79,7 +77,7 @@ ,`Frequency' ,fromEnumQuantity`(Int,TimeUnit)'& -- ^availabilityLag ,withCurrency*`Currency'- ,withMaybeZeroInflationTermStructure*`Maybe ZeroInflationTermStructure'+ ,withMaybeZeroInflationTermStructure*`Maybe (GenZeroInflationTermStructure z)' ,preErrorCheck-`String'errorCheck*-}->`ZeroInflationIndex'peekZeroInflationIndex*#} -- |A custom quoted year-on-year inflation index (arbitrary family name/region/currency); needs@@ -91,32 +89,29 @@ ,`Frequency' ,fromEnumQuantity`(Int,TimeUnit)'& -- ^availabilityLag ,withCurrency*`Currency'- ,withMaybeYoYInflationTermStructure*`Maybe YoYInflationTermStructure'+ ,withMaybeYoYInflationTermStructure*`Maybe (GenYoYInflationTermStructure yoy)' ,preErrorCheck-`String'errorCheck*-}->`YoYInflationIndex'peekYoYInflationIndex*#} -- |A year-on-year index defined as the ratio of an existing 'ZeroInflationIndex'\'s fixings; -- stores no fixings of its own. {#fun qlYoYInflationIndexFromZero as yoyInflationIndexFromZero{withZeroInflationIndex*`GenZeroInflationIndex zidx'- ,withMaybeYoYInflationTermStructure*`Maybe YoYInflationTermStructure'+ ,withMaybeYoYInflationTermStructure*`Maybe (GenYoYInflationTermStructure yoy)' ,preErrorCheck-`String'errorCheck*-}->`YoYInflationIndex'peekYoYInflationIndex*#} --- |The (possibly forecast) fixing at the given date; for a date with no linked term--- structure this returns the stored historical fixing added via 'QuantLib.Index.addFixing'.-{#fun qlZeroInflationIndexFixing as fixing{withZeroInflationIndex*`GenZeroInflationIndex zidx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Double'#}---- |The (possibly forecast) year-on-year fixing at the given date; for a date with no linked--- term structure this returns the stored historical fixing added via 'QuantLib.Index.addFixing'.-{#fun qlYoYInflationIndexFixing as yoyFixing{withYoYInflationIndex*`GenYoYInflationIndex yidx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Double'#}---- |Whether 'fixing' at the given date would have to be forecast rather than served from a stored--- historical fixing -- true once the date falls after the latest period a fixing could plausibly--- already be published for, given the index's publication lag.--- /Warning/ It raises an exception if the index was built with a frequency outside--- @Annual@..@Monthly@, which the inflation-period calculation does not handle.-{#fun qlZeroInflationIndexNeedsForecast as needsForecast{withZeroInflationIndex*`GenZeroInflationIndex zidx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Bool'#}+-- |Zero and year-on-year inflation indexes; read their fixings with 'QuantLib.Index.fixing'.+class HasNeedsForecast idx where+ -- |Whether 'QuantLib.Index.fixing' at the given date would have to be forecast rather than+ -- served from a stored historical fixing -- true once the date falls after the latest period+ -- a fixing could plausibly already be published for, given the index's publication lag.+ -- /Warning/ It raises an exception if the index was built with a frequency outside+ -- @Annual@..@Monthly@, which the inflation-period calculation does not handle.+ needsForecast :: idx -> Day -> IO Bool+instance HasNeedsForecast (GenZeroInflationIndex zidx) where+ needsForecast = qlZeroInflationIndexNeedsForecast+instance HasNeedsForecast (GenYoYInflationIndex yidx) where+ needsForecast = qlYoYInflationIndexNeedsForecast --- |The year-on-year counterpart of 'needsForecast', for 'yoyFixing'.--- /Warning/ It raises an exception on an unhandled frequency, as 'needsForecast' does.-{#fun qlYoYInflationIndexNeedsForecast as yoyNeedsForecast{withYoYInflationIndex*`GenYoYInflationIndex yidx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Bool'#}+{#fun qlZeroInflationIndexNeedsForecast{withZeroInflationIndex*`GenZeroInflationIndex zidx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Bool'#}+{#fun qlYoYInflationIndexNeedsForecast{withYoYInflationIndex*`GenYoYInflationIndex yidx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Bool'#} -- vim: set ff=unix ts=8 sts=2 sw=2 et:
QuantLib/Index/InterestRate.chs view
@@ -283,7 +283,7 @@ {#fun qlInterestRateIndexDayCounter as dayCounter{withInterestRateIndex*`GenInterestRateIndex ridx',preErrorCheck-`String'errorCheck*-}->`DayCounter'peekDayCounter*#} -- |Returns the number of business days between a fixing date and the corresponding value date.-{#fun pure qlInterestRateIndexFixingDays as fixingDays{withInterestRateIndex*`GenInterestRateIndex ridx'}->`Word'fromIntegral#}+{#fun qlInterestRateIndexFixingDays as fixingDays{withInterestRateIndex*`GenInterestRateIndex ridx'}->`Word'fromIntegral#} -- |Returns the index's tenor. {#fun qlInterestRateIndexTenor as tenor{withInterestRateIndex*`GenInterestRateIndex ridx',preEnum-`TimeUnit'peekEnum*,preErrorCheck-`String'errorCheck*-}->`Word'fromIntegral#}@@ -393,10 +393,10 @@ ,withCurrency*`Currency',withCalendar*`Calendar',withDayCounter*`DayCounter',withMaybeYieldTermStructure*`Maybe (GenYieldTermStructure y)',preErrorCheck-`String'errorCheck*-}->`OvernightIborIndex'peekOvernightIborIndex*#} -- |Returns the business day convention used to adjust the index's value/maturity dates.-{#fun pure qlIborIndexBusinessDayConvention as businessDayConvention{withIborIndex*`GenIborIndex ibor'}->`BusinessDayConvention'toEnumC#}+{#fun qlIborIndexBusinessDayConvention as businessDayConvention{withIborIndex*`GenIborIndex ibor'}->`BusinessDayConvention'toEnumC#} -- |Returns whether the index's date calculations roll to the end of the month.-{#fun pure qlIborIndexEndOfMonth as endOfMonth{withIborIndex*`GenIborIndex ibor'}->`Bool'#}+{#fun qlIborIndexEndOfMonth as endOfMonth{withIborIndex*`GenIborIndex ibor'}->`Bool'#} -- |Returns the overnight-indexed swap underlying the index for a given fixing date. Relinking the index's term structure afterwards has no effect on the returned swap. {#fun qlOvernightIndexedSwapIndexUnderlyingSwap as underlyingOis {withOvernightIndexedSwapIndex*`OvernightIndexedSwapIndex',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`OvernightIndexedSwap'peekOvernightIndexedSwap*#}
QuantLib/Instrument/Bond.chs view
@@ -187,7 +187,7 @@ ,preErrorCheck-`String'errorCheck*-}->`Bond'peekBond*#} -- |Returns the maturity date of the bond-{#fun qlBondMaturityDate as maturityDate{withBond*`GenBond b',preErrorCheck-`String'errorCheck*-}->`Maybe Day' toMaybeDay#}+{#fun qlBondMaturityDate as maturityDate{withBond*`GenBond b',preErrorCheck-`String'errorCheck*-}->`Day'toDay#} -- |generic compounding and frequency InterestRate coupons {#fun qlFixedRateBond as fixedRateBond{fromIntegral`Word' -- ^settlementDays
QuantLib/Instrument/Credit.chs view
@@ -38,7 +38,7 @@ , protectionValue , premiumLegNpv , protectionLegNpv- , cdoRemainingNotional+ , remainingNotional , implicitCorrelation -- ** Nth-to-default , ntdFairPremium@@ -190,7 +190,7 @@ {#fun qlSyntheticCDOProtectionLegNPV as protectionLegNpv{withGenInstrument*`SyntheticCDO',preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Total outstanding tranche notional, not wiped out by realized losses.-{#fun qlSyntheticCDORemainingNotional as cdoRemainingNotional{withGenInstrument*`SyntheticCDO',preErrorCheck-`String'errorCheck*-}->`Double'#}+{#fun qlSyntheticCDORemainingNotional as remainingNotional{withGenInstrument*`SyntheticCDO',preErrorCheck-`String'errorCheck*-}->`Double'#} -- |The flat Gaussian-copula LHP correlation (constant along time and portfolio loss level) -- that makes the tranche's NPV equal @targetNPV@.
QuantLib/Instrument/Energy.chs view
@@ -132,13 +132,13 @@ {#fun qlCommodityCashFlowUndiscountedPaymentAmount as undiscountedPaymentAmount{withCommodityCashFlow*`CommodityCashFlow',alloca-`Currency'peekCurrencyPtr*,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |The discount factor applied to the base-currency amount.-{#fun pure qlCommodityCashFlowDiscountFactor as discountFactor{withCommodityCashFlow*`CommodityCashFlow'}->`Double'#}+{#fun qlCommodityCashFlowDiscountFactor as discountFactor{withCommodityCashFlow*`CommodityCashFlow'}->`Double'#} -- |The discount factor applied to the payment-currency amount.-{#fun pure qlCommodityCashFlowPaymentDiscountFactor as paymentDiscountFactor{withCommodityCashFlow*`CommodityCashFlow'}->`Double'#}+{#fun qlCommodityCashFlowPaymentDiscountFactor as paymentDiscountFactor{withCommodityCashFlow*`CommodityCashFlow'}->`Double'#} -- |Whether this cash flow's payment date has already occurred as of the evaluation date.-{#fun pure qlCommodityCashFlowFinalized as finalized{withCommodityCashFlow*`CommodityCashFlow'}->`Bool'#}+{#fun qlCommodityCashFlowFinalized as finalized{withCommodityCashFlow*`CommodityCashFlow'}->`Bool'#} -- |Record a pricing diagnostic against a 'Commodity'\/'EnergyCommodity' leaf (any of 'EnergyFuture', -- 'EnergyVanillaSwap', 'EnergyBasisSwap'), retrievable afterwards via 'pricingErrors'. Mirrors
QuantLib/Instrument/Forward.chs view
@@ -124,7 +124,7 @@ -- |The contracted forward exchange rate (target\/source), computed as @targetNominal \/ -- sourceNominal@ -- distinct from 'fairForwardRate', the market-implied rate.-{#fun pure qlFxForwardForwardRate as fxForwardRate{withGenInstrument*`FxForward'}->`Double'#}+{#fun qlFxForwardForwardRate as fxForwardRate{withGenInstrument*`FxForward'}->`Double'#} -- |The market-implied fair forward rate, computed by the pricing engine. {#fun qlFxForwardFairForwardRate as fairForwardRate{withGenInstrument*`FxForward',preErrorCheck-`String'errorCheck*-}->`Double'#}
QuantLib/Instrument/Option.chs view
@@ -132,6 +132,7 @@ {#pointer *QlEverestOption as EverestOption foreign -> CEverestOption' nocode#} {#pointer *QlMultiAssetOption as MultiAssetOption foreign -> CMultiAssetOption' nocode#} {#pointer *QlOneAssetOption as OneAssetOption foreign -> COneAssetOption' nocode#}+{#pointer *QlOption as Option foreign -> COption' nocode#} {#pointer *QlQuantoBarrierOption as QuantoBarrierOption foreign -> CQuantoBarrierOption' nocode#} {#pointer *QlQuantoDoubleBarrierOption as QuantoDoubleBarrierOption foreign -> CQuantoDoubleBarrierOption' nocode#} {#pointer *QlQuantoForwardVanillaOption as QuantoForwardVanillaOption foreign -> CQuantoForwardVanillaOption' nocode#}@@ -266,7 +267,7 @@ -- |Barrier option on two assets: the first asset's value is compared to the strike to determine the payoff, while the second asset's value is monitored against the barrier. {#fun qlTwoAssetBarrierOption as twoAssetBarrierOption{`BarrierType' ,`Double' -- ^barrier- ,withStrikedPayoff*`StrikedPayoff',withExercise*`Exercise',preErrorCheck-`String'errorCheck*-}->`Instrument'peekInstrument*#}+ ,withStrikedPayoff*`StrikedPayoff',withExercise*`Exercise',preErrorCheck-`String'errorCheck*-}->`Option'peekOption*#} -- |Base construction for an option on multiple assets. {#fun qlMultiAssetOption as multiAssetOption{withPayoff*`Payoff',withExercise*`Exercise',preErrorCheck-`String'errorCheck*-}->`MultiAssetOption'peekMultiAssetOption*#}
QuantLib/Instrument/Swap.chs view
@@ -123,7 +123,7 @@ , npvDateDiscount , startDate , startDiscounts- , nonstandardSwapFixedRate+ , fixedRates -- ** Cross-currency swaps @@ -412,7 +412,7 @@ -- 'nonstandardSwap'\/'nonstandardSwapFromGearingsAndSpreads', this simply echoes the constructor's @fixedRate@; for -- one built via 'nonstandardSwapFromVanilla' it is derived from the underlying vanilla swap's -- fixed leg coupons.-{#fun qlNonstandardSwapFixedRate as nonstandardSwapFixedRate{withNonstandardSwap*`NonstandardSwap',preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}+{#fun qlNonstandardSwapFixedRate as fixedRates{withNonstandardSwap*`NonstandardSwap',preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Swap exchanging capped\/floored Libor or CMS coupons with a single flat nominal on each leg. -- 'FloatFloatSwapOpts' bundles every trailing param the C++ constructor defaults (gearing\/@@ -532,8 +532,8 @@ floatTenor <- tenor index floatDayCount <- dayCounter index refDate <- evaluationDate- let floatConv = businessDayConvention index- floatCalendar = fromMaybe idxCalendar mFloatCalendar+ floatConv <- businessDayConvention index+ let floatCalendar = fromMaybe idxCalendar mFloatCalendar fixedCalendar = fromMaybe idxCalendar mFixedCalendar fixedConvention = fromMaybe ModifiedFollowing mFixedConvention fixedTerminationConvention = fromMaybe ModifiedFollowing mFixedTerminationConvention@@ -596,8 +596,8 @@ floatTenor <- tenor iborIndex floatDayCount <- dayCounter iborIndex refDate <- evaluationDate- let floatConv = businessDayConvention iborIndex- floatCalendar = fromMaybe idxCalendar mFloatCalendar+ floatConv <- businessDayConvention iborIndex+ let floatCalendar = fromMaybe idxCalendar mFloatCalendar cmsCalendar = fromMaybe idxCalendar mCmsCalendar settlementDays = fromMaybe 0 mSettlementDays nominal = fromMaybe 1.0 mNominal@@ -932,11 +932,11 @@ ,fromMaybeInt`Maybe Int' -- ^roundingPrecision (1.44; QuantLib 1.43 requires 'Nothing') ,preErrorCheck-`String'errorCheck*-}->`OvernightIndexedSwap'peekOvernightIndexedSwap*#} --- |The swap's maturity date, or 'Nothing' if the swap has no legs.-{#fun qlSwapMaturityDate as maturityDate{withSwap*`GenSwap s',preErrorCheck-`String'errorCheck*-}->`(Maybe Day)' toMaybeDay#}+-- |The swap's maturity date: the latest across its legs. Throws if the swap has no legs.+{#fun qlSwapMaturityDate as maturityDate{withSwap*`GenSwap s',preErrorCheck-`String'errorCheck*-}->`Day'toDay#} --- |The swap's start date, or 'Nothing' if the swap has no legs.-{#fun qlSwapStartDate as startDate{withSwap*`GenSwap s',preErrorCheck-`String'errorCheck*-}->`(Maybe Day)' toMaybeDay#}+-- |The swap's start date: the earliest across its legs. Throws if the swap has no legs.+{#fun qlSwapStartDate as startDate{withSwap*`GenSwap s',preErrorCheck-`String'errorCheck*-}->`Day'toDay#} -- |Discount factor at the instrument's NPV date. {#fun qlSwapNpvDateDiscount as npvDateDiscount{withSwap*`GenSwap s',preErrorCheck-`String'errorCheck*-}->`Double'#}@@ -1442,12 +1442,12 @@ -- |Calculated reset rates for non-occurred coupons in leg order (1.44). {#fun qlMtMFxResetRates as fxResetRates{withMtMCrossCurrencyBasisSwap*`MtMCrossCurrencyBasisSwap' -- ^swap- ,preDoubleArray-`RealVector'&peekRealVector* -- ^result+ ,preDoubleArray-`[Double]'&peekDoubleArray* -- ^result ,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Calculated reset notionals for non-occurred coupons in leg order (1.44). {#fun qlMtMFxResetNotionals as fxResetNotionals{withMtMCrossCurrencyBasisSwap*`MtMCrossCurrencyBasisSwap' -- ^swap- ,preDoubleArray-`RealVector'&peekRealVector* -- ^result+ ,preDoubleArray-`[Double]'&peekDoubleArray* -- ^result ,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Upstream defaults for MTM cross-currency construction.
QuantLib/InterestRate.chs view
@@ -44,6 +44,7 @@ data EquivalentPeriod = EquivalentAtTime !Double | EquivalentBetween !DayCounter !Day !Day !(Maybe Day) !(Maybe Day) -- ^resultDC, d1, d2, refStart, refEnd+ deriving (Eq, Show) -- |construct an interest rate from a rate value, a day counter, a compounding convention and a frequency. {#fun qlInterestRate as interestRate{`Double' -- ^r
QuantLib/Internal.hs view
@@ -80,6 +80,12 @@ , peekPtrArray , Matrix(..) , RealMatrix(..)+ , matrixRows+ , matrixColumns+ , matrixData+ , realMatrixRows+ , realMatrixColumns+ , realMatrixData , boxedRealMatrix , realMatrixFromVector , objectMatrix@@ -442,9 +448,27 @@ maxDate :: Day maxDate = fromSerial qlMaxDateSerialNumber -data Matrix a = Matrix {matrixRows::Word, matrixColumns::Word, matrixData::[a]}- deriving (Eq, Show)+-- Public accessors must not be record fields: exported fields permit unchecked record updates.+data Matrix a = Matrix Word Word [a]+ deriving (Eq) +instance Show a => Show (Matrix a) where+ showsPrec p (Matrix r c d) = showParen (p > 10) $+ showString "Matrix {matrixRows = " . shows r . showString ", matrixColumns = " . shows c+ . showString ", matrixData = " . shows d . showChar '}'++-- |Number of rows.+matrixRows :: Matrix a -> Word+matrixRows (Matrix r _ _) = r++-- |Number of columns.+matrixColumns :: Matrix a -> Word+matrixColumns (Matrix _ c _) = c++-- |Elements in row-major order.+matrixData :: Matrix a -> [a]+matrixData (Matrix _ _ d) = d+ -- |Row-major numeric matrix backed by contiguous storage. Use this for -- large dense grids such as regression and volatility-surface data; small -- process/correlation matrices remain boxed 'Matrix' values; object@@ -457,12 +481,25 @@ -- The reverse conversion through @flatten@ is zero-copy only for a contiguous -- row-major hmatrix matrix; BLAS-produced or sliced matrices can require a -- reorder/copy.-data RealMatrix = RealMatrix- { realMatrixRows :: Word- , realMatrixColumns :: Word- , realMatrixData :: RealVector- }- deriving (Eq, Show)+data RealMatrix = RealMatrix Word Word RealVector+ deriving (Eq)++instance Show RealMatrix where+ showsPrec p (RealMatrix r c d) = showParen (p > 10) $+ showString "RealMatrix {realMatrixRows = " . shows r . showString ", realMatrixColumns = " . shows c+ . showString ", realMatrixData = " . shows d . showChar '}'++-- |Number of rows.+realMatrixRows :: RealMatrix -> Word+realMatrixRows (RealMatrix r _ _) = r++-- |Number of columns.+realMatrixColumns :: RealMatrix -> Word+realMatrixColumns (RealMatrix _ c _) = c++-- |Contiguous elements in row-major order.+realMatrixData :: RealMatrix -> RealVector+realMatrixData (RealMatrix _ _ d) = d -- |Construct a list-backed numeric matrix for small-dimensional APIs such as process -- correlation and diffusion matrices. Returns a boxed 'Matrix' 'Double', /not/ a
QuantLib/Internal/Type.hs view
@@ -1772,11 +1772,16 @@ data CCallableBondVolatilityStructure' data CDefaultProbabilityTermStructure' data CAffineHazardRateCurve'+data CPiecewiseDefaultCurve'+data CPiecewiseYieldCurve' data CZeroInflationTermStructure' data CYoYInflationTermStructure'+data CPiecewiseZeroInflationCurve'+data CPiecewiseYoYInflationCurve' data CCommodityCurve' -- | > TermStructure = GenTermStructure t -- > YieldTermStructure = GenYieldTermStructure y = GenTermStructure t+-- > PiecewiseYieldCurve = GenYieldTermStructure ... -- > FittedBondDiscountCurve = GenYieldTermStructure ... -- > RelinkableYieldTermStructure = GenYieldTermStructure ... -- > VolatilityTermStructure@@ -1807,8 +1812,11 @@ -- > CallableBondVolatilityStructure -- > DefaultProbabilityTermStructure = GenDefaultProbabilityTermStructure d = GenTermStructure t -- > AffineHazardRateCurve = GenDefaultProbabilityTermStructure ...--- > ZeroInflationTermStructure--- > YoYInflationTermStructure+-- > PiecewiseDefaultCurve = GenDefaultProbabilityTermStructure ...+-- > ZeroInflationTermStructure = GenZeroInflationTermStructure z = GenTermStructure t+-- > PiecewiseZeroInflationCurve = GenZeroInflationTermStructure ...+-- > YoYInflationTermStructure = GenYoYInflationTermStructure yoy = GenTermStructure t+-- > PiecewiseYoYInflationCurve = GenYoYInflationTermStructure ... -- > YoYCapFloorTermPriceSurface -- > CPICapFloorTermPriceSurface -- > CommodityCurve@@ -1819,6 +1827,9 @@ type CYieldTermStructure = ForeignPtr CYieldTermStructure' -- |A 'TermStructure'; see the hierarchy under t'GenTermStructure'. type YieldTermStructure = GenYieldTermStructure CYieldTermStructure+type CPiecewiseYieldCurve = ForeignPtr CPiecewiseYieldCurve'+-- |A bootstrapped yield curve retaining its concrete native node accessor.+type PiecewiseYieldCurve = GenYieldTermStructure CPiecewiseYieldCurve type CFittedBondDiscountCurve = ForeignPtr CFittedBondDiscountCurve' -- |A 'YieldTermStructure'; see the hierarchy under t'GenTermStructure'. type FittedBondDiscountCurve = GenYieldTermStructure CFittedBondDiscountCurve@@ -1954,7 +1965,7 @@ type CSabrVolSurface = ForeignPtr CSabrVolSurface' -- | SABR-smile surface built from an interest-rate index, an ATM 'BlackAtmVolCurve', and -- per-tenor vol spreads. A dedicated 'BlackVolSurface' leaf (own getters: @atmCurve@,--- @sabrVolatilitySpreads@; plus @index@\/@optionDateFromTenor@ folded in directly from upstream's+-- @sabrVolSurfaceVolatilitySpreads@; plus @index@\/@optionDateFromTenor@ folded in directly from upstream's -- @InterestRateVolSurface@, which is not given its own hierarchy level here since -- 'SabrVolSurface' is its only concrete member in this binding -- per CLAUDE.md's "don't mirror -- the C++ hierarchy 1:1" rule). Two 'AnyOf' layers under 'GenBlackVolSurface' (mirrors@@ -2021,6 +2032,10 @@ type CAffineHazardRateCurve = ForeignPtr CAffineHazardRateCurve' -- |A 'DefaultProbabilityTermStructure'; see the hierarchy under t'GenTermStructure'. type AffineHazardRateCurve = GenDefaultProbabilityTermStructure CAffineHazardRateCurve+type CPiecewiseDefaultCurve = ForeignPtr CPiecewiseDefaultCurve'+-- |A 'DefaultProbabilityTermStructure' bootstrapped from default-probability helpers, whose nodes+-- can be read; see the hierarchy under t'GenTermStructure'.+type PiecewiseDefaultCurve = GenDefaultProbabilityTermStructure CPiecewiseDefaultCurve withDefaultProbabilityTermStructureArray :: [GenDefaultProbabilityTermStructure d] -> ((CUInt, Ptr (Ptr CDefaultProbabilityTermStructure')) -> IO b) -> IO b withDefaultProbabilityTermStructureArray = withGenArray withDefaultProbabilityTermStructure withDefaultProbabilityTermStructureArrayRaw :: [GenDefaultProbabilityTermStructure d] -> (Ptr (Ptr CDefaultProbabilityTermStructure') -> IO b) -> IO b@@ -2102,12 +2117,24 @@ withDigitalLossModel :: DigitalLossModel -> (Ptr CDefaultLossModel -> IO b) -> IO b withDigitalLossModel = withStandalone . getCDigitalLossModel +-- |A 'ZeroInflationTermStructure' or one of its leaves; see the hierarchy under t'GenTermStructure'.+type GenZeroInflationTermStructure z = GenTermStructure (AnyOf CZeroInflationTermStructure' z) type CZeroInflationTermStructure = ForeignPtr CZeroInflationTermStructure' -- |A 'TermStructure'; see the hierarchy under t'GenTermStructure'.-type ZeroInflationTermStructure = GenTermStructure CZeroInflationTermStructure+type ZeroInflationTermStructure = GenZeroInflationTermStructure CZeroInflationTermStructure+type CPiecewiseZeroInflationCurve = ForeignPtr CPiecewiseZeroInflationCurve'+-- |A 'ZeroInflationTermStructure' bootstrapped from swap helpers, whose nodes can be read; see the+-- hierarchy under t'GenTermStructure'.+type PiecewiseZeroInflationCurve = GenZeroInflationTermStructure CPiecewiseZeroInflationCurve+-- |A 'YoYInflationTermStructure' or one of its leaves; see the hierarchy under t'GenTermStructure'.+type GenYoYInflationTermStructure yoy = GenTermStructure (AnyOf CYoYInflationTermStructure' yoy) type CYoYInflationTermStructure = ForeignPtr CYoYInflationTermStructure' -- |A 'TermStructure'; see the hierarchy under t'GenTermStructure'.-type YoYInflationTermStructure = GenTermStructure CYoYInflationTermStructure+type YoYInflationTermStructure = GenYoYInflationTermStructure CYoYInflationTermStructure+type CPiecewiseYoYInflationCurve = ForeignPtr CPiecewiseYoYInflationCurve'+-- |A 'YoYInflationTermStructure' bootstrapped from swap helpers, whose nodes can be read; see the+-- hierarchy under t'GenTermStructure'.+type PiecewiseYoYInflationCurve = GenYoYInflationTermStructure CPiecewiseYoYInflationCurve type CCommodityCurve = ForeignPtr CCommodityCurve' -- | A plain 'TermStructure' leaf (not a 'YieldTermStructure' -- it has no discount-factor -- semantics, just an interpolated price curve), constructed and consumed by @shared_ptr@ like@@ -2118,7 +2145,7 @@ type CYoYCapFloorTermPriceSurface = ForeignPtr CYoYCapFloorTermPriceSurface' -- | Prices YoY cap\/floors by cap\/floor-surface intersection and put\/call parity, deriving an -- ATM YoY swap curve as a side effect -- the market-data input the YoY optionlet stripper--- ('QuantLib.TermStructure.InflationVolatility.kInterpolatedYoyOptionletVolatilitySurfaceBlack'+-- ('QuantLib.TermStructure.InflationVolatility.kInterpolatedYoyOptionletVolatilitySurface' -- et al.) bootstraps from. A plain 'TermStructure' leaf, constructed and consumed by -- @shared_ptr@ like 'CPICapFloorTermPriceSurface', never a @Handle@. Takes independent -- 'Interpolation2D' (cap\/floor price grid) and 'Interpolation' (per-maturity) choices --@@ -2172,8 +2199,12 @@ foreign import ccall unsafe "ql.h &qlFreeCallableBondVolatilityStructure" qlFreeCallableBondVolatilityStructure :: FinalizerPtr CCallableBondVolatilityStructure' foreign import ccall unsafe "ql.h &qlFreeDefaultProbabilityTermStructure" qlFreeDefaultProbabilityTermStructure :: FinalizerPtr CDefaultProbabilityTermStructure' foreign import ccall unsafe "ql.h &qlFreeAffineHazardRateCurve" qlFreeAffineHazardRateCurve :: FinalizerPtr CAffineHazardRateCurve'+foreign import ccall unsafe "ql.h &qlFreePiecewiseDefaultCurve" qlFreePiecewiseDefaultCurve :: FinalizerPtr CPiecewiseDefaultCurve'+foreign import ccall unsafe "ql.h &qlFreePiecewiseYieldCurve" qlFreePiecewiseYieldCurve :: FinalizerPtr CPiecewiseYieldCurve' foreign import ccall unsafe "ql.h &qlFreeZeroInflationTermStructure" qlFreeZeroInflationTermStructure :: FinalizerPtr CZeroInflationTermStructure' foreign import ccall unsafe "ql.h &qlFreeYoYInflationTermStructure" qlFreeYoYInflationTermStructure :: FinalizerPtr CYoYInflationTermStructure'+foreign import ccall unsafe "ql.h &qlFreePiecewiseZeroInflationCurve" qlFreePiecewiseZeroInflationCurve :: FinalizerPtr CPiecewiseZeroInflationCurve'+foreign import ccall unsafe "ql.h &qlFreePiecewiseYoYInflationCurve" qlFreePiecewiseYoYInflationCurve :: FinalizerPtr CPiecewiseYoYInflationCurve' foreign import ccall unsafe "ql.h &qlFreeYoYCapFloorTermPriceSurface" qlFreeYoYCapFloorTermPriceSurface :: FinalizerPtr CYoYCapFloorTermPriceSurface' foreign import ccall unsafe "ql.h &qlFreeCPICapFloorTermPriceSurface" qlFreeCPICapFloorTermPriceSurface :: FinalizerPtr CCPICapFloorTermPriceSurface' foreign import ccall unsafe "ql.h &qlFreeCommodityCurve" qlFreeCommodityCurve :: FinalizerPtr CCommodityCurve'@@ -2210,8 +2241,12 @@ instance Finalizable CCallableBondVolatilityStructure' where finalize = qlFreeCallableBondVolatilityStructure instance Finalizable CDefaultProbabilityTermStructure' where finalize = qlFreeDefaultProbabilityTermStructure instance Finalizable CAffineHazardRateCurve' where finalize = qlFreeAffineHazardRateCurve+instance Finalizable CPiecewiseDefaultCurve' where finalize = qlFreePiecewiseDefaultCurve+instance Finalizable CPiecewiseYieldCurve' where finalize = qlFreePiecewiseYieldCurve instance Finalizable CZeroInflationTermStructure' where finalize = qlFreeZeroInflationTermStructure instance Finalizable CYoYInflationTermStructure' where finalize = qlFreeYoYInflationTermStructure+instance Finalizable CPiecewiseZeroInflationCurve' where finalize = qlFreePiecewiseZeroInflationCurve+instance Finalizable CPiecewiseYoYInflationCurve' where finalize = qlFreePiecewiseYoYInflationCurve instance Finalizable CYoYCapFloorTermPriceSurface' where finalize = qlFreeYoYCapFloorTermPriceSurface instance Finalizable CCPICapFloorTermPriceSurface' where finalize = qlFreeCPICapFloorTermPriceSurface instance Finalizable CCommodityCurve' where finalize = qlFreeCommodityCurve@@ -2246,8 +2281,12 @@ foreign import ccall "ql.h qlCallableBondVolatilityStructureAsTermStructure" qlCallableBondVolatilityStructureAsTermStructure :: Ptr CCallableBondVolatilityStructure' -> IO (Ptr CTermStructure') foreign import ccall "ql.h qlDefaultProbabilityTermStructureAsTermStructure" qlDefaultProbabilityTermStructureAsTermStructure :: Ptr CDefaultProbabilityTermStructure' -> IO (Ptr CTermStructure') foreign import ccall "ql.h qlAffineHazardRateCurveAsDefaultProbabilityTermStructure" qlAffineHazardRateCurveAsDefaultProbabilityTermStructure :: Ptr CAffineHazardRateCurve' -> IO (Ptr CDefaultProbabilityTermStructure')+foreign import ccall "ql.h qlPiecewiseDefaultCurveAsDefaultProbabilityTermStructure" qlPiecewiseDefaultCurveAsDefaultProbabilityTermStructure :: Ptr CPiecewiseDefaultCurve' -> IO (Ptr CDefaultProbabilityTermStructure')+foreign import ccall "ql.h qlPiecewiseYieldCurveAsYieldTermStructure" qlPiecewiseYieldCurveAsYieldTermStructure :: Ptr CPiecewiseYieldCurve' -> IO (Ptr CYieldTermStructure') foreign import ccall "ql.h qlZeroInflationTermStructureAsTermStructure" qlZeroInflationTermStructureAsTermStructure :: Ptr CZeroInflationTermStructure' -> IO (Ptr CTermStructure') foreign import ccall "ql.h qlYoYInflationTermStructureAsTermStructure" qlYoYInflationTermStructureAsTermStructure :: Ptr CYoYInflationTermStructure' -> IO (Ptr CTermStructure')+foreign import ccall "ql.h qlPiecewiseZeroInflationCurveAsZeroInflationTermStructure" qlPiecewiseZeroInflationCurveAsZeroInflationTermStructure :: Ptr CPiecewiseZeroInflationCurve' -> IO (Ptr CZeroInflationTermStructure')+foreign import ccall "ql.h qlPiecewiseYoYInflationCurveAsYoYInflationTermStructure" qlPiecewiseYoYInflationCurveAsYoYInflationTermStructure :: Ptr CPiecewiseYoYInflationCurve' -> IO (Ptr CYoYInflationTermStructure') foreign import ccall "ql.h qlYoYCapFloorTermPriceSurfaceAsTermStructure" qlYoYCapFloorTermPriceSurfaceAsTermStructure :: Ptr CYoYCapFloorTermPriceSurface' -> IO (Ptr CTermStructure') foreign import ccall "ql.h qlCPICapFloorTermPriceSurfaceAsTermStructure" qlCPICapFloorTermPriceSurfaceAsTermStructure :: Ptr CCPICapFloorTermPriceSurface' -> IO (Ptr CTermStructure') foreign import ccall "ql.h qlCommodityCurveAsTermStructure" qlCommodityCurveAsTermStructure :: Ptr CCommodityCurve' -> IO (Ptr CTermStructure')@@ -2258,8 +2297,12 @@ instance Upcastable CCallableBondVolatilityStructure' where {type Base CCallableBondVolatilityStructure' = CTermStructure'; upcast = qlCallableBondVolatilityStructureAsTermStructure} instance Upcastable CDefaultProbabilityTermStructure' where {type Base CDefaultProbabilityTermStructure' = CTermStructure'; upcast = qlDefaultProbabilityTermStructureAsTermStructure} instance Upcastable CAffineHazardRateCurve' where {type Base CAffineHazardRateCurve' = CDefaultProbabilityTermStructure'; upcast = qlAffineHazardRateCurveAsDefaultProbabilityTermStructure}+instance Upcastable CPiecewiseDefaultCurve' where {type Base CPiecewiseDefaultCurve' = CDefaultProbabilityTermStructure'; upcast = qlPiecewiseDefaultCurveAsDefaultProbabilityTermStructure}+instance Upcastable CPiecewiseYieldCurve' where {type Base CPiecewiseYieldCurve' = CYieldTermStructure'; upcast = qlPiecewiseYieldCurveAsYieldTermStructure} instance Upcastable CZeroInflationTermStructure' where {type Base CZeroInflationTermStructure' = CTermStructure'; upcast = qlZeroInflationTermStructureAsTermStructure} instance Upcastable CYoYInflationTermStructure' where {type Base CYoYInflationTermStructure' = CTermStructure'; upcast = qlYoYInflationTermStructureAsTermStructure}+instance Upcastable CPiecewiseZeroInflationCurve' where {type Base CPiecewiseZeroInflationCurve' = CZeroInflationTermStructure'; upcast = qlPiecewiseZeroInflationCurveAsZeroInflationTermStructure}+instance Upcastable CPiecewiseYoYInflationCurve' where {type Base CPiecewiseYoYInflationCurve' = CYoYInflationTermStructure'; upcast = qlPiecewiseYoYInflationCurveAsYoYInflationTermStructure} instance Upcastable CYoYCapFloorTermPriceSurface' where {type Base CYoYCapFloorTermPriceSurface' = CTermStructure'; upcast = qlYoYCapFloorTermPriceSurfaceAsTermStructure} instance Upcastable CCPICapFloorTermPriceSurface' where {type Base CCPICapFloorTermPriceSurface' = CTermStructure'; upcast = qlCPICapFloorTermPriceSurfaceAsTermStructure} instance Upcastable CCommodityCurve' where {type Base CCommodityCurve' = CTermStructure'; upcast = qlCommodityCurveAsTermStructure}@@ -2451,14 +2494,45 @@ -- 'withDefaultProbabilityTermStructure' instead, which upcasts. withAffineHazardRateCurve :: AffineHazardRateCurve -> (Ptr CAffineHazardRateCurve' -> IO b) -> IO b withAffineHazardRateCurve = withForeignPtr . ptr . peel . getTermStructure+peekPiecewiseDefaultCurve :: Ptr CPiecewiseDefaultCurve' -> IO PiecewiseDefaultCurve+peekPiecewiseDefaultCurve = newGenForeignPtr >=> newGenDefaultProbabilityTermStructure+-- | Reach the concrete leaf, for its nodes; ordinary curve arguments go through+-- 'withDefaultProbabilityTermStructure', which upcasts.+withPiecewiseDefaultCurve :: PiecewiseDefaultCurve -> (Ptr CPiecewiseDefaultCurve' -> IO b) -> IO b+withPiecewiseDefaultCurve = withForeignPtr . ptr . peel . getTermStructure+peekPiecewiseYieldCurve :: Ptr CPiecewiseYieldCurve' -> IO PiecewiseYieldCurve+peekPiecewiseYieldCurve = newGenForeignPtr >=> newGenYieldTermStructure+-- |Reach the concrete leaf for its nodes; ordinary consumers use the yield upcast.+withPiecewiseYieldCurve :: PiecewiseYieldCurve -> (Ptr CPiecewiseYieldCurve' -> IO b) -> IO b+withPiecewiseYieldCurve = withForeignPtr . ptr . peel . getTermStructure+asZeroInflationTermStructure :: GenZeroInflationTermStructure z -> IO ZeroInflationTermStructure+asZeroInflationTermStructure = transferGenForeignPtr newGenZeroInflationTermStructure . peel . getTermStructure peekZeroInflationTermStructure :: Ptr CZeroInflationTermStructure' -> IO ZeroInflationTermStructure-peekZeroInflationTermStructure = GenTermStructure <.> newGenForeignPtr-withMaybeZeroInflationTermStructure :: Maybe ZeroInflationTermStructure -> (Ptr CZeroInflationTermStructure' -> IO b) -> IO b-withMaybeZeroInflationTermStructure x f = maybe (f nullPtr) (`withGenTermStructure` f) x+peekZeroInflationTermStructure = newCastForeignPtr >=> newGenZeroInflationTermStructure+withZeroInflationTermStructure :: GenZeroInflationTermStructure z -> (Ptr CZeroInflationTermStructure' -> IO b) -> IO b+withZeroInflationTermStructure = withGenForeignPtr . peel . getTermStructure+withMaybeZeroInflationTermStructure :: Maybe (GenZeroInflationTermStructure z) -> (Ptr CZeroInflationTermStructure' -> IO b) -> IO b+withMaybeZeroInflationTermStructure x f = maybe (f nullPtr) (`withZeroInflationTermStructure` f) x+newGenZeroInflationTermStructure :: GenForeignPtr z CZeroInflationTermStructure' -> IO (GenZeroInflationTermStructure z)+newGenZeroInflationTermStructure = pure . GenTermStructure . newAnyOf+peekPiecewiseZeroInflationCurve :: Ptr CPiecewiseZeroInflationCurve' -> IO PiecewiseZeroInflationCurve+peekPiecewiseZeroInflationCurve = newGenForeignPtr >=> newGenZeroInflationTermStructure+withPiecewiseZeroInflationCurve :: PiecewiseZeroInflationCurve -> (Ptr CPiecewiseZeroInflationCurve' -> IO b) -> IO b+withPiecewiseZeroInflationCurve = withForeignPtr . ptr . peel . getTermStructure+asYoyInflationTermStructure :: GenYoYInflationTermStructure yoy -> IO YoYInflationTermStructure+asYoyInflationTermStructure = transferGenForeignPtr newGenYoYInflationTermStructure . peel . getTermStructure peekYoYInflationTermStructure :: Ptr CYoYInflationTermStructure' -> IO YoYInflationTermStructure-peekYoYInflationTermStructure = GenTermStructure <.> newGenForeignPtr-withMaybeYoYInflationTermStructure :: Maybe YoYInflationTermStructure -> (Ptr CYoYInflationTermStructure' -> IO b) -> IO b-withMaybeYoYInflationTermStructure x f = maybe (f nullPtr) (`withGenTermStructure` f) x+peekYoYInflationTermStructure = newCastForeignPtr >=> newGenYoYInflationTermStructure+withYoYInflationTermStructure :: GenYoYInflationTermStructure yoy -> (Ptr CYoYInflationTermStructure' -> IO b) -> IO b+withYoYInflationTermStructure = withGenForeignPtr . peel . getTermStructure+withMaybeYoYInflationTermStructure :: Maybe (GenYoYInflationTermStructure yoy) -> (Ptr CYoYInflationTermStructure' -> IO b) -> IO b+withMaybeYoYInflationTermStructure x f = maybe (f nullPtr) (`withYoYInflationTermStructure` f) x+newGenYoYInflationTermStructure :: GenForeignPtr yoy CYoYInflationTermStructure' -> IO (GenYoYInflationTermStructure yoy)+newGenYoYInflationTermStructure = pure . GenTermStructure . newAnyOf+peekPiecewiseYoYInflationCurve :: Ptr CPiecewiseYoYInflationCurve' -> IO PiecewiseYoYInflationCurve+peekPiecewiseYoYInflationCurve = newGenForeignPtr >=> newGenYoYInflationTermStructure+withPiecewiseYoYInflationCurve :: PiecewiseYoYInflationCurve -> (Ptr CPiecewiseYoYInflationCurve' -> IO b) -> IO b+withPiecewiseYoYInflationCurve = withForeignPtr . ptr . peel . getTermStructure peekYoYCapFloorTermPriceSurface :: Ptr CYoYCapFloorTermPriceSurface' -> IO YoYCapFloorTermPriceSurface peekYoYCapFloorTermPriceSurface = GenTermStructure <.> newGenForeignPtr peekCPICapFloorTermPriceSurface :: Ptr CCPICapFloorTermPriceSurface' -> IO CPICapFloorTermPriceSurface
QuantLib/Quote.chs view
@@ -26,6 +26,7 @@ , eurodollarFuturesImpliedStdDevQuote , forwardSwapQuote , forwardValueQuote+ , fxCashSpotQuote , futuresConvAdjustmentQuoteFromImmCode , futuresConvAdjustmentQuote , impliedStdDevQuote@@ -80,6 +81,8 @@ {#pointer *QlDeltaVolQuote as DeltaVolQuote foreign -> CDeltaVolQuote' nocode#} {#pointer *QlFuturesConvAdjustmentQuote as FuturesConvAdjustmentQuote foreign -> CFuturesConvAdjustmentQuote' nocode#} {#pointer *QlRelinkableQuote as RelinkableQuote foreign -> CRelinkableQuote' nocode#}+{#pointer *QlYieldTermStructure as YieldTermStructure foreign -> CYieldTermStructure' nocode#}+{#pointer *Calendar foreign -> CCalendar nocode#} -- |market element returning a stored value {#fun qlSimpleQuote as simpleQuote{`Double',preErrorCheck-`String'errorCheck*-}->`SimpleQuote'peekSimpleQuote*#}@@ -101,9 +104,8 @@ -- |Returns the current value of the given Quote object {#fun qlQuoteValue as value{withQuote*`GenQuote q',preErrorCheck-`String'errorCheck*-}->`Double'#} --- |returns the difference between the new value and the old value--- /NB/ The change will propagate to all users of the quote-{#fun qlSimpleQuoteSetValue as setValue{withGenQuote*`SimpleQuote',`Double',preErrorCheck-`String'errorCheck*-}->`Double'#}+-- |Set the quote's value. The change propagates to all users of the quote.+{#fun qlSimpleQuoteSetValue as setValue{withGenQuote*`SimpleQuote',`Double',preErrorCheck-`String'errorCheck*-}->`()'#} -- |implied standard deviation of a Eurodollar future's underlying, solved from its call/put prices {#fun qlEurodollarFuturesImpliedStdDevQuote as eurodollarFuturesImpliedStdDevQuote{withQuote*`GenQuote q1' -- ^forward@@ -122,6 +124,28 @@ -- |forward value of an index as of a given fixing date {#fun qlForwardValueQuote as forwardValueQuote{withIndex*`GenIndex idx',withDay*`Day',preErrorCheck-`String'errorCheck*-}->`Quote'peekQuote*#}++-- |The cash value, at the evaluation date @d@, of an FX spot quoted for settlement on+-- @V = advance calendar d settlementDays Days@ (business days; with zero days, @d@ adjusted+-- Following). Its value is+--+-- > S_d = S_V * (P_dom(V) / P_dom(d)) / (P_for(V) / P_for(d))+--+-- with @P@ each curve's discount factor, so a forward built from it,+-- @S_d * (P_for(T) \/ P_for(d)) \/ (P_dom(T) \/ P_dom(d))@, equals @S_V@ at @T = V@. Use it as a+-- Garman-Kohlhagen process's spot when the market quotes spot for settlement rather than cash.+--+-- This class is defined by hasquant, not QuantLib (which has no quote observing yield curves);+-- QuantExt's @FxRateQuote@ is the prior art. It is live: it notifies its observers when the+-- settlement spot, either curve (including a relink) or the evaluation date changes, and recomputes+-- @V@ and every discount factor on each read. A read throws when a curve cannot discount to @d@, for+-- instance when its reference date is after the evaluation date.+{#fun qlFxCashSpotQuote as fxCashSpotQuote{withQuote*`GenQuote q' -- ^settlementSpot: @S_V@, domestic currency per unit of foreign, for settlement on @V@+ ,withYieldTermStructure*`GenYieldTermStructure y1' -- ^domesticTS: discounting in the domestic (quote) currency+ ,withYieldTermStructure*`GenYieldTermStructure y2' -- ^foreignTS: discounting in the foreign (base) currency+ ,withCalendar*`Calendar' -- ^settlementCalendar: business days that set @V@+ ,fromIntegral`Word' -- ^settlementDays: spot lag in business days from the evaluation date+ ,preErrorCheck-`String'errorCheck*-}->`Quote'peekQuote*#} -- |futures-convexity adjustment for an Ibor future identified by its IMM code {#fun qlFuturesConvAdjustmentQuote1 as futuresConvAdjustmentQuoteFromImmCode{withIborIndex*`GenIborIndex ibor',`String' -- ^immCode
QuantLib/TermStructure.chs view
@@ -12,6 +12,7 @@ , TermPoint(..) , TermInterval(..) , RatePoint(..)+ , RateInterval(..) -- * Constructors , asTermStructure@@ -21,6 +22,7 @@ -- * Inspectors , HasHelperUnderlying(..)+ , HasNodes(..) , referenceDate , maxDate , maxTime@@ -49,6 +51,10 @@ {#pointer *QlYearOnYearInflationSwap as YearOnYearInflationSwap foreign -> CYearOnYearInflationSwap' nocode#} {#pointer *QlFixedVsFloatingSwap as FixedVsFloatingSwap foreign -> CFixedVsFloatingSwap' nocode#} {#pointer *QlTermStructure as TermStructure foreign -> CTermStructure' nocode#}+{#pointer *QlPiecewiseYieldCurve as PiecewiseYieldCurve foreign -> CPiecewiseYieldCurve' nocode#}+{#pointer *QlPiecewiseDefaultCurve as PiecewiseDefaultCurve foreign -> CPiecewiseDefaultCurve' nocode#}+{#pointer *QlPiecewiseZeroInflationCurve as PiecewiseZeroInflationCurve foreign -> CPiecewiseZeroInflationCurve' nocode#}+{#pointer *QlPiecewiseYoYInflationCurve as PiecewiseYoYInflationCurve foreign -> CPiecewiseYoYInflationCurve' nocode#} -- |Bootstrap and calibration helpers that build and hold the instrument whose market quote -- they match. The class lives here, in the term-structure root module, because its instances@@ -88,6 +94,35 @@ {#fun qlYearOnYearInflationSwapHelperSwap{withYearOnYearInflationSwapHelper*`YearOnYearInflationSwapHelper',preErrorCheck-`String'errorCheck*-}->`YearOnYearInflationSwap'peekYearOnYearInflationSwap*#} {#fun qlSwaptionHelperUnderlying{withSwaptionHelper*`SwaptionHelper',preErrorCheck-`String'errorCheck*-}->`FixedVsFloatingSwap'peekFixedVsFloatingSwap*#} +-- |Bootstrapped curve leaves that retain their native nodes. The class lives in this root module+-- for the same reason as 'HasHelperUnderlying': its instances span the topical curve modules.+class HasNodes c where+ -- |The curve's (date, value) nodes; reading them runs the bootstrap. The first node is the+ -- reference date (inflation curves: the base date), the rest are helper pillars. Each value is+ -- what the curve interpolates: the trait's quantity for yield and default curves, a+ -- discount-factor spread for 'QuantLib.TermStructure.Yield.piecewiseSpreadYieldCurve', and+ -- the rate before seasonality for inflation curves. Jump factors are applied separately and+ -- are not part of the nodes.+ --+ -- An interpolated curve of the same kind on these nodes, with the original day counter,+ -- interpolation, jumps and seasonality, reproduces the bootstrapped curve. The exception is a+ -- local bootstrap, whose convex-monotone shape also depends on state the nodes do not carry.+ bootstrappedNodes :: c -> IO [(Day, Double)]++instance HasNodes PiecewiseYieldCurve where+ bootstrappedNodes = fmap (uncurry zip) . qlPiecewiseYieldCurveNodes+instance HasNodes PiecewiseDefaultCurve where+ bootstrappedNodes = fmap (uncurry zip) . qlPiecewiseDefaultCurveNodes+instance HasNodes PiecewiseZeroInflationCurve where+ bootstrappedNodes = fmap (uncurry zip) . qlPiecewiseZeroInflationCurveNodes+instance HasNodes PiecewiseYoYInflationCurve where+ bootstrappedNodes = fmap (uncurry zip) . qlPiecewiseYoYInflationCurveNodes++{#fun qlPiecewiseYieldCurveNodes{withPiecewiseYieldCurve*`PiecewiseYieldCurve',preIntArray-`[Day]'&peekDayArray*,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}+{#fun qlPiecewiseDefaultCurveNodes{withPiecewiseDefaultCurve*`PiecewiseDefaultCurve',preIntArray-`[Day]'&peekDayArray*,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}+{#fun qlPiecewiseZeroInflationCurveNodes{withPiecewiseZeroInflationCurve*`PiecewiseZeroInflationCurve',preIntArray-`[Day]'&peekDayArray*,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}+{#fun qlPiecewiseYoYInflationCurveNodes{withPiecewiseYoYInflationCurve*`PiecewiseYoYInflationCurve',preIntArray-`[Day]'&peekDayArray*,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#}+ -- |A term-structure reference point. 'ReferenceDate' stays fixed for the object's lifetime; -- 'SettlementDays' follows the global evaluation date using the supplied calendar. data Reference@@ -117,6 +152,13 @@ data RatePoint = RateAtDate !Day !DayCounter | RateAtTime !Double+ deriving (Eq, Show)++-- |A same-representation interval where dates need their day-counting rule; times use the+-- curve's own.+data RateInterval+ = RateBetweenDates !Day !Day !DayCounter+ | RateBetweenTimes !Double !Double deriving (Eq, Show) -- |the date at which discount = 1.0 and/or variance = 0.0
QuantLib/TermStructure/Commodity.chs view
@@ -88,7 +88,7 @@ {#fun qlCommodityCurvePrices as qlCommodityCurvePrices{withGenTermStructure*`CommodityCurve',preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Whether this curve has any nodes.-{#fun pure qlCommodityCurveEmpty as isEmpty{withGenTermStructure*`CommodityCurve'}->`Bool'#}+{#fun qlCommodityCurveEmpty as isEmpty{withGenTermStructure*`CommodityCurve'}->`Bool'#} -- |The basis curve this curve was chained to via 'setBasisOfCurve', if any. {#fun qlCommodityCurveBasisOfCurve as basisOfCurve{withGenTermStructure*`CommodityCurve'}->`Maybe CommodityCurve'peekMaybeCommodityCurve*#}
QuantLib/TermStructure/Credit.chs view
@@ -1,3 +1,34 @@+-- | Credit term structures and helpers.+--+-- = Hazard shifts #hazard-shifts#+--+-- 'shiftedHazardRateCurve' retains QuantLib's parallel and relative wrappers. Their+-- survival calculation uses 48-point Gauss-Chebyshev quadrature, so even+-- a constant hazard integrates with a small numerical error. For a flat annual+-- hazard h, parallel survival is @exp(-k*h*t)@, with @k = pi\/(96*sin(pi\/96))@, rather+-- than exp(-h*t). This numerical behavior is retained for compatibility.+-- Parallel queries now refuse negative or non-finite resulting hazards, including+-- during native survival integration, rather than returning invalid credit rates.+-- Shaped shifts instead retain base survival and apply the exact interpolation+-- primitive of their spread; see 'shiftedHazardRateCurve' for bounds and query checks.+--+-- = Conditional survival #conditional-survival#+--+-- 'conditionalSurvivalCurve' is a hasquant curve view, not a QuantLib class binding.+-- It keeps the original native interpolation and hazard-wrapper quadrature. For+-- original-curve time s at its new fixed reference, a view-time t reads+-- @S(s+t)/S(s)@, @f(s+t)/S(s)@ and @h(s+t)@ from the original curve.+-- View times are years from the new reference on the original day counter. Date+-- queries preserve original-date ratios when that day counter adds year fractions;+-- callers must check that clock convention rather than silently re-interpolate.+-- The new reference must lie within the original support and have positive finite+-- survival: normalizing zero or an invalid value cannot define a conditional curve.+-- Sources exposing scheduled jumps are refused: the generic curve interface does not+-- expose their quote handles, so transferring their jump metadata would lose updates.+-- The view keeps its original curve alive, observes its updates and inherits its+-- calendar, day counter, maximum date and extrapolation permission. Its reference+-- remains fixed if the original curve moves; a reference that then becomes invalid+-- is refused when queried. Native query values must remain finite. module QuantLib.TermStructure.Credit ( -- * Types@@ -5,6 +36,7 @@ GenDefaultProbabilityTermStructure , DefaultProbabilityTermStructure , AffineHazardRateCurve+ , PiecewiseDefaultCurve , DefaultProbabilityHelper -- ** Coordinates@@ -12,15 +44,18 @@ , TermPoint(..) , TermInterval(..) + -- ** Hazard shifts+ , HazardRateShift(..)+ -- ** Bootstrap configuration , ProbabilityTrait(..) , IterativeBootstrapOpts(..) -- * Constructors- -- ** Flat and spreaded curves- , factorSpreadedHazardRateCurve+ -- ** Flat, conditional and spreaded curves+ , shiftedHazardRateCurve , flatHazardRate- , spreadedHazardRateCurve+ , conditionalSurvivalCurve -- ** Helpers and bootstrapped curves , spreadCdsHelper , upfrontCdsHelper@@ -30,6 +65,7 @@ , interpolatedSurvivalProbabilityCurve , defaultIterativeBootstrapOpts , piecewiseDefaultCurve+ , asDefaultProbabilityTermStructure -- * Inspectors , defaultProbability@@ -40,6 +76,7 @@ , conditionalSurvivalProbability , impliedQuote , impliedQuoteOn+ , HasNodes(..) ) where #include "qlTypesC2HS.h" #include "qlEnumC2HS.h"@@ -51,22 +88,81 @@ import QuantLib.Internal.Type {#import QuantLib.Time.Schedule#}(DateGenerationRule, Frequency) import QuantLib.Internal.Common-import QuantLib.TermStructure (Reference(..), TermPoint(..), TermInterval(..), setExtrapolation)+import QuantLib.TermStructure (Reference(..), TermPoint(..), TermInterval(..), setExtrapolation, HasNodes(..)) import Data.List.NonEmpty(NonEmpty, toList) {#enum ProbabilityTrait{} deriving(Show, Eq, Read)#} {#pointer *Calendar foreign -> CCalendar nocode#} {#pointer *QlDefaultProbabilityTermStructure as DefaultProbabilityTermStructure foreign -> CDefaultProbabilityTermStructure' nocode#}+{#pointer *QlPiecewiseDefaultCurve as PiecewiseDefaultCurve foreign -> CPiecewiseDefaultCurve' nocode#} {#pointer *QlAffineHazardRateCurve as AffineHazardRateCurve foreign -> CAffineHazardRateCurve' nocode#} {#pointer *QlYieldTermStructure as YieldTermStructure foreign -> CYieldTermStructure' nocode#} {#pointer *QlQuote as Quote foreign -> CQuote' nocode#} {#pointer *QlDefaultProbabilityHelper as DefaultProbabilityHelper foreign -> CDefaultProbabilityHelper nocode#} {#pointer *QlOneFactorAffineModel as OneFactorAffineModel foreign -> COneFactorAffineModel' nocode#} --- |a curve whose hazard rate is another curve's, scaled by a spread factor-{#fun qlFactorSpreadedHazardRateCurve as factorSpreadedHazardRateCurve{withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d',withQuote*`GenQuote q',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}+-- | A live shift of a credit curve. Spreads are annual continuous hazard fractions;+-- relative operands are dimensionless (0.01 means multiplying hazards by 1.01).+data HazardRateShift q+ = -- | QuantLib's additive parallel hazard wrapper.+ ParallelHazardShift (GenQuote q) -- ^Annual additive spread quote.+ | -- | QuantLib's relative hazard wrapper.+ RelativeHazardShift (GenQuote q) -- ^Fractional change quote, normally at least -1.+ | -- | Linear spread in curve time between dates, flat outside the grid.+ KeyRateHazardShifts (NonEmpty (Day, GenQuote q)) -- ^Strictly increasing dates after the underlying reference date, paired with annual spread quotes.+ | -- | Constant spread on [previous end, end), zero at and after the last end.+ BucketHazardShifts (NonEmpty (Day, GenQuote q)) -- ^Strictly increasing period ends after the underlying reference date, paired with annual spread quotes; the first period starts at that reference date. +-- | Apply a live hazard shift, retaining the underlying reference date, day counter,+-- calendar and maximum date. The underlying and all quotes remain observed.+--+-- Parallel and relative shifts retain QuantLib's original wrappers and numerical+-- integration; parallel queries additionally check finite nonnegative hazards.+-- The shaped adapter is defined by hasquant: it adds the spread to+-- the underlying hazard and multiplies underlying survival by+-- @exp(-integral spread dt)@. QuantLib's linear/forward-flat interpolation primitives+-- integrate the spread exactly, so bucket boundaries introduce no survival jumps+-- and the accumulated change remains after the last bucket. The base curve is+-- never sampled or re-interpolated. Curve times use its own day counter.+--+-- Shaped queries refuse non-finite spreads, negative or non-finite resulting hazards,+-- and non-finite survival probabilities or values outside [0,1]. Multiplication+-- roundoff at most four machine epsilons above one is clamped to one, so exactly+-- zero hazards are not refused because @exp(-x) * exp(x)@ rounded upward.+-- Survival queries+-- check their endpoint and both sides of earlier spread knots; this is not a proof+-- of positivity at every point of an arbitrary underlying curve. Underflow and+-- overflow of the exponential correction remain native floating-point limits.+shiftedHazardRateCurve+ :: GenDefaultProbabilityTermStructure d -- ^Underlying credit curve.+ -> HazardRateShift q -- ^Live shift quotes and, for shapes, their date grid.+ -> IO DefaultProbabilityTermStructure+shiftedHazardRateCurve base shift = case shift of+ ParallelHazardShift q -> parallelHazardRateCurveRaw base q+ RelativeHazardShift q -> relativeHazardRateCurveRaw base q+ KeyRateHazardShifts nodes -> shaped False nodes+ BucketHazardShifts nodes -> shaped True nodes+ where+ shaped buckets nodes = let (dates, quotes) = unzip (toList nodes)+ in shapedHazardRateCurveRaw base quotes dates buckets++{#fun qlShapedHazardRateCurve as shapedHazardRateCurveRaw+ {withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d'+ ,withQuoteArray*`[GenQuote q]'&+ ,withDayArray*`[Day]'&+ ,`Bool'+ ,preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}++{#fun qlFactorSpreadedHazardRateCurve as relativeHazardRateCurveRaw{withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d',withQuote*`GenQuote q',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}++-- | The original native credit curve conditioned on survival at a later fixed reference.+-- This is the delegated curve view described in [Conditional survival](#conditional-survival).+{#fun qlConditionalSurvivalCurve as conditionalSurvivalCurve+ {withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d' -- ^Original credit curve, retained and observed by the view.+ ,withDay*`Day' -- ^New fixed reference date, on or after the original reference and no later than its maximum date.+ ,preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}+ -- |Flat hazard-rate curve with either a fixed or evaluation-date-relative reference point. flatHazardRate :: Reference -> GenQuote q -> DayCounter -> IO DefaultProbabilityTermStructure flatHazardRate (ReferenceDate d) = flatHazardRateFixed d@@ -74,8 +170,7 @@ {#fun qlFlatHazardRate1 as flatHazardRateMovingRaw{fromIntegral`Word',withCalendar*`Calendar',withQuote*`GenQuote q',withDayCounter*`DayCounter',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#} {#fun qlFlatHazardRate as flatHazardRateFixed{withDay*`Day',withQuote*`GenQuote q',withDayCounter*`DayCounter',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#} --- |a curve whose survival probability is another curve's, multiplied by a spread factor-{#fun qlSpreadedHazardRateCurve as spreadedHazardRateCurve{withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d',withQuote*`GenQuote q',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}+{#fun qlSpreadedHazardRateCurve as parallelHazardRateCurveRaw{withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d',withQuote*`GenQuote q',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#} {#fun qlDefaultProbabilityTermStructureDefaultProbability as defaultProbabilityAtDateRaw{withDefaultProbabilityTermStructure*`GenDefaultProbabilityTermStructure d',withDay*`Day',`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`Double'#}@@ -258,7 +353,7 @@ -> Interpolation -- ^interpolator -> IterativeBootstrapOpts -- ^bootstrap settings -> Bool -- ^extrapolate past the curve's max date- -> IO DefaultProbabilityTermStructure+ -> IO PiecewiseDefaultCurve piecewiseDefaultCurve reference h dc q t i b ex = do curve <- case reference of ReferenceDate d -> uncurryNested (piecewiseDefaultCurve_ d hs dc qq qd t) (qlInterpolation i)@@ -271,7 +366,7 @@ pure curve where (qd, qq) = unzip q hs = toList h-{#fun qlPiecewiseDefaultCurve as piecewiseDefaultCurve_{withDay*`Day',withDefaultProbabilityHelperArray*`[DefaultProbabilityHelper]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`ProbabilityTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}-{#fun qlPiecewiseDefaultCurve1 as piecewiseDefaultCurve1_{fromIntegral`Word',withCalendar*`Calendar',withDefaultProbabilityHelperArray*`[DefaultProbabilityHelper]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`ProbabilityTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',preErrorCheck-`String'errorCheck*-}->`DefaultProbabilityTermStructure'peekDefaultProbabilityTermStructure*#}+{#fun qlPiecewiseDefaultCurve as piecewiseDefaultCurve_{withDay*`Day',withDefaultProbabilityHelperArray*`[DefaultProbabilityHelper]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`ProbabilityTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',preErrorCheck-`String'errorCheck*-}->`PiecewiseDefaultCurve'peekPiecewiseDefaultCurve*#}+{#fun qlPiecewiseDefaultCurve1 as piecewiseDefaultCurve1_{fromIntegral`Word',withCalendar*`Calendar',withDefaultProbabilityHelperArray*`[DefaultProbabilityHelper]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`ProbabilityTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',preErrorCheck-`String'errorCheck*-}->`PiecewiseDefaultCurve'peekPiecewiseDefaultCurve*#} -- vim: set ff=unix ts=8 sts=2 sw=2 et:
QuantLib/TermStructure/Inflation.chs view
@@ -1,8 +1,13 @@+{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} module QuantLib.TermStructure.Inflation ( -- * Types- ZeroInflationTermStructure+ GenZeroInflationTermStructure+ , ZeroInflationTermStructure+ , PiecewiseZeroInflationCurve+ , GenYoYInflationTermStructure , YoYInflationTermStructure+ , PiecewiseYoYInflationCurve , ZeroCouponInflationSwapHelper , YearOnYearInflationSwapHelper , CPIInterpolationType(..) -- ^re-exported from "QuantLib.Internal.Common"@@ -20,19 +25,22 @@ , piecewiseYoyInflationCurve , interpolatedYoyInflationCurve , interpolatedZeroInflationCurve+ -- ** Conversions+ , asZeroInflationTermStructure+ , asYoyInflationTermStructure -- * Inspectors , HasHelperUnderlying(..) , zeroRate , yoyRate- , zeroCouponInflationSwapImpliedQuoteOn- , yearOnYearInflationSwapImpliedQuoteOn+ , HasImpliedQuoteOn(..)+ , HasNodes(..) ) where import QuantLib.Internal import QuantLib.Internal.Type {#import QuantLib.Time.Schedule#}(Frequency(..)) import QuantLib.Internal.Common-import QuantLib.TermStructure(HasHelperUnderlying(..))+import QuantLib.TermStructure(HasHelperUnderlying(..), HasNodes(..)) import Data.List.NonEmpty(NonEmpty, toList) {#import QuantLib.TermStructure.Yield#}(PillarChoice) @@ -45,6 +53,8 @@ {#pointer *Calendar foreign -> CCalendar nocode#} {#pointer *QlZeroInflationTermStructure as ZeroInflationTermStructure foreign -> CZeroInflationTermStructure' nocode#} {#pointer *QlYoYInflationTermStructure as YoYInflationTermStructure foreign -> CYoYInflationTermStructure' nocode#}+{#pointer *QlPiecewiseZeroInflationCurve as PiecewiseZeroInflationCurve foreign -> CPiecewiseZeroInflationCurve' nocode#}+{#pointer *QlPiecewiseYoYInflationCurve as PiecewiseYoYInflationCurve foreign -> CPiecewiseYoYInflationCurve' nocode#} {#pointer *QlZeroInflationIndex as ZeroInflationIndex foreign -> CZeroInflationIndex' nocode#} {#pointer *QlYoYInflationIndex as YoYInflationIndex foreign -> CYoYInflationIndex' nocode#} {#pointer *QlZeroCouponInflationSwapHelper as ZeroCouponInflationSwapHelper foreign -> CZeroCouponInflationSwapHelper nocode#}@@ -171,14 +181,14 @@ piecewiseZeroInflationCurve :: Day -- ^referenceDate -> Day -- ^baseDate -> Frequency -> DayCounter -> NonEmpty ZeroCouponInflationSwapHelper -> Maybe Seasonality -> Interpolation- -> IO ZeroInflationTermStructure+ -> IO PiecewiseZeroInflationCurve piecewiseZeroInflationCurve r b f dc h s i = seasonalityArgs r s $ \sk sd sf sfs -> uncurryNested (qlPiecewiseZeroInflationCurve r b f dc (toList h) sk sd sf sfs) (qlInterpolation i) {#fun qlPiecewiseZeroInflationCurve{withDay*`Day',withDay*`Day',`Frequency',withDayCounter*`DayCounter' ,withZeroCouponInflationSwapHelperArray*`[ZeroCouponInflationSwapHelper]'& ,`Int',withDay*`Day',`Frequency',withDoubleArray*`[Double]'&- ,`Int',`Int',`Int',preErrorCheck-`String'errorCheck*-}->`ZeroInflationTermStructure'peekZeroInflationTermStructure*#}+ ,`Int',`Int',`Int',preErrorCheck-`String'errorCheck*-}->`PiecewiseZeroInflationCurve'peekPiecewiseZeroInflationCurve*#} -- |Bootstraps a year-on-year inflation term structure piecewise from a set of helpers, -- interpolating between the bootstrapped nodes with the given 'Interpolation'.@@ -186,14 +196,14 @@ -> Day -- ^baseDate -> Double -- ^baseYoYRate -> Frequency -> DayCounter -> NonEmpty YearOnYearInflationSwapHelper -> Maybe Seasonality -> Interpolation- -> IO YoYInflationTermStructure+ -> IO PiecewiseYoYInflationCurve piecewiseYoyInflationCurve r b y f dc h s i = seasonalityArgs r s $ \sk sd sf sfs -> uncurryNested (qlPiecewiseYoYInflationCurve r b y f dc (toList h) sk sd sf sfs) (qlInterpolation i) {#fun qlPiecewiseYoYInflationCurve{withDay*`Day',withDay*`Day',`Double',`Frequency',withDayCounter*`DayCounter' ,withYearOnYearInflationSwapHelperArray*`[YearOnYearInflationSwapHelper]'& ,`Int',withDay*`Day',`Frequency',withDoubleArray*`[Double]'&- ,`Int',`Int',`Int',preErrorCheck-`String'errorCheck*-}->`YoYInflationTermStructure'peekYoYInflationTermStructure*#}+ ,`Int',`Int',`Int',preErrorCheck-`String'errorCheck*-}->`PiecewiseYoYInflationCurve'peekPiecewiseYoYInflationCurve*#} -- |A YoY-inflation curve interpolating directly between given (date, rate) nodes, unlike -- 'piecewiseYoyInflationCurve' bootstrap from swap helpers -- useful when the rates are@@ -240,21 +250,27 @@ Just (KerkhofSeasonality b fs) -> k 1 b Monthly fs -- |Zero-coupon inflation rate implied by the curve.-{#fun qlZeroInflationTermStructureZeroRate as zeroRate{withGenTermStructure*`ZeroInflationTermStructure',withDay*`Day',`Bool' -- ^extrapolate+{#fun qlZeroInflationTermStructureZeroRate as zeroRate{withZeroInflationTermStructure*`GenZeroInflationTermStructure z',withDay*`Day',`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`Double'#} --- |The swap rate that would make a zero-coupon inflation swap helper reprice exactly on the given--- zero-inflation curve, bootstrapped from it or not.-{#fun qlZeroCouponInflationSwapHelperImpliedQuoteOn as zeroCouponInflationSwapImpliedQuoteOn{withZeroCouponInflationSwapHelper*`ZeroCouponInflationSwapHelper'- ,withGenTermStructure*`ZeroInflationTermStructure',preErrorCheck-`String'errorCheck*-}->`Double'#}+-- |Inflation swap helpers paired with the only curve family each can reprice on.+class HasImpliedQuoteOn helper curve where+ -- |The swap rate that would make the helper reprice exactly on the given curve, bootstrapped+ -- from it or not.+ impliedQuoteOn :: helper -> curve -> IO Double+instance HasImpliedQuoteOn ZeroCouponInflationSwapHelper (GenZeroInflationTermStructure z) where+ impliedQuoteOn = qlZeroCouponInflationSwapHelperImpliedQuoteOn+instance HasImpliedQuoteOn YearOnYearInflationSwapHelper (GenYoYInflationTermStructure yoy) where+ impliedQuoteOn = qlYearOnYearInflationSwapHelperImpliedQuoteOn --- |The swap rate that would make a year-on-year inflation swap helper reprice exactly on the given--- year-on-year curve.-{#fun qlYearOnYearInflationSwapHelperImpliedQuoteOn as yearOnYearInflationSwapImpliedQuoteOn{withYearOnYearInflationSwapHelper*`YearOnYearInflationSwapHelper'- ,withGenTermStructure*`YoYInflationTermStructure',preErrorCheck-`String'errorCheck*-}->`Double'#}+{#fun qlZeroCouponInflationSwapHelperImpliedQuoteOn{withZeroCouponInflationSwapHelper*`ZeroCouponInflationSwapHelper'+ ,withZeroInflationTermStructure*`GenZeroInflationTermStructure z',preErrorCheck-`String'errorCheck*-}->`Double'#} +{#fun qlYearOnYearInflationSwapHelperImpliedQuoteOn{withYearOnYearInflationSwapHelper*`YearOnYearInflationSwapHelper'+ ,withYoYInflationTermStructure*`GenYoYInflationTermStructure yoy',preErrorCheck-`String'errorCheck*-}->`Double'#}+ -- |Year-on-year inflation rate implied by the curve.-{#fun qlYoYInflationTermStructureYoYRate as yoyRate{withGenTermStructure*`YoYInflationTermStructure',withDay*`Day',`Bool' -- ^extrapolate+{#fun qlYoYInflationTermStructureYoYRate as yoyRate{withYoYInflationTermStructure*`GenYoYInflationTermStructure yoy',withDay*`Day',`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- vim: set ff=unix ts=8 sts=2 sw=2 et:
QuantLib/TermStructure/InflationVolatility.chs view
@@ -5,13 +5,15 @@ , YoYCapFloorTermPriceSurface , CPICapFloorTermPriceSurface , CPIVolatilitySurface+ -- ** Pricing model+ , YoyOptionletModel(..)+ -- ** Price-surface dating+ , YoyPriceSurfaceStart(..) -- * Constructors -- ** YoY volatility and price surfaces , constantYoyOptionletVolatility- , kInterpolatedYoyOptionletVolatilitySurfaceBlack- , kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack- , kInterpolatedYoyOptionletVolatilitySurfaceBachelier+ , kInterpolatedYoyOptionletVolatilitySurface , yoyCapFloorTermPriceSurface -- ** CPI surfaces , cpiCapFloorTermPriceSurface@@ -58,7 +60,7 @@ -- 'QuantLib.TermStructure.Volatility.constantOptionletVolatility', taking a t'GenQuote' rather -- than a plain 'Double' per the @std::variant@\/overload-collapse rule (the flat case is already -- reachable via 'QuantLib.Quote.simpleQuote'). Not the only concrete leaf of this type any--- more -- see 'kInterpolatedYoyOptionletVolatilitySurfaceBlack' for the market-quote-bootstrapped+-- more -- see 'kInterpolatedYoyOptionletVolatilitySurface' for the market-quote-bootstrapped -- alternative. {#fun qlConstantYoYOptionletVolatility as constantYoyOptionletVolatility{withQuote*`GenQuote q' ,fromIntegral`Word' -- ^settlementDays@@ -93,10 +95,24 @@ ,`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`Double'#} +-- |How a 'yoyCapFloorTermPriceSurface' is dated.+data YoyPriceSurfaceStart+ = -- |QuantLib's moving reference date and swap helpers, following the evaluation date.+ MovingStart+ | -- |Reference date fixed at the construction evaluation date; the derived ATM curve uses+ -- fixed-start swap helpers with the same native pillars, so a later evaluation date cannot+ -- rebuild a swap after its maturity. Rebuild the surface to value it on another date.+ BookedAtEvaluationDate+ deriving (Eq, Show, Read)+ -- |Prices YoY cap\/floors by cap\/floor-surface intersection and put\/call parity, deriving an -- ATM YoY swap curve as a side effect. 'Interpolation2D' chooses the cap\/floor price-grid -- interpolator, 'Interpolation' the per-maturity one.-yoyCapFloorTermPriceSurface :: Word -- ^fixingDays+--+-- See 'YoyPriceSurfaceStart' for the moving and booked dating choices. The intersection, parity,+-- interpolation and bootstrapping calculations remain QuantLib's.+yoyCapFloorTermPriceSurface :: YoyPriceSurfaceStart -- ^Moving dates, or a grid booked at the evaluation date.+ -> Word -- ^fixingDays -> (Word, TimeUnit) -- ^yyLag -> GenYoYInflationIndex yidx -> CPIInterpolationType -> GenYieldTermStructure y -- ^nominal -> DayCounter -> Calendar -> BusinessDayConvention@@ -107,10 +123,11 @@ -> RealMatrix -- ^fPrice -> Interpolation2D -> Interpolation -> IO YoYCapFloorTermPriceSurface-yoyCapFloorTermPriceSurface fixingDays yyLag yii interp nominal dc cal bdc cStrikes fStrikes cfMaturities (RealMatrix cr cc cd) (RealMatrix fr fc fd) i2d i1d =- uncurryNested (qlYoYCapFloorTermPriceSurface fixingDays yyLag yii interp nominal dc cal bdc cStrikes fStrikes maturityNums maturityUnits cr cc cd fr fc fd (fromEnum i2d)) (qlInterpolation i1d)+yoyCapFloorTermPriceSurface startDate fixingDays yyLag yii interp nominal dc cal bdc cStrikes fStrikes cfMaturities (RealMatrix cr cc cd) (RealMatrix fr fc fd) i2d i1d =+ uncurryNested (qlYoYCapFloorTermPriceSurface (startDate == BookedAtEvaluationDate) fixingDays yyLag yii interp nominal dc cal bdc cStrikes fStrikes maturityNums maturityUnits cr cc cd fr fc fd (fromEnum i2d)) (qlInterpolation i1d) where (maturityNums, maturityUnits) = unzip cfMaturities-{#fun qlYoYCapFloorTermPriceSurface{fromIntegral`Word' -- ^fixingDays+{#fun qlYoYCapFloorTermPriceSurface{`Bool' -- ^Whether the grid is booked at the evaluation date.+ ,fromIntegral`Word' -- ^fixingDays ,fromEnumQuantity`(Word,TimeUnit)'& -- ^yyLag ,withYoYInflationIndex*`GenYoYInflationIndex yidx' ,fromEnumC`CPIInterpolationType'@@ -166,84 +183,43 @@ ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |The union of cap and floor strikes in the surface's price grid -- the strikes a stripped--- 'YoYOptionletVolatilitySurface' (via 'kInterpolatedYoyOptionletVolatilitySurfaceBlack' et al.)+-- 'YoYOptionletVolatilitySurface' (via 'kInterpolatedYoyOptionletVolatilitySurface') -- has a bootstrapped vol curve for. {#fun qlYoYCapFloorTermPriceSurfaceStrikes as yoyCapFloorStrikes{withGenTermStructure*`YoYCapFloorTermPriceSurface' ,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#} --- |Strips a 'YoYOptionletVolatilitySurface' from a 'YoYCapFloorTermPriceSurface' by bootstrapping--- a per-strike vol curve against Black-priced YoY caps\/floors (mirrors upstream's own--- @testYoYPriceSurfaceToVol@: an @InterpolatedYoYOptionletStripper@ solving each strike's initial--- vol, then a @KInterpolatedYoYOptionletVolatilitySurface@ interpolating across strikes, both--- sharing the given 'Interpolation' -- neither is exposed as its own type, since nothing in--- upstream reaches them from outside this one bootstrap; see this function's C shim for the full--- pipeline). /index/\//nominalTermStructure/ price the null-vol engine the stripper solves--- against; /slope/ is the assumed initial caplet-vol slope for strikes past the edge of good--- price data (a negative slope for typically low\/flat short-dated extreme-strike prices, per--- upstream's own comment -- too extreme a slope can leave no arbitrage-free solution).-kInterpolatedYoyOptionletVolatilitySurfaceBlack :: Word -- ^settlementDays- -> Calendar -> BusinessDayConvention -> DayCounter- -> YoYCapFloorTermPriceSurface -- ^capFloorPrices- -> GenYoYInflationIndex yidx -- ^index- -> GenYieldTermStructure y -- ^nominalTermStructure- -> Double -- ^slope- -> Interpolation- -> IO YoYOptionletVolatilitySurface-kInterpolatedYoyOptionletVolatilitySurfaceBlack settlementDays cal bdc dc capFloorPrices index nominalTs slope i1d =- uncurryNested (qlKInterpolatedYoYOptionletVolatilitySurfaceBlack settlementDays cal bdc dc capFloorPrices index nominalTs slope) (qlInterpolation i1d)-{#fun qlKInterpolatedYoYOptionletVolatilitySurfaceBlack{fromIntegral`Word' -- ^settlementDays- ,withCalendar*`Calendar'- ,fromEnumC`BusinessDayConvention'- ,withDayCounter*`DayCounter'- ,withGenTermStructure*`YoYCapFloorTermPriceSurface' -- ^capFloorPrices- ,withYoYInflationIndex*`GenYoYInflationIndex yidx' -- ^index- ,withYieldTermStructure*`GenYieldTermStructure y' -- ^nominalTermStructure- ,`Double' -- ^slope- ,`Int',`Int',`Int' -- ^interpolator, approximator, approximatorArg- ,preErrorCheck-`String'errorCheck*-}->`YoYOptionletVolatilitySurface'peekYoYOptionletVolatilityStructure*#}---- |As 'kInterpolatedYoyOptionletVolatilitySurfaceBlack', but unit-displaced Black.-kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack :: Word -- ^settlementDays- -> Calendar -> BusinessDayConvention -> DayCounter- -> YoYCapFloorTermPriceSurface -- ^capFloorPrices- -> GenYoYInflationIndex yidx -- ^index- -> GenYieldTermStructure y -- ^nominalTermStructure- -> Double -- ^slope- -> Interpolation- -> IO YoYOptionletVolatilitySurface-kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack settlementDays cal bdc dc capFloorPrices index nominalTs slope i1d =- uncurryNested (qlKInterpolatedYoYOptionletVolatilitySurfaceUnitDisplacedBlack settlementDays cal bdc dc capFloorPrices index nominalTs slope) (qlInterpolation i1d)-{#fun qlKInterpolatedYoYOptionletVolatilitySurfaceUnitDisplacedBlack{fromIntegral`Word' -- ^settlementDays- ,withCalendar*`Calendar'- ,fromEnumC`BusinessDayConvention'- ,withDayCounter*`DayCounter'- ,withGenTermStructure*`YoYCapFloorTermPriceSurface' -- ^capFloorPrices- ,withYoYInflationIndex*`GenYoYInflationIndex yidx' -- ^index- ,withYieldTermStructure*`GenYieldTermStructure y' -- ^nominalTermStructure- ,`Double' -- ^slope- ,`Int',`Int',`Int' -- ^interpolator, approximator, approximatorArg- ,preErrorCheck-`String'errorCheck*-}->`YoYOptionletVolatilitySurface'peekYoYOptionletVolatilityStructure*#}+-- |Pricing model for stripping YoY cap/floor price quotes.+{#enum YoyOptionletModel{} deriving(Show, Eq, Read)#} --- |As 'kInterpolatedYoyOptionletVolatilitySurfaceBlack', but Bachelier (normal model).-kInterpolatedYoyOptionletVolatilitySurfaceBachelier :: Word -- ^settlementDays+-- |Strip a native per-strike volatility curve and interpolate across strikes. The optional+-- initial volatility bracket replaces QuantLib's fixed 1e-5 to 0.08 bounds; Nothing uses the+-- unmodified native stripper. An explicit bracket uses its protected native objective, Brent+-- solver (accuracy 1e-7), helpers and piecewise bootstrap, changing only those bounds.+-- Bounds must be finite, positive and strictly ordered. The slope is the native relative+-- initial caplet-volatility slope outside reliable short-end prices. LogCubic is unsupported+-- because the native stripper default-constructs its interpolator. The index and nominal curve+-- price the null-vol engine the stripper solves against.+kInterpolatedYoyOptionletVolatilitySurface+ :: YoyOptionletModel+ -> Word -- ^Business-day settlement lag of the volatility surface. -> Calendar -> BusinessDayConvention -> DayCounter- -> YoYCapFloorTermPriceSurface -- ^capFloorPrices- -> GenYoYInflationIndex yidx -- ^index- -> GenYieldTermStructure y -- ^nominalTermStructure- -> Double -- ^slope+ -> YoYCapFloorTermPriceSurface -- ^Quoted cap/floor term prices to strip.+ -> GenYoYInflationIndex yidx -- ^YoY index used to price the stripping helpers.+ -> GenYieldTermStructure y -- ^Nominal discount curve used to price the stripping helpers.+ -> Double -- ^Initial relative caplet-volatility slope per year.+ -> Maybe (Double, Double) -- ^Optional (lower, upper) initial annual volatility bounds, per square root year: log-rate units for Black, log(1+rate) for unit-displaced Black, absolute decimal-rate units for Bachelier. -> Interpolation -> IO YoYOptionletVolatilitySurface-kInterpolatedYoyOptionletVolatilitySurfaceBachelier settlementDays cal bdc dc capFloorPrices index nominalTs slope i1d =- uncurryNested (qlKInterpolatedYoYOptionletVolatilitySurfaceBachelier settlementDays cal bdc dc capFloorPrices index nominalTs slope) (qlInterpolation i1d)-{#fun qlKInterpolatedYoYOptionletVolatilitySurfaceBachelier{fromIntegral`Word' -- ^settlementDays- ,withCalendar*`Calendar'- ,fromEnumC`BusinessDayConvention'- ,withDayCounter*`DayCounter'- ,withGenTermStructure*`YoYCapFloorTermPriceSurface' -- ^capFloorPrices- ,withYoYInflationIndex*`GenYoYInflationIndex yidx' -- ^index- ,withYieldTermStructure*`GenYieldTermStructure y' -- ^nominalTermStructure- ,`Double' -- ^slope- ,`Int',`Int',`Int' -- ^interpolator, approximator, approximatorArg+kInterpolatedYoyOptionletVolatilitySurface model settlementDays cal bdc dc prices index nominal slope bracket i1d =+ let (useBracket, lower, upper) = case bracket of Nothing -> (False, 1e-5, 0.08); Just (lo, hi) -> (True, lo, hi)+ in uncurryNested (qlKInterpolatedYoYOptionletVolatilitySurface model settlementDays cal bdc dc prices index nominal slope useBracket lower upper) (qlInterpolation i1d)+{#fun qlKInterpolatedYoYOptionletVolatilitySurface{fromEnumC`YoyOptionletModel'+ ,fromIntegral`Word',withCalendar*`Calendar',fromEnumC`BusinessDayConvention',withDayCounter*`DayCounter'+ ,withGenTermStructure*`YoYCapFloorTermPriceSurface'+ ,withYoYInflationIndex*`GenYoYInflationIndex yidx'+ ,withYieldTermStructure*`GenYieldTermStructure y'+ ,`Double',`Bool',`Double',`Double'+ ,`Int',`Int',`Int' ,preErrorCheck-`String'errorCheck*-}->`YoYOptionletVolatilitySurface'peekYoYOptionletVolatilityStructure*#} -- |Prices CPI cap\/floors by interpolation and put\/call parity off a market strike\/maturity
QuantLib/TermStructure/Volatility.chs view
@@ -53,6 +53,7 @@ , SmileInterpolationMethod(..) , BlackVolTimeExtrapolationType(..) , BlackVolatilitySurfaceDeltaOpts(..)+ , PiecewiseVarianceNodes(..) , SabrInterpolatedSmileSectionOpts(..) -- ** Coordinates@@ -63,6 +64,7 @@ , RatePoint(..) , OptionMaturity(..) , SwapMaturity(..)+ , SwapSpan(..) , CallableBondMaturity(..) , CallableBondSmileMaturity(..) , SabrVolatilitySpreadsMaturity(..)@@ -168,7 +170,7 @@ , capFloorTermVolSurfaceOptionTimes -- ** Black and local volatility , blackVol- , blackVolVariance+ , blackVariance , blackForwardVol , blackForwardVariance , localVol@@ -180,7 +182,6 @@ , maxSwapLength , maxSwapTenor , smileSection- , swapLengthBetweenDates , swapLength , callableBondVolatility , callableBondBlackVariance@@ -236,23 +237,23 @@ , abcdEndCriteria , abcdK , abcdKs- , abcdAtmVolCurveOptionTenors+ , abcdOptionTenors , abcdOptionTenorsInInterpolation , abcdOptionDates , abcdOptionTimes , sabrVolSurfaceAtmCurve , sabrVolSurfaceIndex , sabrVolSurfaceOptionDateFromTenor- , sabrVolatilitySpreads+ , sabrVolSurfaceVolatilitySpreads -- ** Swaption matrices and cubes , swaptionVolatilityMatrixLocate , interpolatedSwaptionVolatilityCubeVolSpreads- , sparseSabrParameters- , denseSabrParameters- , marketVolCube- , volCubeAtmCalibrated- , noArbSabrSparseSabrParameters- , noArbSabrDenseSabrParameters+ , sabrSparseParameters+ , sabrDenseParameters+ , sabrMarketVolCube+ , sabrVolCubeAtmCalibrated+ , noArbSabrSparseParameters+ , noArbSabrDenseParameters , noArbSabrMarketVolCube , noArbSabrVolCubeAtmCalibrated , zabrSparseParameters@@ -364,6 +365,12 @@ | SwapTenor (Word, TimeUnit) deriving (Eq, Show) +-- |The underlying swap whose (time) length a swaption volatility structure reports.+data SwapSpan+ = SwapSpanTenor !(Word, TimeUnit)+ | SwapSpanDates !Day !Day -- ^start, end+ deriving (Eq, Show)+ -- |Supported option and bond maturity pairs for callable-bond volatility queries. data CallableBondMaturity = CallableBondTimeLength !Double !Double@@ -377,7 +384,7 @@ | CallableBondSmileTenorTenor !(Word, TimeUnit) !(Word, TimeUnit) deriving (Eq, Show) --- |Option maturities accepted by 'sabrVolatilitySpreads'.+-- |Option maturities accepted by 'sabrVolSurfaceVolatilitySpreads'. data SabrVolatilitySpreadsMaturity = SabrVolatilitySpreadsDate !Day | SabrVolatilitySpreadsTenor !(Word, TimeUnit)@@ -389,6 +396,20 @@ | AtmStrikeTenor !(Word, TimeUnit) deriving (Eq, Show) +-- |The smile sections of a 'piecewiseBlackVarianceSurface', one per expiry date. Dates must be+-- strictly increasing and after the surface's reference date; each date's strikes must be strictly+-- increasing. Volatilities are Black (lognormal) volatilities, not standard deviations.+data PiecewiseVarianceNodes+ = -- |One strike axis shared by every date, as upstream's @makeFromGrid@.+ VarianceGrid+ [Day] -- ^expiry dates, one matrix column each+ [Double] -- ^strikes, one matrix row each+ RealMatrix -- ^Black volatilities, rows indexed by strike and columns by date+ | -- |Each expiry date with its own non-empty (strike, Black volatility) nodes, at least two per+ -- date; the strike sets may differ between dates.+ VarianceSlices (NonEmpty (Day, NonEmpty (Double, Double)))+ deriving (Eq, Show)+ -- SabrInterpolatedSmileSectionOpts bundles every trailing param -- sabrInterpolatedSmileSection_ hardcodes, pre-populated with upstream's own defaults, -- overridden through record-update syntax -- see OISRateHelperOpts (QuantLib.TermStructure.Yield)@@ -563,8 +584,15 @@ -- |Optionlet volatility curve interpolating the supplied caplet-volatility nodes by variance. -- Each node pairs an option date with its volatility, so mismatched date/value inputs are--- unrepresentable.-capletVarianceCurve :: Day -> NonEmpty (Day, Double) -> DayCounter -> VolatilityType -> Double+-- unrepresentable. With @extrapolate@, a read after the last node keeps that node's+-- volatility; without it, QuantLib refuses the read.+capletVarianceCurve+ :: Day -- ^Reference date, from which option times are measured.+ -> NonEmpty (Day, Double) -- ^Option dates and their caplet volatilities.+ -> DayCounter -- ^Day counter of the time axis.+ -> VolatilityType+ -> Double -- ^Displacement of a shifted-lognormal rate, as a fraction.+ -> Bool -- ^Whether reads after the last node are allowed (@extrapolate@). -> IO OptionletVolatilityStructure capletVarianceCurve referenceDate nodes = qlCapletVarianceCurve referenceDate dates vols where (dates, vols) = unzip (toList nodes)@@ -574,6 +602,7 @@ ,withDayCounter*`DayCounter' -- ^dayCounter ,`VolatilityType' -- ^type ,`Double' -- ^displacement+ ,`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`OptionletVolatilityStructure'peekOptionletVolatilityStructure*#} -- |Strips a 'CapFloorTermVolSurface' (quoted cap\/floor term vols) into caplet\/floorlet vols via@@ -688,10 +717,10 @@ ,`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`Double'#} --- |Black variance for the given maturity and strike. Named 'blackVolVariance' to distinguish it+-- |Black variance for the given maturity and strike. Named 'blackVariance' to distinguish it -- from the two-maturity swaption and callable-bond queries.-blackVolVariance :: GenBlackVolTermStructure bv -> TermPoint -> Double -> Bool -> IO Double-blackVolVariance surface point strike = case point of+blackVariance :: GenBlackVolTermStructure bv -> TermPoint -> Double -> Bool -> IO Double+blackVariance surface point strike = case point of DatePoint d -> blackVarianceAtDateRaw surface d strike TimePoint t -> blackVarianceAtTimeRaw surface t strike @@ -1377,14 +1406,18 @@ -- |the reason the calibration's optimizer stopped {#fun qlZabrInterpolatedSmileSectionEndCriteria as zabrInterpolatedEndCriteria{withZabrInterpolatedSmileSection*`ZabrInterpolatedSmileSection',preErrorCheck-`String'errorCheck*-}->`EndCriteriaType'#} --- |implements the conversion between swap dates and swap (time) length-{#fun qlSwaptionVolatilityStructureSwapLength1 as swapLengthBetweenDates{withSwaptionVolatilityStructure*`GenSwaptionVolatilityStructure sv'+-- |The swap (time) length the structure assigns to a swap tenor or to swap dates.+swapLength :: GenSwaptionVolatilityStructure sv -> SwapSpan -> IO Double+swapLength structure swapSpan = case swapSpan of+ SwapSpanTenor t -> swapLengthOfTenorRaw structure t+ SwapSpanDates start end -> swapLengthBetweenDatesRaw structure start end++{#fun qlSwaptionVolatilityStructureSwapLength1 as swapLengthBetweenDatesRaw{withSwaptionVolatilityStructure*`GenSwaptionVolatilityStructure sv' ,withDay*`Day' -- ^start ,withDay*`Day' -- ^end ,preErrorCheck-`String'errorCheck*-}->`Double'#} --- |implements the conversion between swap tenor and swap (time) length-{#fun qlSwaptionVolatilityStructureSwapLength as swapLength{withSwaptionVolatilityStructure*`GenSwaptionVolatilityStructure sv',fromEnumQuantity`(Word,TimeUnit)'&,preErrorCheck-`String'errorCheck*-}->`Double'#}+{#fun qlSwaptionVolatilityStructureSwapLength as swapLengthOfTenorRaw{withSwaptionVolatilityStructure*`GenSwaptionVolatilityStructure sv',fromEnumQuantity`(Word,TimeUnit)'&,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |returns the volatility for a given option date and swap tenor {#fun qlSwaptionVolatilityStructureVolatility1 as volatilityDateTenor{withSwaptionVolatilityStructure*`GenSwaptionVolatilityStructure sv'@@ -1723,13 +1756,13 @@ -- |@k@ adjustment factors for every option tenor used in interpolation {#fun qlAbcdAtmVolCurveK as abcdKs{withAbcdAtmVolCurve*`AbcdAtmVolCurve',preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#} -abcdAtmVolCurveOptionTenors :: AbcdAtmVolCurve -> IO [(Word, TimeUnit)]-abcdAtmVolCurveOptionTenors o = do+abcdOptionTenors :: AbcdAtmVolCurve -> IO [(Word, TimeUnit)]+abcdOptionTenors o = do (ns, us) <- qlAbcdAtmVolCurveOptionTenors o pure $ zip (map fromIntegral ns) (map toEnum us) {#fun qlAbcdAtmVolCurveOptionTenors{withAbcdAtmVolCurve*`AbcdAtmVolCurve',preIntArray-`[Int]'&peekIntArray*,preIntArray-`[Int]'&peekIntArray*,preErrorCheck-`String'errorCheck*-}->`()'#} --- |As 'abcdAtmVolCurveOptionTenors', but only the tenors actually used in the ABCD fit.+-- |As 'abcdOptionTenors', but only the tenors actually used in the ABCD fit. abcdOptionTenorsInInterpolation :: AbcdAtmVolCurve -> IO [(Word, TimeUnit)] abcdOptionTenorsInInterpolation o = do (ns, us) <- qlAbcdAtmVolCurveOptionTenorsInInterpolation o@@ -1770,8 +1803,8 @@ ,preDoubleArray-`[Double]'&peekDoubleArray*,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Volatility-spread row at an option date or tenor.-sabrVolatilitySpreads :: SabrVolSurface -> SabrVolatilitySpreadsMaturity -> IO [Double]-sabrVolatilitySpreads surface maturity = case maturity of+sabrVolSurfaceVolatilitySpreads :: SabrVolSurface -> SabrVolatilitySpreadsMaturity -> IO [Double]+sabrVolSurfaceVolatilitySpreads surface maturity = case maturity of SabrVolatilitySpreadsDate optionDate -> sabrVolSurfaceVolatilitySpreadsAtDateRaw surface optionDate SabrVolatilitySpreadsTenor optionTenor ->@@ -1842,11 +1875,12 @@ -- |A cap/floor term-volatility curve with either a fixed or evaluation-date-relative reference. capFloorTermVolCurve :: CalendarReference -> Calendar -> BusinessDayConvention- -> NonEmpty (Word, TimeUnit, GenQuote q) -> DayCounter -> IO CapFloorTermVolCurve-capFloorTermVolCurve reference c bd ntq = case reference of+ -> NonEmpty ((Word, TimeUnit), GenQuote q) -> DayCounter -> IO CapFloorTermVolCurve+capFloorTermVolCurve reference c bd tenorQuotes = case reference of CalendarReferenceDate d -> qlCapFloorTermVolCurveFixed d c bd n t q CalendarSettlementDays d -> qlCapFloorTermVolCurveMovingRaw d c bd n t q- where (n, t, q) = unzip3 (toList ntq)+ where (tenors, q) = unzip (toList tenorQuotes)+ (n, t) = unzip tenors {#fun qlCapFloorTermVolCurve1 as qlCapFloorTermVolCurveFixed{withDay*`Day',withCalendar*`Calendar',fromEnumC`BusinessDayConvention',withIntArray*`[Word]'&,withEnumArray*`[TimeUnit]'&,withQuoteArray*`[GenQuote q]'&,withDayCounter*`DayCounter',preErrorCheck-`String'errorCheck*-}->`CapFloorTermVolCurve'peekCapFloorTermVolCurve*#} {#fun qlCapFloorTermVolCurve as qlCapFloorTermVolCurveMovingRaw{fromIntegral`Word',withCalendar*`Calendar',fromEnumC`BusinessDayConvention',withIntArray*`[Word]'&,withEnumArray*`[TimeUnit]'&,withQuoteArray*`[GenQuote q]'&,withDayCounter*`DayCounter',preErrorCheck-`String'errorCheck*-}->`CapFloorTermVolCurve'peekCapFloorTermVolCurve*#} @@ -1892,17 +1926,39 @@ extendedBlackVarianceSurface d c ds s (Matrix mr mc md) = qlExtendedBlackVarianceSurface d c ds s mr mc md {#fun qlExtendedBlackVarianceSurface{withDay*`Day',withCalendar*`Calendar',withDayArray*`[Day]'&,withDoubleArray*`[Double]'&,fromIntegral`Word',fromIntegral`Word',withQuoteArrayRaw*`[GenQuote q]',withDayCounter*`DayCounter',`ExtendedBlackVarianceSurfaceExtrapolation',`ExtendedBlackVarianceSurfaceExtrapolation',preErrorCheck-`String'errorCheck*-}->`BlackVolTermStructure'peekBlackVolTermStructure*#} --- |Builds a Black volatility surface from a rectangular vol grid via--- 'PiecewiseBlackVarianceSurface::makeFromGrid': one interpolated smile section per date--- column, linear in total variance between columns -- a fixed interpolation scheme, unlike--- 'blackVarianceSurface''s configurable 2-D interpolator.-piecewiseBlackVarianceSurface :: Day -> [Day] -- ^dates- -> [Double] -- ^strikes- -> RealMatrix -- ^blackVols- -> DayCounter+-- |A Black volatility surface built from one smile section per expiry date+-- (@PiecewiseBlackVarianceSurface@). Each section interpolates volatility linearly in strike,+-- holding standard deviations @vol * sqrt t@ where @t@ is the day counter's year fraction from the+-- reference date to that expiry; the surface itself measures time with the same day counter and+-- reference date, so a section's variance and the surface's time weights agree. Between two+-- expiries the surface interpolates total variance linearly in time at the same absolute strike;+-- before the first expiry and after the last it keeps that section's volatility flat.+--+-- Strike domain. The surface reports an unbounded strike range, so a query's own extrapolation+-- flag (as in 'blackVol') never admits or rejects a strike; it only admits dates after the last+-- expiry. The only strike check is on each section and follows the surface's @extrapolate@ flag:+--+-- * Without extrapolation, any section read outside its own strikes throws. At an interior expiry+-- upstream also reads the /next/ section, weighted by zero, so a strike quoted only at that+-- expiry throws if it lies outside the next section's strikes.+-- * With extrapolation, every section extrapolates linearly in strike, floored at zero+-- volatility, and nothing throws. A caller that must refuse strikes outside the quoted domain+-- (the intersection of the two enclosing sections' strikes between expiries; the section's own+-- strikes at an expiry or beyond the end expiries) has to check them itself.+piecewiseBlackVarianceSurface :: Day -- ^referenceDate: time origin of the surface and of every section+ -> PiecewiseVarianceNodes -- ^nodes: expiry dates with their (strike, Black volatility) nodes+ -> DayCounter -- ^dayCounter: year fractions from referenceDate for both the sections' standard deviations and the surface's time weights+ -> Bool -- ^extrapolate: enable extrapolation on the surface object -> IO BlackVolTermStructure-piecewiseBlackVarianceSurface d ds s (RealMatrix mr mc md) dc = qlPiecewiseBlackVarianceSurface d ds s mr mc md dc-{#fun qlPiecewiseBlackVarianceSurface{withDay*`Day',withDayArray*`[Day]'&,withDoubleArray*`[Double]'&,fromIntegral`Word',fromIntegral`Word',withRealVectorRaw*`RealVector',withDayCounter*`DayCounter',preErrorCheck-`String'errorCheck*-}->`BlackVolTermStructure'peekBlackVolTermStructure*#}+piecewiseBlackVarianceSurface d nodes dc extrapolate = case nodes of+ VarianceGrid ds s (RealMatrix mr mc md) -> qlPiecewiseBlackVarianceSurface d ds s mr mc md dc extrapolate+ VarianceSlices slices ->+ let (dates, rows) = unzip (toList slices)+ rowLists = map toList rows+ (strikes, vols) = unzip (concat rowLists)+ in qlPiecewiseBlackVarianceSurfaceSlices d dates (map length rowLists) strikes vols dc extrapolate+{#fun qlPiecewiseBlackVarianceSurface{withDay*`Day',withDayArray*`[Day]'&,withDoubleArray*`[Double]'&,fromIntegral`Word',fromIntegral`Word',withRealVectorRaw*`RealVector',withDayCounter*`DayCounter',`Bool',preErrorCheck-`String'errorCheck*-}->`BlackVolTermStructure'peekBlackVolTermStructure*#}+{#fun qlPiecewiseBlackVarianceSurfaceSlices{withDay*`Day',withDayArray*`[Day]'&,withIntArray*`[Int]'&,withDoubleArrayRaw*`[Double]',withDoubleArrayRaw*`[Double]',withDayCounter*`DayCounter',`Bool',preErrorCheck-`String'errorCheck*-}->`BlackVolTermStructure'peekBlackVolTermStructure*#} -- |A Black volatility surface parameterized by market deltas (put\/call deltas and, optionally, -- an ATM quote) rather than fixed strikes -- the standard FX vol quoting convention. Constructed@@ -2038,7 +2094,7 @@ -- tenor) node from an ATM surface plus a grid of vol spreads. The result /is/ a -- 'SwaptionVolatilityStructure' -- pass it anywhere one is expected (pricing engines, -- 'smileSection'\/'volatility'\/etc.) -- but its own extra getters--- ('sparseSabrParameters', 'denseSabrParameters', 'marketVolCube', 'volCubeAtmCalibrated',+-- ('sabrSparseParameters', 'sabrDenseParameters', 'sabrMarketVolCube', 'sabrVolCubeAtmCalibrated', -- ('atmStrike') -- only accept this concrete type, not the generic one. --@@ -2075,7 +2131,7 @@ -> Bool -- ^isRhoFixed -> Bool -- ^isAtmCalibrated: if 'True', @atmVolStructure@ must be a discrete grid structure -- (e.g. 'swaptionVolatilityMatrix' or another cube) -- upstream's ATM-recalibration path- -- ('denseSabrParameters'\/one branch of 'volCubeAtmCalibrated') downcasts it to+ -- ('sabrDenseParameters'\/one branch of 'sabrVolCubeAtmCalibrated') downcasts it to -- @SwaptionVolatilityDiscrete@ and dereferences the result unchecked, which crashes given a -- flat 'constantSwaptionVolatility'. -> Maybe Double -- ^maxErrorTolerance@@ -2115,7 +2171,7 @@ -- over -- fits an arbitrage-free SABR smile (via 'NoArbSabrModel') at every node instead of the -- Hagan-formula SABR smile. Same argument shapes, flattening conventions, lazy calibration, and -- 'EndCriteria'\/'OptimizationMethod' safety as 'sabrSwaptionVolatilityCube'; its own extra--- getters ('noArbSabrSparseSabrParameters', 'noArbSabrDenseSabrParameters',+-- getters ('noArbSabrSparseParameters', 'noArbSabrDenseParameters', -- 'noArbSabrMarketVolCube', 'noArbSabrVolCubeAtmCalibrated', -- 'atmStrike') only accept this concrete type. noArbSabrSwaptionVolatilityCube :: GenSwaptionVolatilityStructure sv -- ^atmVolStructure@@ -2252,32 +2308,32 @@ toRealMatrix (r, c, d) = RealMatrix r c d -- |Per-node calibrated SABR parameters (alpha, beta, nu, rho columns) before ATM recalibration.-sparseSabrParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix-sparseSabrParameters sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeSparseSabrParameters sv+sabrSparseParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix+sabrSparseParameters sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeSparseSabrParameters sv {#fun qlSabrSwaptionVolatilityCubeSparseSabrParameters{withSabrSwaptionVolatilityCube*`SabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Per-node calibrated SABR parameters, meaningfully populated only when the cube was built with -- @isAtmCalibrated = True@ (see 'sabrSwaptionVolatilityCube').-denseSabrParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix-denseSabrParameters sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeDenseSabrParameters sv+sabrDenseParameters :: SabrSwaptionVolatilityCube -> IO RealMatrix+sabrDenseParameters sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeDenseSabrParameters sv {#fun qlSabrSwaptionVolatilityCubeDenseSabrParameters{withSabrSwaptionVolatilityCube*`SabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#} -- |The raw market vol grid the cube's SABR fit targets: ATM vol (interpolated from -- @atmVolStructure@ at each node) plus @volSpreads@.-marketVolCube :: SabrSwaptionVolatilityCube -> IO RealMatrix-marketVolCube sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeMarketVolCube sv+sabrMarketVolCube :: SabrSwaptionVolatilityCube -> IO RealMatrix+sabrMarketVolCube sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeMarketVolCube sv {#fun qlSabrSwaptionVolatilityCubeMarketVolCube{withSabrSwaptionVolatilityCube*`SabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#} --- |Like 'marketVolCube', adjusted so the cube's own ATM row is consistent with @atmVolStructure@;+-- |Like 'sabrMarketVolCube', adjusted so the cube's own ATM row is consistent with @atmVolStructure@; -- meaningfully populated only when the cube was built with @isAtmCalibrated = True@.-volCubeAtmCalibrated :: SabrSwaptionVolatilityCube -> IO RealMatrix-volCubeAtmCalibrated sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeVolCubeAtmCalibrated sv+sabrVolCubeAtmCalibrated :: SabrSwaptionVolatilityCube -> IO RealMatrix+sabrVolCubeAtmCalibrated sv = toRealMatrix <$> qlSabrSwaptionVolatilityCubeVolCubeAtmCalibrated sv {#fun qlSabrSwaptionVolatilityCubeVolCubeAtmCalibrated{withSabrSwaptionVolatilityCube*`SabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#}@@ -2317,22 +2373,22 @@ ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Per-node calibrated no-arb SABR parameters (alpha, beta, nu, rho columns) before ATM--- recalibration, see 'sparseSabrParameters'.-noArbSabrSparseSabrParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix-noArbSabrSparseSabrParameters sv = toRealMatrix <$> qlNoArbSabrSwaptionVolatilityCubeSparseSabrParameters sv+-- recalibration, see 'sabrSparseParameters'.+noArbSabrSparseParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix+noArbSabrSparseParameters sv = toRealMatrix <$> qlNoArbSabrSwaptionVolatilityCubeSparseSabrParameters sv {#fun qlNoArbSabrSwaptionVolatilityCubeSparseSabrParameters{withNoArbSabrSwaptionVolatilityCube*`NoArbSabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Per-node calibrated no-arb SABR parameters, meaningfully populated only when the cube was--- built with @isAtmCalibrated = True@, see 'denseSabrParameters'.-noArbSabrDenseSabrParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix-noArbSabrDenseSabrParameters sv = toRealMatrix <$> qlNoArbSabrSwaptionVolatilityCubeDenseSabrParameters sv+-- built with @isAtmCalibrated = True@, see 'sabrDenseParameters'.+noArbSabrDenseParameters :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix+noArbSabrDenseParameters sv = toRealMatrix <$> qlNoArbSabrSwaptionVolatilityCubeDenseSabrParameters sv {#fun qlNoArbSabrSwaptionVolatilityCubeDenseSabrParameters{withNoArbSabrSwaptionVolatilityCube*`NoArbSabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#} --- |The raw market vol grid the cube's no-arb SABR fit targets, see 'marketVolCube'.+-- |The raw market vol grid the cube's no-arb SABR fit targets, see 'sabrMarketVolCube'. noArbSabrMarketVolCube :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix noArbSabrMarketVolCube sv = toRealMatrix <$> qlNoArbSabrSwaptionVolatilityCubeMarketVolCube sv {#fun qlNoArbSabrSwaptionVolatilityCubeMarketVolCube{withNoArbSabrSwaptionVolatilityCube*`NoArbSabrSwaptionVolatilityCube'@@ -2341,7 +2397,7 @@ -- |Like 'noArbSabrMarketVolCube', adjusted so the cube's own ATM row is consistent with -- @atmVolStructure@; meaningfully populated only when the cube was built with--- @isAtmCalibrated = True@, see 'volCubeAtmCalibrated'.+-- @isAtmCalibrated = True@, see 'sabrVolCubeAtmCalibrated'. noArbSabrVolCubeAtmCalibrated :: NoArbSabrSwaptionVolatilityCube -> IO RealMatrix noArbSabrVolCubeAtmCalibrated sv = toRealMatrix <$> qlNoArbSabrSwaptionVolatilityCubeVolCubeAtmCalibrated sv {#fun qlNoArbSabrSwaptionVolatilityCubeVolCubeAtmCalibrated{withNoArbSabrSwaptionVolatilityCube*`NoArbSabrSwaptionVolatilityCube'@@ -2359,7 +2415,7 @@ ,preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Per-node calibrated ZABR parameters (alpha, beta, nu, rho, gamma columns) before ATM--- recalibration, see 'sparseSabrParameters'.+-- recalibration, see 'sabrSparseParameters'. zabrSparseParameters :: ZabrSwaptionVolatilityCube -> IO RealMatrix zabrSparseParameters sv = toRealMatrix <$> qlZabrSwaptionVolatilityCubeSparseSabrParameters sv {#fun qlZabrSwaptionVolatilityCubeSparseSabrParameters{withZabrSwaptionVolatilityCube*`ZabrSwaptionVolatilityCube'@@ -2367,14 +2423,14 @@ ,preErrorCheck-`String'errorCheck*-}->`()'#} -- |Per-node calibrated ZABR parameters, meaningfully populated only when the cube was built with--- @isAtmCalibrated = True@, see 'denseSabrParameters'.+-- @isAtmCalibrated = True@, see 'sabrDenseParameters'. zabrDenseParameters :: ZabrSwaptionVolatilityCube -> IO RealMatrix zabrDenseParameters sv = toRealMatrix <$> qlZabrSwaptionVolatilityCubeDenseSabrParameters sv {#fun qlZabrSwaptionVolatilityCubeDenseSabrParameters{withZabrSwaptionVolatilityCube*`ZabrSwaptionVolatilityCube' ,prePtr-`Word'peekWord*,prePtr-`Word'peekWord*,preDoubleArray-`RealVector'&peekRealVector* ,preErrorCheck-`String'errorCheck*-}->`()'#} --- |The raw market vol grid the cube's ZABR fit targets, see 'marketVolCube'.+-- |The raw market vol grid the cube's ZABR fit targets, see 'sabrMarketVolCube'. zabrMarketVolCube :: ZabrSwaptionVolatilityCube -> IO RealMatrix zabrMarketVolCube sv = toRealMatrix <$> qlZabrSwaptionVolatilityCubeMarketVolCube sv {#fun qlZabrSwaptionVolatilityCubeMarketVolCube{withZabrSwaptionVolatilityCube*`ZabrSwaptionVolatilityCube'
QuantLib/TermStructure/Yield.chs view
@@ -1,10 +1,11 @@-{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TemplateHaskell, FlexibleInstances #-} module QuantLib.TermStructure.Yield ( -- * Types -- ** Curves and helpers GenYieldTermStructure , YieldTermStructure+ , PiecewiseYieldCurve , RelinkableYieldTermStructure , FittedBondDiscountCurve , MultiCurve@@ -20,6 +21,7 @@ , Reference(..) , TermPoint(..) , RatePoint(..)+ , RateInterval(..) -- ** Bootstrap and contract configuration , FittingMethod(..)@@ -103,15 +105,15 @@ -- * Inspectors , HasHelperUnderlying(..)+ , HasNodes(..) , rateHelperFixingDependencies , forwardRate- , forwardRateBetweenTimes , zeroRate , discount+ , rateHelperPillarDate , impliedQuote , impliedQuoteOn- , futuresRateHelperConvexityAdjustment- , overnightIndexFutureRateHelperConvexityAdjustment+ , HasConvexityAdjustment(..) , minimumCostValue , numberOfIterations , fittingMethodSize@@ -126,7 +128,7 @@ import Language.Haskell.TH.Lib(varT) import QuantLib.Math(EndCriteriaType(..)) import QuantLib.Quote hiding(linkTo)-import QuantLib.TermStructure (Reference(..), TermPoint(..), RatePoint(..), setExtrapolation, HasHelperUnderlying(..))+import QuantLib.TermStructure (Reference(..), TermPoint(..), RatePoint(..), RateInterval(..), setExtrapolation, HasHelperUnderlying(..), HasNodes(..)) import Data.Maybe(fromMaybe) import Data.List.NonEmpty(NonEmpty, toList) import Foreign.Ptr(Ptr, nullPtr, castPtr)@@ -158,6 +160,7 @@ {#pointer *QlBMAIndex as BMAIndex foreign -> CBMAIndex' nocode#} {#pointer *QlBond as Bond foreign -> CBond' nocode#} {#pointer *QlOvernightIndex as OvernightIborIndex foreign -> COvernightIndex' nocode#}+{#pointer *QlPiecewiseYieldCurve as PiecewiseYieldCurve foreign -> CPiecewiseYieldCurve' nocode#} {#pointer *QlYieldTermStructure as YieldTermStructure foreign -> CYieldTermStructure' nocode#} {#pointer *QlFittedBondDiscountCurve as FittedBondDiscountCurve foreign -> CFittedBondDiscountCurve' nocode#} {#pointer *QlRelinkableYieldTermStructure as RelinkableYieldTermStructure foreign -> CRelinkableYieldTermStructure' nocode#}@@ -372,14 +375,19 @@ ,`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`InterestRate'peekInterestRate*#} --- |The forward rate between two dates, in the given day-counting rule.--- /Warning/ Dates are not adjusted for holidays.-{#fun qlYieldTermStructureForwardRate as forwardRate{withYieldTermStructure*`GenYieldTermStructure y',withDay*`Day',withDay*`Day',withDayCounter*`DayCounter',`Compounding',`Frequency'+-- |The forward rate over a date or year-fraction interval. Dates are not adjusted for+-- holidays; a time interval's rate carries the curve's own day-counting rule.+forwardRate :: GenYieldTermStructure y -> RateInterval -> Compounding -> Frequency -> Bool+ -> IO InterestRate+forwardRate curve interval = case interval of+ RateBetweenDates d1 d2 dc -> forwardRateBetweenDatesRaw curve d1 d2 dc+ RateBetweenTimes t1 t2 -> forwardRateBetweenTimesRaw curve t1 t2++{#fun qlYieldTermStructureForwardRate as forwardRateBetweenDatesRaw{withYieldTermStructure*`GenYieldTermStructure y',withDay*`Day',withDay*`Day',withDayCounter*`DayCounter',`Compounding',`Frequency' ,`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`InterestRate'peekInterestRate*#} --- |The resulting interest rate has the same day-counting rule used by the term structure. The same rule should be used for calculating the passed times t1 and t2.-{#fun qlYieldTermStructureForwardRate2 as forwardRateBetweenTimes{withYieldTermStructure*`GenYieldTermStructure y',`Double',`Double',`Compounding',`Frequency'+{#fun qlYieldTermStructureForwardRate2 as forwardRateBetweenTimesRaw{withYieldTermStructure*`GenYieldTermStructure y',`Double',`Double',`Compounding',`Frequency' ,`Bool' -- ^extrapolate ,preErrorCheck-`String'errorCheck*-}->`InterestRate'peekInterestRate*#} @@ -901,9 +909,17 @@ ,`FuturesType' -- ^type ,preErrorCheck-`String'errorCheck*-}->`FuturesRateHelper'peekFuturesRateHelper*#} --- |The futures-vs-forward convexity adjustment this helper was built with (0 if none was given).-{#fun qlFuturesRateHelperConvexityAdjustment as futuresRateHelperConvexityAdjustment{withGenRateHelper*`FuturesRateHelper',preErrorCheck-`String'errorCheck*-}->`Double'#}+-- |Futures rate helpers built with an optional futures-vs-forward convexity adjustment.+class HasConvexityAdjustment h where+ -- |The convexity adjustment this helper was built with (0 if none was given).+ convexityAdjustment :: h -> IO Double+instance HasConvexityAdjustment FuturesRateHelper where+ convexityAdjustment = qlFuturesRateHelperConvexityAdjustment+instance HasConvexityAdjustment OvernightIndexFutureRateHelper where+ convexityAdjustment = qlOvernightIndexFutureRateHelperConvexityAdjustment +{#fun qlFuturesRateHelperConvexityAdjustment{withGenRateHelper*`FuturesRateHelper',preErrorCheck-`String'errorCheck*-}->`Double'#}+ -- |Rate helper for bootstrapping over overnight-index compounding futures. {#fun qlOvernightIndexFutureRateHelper as overnightIndexFutureRateHelper{withQuote*`GenQuote q1',withDay*`Day' -- ^valueDate ,withDay*`Day' -- ^maturityDate@@ -914,8 +930,7 @@ ,withMaybeDay*`Maybe Day' -- ^customPillarDate ,preErrorCheck-`String'errorCheck*-}->`OvernightIndexFutureRateHelper'peekOvernightIndexFutureRateHelper*#} --- |The futures-vs-forward convexity adjustment this helper was built with (0 if none was given).-{#fun qlOvernightIndexFutureRateHelperConvexityAdjustment as overnightIndexFutureRateHelperConvexityAdjustment{withGenRateHelper*`OvernightIndexFutureRateHelper',preErrorCheck-`String'errorCheck*-}->`Double'#}+{#fun qlOvernightIndexFutureRateHelperConvexityAdjustment{withGenRateHelper*`OvernightIndexFutureRateHelper',preErrorCheck-`String'errorCheck*-}->`Double'#} -- |Every fixing this rate helper reads from the store, as @(index name, fixing date)@ pairs. A -- bootstrapped curve cannot be asked what it was built from -- @PiecewiseYieldCurve@ is a@@ -958,6 +973,12 @@ ,withMaybeDay*`Maybe Day' -- ^customPillarDate ,preErrorCheck-`String'errorCheck*-}->`RateHelper'peekRateHelper*#} +-- |The date of this helper's bootstrap pillar, computed from its instrument's conventions.+-- This can differ from contractual maturity. Relative-date helpers update it when the+-- evaluation date changes; no curve needs to be attached to inspect the date.+{#fun qlRateHelperPillarDate as rateHelperPillarDate{withRateHelper*`GenRateHelper rh' -- ^helper+ ,preErrorCheck-`String'errorCheck*-}->`Day'toDay#}+ -- |The quote value implied by the current bootstrapped state of the curve the helper was -- last used against, i.e. what the helper's own market quote would need to be to make it -- reprice exactly.@@ -1028,40 +1049,40 @@ -- pillar\"), not to a number. 'ibDontThrow' is the one to reach for when a curve fails to -- bootstrap: it substitutes the best value found so far for a pillar that won't solve, -- rather than throwing.-{#fun qlPiecewiseYieldCurveFull{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+{#fun qlPiecewiseYieldCurveFull{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} -{#fun qlPiecewiseYieldCurveFull1{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',`Bool',preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+{#fun qlPiecewiseYieldCurveFull1{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',`Bool',preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} -- Raw moving-curve bindings used by 'piecewiseYieldCurve'. {#fun qlPiecewiseYieldCurveGlobalBootstrap1{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrap2{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrap3{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh1]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,withRateHelperArray*`[GenRateHelper rh2]'&,withDayArray*`[Day]'&,`Double',`Bool',withDoubleArray*`[Double]'&,withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrap4{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrap5{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} -{#fun qlPiecewiseYieldCurveLocalBootstrap1{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',fromIntegral`Word',`Bool',`Double',`Double',`Double',`Bool',`Bool',preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+{#fun qlPiecewiseYieldCurveLocalBootstrap1{fromIntegral`Word',withCalendar*`Calendar',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',fromIntegral`Word',`Bool',`Double',`Double',`Double',`Bool',`Bool',preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} -- Raw fixed-curve bindings for the non-iterative bootstrap choices. {#fun qlPiecewiseYieldCurveGlobalBootstrapFixed1{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrapFixed2{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrapFixed3{withDay*`Day',withRateHelperArray*`[GenRateHelper rh1]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,withRateHelperArray*`[GenRateHelper rh2]'&,withDayArray*`[Day]'&,`Double',`Bool',withDoubleArray*`[Double]'&,withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrapFixed4{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseYieldCurveGlobalBootstrapFixed5{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}-{#fun qlPiecewiseYieldCurveLocalBootstrapFixed{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',fromIntegral`Word',`Bool',`Double',`Double',`Double',`Bool',`Bool',preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#}+{#fun qlPiecewiseYieldCurveLocalBootstrapFixed{withDay*`Day',withRateHelperArray*`[GenRateHelper rh]'&,withDayCounter*`DayCounter',withQuoteArray*`[GenQuote q]'&,withDayArray*`[Day]'&,`BootstrapTrait',fromIntegral`Word',`Bool',`Double',`Double',`Double',`Bool',`Bool',preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} -- |Selects the bootstrapper used by 'piecewiseYieldCurve' and carries exactly the -- parameters valid for that choice. 'Iterative' uses the selected trait, interpolation, and@@ -1106,7 +1127,7 @@ -> [(Day, GenQuote q)] -- ^jumps -> Bootstrap rh2 -- ^bootstrapper choice -> Bool -- ^extrapolate past the curve's max date- -> IO YieldTermStructure+ -> IO PiecewiseYieldCurve piecewiseYieldCurve reference r dc qd bootstrap ex = case (reference, bootstrap) of (ReferenceDate d, Iterative t i b) -> enable ex $ uncurryNested (qlPiecewiseYieldCurveFull d rs dc qs ds t) (qlInterpolation i) (nullableDouble (ibAccuracy b)) (nullableDouble (ibMinValue b)) (nullableDouble (ibMaxValue b))@@ -1136,22 +1157,24 @@ -- |Bootstraps multiplicative discount-factor spreads over 'baseCurve' so that each instrument -- reprices on the combined curve. Reference date, calendar and day counter come from the linked--- base curve; past the last node the forward spread stays flat.+-- base curve; past the last node the forward spread stays flat. 'bootstrappedNodes'+-- reads the calibrated spread geometry for both bootstrap choices. Upcast explicitly with+-- 'asYieldTermStructure' when a concrete parent type is required. piecewiseSpreadYieldCurve :: GenYieldTermStructure y -- ^baseCurve -> NonEmpty (GenRateHelper rh) -- ^instruments -> SpreadBootstrap -- ^bootstrapper choice -> Bool -- ^extrapolate past the curve's max date- -> IO YieldTermStructure+ -> IO PiecewiseYieldCurve piecewiseSpreadYieldCurve base r bootstrap ex = case bootstrap of SpreadIterative i b -> uncurryNested (qlPiecewiseSpreadYieldCurve base rs) (qlInterpolation i) (nullableDouble (ibAccuracy b)) (nullableDouble (ibMinValue b)) (nullableDouble (ibMaxValue b)) (ibMaxAttempts b) (ibMaxFactor b) (ibMinFactor b) (ibDontThrow b) (ibDontThrowSteps b) (ibMaxEvaluations b) ex SpreadGlobalLogLinear acc w guess -> qlPiecewiseSpreadYieldCurveGlobalBootstrap base rs acc w ex guess where rs = toList r-{#fun qlPiecewiseSpreadYieldCurve{withYieldTermStructure*`GenYieldTermStructure y',withRateHelperArray*`[GenRateHelper rh]'&,`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',`Bool',preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+{#fun qlPiecewiseSpreadYieldCurve{withYieldTermStructure*`GenYieldTermStructure y',withRateHelperArray*`[GenRateHelper rh]'&,`Int',`Int',`Int',`Double',`Double',`Double',fromIntegral`Word',`Double',`Double',`Bool',fromIntegral`Word',fromIntegral`Word',`Bool',preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} {#fun qlPiecewiseSpreadYieldCurveGlobalBootstrap{withYieldTermStructure*`GenYieldTermStructure y',withRateHelperArray*`[GenRateHelper rh]'&,`Double',withDoubleArray*`[Double]'&,`Bool',withMaybeBootstrapInitialGuess*`Maybe BootstrapInitialGuess'- ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#}+ ,preErrorCheck-`String'errorCheck*-}->`PiecewiseYieldCurve'peekPiecewiseYieldCurve*#} -- |Yield curve interpolating discount factors directly between the given dates. interpolatedDiscountCurve :: NonEmpty (Day, Double) -- ^dates, dfs@@ -1296,11 +1319,11 @@ {#fun qlMultiCurve as multiCurve{`Double' -- ^accuracy ,preErrorCheck-`String'errorCheck*-}->`MultiCurve'peekMultiCurve*#} --- |Add a curve built with a bootstrapper (e.g. 'piecewiseYieldCurve') to the--- cycle. See 'multiCurve' for the protocol.+-- |Add a curve built by 'piecewiseYieldCurve' to the cycle; QuantLib accepts only its global+-- bootstrappers here. See 'multiCurve' for the protocol. {#fun qlMultiCurveAddBootstrappedCurve as addBootstrappedCurve{withMultiCurve*`MultiCurve' ,withRelinkableYieldTermStructure*`RelinkableYieldTermStructure' -- ^internalHandle- ,withYieldTermStructure*`GenYieldTermStructure y' -- ^curve+ ,withPiecewiseYieldCurve*`PiecewiseYieldCurve' -- ^curve ,preErrorCheck-`String'errorCheck*-}->`YieldTermStructure'peekYieldTermStructure*#} -- |Add a curve that isn't built with a bootstrapper (e.g. a spreaded curve) to the cycle. See
README.md view
@@ -26,7 +26,7 @@ Add a `HACKAGE_TOKEN` repository secret containing an API token from a Hackage account with permission to upload `hasquant`. The Release workflow uses the existing-Linux CI image (GHC 9.10.3 / QuantLib 1.43) to build source and Haddock tarballs.+Linux CI image (GHC 9.10.3 / QuantLib 1.44) to build source and Haddock tarballs. 1. Push a version tag matching `hasquant.cabal` (`v.0.8.0.0`, `v0.8.0.0`, or `0.8.0.0`), then dispatch **Release** from the default branch with that `tag`@@ -102,8 +102,10 @@ - Build a declarative embedded DSL as a sibling project to define contracts, portfolios, market data, and calculation scenarios (unpublished WIP), use it for XVA and other complext calculations - Expose that DSL through an agent-callable tool, so an LLM can construct and price products through validated hasquant operations rather than generated pricing logic. - Keep the exact-mean H1-HW backport (`cbits/qlExactMeanH1HwEngine.h`) until both supported QuantLib release series provide `AnalyticH1HWEngine::VarianceRootMean::Exact`; `ExactMean` already selects the native engine when the linked headers expose it.+- Drop the two restated upstream YoY routines in `cbits/qlTermStructureAux.cpp` (`BracketedYoyOptionletStripper::initialize`, `FixedStartYoyPriceSurface`) once QuantLib exposes the stripper's root bracket and a fixed-start price surface; `tools/check-yoy-upstream-copies.py` guards them until then - On adopting QuantLib 1.45 (dropping 1.43): - remove the `ItalyExchange` calendar, deprecated in 1.44 (replacement: `TARGET`);+ - delete the two 1.43-only `dynamic_cast` guards: `qlOvernightUnderlyingSupported` (`cbits/qlInstrument.cpp`) and `CheckedFdEngine` (`cbits/qlCheckedFdEngine.h`); - drop the boost branches of `cbits/qlStdCompat.h` and spell `std::optional`/`std::any` directly; its versioned-argument macro then becomes unconditional or moves to the 1.45 pair. - See [github issues](https://github.com/khorser/hasquant/issues) for more formalized tasks@@ -135,15 +137,15 @@ GHC 9.10 is the primary development version. GHC 8.10.6 (`base >= 4.14`) is the supported floor and is checked against Stackage lts-18.8. GitHub CI also tests with GHC 9.6.7, 9.8.4, 9.12.4, 9.14.1. -Install QuantLib 1.43 or 1.44: [Linux](https://www.quantlib.org/install/linux.shtml), [macOS](https://www.quantlib.org/install/macosx.shtml), or [CMake](https://www.quantlib.org/install/cmake.shtml).+QuantLib 1.44 is the default; 1.43 remains supported. Install either version: [Linux](https://www.quantlib.org/install/linux.shtml), [macOS](https://www.quantlib.org/install/macosx.shtml), or [CMake](https://www.quantlib.org/install/cmake.shtml). Linux and macOS are the primary, well-tested platforms. Windows builds work too, but QuantLib has to be rebuilt with GHC's own bundled Clang first — see [`WINDOWS.md`](WINDOWS.md) for the recipe. hasquant never uses intraday dates, so prefer a QuantLib built without `QL_HIGH_RESOLUTION_DATE` (check `ql/config.hpp`). With it, every `Date` operation goes through boost `posix_time`. In a GSR-calibration-heavy workload that was 59% of CPU, and turning it off cut run times from 309 s to 156 s and from 76 s to 28 s, with bit-identical results. Homebrew's formula turns it on (`--enable-intraday`); CMake leaves it off by default: ```-cmake -S QuantLib-1.43 -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$HOME/opt/quantlib-1.43 \- -DCMAKE_INSTALL_NAME_DIR=$HOME/opt/quantlib-1.43/lib -DQL_BUILD_EXAMPLES=OFF -DQL_BUILD_TEST_SUITE=OFF+cmake -S QuantLib-1.44 -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$HOME/opt/quantlib-1.44 \+ -DCMAKE_INSTALL_NAME_DIR=$HOME/opt/quantlib-1.44/lib -DQL_BUILD_EXAMPLES=OFF -DQL_BUILD_TEST_SUITE=OFF cmake --build build -j && cmake --install build brew unlink quantlib ```
+ cbits/qlConditionalSurvivalCurve.h view
@@ -0,0 +1,69 @@+#ifndef HASQUANT_CONDITIONAL_SURVIVAL_CURVE_H+#define HASQUANT_CONDITIONAL_SURVIVAL_CURVE_H++#include <ql/termstructures/defaulttermstructure.hpp>+#include <cmath>+#include <utility>++namespace hasquant {++// Keep the original curve and its native numerics, conditioning on a fixed later reference.+class ConditionalSurvivalCurve final : public QuantLib::DefaultProbabilityTermStructure {+ public:+ ConditionalSurvivalCurve(QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure> base,+ QuantLib::Date reference)+ : QuantLib::DefaultProbabilityTermStructure(reference), base_(std::move(base)) {+ QL_REQUIRE(!base_.empty(), "a conditional survival curve needs an underlying curve");+ QL_REQUIRE(base_->jumpDates().empty(),+ "conditional survival views cannot transfer scheduled-jump metadata");+ checkReference();+ normalization();+ registerWith(base_);+ enableExtrapolation(base_->allowsExtrapolation());+ }+ QuantLib::DayCounter dayCounter() const override { return base_->dayCounter(); }+ QuantLib::Calendar calendar() const override { return base_->calendar(); }+ QuantLib::Date maxDate() const override { return base_->maxDate(); }+ QuantLib::Time maxTime() const override { return base_->maxTime() - offset(); }++ protected:+ QuantLib::Probability survivalProbabilityImpl(QuantLib::Time t) const override {+ const auto result = base_->survivalProbability(offset() + t, true) / normalization();+ QL_REQUIRE(std::isfinite(result), "conditional survival probability must be finite");+ return result;+ }+ QuantLib::Real defaultDensityImpl(QuantLib::Time t) const override {+ const auto result = base_->defaultDensity(offset() + t, true) / normalization();+ QL_REQUIRE(std::isfinite(result), "conditional default density must be finite");+ return result;+ }+ QuantLib::Real hazardRateImpl(QuantLib::Time t) const override {+ normalization();+ const auto result = base_->hazardRate(offset() + t, true);+ QL_REQUIRE(std::isfinite(result), "conditional hazard rate must be finite");+ return result;+ }++ private:+ void checkReference() const {+ QL_REQUIRE(referenceDate() >= base_->referenceDate(),+ "a conditional reference must not precede the original reference");+ QL_REQUIRE(referenceDate() <= base_->maxDate(),+ "a conditional reference must lie within the original curve support");+ }+ QuantLib::Time offset() const {+ checkReference();+ return base_->timeFromReference(referenceDate());+ }+ QuantLib::Probability normalization() const {+ checkReference();+ const auto result = base_->survivalProbability(referenceDate(), false);+ QL_REQUIRE(std::isfinite(result) && result > 0.0,+ "conditional survival normalization must be positive and finite");+ return result;+ }+ QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure> base_;+};++}+#endif
cbits/qlEnumObjects.h view
@@ -1,3 +1,5 @@+enum YoyOptionletModel { YoyBlack, YoyUnitDisplacedBlack, YoyBachelier };+ enum ReplicationType { ReplicationSub = 0, ReplicationCentral = 1, ReplicationSuper = 2 }; // Enumerations to be mapped to specific QuantLib classes
cbits/qlInstrument.cpp view
@@ -971,9 +971,9 @@ Leg* qlSwapLeg(QlSwap* o, unsigned j, QlError **e) { QlCallScope callbackScope(e);try {return ret(new Leg((*arg(o))->leg(j)));} catch (std::exception& er) {return handleException<Leg*>(e, er);}} double qlSwapLegBPS(QlSwap* o, unsigned j, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->legBPS(j);} catch (std::exception& er) {return handleException<double>(e, er);}} double qlSwapLegNPV(QlSwap* o, unsigned j, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->legNPV(j);} catch (std::exception& er) {return handleException<double>(e, er);}}-int qlSwapMaturityDate(QlSwap* o, QlError **e) { QlCallScope callbackScope(e);try {return qlNullableDate((*arg(o))->maturityDate());} catch (std::exception& er) {return handleException<int>(e, er);}}+int qlSwapMaturityDate(QlSwap* o, QlError **e) { QlCallScope callbackScope(e);try {return ((*arg(o))->maturityDate()).serialNumber();} catch (std::exception& er) {return handleException<int>(e, er);}} double qlSwapNpvDateDiscount(QlSwap* o, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->npvDateDiscount();} catch (std::exception& er) {return handleException<double>(e, er);}}-int qlSwapStartDate(QlSwap* o, QlError **e) { QlCallScope callbackScope(e);try {return qlNullableDate((*arg(o))->startDate());} catch (std::exception& er) {return handleException<int>(e, er);}}+int qlSwapStartDate(QlSwap* o, QlError **e) { QlCallScope callbackScope(e);try {return ((*arg(o))->startDate()).serialNumber();} catch (std::exception& er) {return handleException<int>(e, er);}} double qlSwapStartDiscounts(QlSwap* o, unsigned j, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->startDiscounts(j);} catch (std::exception& er) {return handleException<double>(e, er);}} double qlFixedVsFloatingSwapFairRate(QlFixedVsFloatingSwap* o, QlError **e) { QlCallScope callbackScope(e);try {const double value = (*arg(o))->fairRate(); QL_REQUIRE(std::isfinite(value), "fair rate/spread is undefined for zero leg BPS"); return value;} catch (std::exception& er) {return handleException<double>(e, er);}} double qlFixedVsFloatingSwapFairSpread(QlFixedVsFloatingSwap* o, QlError **e) { QlCallScope callbackScope(e);try {const double value = (*arg(o))->fairSpread(); QL_REQUIRE(std::isfinite(value), "fair rate/spread is undefined for zero leg BPS"); return value;} catch (std::exception& er) {return handleException<double>(e, er);}}@@ -1251,9 +1251,9 @@ QlBarrierOption* qlBarrierOption(int barrierType, double barrier, double rebate, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlBarrierOption(alloc(new BarrierOption((Barrier::Type)barrierType, barrier, rebate, *arg(payoff), (*arg(exercise)))))); } catch (std::exception& er) {return handleException<QlBarrierOption*>(e, er);}}-QlInstrument* qlTwoAssetBarrierOption(int barrierType, double barrier, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e) { QlCallScope callbackScope(e);- try {return ret(new QlInstrument(alloc(new TwoAssetBarrierOption((Barrier::Type)barrierType, barrier, *arg(payoff), (*arg(exercise))))));- } catch (std::exception& er) {return handleException<QlInstrument*>(e, er);}}+QlOption* qlTwoAssetBarrierOption(int barrierType, double barrier, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e) { QlCallScope callbackScope(e);+ try {return ret(new QlOption(alloc(new TwoAssetBarrierOption((Barrier::Type)barrierType, barrier, *arg(payoff), (*arg(exercise))))));+ } catch (std::exception& er) {return handleException<QlOption*>(e, er);}} double qlBarrierOptionImpliedVolatility(QlBarrierOption* o, double price, QlGeneralizedBlackScholesProcess* process, unsigned dividendsLen, QlDividend** dividends, double accuracy, unsigned maxEvaluations, double minVol, double maxVol, QlError **e) { QlCallScope callbackScope(e); try {DividendSchedule d = qlVector(dividends, dividendsLen); return (*arg(o))->impliedVolatility(price, *arg(process), d, accuracy, maxEvaluations, minVol, maxVol);@@ -1392,7 +1392,7 @@ try {return ret(new QlBond(alloc(new Bond(settlDays, *arg(calendar), qlNullableDate(issueDate), *arg(coupons))))); } catch (std::exception& er) {return handleException<QlBond *>(e, er);}} int qlBondMaturityDate(QlBond *bond, QlError **e) { QlCallScope callbackScope(e);- try {return qlNullableDate((*arg(bond))->maturityDate());+ try {return ((*arg(bond))->maturityDate()).serialNumber(); } catch (std::exception& er) {return handleException<int>(e, er);}} void qlFreeBond(QlBond *bond) {del(bond);} void qlFreeFixedRateBond(QlFixedRateBond *bond) {del(bond);}@@ -2095,6 +2095,9 @@ for (unsigned i = 0; i < ds.size(); ++i) out[i] = ds[i].serialNumber(); result.commit(); } catch (std::exception& er) {(void)handleException<int*>(e, er);}}+void qlMultipleResetsCouponAccrualFractions(QlMultipleResetsCoupon *o, unsigned *len, double **fractions, QlError **e) { QlCallScope callbackScope(e);+ try {fillVectorOut([&] {return (*arg(o))->dt();}, len, fractions);+ } catch (std::exception& er) {(void)handleException<double*>(e, er);}} void qlFreeRangeAccrualFloatersCoupon(QlRangeAccrualFloatersCoupon* o) {del(o);} QlFloatingRateCoupon* qlRangeAccrualFloatersCouponAsFloatingRateCoupon(QlRangeAccrualFloatersCoupon* o) {return ret(new QlFloatingRateCoupon(*arg(o)));} QlRangeAccrualFloatersCoupon* qlRangeAccrualFloatersCoupon(int paymentDate, double nominal, QlIborIndex* index, int startDate, int endDate, unsigned fixingDays, DayCounter* dayCounter, double gearing, double spread, int refStart, int refEnd, Schedule* observations, double lower, double upper, QlError **e) { QlCallScope callbackScope(e);@@ -2124,6 +2127,9 @@ for (unsigned i = 0; i < ds.size(); ++i) out[i] = ds[i].serialNumber(); result.commit(); } catch (std::exception& er) {(void)handleException<int*>(e, er);}}+void qlOvernightIndexedCouponAccrualFractions(QlOvernightIndexedCoupon *o, unsigned *len, double **fractions, QlError **e) { QlCallScope callbackScope(e);+ try {fillVectorOut([&] {return (*arg(o))->dt();}, len, fractions);+ } catch (std::exception& er) {(void)handleException<double*>(e, er);}} void qlOvernightIndexedCouponIndexFixings(QlOvernightIndexedCoupon *o, unsigned *len, double **fixings, QlError **e) { QlCallScope callbackScope(e); try {fillVectorOut([&] {return (*arg(o))->indexFixings();}, len, fixings); } catch (std::exception& er) {(void)handleException<double*>(e, er);}}
cbits/qlInstrument.h view
@@ -361,7 +361,7 @@ QlOption* qlQuantoForwardVanillaOptionAsOption(QlQuantoForwardVanillaOption *o); QlBarrierOption* qlBarrierOption(int barrierType, double barrier, double rebate, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e);- QlInstrument* qlTwoAssetBarrierOption(int barrierType, double barrier, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e);+ QlOption* qlTwoAssetBarrierOption(int barrierType, double barrier, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e); double qlBarrierOptionImpliedVolatility(QlBarrierOption* o, double price, QlGeneralizedBlackScholesProcess* process, unsigned dividendsLen, QlDividend** dividends, double accuracy, unsigned maxEvaluations, double minVol, double maxVol, QlError **e); QlOneAssetOption* qlPartialTimeBarrierOption(int barrierType, int barrierRange, double barrier, double rebate, int coverEventDate, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e); QlDoubleBarrierOption* qlDoubleBarrierOption(int barrierType, double barrierLo, double barrierHi, double rebate, QlStrikedTypePayoff* payoff, QlExercise* exercise, QlError **e);@@ -684,6 +684,7 @@ QlFloatingRateCoupon* qlMultipleResetsCouponAsFloatingRateCoupon(QlMultipleResetsCoupon* o); QlMultipleResetsCoupon* qlMultipleResetsCoupon(int paymentDate, double nominal, Schedule *schedule, unsigned fixingDays, QlIborIndex *index, double gearing, double couponSpread, double rateSpread, int refPeriodStart, int refPeriodEnd, DayCounter *dayCounter, int exCouponDate, QlError **e); void qlMultipleResetsCouponFixingDates(QlMultipleResetsCoupon *o, unsigned *len, int **dates, QlError **e);+ void qlMultipleResetsCouponAccrualFractions(QlMultipleResetsCoupon *o, unsigned *len, double **fractions, QlError **e); void qlFreeRangeAccrualFloatersCoupon(QlRangeAccrualFloatersCoupon*); QlFloatingRateCoupon* qlRangeAccrualFloatersCouponAsFloatingRateCoupon(QlRangeAccrualFloatersCoupon*); QlRangeAccrualFloatersCoupon* qlRangeAccrualFloatersCoupon(int paymentDate, double nominal, QlIborIndex*, int startDate, int endDate, unsigned fixingDays, DayCounter*, double gearing, double spread, int refStart, int refEnd, Schedule*, double lower, double upper, QlError **e);@@ -699,6 +700,7 @@ QlOvernightIndexedCoupon* qlOvernightIndexedCoupon(int paymentDate, double nominal, int startDate, int endDate, QlOvernightIndex *index, double gearing, double spread, int refPeriodStart, int refPeriodEnd, DayCounter *dayCounter, int telescopic, int averaging, unsigned lookback, unsigned lockout, int observationShift, int compoundSpread, int rateStart, int rateEnd, int exCouponDate, int rounding, QlError **e); QlFloatingRateCoupon* qlCappedFlooredOvernightIndexedCoupon(QlOvernightIndexedCoupon *underlying, double cap, double floor, int naked, int daily, QlError **e); void qlOvernightIndexedCouponFixingDates(QlOvernightIndexedCoupon *o, unsigned *len, int **dates, QlError **e);+ void qlOvernightIndexedCouponAccrualFractions(QlOvernightIndexedCoupon *o, unsigned *len, double **fractions, QlError **e); void qlOvernightIndexedCouponIndexFixings(QlOvernightIndexedCoupon *o, unsigned *len, double **fixings, QlError **e); QlFloatingRateCouponPricer* qlCompoundingOvernightIndexedCouponPricer(QlOptionletVolatilityStructure *vol, int effective, QlError **e); QlFloatingRateCouponPricer* qlArithmeticAveragedOvernightIndexedCouponPricer(double mr, double volatility, int byApprox, QlOptionletVolatilityStructure *vol, int effective, QlError **e);
cbits/qlMisc.cpp view
@@ -172,6 +172,38 @@ }; using HsMultiCompositeQuote = MultiCompositeQuote<HsArrayFun>; + // A hasquant-defined quote: QuantLib has none that observes yield curves. It turns an FX spot+ // quoted for settlement V = calendar.advance(d, lag, Days) into its cash value at the evaluation+ // date d, S_V * (P_dom(V)/P_dom(d)) / (P_for(V)/P_for(d)), so that a forward+ // S_d * (P_for(T)/P_for(d)) / (P_dom(T)/P_dom(d)) equals S_V at T = V. QuantExt's FxRateQuote is+ // the prior art. value() reads the quote, both curves and the evaluation date on every call, so+ // update() only forwards the notification and never re-enters QuantLib.+ class FxCashSpotQuote : public Quote, public Observer {+ public:+ FxCashSpotQuote(const Handle<Quote>& settlementSpot, const Handle<YieldTermStructure>& domestic,+ const Handle<YieldTermStructure>& foreign, const Calendar& calendar, Natural lag)+ : spot_(settlementSpot), domestic_(domestic), foreign_(foreign), calendar_(calendar), lag_(lag) {+ registerWith(spot_);+ registerWith(domestic_);+ registerWith(foreign_);+ registerWith(Settings::instance().evaluationDate());+ }+ Real value() const override {+ QL_ENSURE(isValid(), "invalid FX cash spot quote: the settlement spot has no valid value");+ const Date d = Settings::instance().evaluationDate();+ const Date v = calendar_.advance(d, lag_, Days);+ return spot_->value() * (domestic_->discount(v) / domestic_->discount(d))+ / (foreign_->discount(v) / foreign_->discount(d));+ }+ bool isValid() const override {return !spot_.empty() && spot_->isValid();}+ void update() override {notifyObservers();}+ private:+ Handle<Quote> spot_;+ Handle<YieldTermStructure> domestic_, foreign_;+ Calendar calendar_;+ Natural lag_;+ };+ RiskStatistics riskStats(unsigned n, double *xs) { RiskStatistics s; s.addSequence(xs, xs+n);@@ -248,6 +280,7 @@ QL_TRACE_NAME(HsDerivedQuote) QL_TRACE_NAME(HsCompositeQuote) QL_TRACE_NAME(HsMultiCompositeQuote)+QL_TRACE_NAME(FxCashSpotQuote) QL_TRACE_NAME(SavedSettingsWithObservable) #endif @@ -796,7 +829,7 @@ QlSimpleQuote *qlSimpleQuote(double value, QlError **e) { QlCallScope callbackScope(e);try {return ret(new QlSimpleQuote(alloc(new SimpleQuote(value))));} catch (std::exception& er) {return handleException<QlSimpleQuote *>(e, er);}} double qlQuoteValue(QlQuote *quote, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(quote))->value();} catch (std::exception& er) {return handleException<double>(e, er);}}-double qlSimpleQuoteSetValue(QlSimpleQuote* o, double value, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->setValue(value);} catch (std::exception& er) {return handleException<double>(e, er);}}+void qlSimpleQuoteSetValue(QlSimpleQuote* o, double value, QlError **e) { QlCallScope callbackScope(e);try {(*arg(o))->setValue(value);} catch (std::exception& er) {(void)handleException<void *>(e, er);}} QlQuote* qlEurodollarFuturesImpliedStdDevQuote(QlQuote* forward, QlQuote* callPrice, QlQuote* putPrice, double strike, double guess, double accuracy, unsigned maxIter, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlQuote(shared_ptr<Quote>(alloc(new EurodollarFuturesImpliedStdDevQuote(*arg(forward), *arg(callPrice), *arg(putPrice), strike, guess, accuracy, maxIter)))));@@ -821,6 +854,9 @@ } catch (std::exception& er) {return handleException<double>(e, er);}} QlQuote* qlImpliedStdDevQuote(int optionType, QlQuote* forward, QlQuote* price, double strike, double guess, double accuracy, unsigned maxIter, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlQuote(shared_ptr<Quote>(alloc(new ImpliedStdDevQuote((Option::Type)optionType, *arg(forward), *arg(price), strike, guess, accuracy, maxIter)))));+ } catch (std::exception& er) {return handleException<QlQuote*>(e, er);}}+QlQuote* qlFxCashSpotQuote(QlQuote* settlementSpot, QlYieldTermStructure* domesticTS, QlYieldTermStructure* foreignTS, Calendar* calendar, unsigned settlementDays, QlError **e) { QlCallScope callbackScope(e);+ try {return ret(new QlQuote(shared_ptr<Quote>(alloc(new FxCashSpotQuote(*arg(settlementSpot), *arg(domesticTS), *arg(foreignTS), *arg(calendar), settlementDays))))); } catch (std::exception& er) {return handleException<QlQuote*>(e, er);}} QlQuote* qlLastFixingQuote(QlIndex* index, QlError **e) { QlCallScope callbackScope(e);try {return ret(new QlQuote(shared_ptr<Quote>(alloc(new LastFixingQuote(*arg(index))))));} catch (std::exception& er) {return handleException<QlQuote*>(e, er);}} int qlQuoteIsValid(QlQuote* o, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->isValid();} catch (std::exception& er) {return handleException<int>(e, er);}}
cbits/qlMisc.h view
@@ -153,7 +153,7 @@ void qlFreeQuote(QlQuote *quote); void qlFreeSimpleQuote(QlSimpleQuote *o); QlQuote* qlSimpleQuoteAsQuote(QlSimpleQuote *o);- double qlSimpleQuoteSetValue(QlSimpleQuote* o, double value, QlError **e);+ void qlSimpleQuoteSetValue(QlSimpleQuote* o, double value, QlError **e); QlDeltaVolQuote *qlDeltaVolQuote1(double delta, QlQuote *vol, double maturity, int deltaType, QlError **e); QlDeltaVolQuote *qlDeltaVolQuote2(QlQuote *vol, int deltaType, double maturity, int atmType, QlError **e); void qlFreeDeltaVolQuote(QlDeltaVolQuote *o);@@ -172,6 +172,7 @@ // Quote composition. The op forms select a functor from the QuoteOp/MultiQuoteOp catalogue in // qlEnumObjects.h; DerivedQuote's is applied as `x op operand'.+ QlQuote* qlFxCashSpotQuote(QlQuote* settlementSpot, QlYieldTermStructure* domesticTS, QlYieldTermStructure* foreignTS, Calendar* calendar, unsigned settlementDays, QlError **e); QlQuote* qlDerivedQuote(int op, QlQuote* element, double operand, QlError **e); QlQuote* qlCompositeQuote(int op, QlQuote* element1, QlQuote* element2, QlError **e); QlQuote* qlMultiCompositeQuote(int op, unsigned elementsLen, QlQuote** elements, QlError **e);
+ cbits/qlShapedHazardCurve.h view
@@ -0,0 +1,119 @@+#ifndef HASQUANT_SHAPED_HAZARD_CURVE_H+#define HASQUANT_SHAPED_HAZARD_CURVE_H++#include <ql/termstructures/credit/hazardratestructure.hpp>+#include <ql/math/interpolations/linearinterpolation.hpp>+#include <ql/math/interpolations/forwardflatinterpolation.hpp>+#include <ql/quote.hpp>+#include <ql/experimental/credit/spreadedhazardratecurve.hpp>+#include <algorithm>+#include <cmath>+#include <limits>++namespace hasquant {++// Preserve the native quadrature and arithmetic while refusing invalid queried hazards.+class CheckedParallelHazardCurve final : public QuantLib::SpreadedHazardRateCurve {+ public:+ using QuantLib::SpreadedHazardRateCurve::SpreadedHazardRateCurve;+ protected:+ QuantLib::Real hazardRateImpl(QuantLib::Time t) const override {+ const auto result = QuantLib::SpreadedHazardRateCurve::hazardRateImpl(t);+ QL_REQUIRE(std::isfinite(result) && result >= 0.0, "a shifted hazard rate must be finite and nonnegative");+ return result;+ }+};++// QuantLib supplies interpolation primitives; keep the underlying survival curve intact.+class ShapedHazardCurve final : public QuantLib::HazardRateStructure {+ public:+ ShapedHazardCurve(QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure> base,+ std::vector<QuantLib::Date> dates,+ std::vector<QuantLib::Handle<QuantLib::Quote>> spreads, bool buckets)+ : base_(std::move(base)), dates_(std::move(dates)), spreads_(std::move(spreads)), buckets_(buckets) {+ QL_REQUIRE(!base_.empty(), "a shaped hazard curve needs an underlying curve");+ QL_REQUIRE(!dates_.empty() && dates_.size() == spreads_.size(), "hazard dates and spreads must match and be nonempty");+ registerWith(base_);+ for (const auto& spread : spreads_) registerWith(spread);+ ensureData();+ }+ QuantLib::DayCounter dayCounter() const override { return base_->dayCounter(); }+ QuantLib::Calendar calendar() const override { return base_->calendar(); }+ const QuantLib::Date& referenceDate() const override { return base_->referenceDate(); }+ QuantLib::Date maxDate() const override { return base_->maxDate(); }+ QuantLib::Time maxTime() const override { return base_->maxTime(); }+ void update() override { dirty_ = true; QuantLib::HazardRateStructure::update(); }++ protected:+ QuantLib::Real hazardRateImpl(QuantLib::Time t) const override {+ ensureData();+ const auto spread = buckets_ ? interpolation_(std::min(t, times_.back()), true)+ : values_.size() == 1 ? values_.front()+ : interpolation_(std::clamp(t, times_.front(), times_.back()), true);+ const auto result = base_->hazardRate(t, true) + spread;+ QL_REQUIRE(std::isfinite(result) && result >= 0.0, "a shifted hazard rate must be finite and nonnegative");+ return result;+ }+ QuantLib::Probability survivalProbabilityImpl(QuantLib::Time t) const override {+ ensureData();+ // A far-end survival query must also inspect both sides of earlier spread boundaries.+ hazardRateImpl(0.0);+ hazardRateImpl(t);+ for (auto knot : times_) if (knot > 0.0 && knot <= t) {+ hazardRateImpl(knot);+ hazardRateImpl(std::nextafter(knot, 0.0));+ }+ QuantLib::Real integral;+ if (buckets_) {+ integral = interpolation_.primitive(std::min(t, times_.back()), true);+ } else if (values_.size() == 1 || t <= times_.front()) {+ integral = values_.front() * t;+ } else {+ integral = values_.front() * times_.front()+ + interpolation_.primitive(std::min(t, times_.back()), true)+ + values_.back() * std::max(0.0, t - times_.back());+ }+ const auto result = base_->survivalProbability(t, true) * std::exp(-integral);+ const auto roundoff = 4 * std::numeric_limits<QuantLib::Probability>::epsilon();+ QL_REQUIRE(std::isfinite(result) && result >= 0.0 && result <= 1.0 + roundoff,+ "shifted survival probability must be finite and in [0,1]");+ return std::min(result, 1.0);+ }++ private:+ void ensureData() const {+ if (!dirty_) return;+ times_.clear(); values_.clear();+ if (buckets_) times_.push_back(0.0);+ QuantLib::Date previous = referenceDate();+ for (QuantLib::Size i = 0; i < dates_.size(); ++i) {+ QL_REQUIRE(dates_[i] > previous, "hazard dates must increase strictly after the reference date");+ const auto t = base_->timeFromReference(dates_[i]);+ QL_REQUIRE(std::isfinite(t) && t > (times_.empty() ? 0.0 : times_.back()),+ "hazard times must be finite and strictly increasing");+ QL_REQUIRE(!spreads_[i].empty(), "a hazard spread quote must not be empty");+ const auto value = spreads_[i]->value();+ QL_REQUIRE(std::isfinite(value), "hazard spreads must be finite");+ times_.push_back(t); values_.push_back(value);+ previous = dates_[i];+ }+ if (buckets_) {+ values_.push_back(0.0);+ interpolation_ = QuantLib::ForwardFlat().interpolate(times_.begin(), times_.end(), values_.begin());+ } else if (values_.size() > 1) {+ interpolation_ = QuantLib::Linear().interpolate(times_.begin(), times_.end(), values_.begin());+ }+ dirty_ = false;+ }+ QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure> base_;+ std::vector<QuantLib::Date> dates_;+ std::vector<QuantLib::Handle<QuantLib::Quote>> spreads_;+ bool buckets_;+ mutable bool dirty_ = true;+ mutable std::vector<QuantLib::Time> times_;+ mutable std::vector<QuantLib::Real> values_;+ mutable QuantLib::Interpolation interpolation_;+};++}+#endif
cbits/qlTermStructure.cpp view
@@ -4,6 +4,7 @@ #include <ql/termstructures/volatility/optionlet/strippedoptionletadapter.hpp> #include <ql/termstructures/volatility/optionlet/spreadedoptionletvol.hpp> #include <ql/termstructures/volatility/flatsmilesection.hpp>+#include <ql/termstructures/volatility/interpolatedsmilesection.hpp> #include <ql/termstructures/volatility/spreadedsmilesection.hpp> #include <ql/termstructures/volatility/atmsmilesection.hpp> #include <ql/experimental/volatility/svismilesection.hpp>@@ -89,12 +90,17 @@ using FittedBondDiscountCurveFittingMethod = FittedBondDiscountCurve::FittingMethod; #include "qlTermStructure.h" #include "qlTermStructureAux.h"+#include "qlShapedHazardCurve.h"+#include "qlConditionalSurvivalCurve.h" namespace hasquant { #include "qlEnumObjects.h" } #ifdef QLTRACK_ALLOCATIONS+QL_TRACE_NAME(hasquant::ShapedHazardCurve)+QL_TRACE_NAME(hasquant::ConditionalSurvivalCurve)+QL_TRACE_NAME(hasquant::CheckedParallelHazardCurve) QL_TRACE_NAME(DefaultProbabilityHelper) QL_TRACE_NAME(QlDefaultProbabilityHelper) QL_TRACE_NAME(RateHelper)@@ -164,13 +170,29 @@ } } + // Publish a bootstrapped curve's nodes as parallel arrays; reading them runs the bootstrap.+ template <class CurveHandle>+ void nodesOut(CurveHandle *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e) {+ OutArrayResult<int> ds(daysLen, days);+ OutArrayResult<double> vs(valuesLen, values);+ try {+ const auto nodes = (*arg(o))->nodesFn();+ const auto n = (unsigned)nodes.size();+ int *d = ds.allocate(n);+ double *v = vs.allocate(n);+ for (unsigned i = 0; i < n; ++i) {d[i] = nodes[i].first.serialNumber(); v[i] = nodes[i].second;}+ ds.commit();+ vs.commit();+ } catch (std::exception& er) {qlSetError(e, er.what());}+ }+ template <class Build>- QlDefaultProbabilityTermStructure* piecewiseDefaultCurveImpl(Build&& build, QlError **e) { QlCallScope callbackScope(e);+ QlPiecewiseDefaultCurve* piecewiseDefaultCurveImpl(Build&& build, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(build());- return ret(new QlDefaultProbabilityTermStructure(ts));+ return ret(new QlPiecewiseDefaultCurve(ts)); } catch (std::exception& er) {- return handleException<QlDefaultProbabilityTermStructure*>(e, er);+ return handleException<QlPiecewiseDefaultCurve*>(e, er); } } @@ -275,8 +297,10 @@ try { handle.linkTo({}, false); } catch (...) {} } }+ // A bootstrapped member passes the contributor its leaf retained at construction. Handle<YieldTermStructure> add(RelinkableHandle<YieldTermStructure>& internal,- const Handle<YieldTermStructure>& original, bool bootstrap) {+ const Handle<YieldTermStructure>& original, bool bootstrap,+ const MultiCurveBootstrapContributor* contributor) { QL_REQUIRE(internal.empty(), "internal handle must be empty; was the curve added already?"); auto member = original.currentLink(); // A second registration would give the shared bootstrapper the same contributor twice.@@ -285,12 +309,7 @@ // Retain attempted additions too: upstream can register a raw contributor before throwing. members_.push_back(member); internalHandles_.push_back(internal);- // Same cross-cast as upstream's addBootstrappedCurve: the contributor has no other accessor.- if (bootstrap) {- if (auto provider = ext::dynamic_pointer_cast<MultiCurveBootstrapProvider>(member))- if (const auto* contributor = provider->multiCurveBootstrapContributor())- contributors_.push_back(contributor);- }+ if (bootstrap && contributor) contributors_.push_back(contributor); return bootstrap ? addBootstrappedCurve(internal, std::move(member)) : addNonBootstrappedCurve(internal, std::move(member)); }@@ -309,8 +328,11 @@ QlOptionletVolatilityStructure *qlConstantOptionletVol1(unsigned days, Calendar *cal, int conv, QlQuote *q, DayCounter *dc, int type, double displacement, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlOptionletVolatilityStructure(shared_ptr<OptionletVolatilityStructure>(alloc(new ConstantOptionletVolatility(days, *arg(cal), (BusinessDayConvention) conv, *arg(q), *arg(dc), (VolatilityType)type, displacement))))); } catch (std::exception& er) {return handleException<QlOptionletVolatilityStructure *>(e, er);}}-QlOptionletVolatilityStructure *qlCapletVarianceCurve(int referenceDate, unsigned datesLen, int* dates, unsigned volsLen, double* vols, DayCounter* dc, int type, double displacement, QlError **e) { QlCallScope callbackScope(e);- try {return ret(new QlOptionletVolatilityStructure(shared_ptr<OptionletVolatilityStructure>(alloc(new CapletVarianceCurve(Date(referenceDate), qlDateVector(dates, datesLen), std::vector<double>(vols, vols+volsLen), *arg(dc), (VolatilityType)type, displacement)))));+QlOptionletVolatilityStructure *qlCapletVarianceCurve(int referenceDate, unsigned datesLen, int* dates, unsigned volsLen, double* vols, DayCounter* dc, int type, double displacement, int extrapolate, QlError **e) { QlCallScope callbackScope(e);+ try {+ shared_ptr<OptionletVolatilityStructure> ts(alloc(new CapletVarianceCurve(Date(referenceDate), qlDateVector(dates, datesLen), std::vector<double>(vols, vols+volsLen), *arg(dc), (VolatilityType)type, displacement)));+ if (extrapolate) ts->enableExtrapolation();+ return ret(new QlOptionletVolatilityStructure(ts)); } catch (std::exception& er) {return handleException<QlOptionletVolatilityStructure *>(e, er);}} void qlFreeOptionletVolatilityStructure(QlOptionletVolatilityStructure *p) {del(p);}@@ -1104,12 +1126,45 @@ (ExtendedBlackVarianceSurface::Extrapolation)lowerExtrapolation, (ExtendedBlackVarianceSurface::Extrapolation)upperExtrapolation))))); #endif } catch (std::exception& er) {return handleException<QlBlackVolTermStructure*>(e, er);}}-QlBlackVolTermStructure* qlPiecewiseBlackVarianceSurface(int referenceDate, unsigned datesLen, int* dates, unsigned strikesLen, double* strikes, unsigned blackVolsRows, unsigned blackVolsCols, double* blackVols, DayCounter* dayCounter, QlError **e) { QlCallScope callbackScope(e);+QlBlackVolTermStructure* qlPiecewiseBlackVarianceSurface(int referenceDate, unsigned datesLen, int* dates, unsigned strikesLen, double* strikes, unsigned blackVolsRows, unsigned blackVolsCols, double* blackVols, DayCounter* dayCounter, int extrapolate, QlError **e) { QlCallScope callbackScope(e); try {- return ret(new QlBlackVolTermStructure(shared_ptr<BlackVolTermStructure>(- PiecewiseBlackVarianceSurface::makeFromGrid(Date(referenceDate), qlDateVector(dates, datesLen),- std::vector<Real>(strikes, strikes+strikesLen), qlMatrix(blackVols, blackVolsRows, blackVolsCols), *arg(dayCounter)))));+ auto ts = PiecewiseBlackVarianceSurface::makeFromGrid(Date(referenceDate), qlDateVector(dates, datesLen),+ std::vector<Real>(strikes, strikes+strikesLen), qlMatrix(blackVols, blackVolsRows, blackVolsCols), *arg(dayCounter));+ if (extrapolate) ts->enableExtrapolation();+ return ret(new QlBlackVolTermStructure(shared_ptr<BlackVolTermStructure>(ts))); } catch (std::exception& er) {return handleException<QlBlackVolTermStructure*>(e, er);}}+// One InterpolatedSmileSection<Linear> per date, built exactly as makeFromGrid builds its columns+// (stdDev = vol * sqrt(dc.yearFraction(referenceDate, date)), same reference date and day counter),+// so every section's exercise time equals the surface's time to that date.+QlBlackVolTermStructure* qlPiecewiseBlackVarianceSurfaceSlices(int referenceDate, unsigned datesLen, int* dates, unsigned slicesLen, unsigned* strikeLengths, double* strikes, double* blackVols, DayCounter* dayCounter, int extrapolate, QlError **e) { QlCallScope callbackScope(e);+ try {+ QL_REQUIRE(slicesLen == datesLen, "mismatch between " << datesLen << " dates and " << slicesLen << " smile slices");+ const Date ref(referenceDate);+ const std::vector<Date> ds = qlDateVector(dates, datesLen);+ const DayCounter& dc = *arg(dayCounter);+ std::vector<ext::shared_ptr<SmileSection>> sections;+ sections.reserve(datesLen);+ size_t offset = 0;+ for (size_t j = 0; j < datesLen; ++j) {+ const size_t n = strikeLengths[j];+ QL_REQUIRE(n >= 2, "smile slice " << j << " (" << ds[j] << ") has " << n << " strike(s); linear interpolation needs at least 2");+ std::vector<Real> ks(strikes + offset, strikes + offset + n);+ for (size_t i = 1; i < n; ++i)+ QL_REQUIRE(ks[i] > ks[i-1], "strikes of smile slice " << j << " (" << ds[j] << ") must be strictly increasing");+ const Time t = dc.yearFraction(ref, ds[j]);+ QL_REQUIRE(t > 0.0, "date " << ds[j] << " must be after reference date " << ref);+ const Real sqrtT = std::sqrt(t);+ std::vector<Real> stdDevs(n);+ for (size_t i = 0; i < n; ++i)+ stdDevs[i] = blackVols[offset + i] * sqrtT;+ offset += n;+ sections.push_back(ext::make_shared<InterpolatedSmileSection<Linear>>(+ ds[j], std::move(ks), stdDevs, Null<Real>(), dc, Linear(), ref));+ }+ auto ts = allocShared(new PiecewiseBlackVarianceSurface(ref, ds, std::move(sections), dc));+ if (extrapolate) ts->enableExtrapolation();+ return ret(new QlBlackVolTermStructure(shared_ptr<BlackVolTermStructure>(ts)));+ } catch (std::exception& er) {return handleException<QlBlackVolTermStructure*>(e, er);}} void qlFreeBlackVolatilitySurfaceDelta(QlBlackVolatilitySurfaceDelta *o) {del(o);} QlBlackVolTermStructure* qlBlackVolatilitySurfaceDeltaAsBlackVolTermStructure(QlBlackVolatilitySurfaceDelta *o) {return ret(new QlBlackVolTermStructure(*arg(o)));} QlBlackVolatilitySurfaceDelta* qlBlackVolatilitySurfaceDelta(int referenceDate, unsigned datesLen, int* dates,@@ -1469,6 +1524,14 @@ double qlCallableBondVolatilityStructureMaxStrike(QlCallableBondVolatilityStructure* o, QlError **e) { QlCallScope callbackScope(e); try {return (*arg(o))->maxStrike(); } catch (std::exception& er) {return handleException<double>(e, er);}}+QlDefaultProbabilityTermStructure* qlConditionalSurvivalCurve(QlDefaultProbabilityTermStructure* originalCurve,+ int referenceDate, QlError **e) { QlCallScope callbackScope(e);+ try {+ auto curve = allocShared(new hasquant::ConditionalSurvivalCurve(+ Handle<DefaultProbabilityTermStructure>(*arg(originalCurve)), Date(referenceDate)));+ return ret(new QlDefaultProbabilityTermStructure(curve));+ } catch (std::exception& er) {return handleException<QlDefaultProbabilityTermStructure*>(e, er);}}+ QlDefaultProbabilityTermStructure* qlFactorSpreadedHazardRateCurve(QlDefaultProbabilityTermStructure* originalCurve, QlQuote* spread, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlDefaultProbabilityTermStructure(alloc(new FactorSpreadedHazardRateCurve(Handle<DefaultProbabilityTermStructure>(*arg(originalCurve)), *arg(spread))))); } catch (std::exception& er) {return handleException<QlDefaultProbabilityTermStructure*>(e, er);}}@@ -1478,8 +1541,17 @@ QlDefaultProbabilityTermStructure* qlFlatHazardRate(int referenceDate, QlQuote* hazardRate, DayCounter* x2, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlDefaultProbabilityTermStructure(alloc(new FlatHazardRate(Date(referenceDate), *arg(hazardRate), (*arg(x2)))))); } catch (std::exception& er) {return handleException<QlDefaultProbabilityTermStructure*>(e, er);}}+QlDefaultProbabilityTermStructure* qlShapedHazardRateCurve(QlDefaultProbabilityTermStructure* originalCurve,+ unsigned spreadsLen, QlQuote** spreads, unsigned datesLen, int* dates, int buckets, QlError **e) { QlCallScope callbackScope(e);+ try {+ QL_REQUIRE(spreadsLen == datesLen, "hazard dates and spreads must match");+ auto curve = allocShared(new hasquant::ShapedHazardCurve(Handle<DefaultProbabilityTermStructure>(*arg(originalCurve)),+ qlDateVector(dates, datesLen), qlHandleVector(spreads, spreadsLen), buckets != 0));+ return ret(new QlDefaultProbabilityTermStructure(curve));+ } catch (std::exception& er) {return handleException<QlDefaultProbabilityTermStructure*>(e, er);}}+ QlDefaultProbabilityTermStructure* qlSpreadedHazardRateCurve(QlDefaultProbabilityTermStructure* originalCurve, QlQuote* spread, QlError **e) { QlCallScope callbackScope(e);- try {return ret(new QlDefaultProbabilityTermStructure(alloc(new SpreadedHazardRateCurve(Handle<DefaultProbabilityTermStructure>(*arg(originalCurve)), *arg(spread)))));+ try {return ret(new QlDefaultProbabilityTermStructure(alloc(new hasquant::CheckedParallelHazardCurve(Handle<DefaultProbabilityTermStructure>(*arg(originalCurve)), *arg(spread))))); } catch (std::exception& er) {return handleException<QlDefaultProbabilityTermStructure*>(e, er);}} QlDefaultProbabilityTermStructure* qlInterpolatedDefaultDensityCurve(unsigned datesLen, int* dates, unsigned densitiesLen, double* densities, DayCounter* dayCounter, Calendar* calendar, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int interpolator, int approximator, int approximatorArg, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlDefaultProbabilityTermStructure(alloc(qlInterpolatedDefaultDensityCurveAux(qlDateVector(dates, datesLen), std::vector<double>(densities, densities+densitiesLen), *arg(dayCounter), *arg(calendar), qlHandleVector(jumps, jumpsLen), qlDateVector(jumpDates, jDatesLen), interpolator, approximator, approximatorArg))));@@ -1520,18 +1592,30 @@ try {return ret(new QlDefaultProbabilityHelper(alloc(new UpfrontCdsHelper(*arg(upfront), runningSpread, Period(n, (TimeUnit)u), settlementDays, *arg(calendar), (Frequency)frequency, (BusinessDayConvention)paymentConvention, (DateGeneration::Rule)rule, *arg(dayCounter), recoveryRate, *arg(discountCurve), upfrontSettlementDays, settlesAccrual, paysAtDefaultTime, qlNullableDate(startDate), *arg(lastPeriodDayCounter), rebatesAccrual, (CreditDefaultSwap::PricingModel)model QL144_ARGS(qlNullableDate(tradeDate)))))); } catch (std::exception& er) {return handleException<QlDefaultProbabilityHelper*>(e, er);}}-QlDefaultProbabilityTermStructure* qlPiecewiseDefaultCurve(int referenceDate, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e) { QlCallScope callbackScope(e);+QlPiecewiseDefaultCurve* qlPiecewiseDefaultCurve(int referenceDate, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e) { QlCallScope callbackScope(e); const auto b = bootstrapOpts(accuracy, minValue, maxValue, maxAttempts, maxFactor, minFactor, dontThrow, dontThrowSteps, maxEvaluations); return piecewiseDefaultCurveImpl([&] { return qlPiecewiseDefaultCurveAux(Date(referenceDate), qlVector(instruments, instrumentsLen), *arg(dayCounter), qlHandleVector(jumps, jumpsLen), qlDateVector(jumpDates, jDatesLen), trait, interpolator, approximator, approximatorArg, b); }, e); }-QlDefaultProbabilityTermStructure* qlPiecewiseDefaultCurve1(unsigned settlementDays, Calendar *calendar, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e) { QlCallScope callbackScope(e);+QlPiecewiseDefaultCurve* qlPiecewiseDefaultCurve1(unsigned settlementDays, Calendar *calendar, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e) { QlCallScope callbackScope(e); const auto b = bootstrapOpts(accuracy, minValue, maxValue, maxAttempts, maxFactor, minFactor, dontThrow, dontThrowSteps, maxEvaluations); return piecewiseDefaultCurveImpl([&] { return qlPiecewiseDefaultCurveAux1(settlementDays, *arg(calendar), qlVector(instruments, instrumentsLen), *arg(dayCounter), qlHandleVector(jumps, jumpsLen), qlDateVector(jumpDates, jDatesLen), trait, interpolator, approximator, approximatorArg, b); }, e); }+void qlFreePiecewiseDefaultCurve(QlPiecewiseDefaultCurve *o) {del(o);}+QlDefaultProbabilityTermStructure* qlPiecewiseDefaultCurveAsDefaultProbabilityTermStructure(QlPiecewiseDefaultCurve *o) {return ret(new QlDefaultProbabilityTermStructure((*arg(o))->curve));}+void qlPiecewiseDefaultCurveNodes(QlPiecewiseDefaultCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e) { QlCallScope callbackScope(e);+ nodesOut(o, daysLen, days, valuesLen, values, e);+}+void qlFreePiecewiseYieldCurve(QlPiecewiseYieldCurve *o) {del(o);}+QlYieldTermStructure *qlPiecewiseYieldCurveAsYieldTermStructure(QlPiecewiseYieldCurve *o) {+ return ret(new QlYieldTermStructure((*arg(o))->curve));+}+void qlPiecewiseYieldCurveNodes(QlPiecewiseYieldCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e) { QlCallScope callbackScope(e);+ nodesOut(o, daysLen, days, valuesLen, values, e);+} double qlDefaultProbabilityTermStructureDefaultDensity1(QlDefaultProbabilityTermStructure* o, double t, int extrapolate, QlError **e) { QlCallScope callbackScope(e); try {return (*arg(o))->defaultDensity(t, extrapolate); } catch (std::exception& er) {return handleException<double>(e, er);}}@@ -1742,7 +1826,7 @@ QlZeroCouponInflationSwap* qlZeroCouponInflationSwapHelperSwap(QlZeroCouponInflationSwapHelper* o, QlError **e) { QlCallScope callbackScope(e);try {return ret(new QlZeroCouponInflationSwap((*arg(o))->swap()));} catch (std::exception& er) {return handleException<QlZeroCouponInflationSwap*>(e, er);}} QlYearOnYearInflationSwap* qlYearOnYearInflationSwapHelperSwap(QlYearOnYearInflationSwapHelper* o, QlError **e) { QlCallScope callbackScope(e);try {return ret(new QlYearOnYearInflationSwap((*arg(o))->swap()));} catch (std::exception& er) {return handleException<QlYearOnYearInflationSwap*>(e, er);}} -QlZeroInflationTermStructure* qlPiecewiseZeroInflationCurve(int referenceDate, int baseDate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlZeroCouponInflationSwapHelper** instruments,+QlPiecewiseZeroInflationCurve* qlPiecewiseZeroInflationCurve(int referenceDate, int baseDate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlZeroCouponInflationSwapHelper** instruments, int seasKind, int seasBaseDate, int seasFreq, unsigned seasLen, double *seasFactors, int interpolator, int approximator, int approximatorArg, QlError **e) { QlCallScope callbackScope(e); try { // instruments[i] is shared_ptr<ZeroCouponInflationSwapHelper>*; push_back upcasts each@@ -1754,9 +1838,9 @@ for (unsigned i = 0; i < instrumentsLen; ++i) instr.push_back(*instruments[i]); auto ts = allocShared(qlPiecewiseZeroInflationCurveAux(Date(referenceDate), Date(baseDate), (Frequency)frequency, *arg(dayCounter), instr, qlSeasonality(seasKind, seasBaseDate, seasFreq, seasLen, seasFactors), interpolator, approximator, approximatorArg));- return ret(new QlZeroInflationTermStructure(ts));- } catch (std::exception& er) {return handleException<QlZeroInflationTermStructure*>(e, er);}}-QlYoYInflationTermStructure* qlPiecewiseYoYInflationCurve(int referenceDate, int baseDate, double baseYoYRate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlYearOnYearInflationSwapHelper** instruments,+ return ret(new QlPiecewiseZeroInflationCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseZeroInflationCurve*>(e, er);}}+QlPiecewiseYoYInflationCurve* qlPiecewiseYoYInflationCurve(int referenceDate, int baseDate, double baseYoYRate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlYearOnYearInflationSwapHelper** instruments, int seasKind, int seasBaseDate, int seasFreq, unsigned seasLen, double *seasFactors, int interpolator, int approximator, int approximatorArg, QlError **e) { QlCallScope callbackScope(e); try { std::vector<shared_ptr<BootstrapHelper<YoYInflationTermStructure> > > instr;@@ -1764,8 +1848,18 @@ for (unsigned i = 0; i < instrumentsLen; ++i) instr.push_back(*instruments[i]); auto ts = allocShared(qlPiecewiseYoYInflationCurveAux(Date(referenceDate), Date(baseDate), baseYoYRate, (Frequency)frequency, *arg(dayCounter), instr, qlSeasonality(seasKind, seasBaseDate, seasFreq, seasLen, seasFactors), interpolator, approximator, approximatorArg));- return ret(new QlYoYInflationTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYoYInflationTermStructure*>(e, er);}}+ return ret(new QlPiecewiseYoYInflationCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYoYInflationCurve*>(e, er);}}+void qlFreePiecewiseZeroInflationCurve(QlPiecewiseZeroInflationCurve *o) {del(o);}+QlZeroInflationTermStructure* qlPiecewiseZeroInflationCurveAsZeroInflationTermStructure(QlPiecewiseZeroInflationCurve *o) {return ret(new QlZeroInflationTermStructure((*arg(o))->curve));}+void qlPiecewiseZeroInflationCurveNodes(QlPiecewiseZeroInflationCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e) { QlCallScope callbackScope(e);+ nodesOut(o, daysLen, days, valuesLen, values, e);+}+void qlFreePiecewiseYoYInflationCurve(QlPiecewiseYoYInflationCurve *o) {del(o);}+QlYoYInflationTermStructure* qlPiecewiseYoYInflationCurveAsYoYInflationTermStructure(QlPiecewiseYoYInflationCurve *o) {return ret(new QlYoYInflationTermStructure((*arg(o))->curve));}+void qlPiecewiseYoYInflationCurveNodes(QlPiecewiseYoYInflationCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e) { QlCallScope callbackScope(e);+ nodesOut(o, daysLen, days, valuesLen, values, e);+} // Interpolated (dates, rates) inflation curves, unlike the piecewise bootstraps from swap helpers. QlYoYInflationTermStructure* qlInterpolatedYoYInflationCurve(int referenceDate,@@ -1805,14 +1899,14 @@ } catch (std::exception& er) {return handleException<QlBondHelper *>(e, er);}} void qlFreeRateHelper(QlRateHelper *helper) {del(helper);} -static QlYieldTermStructure *piecewiseYieldCurveImpl(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& b, QlError **e) { QlCallScope callbackScope(e);+static QlPiecewiseYieldCurve *piecewiseYieldCurveImpl(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& b, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveAux(Date(date), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), trait, interpolator, approximator, approximatorArg, b));- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveFull(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveFull(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e) { QlCallScope callbackScope(e); return piecewiseYieldCurveImpl(date, rateLen, ratehelpers, dayCount, quoteLen, quotes, datesLen, dates, trait, interpolator, approximator, approximatorArg,@@ -1850,40 +1944,40 @@ return qlInterpolatedCurve(&qlInterpolatedSimpleZeroCurveAux, yieldLen, yields, ydatesLen, yieldDates, dayCount, cal, quoteLen, quotes, datesLen, dates, interpolator, approximator, approximatorArg, /*extrapolate=*/0, e); }-static QlYieldTermStructure *piecewiseYieldCurve1Impl(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+static QlPiecewiseYieldCurve *piecewiseYieldCurve1Impl(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& b, int extrapolate, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveAux1(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), trait, interpolator, approximator, approximatorArg, /*bootstrap=*/0, /*accuracy=*/0.0, std::vector<double>(), b)); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurve1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurve1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, int extrapolate, QlError **e) { QlCallScope callbackScope(e); return piecewiseYieldCurve1Impl(settl, cal, rateLen, ratehelpers, dayCount, quoteLen, quotes, datesLen, dates, trait, interpolator, approximator, approximatorArg, defaultBootstrapOpts(), extrapolate, e); } -QlYieldTermStructure *qlPiecewiseYieldCurveFull1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveFull1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, int extrapolate, QlError **e) { QlCallScope callbackScope(e); return piecewiseYieldCurve1Impl(settl, cal, rateLen, ratehelpers, dayCount, quoteLen, quotes, datesLen, dates, trait, interpolator, approximator, approximatorArg, bootstrapOpts(accuracy, minValue, maxValue, maxAttempts, maxFactor, minFactor, dontThrow, dontThrowSteps, maxEvaluations), extrapolate, e); }-QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveAux1(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), hasquant::Discount, hasquant::LogLinear, /*approximator=*/0, /*approximatorArg=*/0, /*bootstrap=*/1, accuracy, std::vector<double>(weights, weights + weightsLen), defaultBootstrapOpts(), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -static QlYieldTermStructure *piecewiseYieldCurveGlobalBootstrapFixed(int date, unsigned rateLen,+static QlPiecewiseYieldCurve *piecewiseYieldCurveGlobalBootstrapFixed(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e);@@ -1893,10 +1987,10 @@ qlDateVector(dates, datesLen), trait, interpolator, accuracy, std::vector<double>(weights, weights + weightsLen), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed1(int date, unsigned rateLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed1(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e);@@ -1905,7 +1999,7 @@ weights, extrapolate, initialGuess, e); } -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed2(int date, unsigned rateLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed2(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e);@@ -1914,37 +2008,37 @@ weights, extrapolate, initialGuess, e); } -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap2(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap2(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveAux1(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), hasquant::SimpleZeroYield, hasquant::Linear, /*approximator=*/0, /*approximatorArg=*/0, /*bootstrap=*/1, accuracy, std::vector<double>(weights, weights + weightsLen), defaultBootstrapOpts(), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap4(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap4(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveAux1(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), hasquant::ForwardRate, hasquant::Linear, /*approximator=*/0, /*approximatorArg=*/0, /*bootstrap=*/1, accuracy, std::vector<double>(weights, weights + weightsLen), defaultBootstrapOpts(), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap5(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap5(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveAux1(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), hasquant::ZeroYield, hasquant::Linear, /*approximator=*/0, /*approximatorArg=*/0, /*bootstrap=*/1, accuracy, std::vector<double>(weights, weights + weightsLen), defaultBootstrapOpts(), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed4(int date, unsigned rateLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed4(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e);@@ -1953,7 +2047,7 @@ weights, extrapolate, initialGuess, e); } -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed5(int date, unsigned rateLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed5(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e);@@ -1962,17 +2056,17 @@ weights, extrapolate, initialGuess, e); } -QlYieldTermStructure *qlPiecewiseYieldCurveLocalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveLocalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, unsigned localisation, int forcePositive, double accuracy, double quadraticity, double monotonicity, int convexForcePositive, int extrapolate, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveLocalBootstrapAux1(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), trait, localisation, forcePositive != 0, accuracy, quadraticity, monotonicity, convexForcePositive != 0)); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveLocalBootstrapFixed(int date, unsigned rateLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveLocalBootstrapFixed(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, unsigned localisation, int forcePositive, double accuracy, double quadraticity, double monotonicity, int convexForcePositive,@@ -1983,20 +2077,20 @@ qlDateVector(dates, datesLen), trait, localisation, forcePositive != 0, accuracy, quadraticity, monotonicity, convexForcePositive != 0)); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap3(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap3(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, unsigned additionalRateLen, QlRateHelper **additionalRatehelpers, unsigned additionalDatesLen, int *additionalDates, double accuracy, int extrapolate, unsigned weightsLen, double* weights, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseYieldCurveGlobalBootstrapFullAux(settl, *arg(cal), qlVector(ratehelpers, rateLen), *arg(dayCount), qlHandleVector(quotes, quoteLen), qlDateVector(dates, datesLen), qlVector(additionalRatehelpers, additionalRateLen), qlDateVector(additionalDates, additionalDatesLen), accuracy, std::vector<double>(weights, weights + weightsLen), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} -QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed3(int date, unsigned rateLen,+QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed3(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, unsigned additionalRateLen, QlRateHelper **additionalRatehelpers, unsigned additionalDatesLen, int *additionalDates,@@ -2007,8 +2101,8 @@ qlDateVector(dates, datesLen), qlVector(additionalRatehelpers, additionalRateLen), qlDateVector(additionalDates, additionalDatesLen), accuracy, std::vector<double>(weights, weights + weightsLen), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure *>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve *>(e, er);}} QlMultiCurve *qlMultiCurve(double accuracy, QlError **e) { QlCallScope callbackScope(e);@@ -2018,11 +2112,11 @@ } catch (std::exception& er) {return handleException<QlMultiCurve*>(e, er);}} void qlFreeMultiCurve(QlMultiCurve *o) {del(o);} -QlYieldTermStructure *qlMultiCurveAddBootstrappedCurve(QlMultiCurve *mc, QlRelinkableYieldTermStructure *internalHandle, QlYieldTermStructure *curve, QlError **e) { QlCallScope callbackScope(e);- try {return ret(new QlYieldTermStructure((*arg(mc))->add(*arg(internalHandle), *arg(curve), true)));+QlYieldTermStructure *qlMultiCurveAddBootstrappedCurve(QlMultiCurve *mc, QlRelinkableYieldTermStructure *internalHandle, QlPiecewiseYieldCurve *curve, QlError **e) { QlCallScope callbackScope(e);+ try {return ret(new QlYieldTermStructure((*arg(mc))->add(*arg(internalHandle), (*arg(curve))->curve, true, (*arg(curve))->contributor))); } catch (std::exception& er) {return handleException<QlYieldTermStructure*>(e, er);}} QlYieldTermStructure *qlMultiCurveAddNonBootstrappedCurve(QlMultiCurve *mc, QlRelinkableYieldTermStructure *internalHandle, QlYieldTermStructure *curve, QlError **e) { QlCallScope callbackScope(e);- try {return ret(new QlYieldTermStructure((*arg(mc))->add(*arg(internalHandle), *arg(curve), false)));+ try {return ret(new QlYieldTermStructure((*arg(mc))->add(*arg(internalHandle), *arg(curve), false, nullptr))); } catch (std::exception& er) {return handleException<QlYieldTermStructure*>(e, er);}} // ql/experimental/termstructures/basisswapratehelpers.hpp -- rate-helper constructors only@@ -2324,6 +2418,10 @@ convexityAdjustment ? std::variant<Rate, Handle<Quote>>(*arg(convexityAdjustment)) : std::variant<Rate, Handle<Quote>>(Rate(0.0)), (Pillar::Choice)pillar, qlNullableDate(customPillarDate))))); } catch (std::exception& er) {return handleException<QlRateHelper*>(e, er);}}+int qlRateHelperPillarDate(QlRateHelper* o, QlError **e) { QlCallScope callbackScope(e);+ try {return (*arg(o))->pillarDate().serialNumber();+ } catch (std::exception& er) {return handleException<int>(e, er);}}+ double qlRateHelperImpliedQuote(QlRateHelper* o, QlError **e) { QlCallScope callbackScope(e);try {return (*arg(o))->impliedQuote();} catch (std::exception& er) {return handleException<double>(e, er);}} // The helper keeps a non-owning pointer to the curve until it is next set; the caller keeps the // curve alive for this call, and only impliedQuote reads it here.@@ -2358,21 +2456,21 @@ auto ts = allocShared(qlPiecewiseForwardSpreadedTermStructureAux(qlNullableHandle(arg(x0)), qlHandleVector(spreads, spreadsLen), qlDateVector(dates, datesLen), interpolator, approximator, approximatorArg)); return ret(new QlYieldTermStructure(ts)); } catch (std::exception& er) {return handleException<QlYieldTermStructure*>(e, er);}}-QlYieldTermStructure* qlPiecewiseSpreadYieldCurve(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, int interpolator, int approximator, int approximatorArg,+QlPiecewiseYieldCurve* qlPiecewiseSpreadYieldCurve(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, int extrapolate, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseSpreadYieldCurveAux(qlNullableHandle(arg(baseCurve)), qlVector(helpers, rateLen), interpolator, approximator, approximatorArg, bootstrapOpts(accuracy, minValue, maxValue, maxAttempts, maxFactor, minFactor, dontThrow, dontThrowSteps, maxEvaluations))); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure*>(e, er);}}-QlYieldTermStructure* qlPiecewiseSpreadYieldCurveGlobalBootstrap(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, double accuracy, unsigned weightsLen, double* weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e);+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve*>(e, er);}}+QlPiecewiseYieldCurve* qlPiecewiseSpreadYieldCurveGlobalBootstrap(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, double accuracy, unsigned weightsLen, double* weights, int extrapolate, QlCallback* initialGuess, QlError **e) { QlCallScope callbackScope(e); try { auto ts = allocShared(qlPiecewiseSpreadYieldCurveGlobalBootstrapAux(qlNullableHandle(arg(baseCurve)), qlVector(helpers, rateLen), accuracy, std::vector<double>(weights, weights + weightsLen), initialGuess ? *initialGuess : QlCallback())); if (extrapolate) ts->enableExtrapolation();- return ret(new QlYieldTermStructure(ts));- } catch (std::exception& er) {return handleException<QlYieldTermStructure*>(e, er);}}+ return ret(new QlPiecewiseYieldCurve(ts));+ } catch (std::exception& er) {return handleException<QlPiecewiseYieldCurve*>(e, er);}} QlYieldTermStructure* qlQuantoTermStructure(QlYieldTermStructure* underlyingDividendTS, QlYieldTermStructure* riskFreeTS, QlYieldTermStructure* foreignRiskFreeTS, QlBlackVolTermStructure* underlyingBlackVolTS, double strike, QlBlackVolTermStructure* exchRateBlackVolTS, double exchRateATMlevel, double underlyingExchRateCorrelation, QlError **e) { QlCallScope callbackScope(e); try {return ret(new QlYieldTermStructure(shared_ptr<YieldTermStructure>(alloc(new QuantoTermStructure(*arg(underlyingDividendTS), *arg(riskFreeTS), *arg(foreignRiskFreeTS), *arg(underlyingBlackVolTS), strike, *arg(exchRateBlackVolTS), exchRateATMlevel, underlyingExchRateCorrelation))))); } catch (std::exception& er) {return handleException<QlYieldTermStructure*>(e, er);}}@@ -2726,12 +2824,6 @@ void qlFreeYoYInflationIndex(QlYoYInflationIndex *o) {del(o);} QlInflationIndex* qlYoYInflationIndexAsInflationIndex(QlYoYInflationIndex *o) {return ret(new QlInflationIndex(*arg(o)));} -double qlZeroInflationIndexFixing(QlZeroInflationIndex* o, int fixingDate, QlError **e) { QlCallScope callbackScope(e);- try {return (*arg(o))->fixing(Date(fixingDate));- } catch (std::exception& er) {return handleException<double>(e, er);}}-double qlYoYInflationIndexFixing(QlYoYInflationIndex* o, int fixingDate, QlError **e) { QlCallScope callbackScope(e);- try {return (*arg(o))->fixing(Date(fixingDate));- } catch (std::exception& er) {return handleException<double>(e, er);}} // Both reach inflationPeriod(), which QL_FAILs on a frequency outside Annual..Monthly -- and the // index constructors above take an unconstrained one -- so these need an error channel despite // looking like plain getters.@@ -2859,7 +2951,7 @@ QlTermStructure *qlYoYCapFloorTermPriceSurfaceAsTermStructure(QlYoYCapFloorTermPriceSurface *o) { return ret(new QlTermStructure(*arg(o)));} -QlYoYCapFloorTermPriceSurface *qlYoYCapFloorTermPriceSurface(unsigned fixingDays,+QlYoYCapFloorTermPriceSurface *qlYoYCapFloorTermPriceSurface(int booked, unsigned fixingDays, int yyLagLen, int yyLagUnit, QlYoYInflationIndex *yii, int interpolationType, QlYieldTermStructure *nominal, DayCounter *dc, Calendar *cal, int bdc, unsigned cStrikesLen, double *cStrikes, unsigned fStrikesLen, double *fStrikes,@@ -2876,7 +2968,7 @@ const std::vector<Period> cfMaturitiesVec = qlPeriodVector(cfMaturitiesNum, cfMaturitiesUnit, cfMaturitiesLen); const Matrix cPriceMat = qlMatrix(cPriceData, cPriceRows, cPriceCols); const Matrix fPriceMat = qlMatrix(fPriceData, fPriceRows, fPriceCols);- auto s = allocShared(qlYoYCapFloorTermPriceSurfaceAux(fixingDays, yyLag, yiiRef,+ auto s = allocShared(qlYoYCapFloorTermPriceSurfaceAux(booked != 0, fixingDays, yyLag, yiiRef, (CPI::InterpolationType)interpolationType, nominalRef, *arg(dc), *arg(cal), (BusinessDayConvention)bdc, cStrikesVec, fStrikesVec, cfMaturitiesVec, cPriceMat, fPriceMat, interpolator2D, interpolator1D, approximator, approximatorArg));@@ -2937,45 +3029,25 @@ /* KInterpolatedYoYOptionletVolatilitySurface */ -QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurfaceBlack(- unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc,- QlYoYCapFloorTermPriceSurface *capFloorPrices, QlYoYInflationIndex *index,- QlYieldTermStructure *nominalTs, double slope,- int interpolator, int approximator, int approximatorArg, QlError **e) { QlCallScope callbackScope(e);- try {- shared_ptr<YoYInflationCapFloorEngine> engine(new YoYInflationBlackCapFloorEngine(- *arg(index), qlNullYoYOptionletVolatilitySurfaceHandle(), *arg(nominalTs)));- auto s = allocShared(qlKInterpolatedYoYOptionletVolatilitySurfaceAux(- settlementDays, *arg(cal), (BusinessDayConvention)bdc, *arg(dc), *arg(capFloorPrices), engine, slope,- interpolator, approximator, approximatorArg));- return ret(new QlYoYOptionletVolatilitySurface(Handle<YoYOptionletVolatilitySurface>(s)));- } catch (std::exception& er) {return handleException<QlYoYOptionletVolatilitySurface*>(e, er);}}--QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurfaceUnitDisplacedBlack(- unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc,- QlYoYCapFloorTermPriceSurface *capFloorPrices, QlYoYInflationIndex *index,- QlYieldTermStructure *nominalTs, double slope,- int interpolator, int approximator, int approximatorArg, QlError **e) { QlCallScope callbackScope(e);- try {- shared_ptr<YoYInflationCapFloorEngine> engine(new YoYInflationUnitDisplacedBlackCapFloorEngine(- *arg(index), qlNullYoYOptionletVolatilitySurfaceHandle(), *arg(nominalTs)));- auto s = allocShared(qlKInterpolatedYoYOptionletVolatilitySurfaceAux(- settlementDays, *arg(cal), (BusinessDayConvention)bdc, *arg(dc), *arg(capFloorPrices), engine, slope,- interpolator, approximator, approximatorArg));- return ret(new QlYoYOptionletVolatilitySurface(Handle<YoYOptionletVolatilitySurface>(s)));- } catch (std::exception& er) {return handleException<QlYoYOptionletVolatilitySurface*>(e, er);}}--QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurfaceBachelier(- unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc,+QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurface(+ int model, unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc, QlYoYCapFloorTermPriceSurface *capFloorPrices, QlYoYInflationIndex *index,- QlYieldTermStructure *nominalTs, double slope,+ QlYieldTermStructure *nominalTs, double slope, int useBracket, double lower, double upper, int interpolator, int approximator, int approximatorArg, QlError **e) { QlCallScope callbackScope(e); try {- shared_ptr<YoYInflationCapFloorEngine> engine(new YoYInflationBachelierCapFloorEngine(- *arg(index), qlNullYoYOptionletVolatilitySurfaceHandle(), *arg(nominalTs)));+ shared_ptr<YoYInflationCapFloorEngine> engine;+ switch (model) {+ case hasquant::YoyBlack:+ engine = allocShared(new YoYInflationBlackCapFloorEngine(*arg(index), qlNullYoYOptionletVolatilitySurfaceHandle(), *arg(nominalTs))); break;+ case hasquant::YoyUnitDisplacedBlack:+ engine = allocShared(new YoYInflationUnitDisplacedBlackCapFloorEngine(*arg(index), qlNullYoYOptionletVolatilitySurfaceHandle(), *arg(nominalTs))); break;+ case hasquant::YoyBachelier:+ engine = allocShared(new YoYInflationBachelierCapFloorEngine(*arg(index), qlNullYoYOptionletVolatilitySurfaceHandle(), *arg(nominalTs))); break;+ default: QL_FAIL("unsupported YoY optionlet model " << model);+ } auto s = allocShared(qlKInterpolatedYoYOptionletVolatilitySurfaceAux( settlementDays, *arg(cal), (BusinessDayConvention)bdc, *arg(dc), *arg(capFloorPrices), engine, slope,- interpolator, approximator, approximatorArg));+ interpolator, approximator, approximatorArg, useBracket != 0, lower, upper)); return ret(new QlYoYOptionletVolatilitySurface(Handle<YoYOptionletVolatilitySurface>(s))); } catch (std::exception& er) {return handleException<QlYoYOptionletVolatilitySurface*>(e, er);}} QlYieldTermStructure* qlImpliedTermStructureMoving(QlYieldTermStructure* curve, unsigned days, Calendar* calendar, QlError **e) { QlCallScope scope(e);
cbits/qlTermStructure.h view
@@ -2,7 +2,7 @@ extern "C" { #endif QlOptionletVolatilityStructure *qlConstantOptionletVol1(unsigned days, Calendar *cal, int conv, QlQuote *q, DayCounter *dc, int type, double displacement, QlError **e);- QlOptionletVolatilityStructure *qlCapletVarianceCurve(int referenceDate, unsigned datesLen, int* dates, unsigned volsLen, double* vols, DayCounter* dc, int type, double displacement, QlError **e);+ QlOptionletVolatilityStructure *qlCapletVarianceCurve(int referenceDate, unsigned datesLen, int* dates, unsigned volsLen, double* vols, DayCounter* dc, int type, double displacement, int extrapolate, QlError **e); void qlFreeOptionletVolatilityStructure(QlOptionletVolatilityStructure *p); QlVolatilityTermStructure* qlOptionletVolatilityStructureAsVolatilityTermStructure(QlOptionletVolatilityStructure *o); QlRelinkableOptionletVolatilityStructure* qlRelinkableOptionletVolatilityStructure(QlOptionletVolatilityStructure *initial, QlError **e);@@ -219,7 +219,8 @@ QlBlackVolTermStructure* qlBlackVarianceSurface(int referenceDate, Calendar* cal, unsigned datesLen, int* dates, unsigned strikesLen, double* strikes, unsigned blackVolMatrixRows, unsigned blackVolMatrixCols, double* blackVolMatrix, DayCounter* dayCounter, int lowerExtrapolation, int upperExtrapolation, int interpolator, QlError **e); QlBlackVolTermStructure* qlExtendedBlackVarianceCurve(int referenceDate, unsigned datesLen, int* dates, unsigned volsLen, QlQuote** vols, DayCounter* dayCounter, int forceMonotoneVariance, QlError **e); QlBlackVolTermStructure* qlExtendedBlackVarianceSurface(int referenceDate, Calendar* cal, unsigned datesLen, int* dates, unsigned strikesLen, double* strikes, unsigned volRows, unsigned volCols, QlQuote** vols, DayCounter* dayCounter, int lowerExtrapolation, int upperExtrapolation, QlError **e);- QlBlackVolTermStructure* qlPiecewiseBlackVarianceSurface(int referenceDate, unsigned datesLen, int* dates, unsigned strikesLen, double* strikes, unsigned blackVolsRows, unsigned blackVolsCols, double* blackVols, DayCounter* dayCounter, QlError **e);+ QlBlackVolTermStructure* qlPiecewiseBlackVarianceSurface(int referenceDate, unsigned datesLen, int* dates, unsigned strikesLen, double* strikes, unsigned blackVolsRows, unsigned blackVolsCols, double* blackVols, DayCounter* dayCounter, int extrapolate, QlError **e);+ QlBlackVolTermStructure* qlPiecewiseBlackVarianceSurfaceSlices(int referenceDate, unsigned datesLen, int* dates, unsigned slicesLen, unsigned* strikeLengths, double* strikes, double* blackVols, DayCounter* dayCounter, int extrapolate, QlError **e); void qlFreeBlackVolatilitySurfaceDelta(QlBlackVolatilitySurfaceDelta *o); QlBlackVolTermStructure* qlBlackVolatilitySurfaceDeltaAsBlackVolTermStructure(QlBlackVolatilitySurfaceDelta *o); QlBlackVolatilitySurfaceDelta* qlBlackVolatilitySurfaceDelta(int referenceDate, unsigned datesLen, int* dates,@@ -337,8 +338,10 @@ double qlAffineHazardRateCurveConditionalSurvivalProbability(QlAffineHazardRateCurve* o, int dFwd, int dTgt, double yVal, int extrapolate, QlError **e); double qlAffineHazardRateCurveConditionalSurvivalProbability1(QlAffineHazardRateCurve* o, double tFwd, double tTgt, double yVal, int extrapolate, QlError **e); QlDefaultProbabilityTermStructure* qlFactorSpreadedHazardRateCurve(QlDefaultProbabilityTermStructure* originalCurve, QlQuote* spread, QlError **e);+ QlDefaultProbabilityTermStructure* qlConditionalSurvivalCurve(QlDefaultProbabilityTermStructure* originalCurve, int referenceDate, QlError **e); QlDefaultProbabilityTermStructure* qlFlatHazardRate1(unsigned settlementDays, Calendar* calendar, QlQuote* hazardRate, DayCounter* x3, QlError **e); QlDefaultProbabilityTermStructure* qlFlatHazardRate(int referenceDate, QlQuote* hazardRate, DayCounter* x2, QlError **e);+ QlDefaultProbabilityTermStructure* qlShapedHazardRateCurve(QlDefaultProbabilityTermStructure* originalCurve, unsigned spreadsLen, QlQuote** spreads, unsigned datesLen, int* dates, int buckets, QlError **e); QlDefaultProbabilityTermStructure* qlSpreadedHazardRateCurve(QlDefaultProbabilityTermStructure* originalCurve, QlQuote* spread, QlError **e); QlDefaultProbabilityTermStructure* qlInterpolatedDefaultDensityCurve(unsigned datesLen, int* dates, unsigned densitiesLen, double* densities, DayCounter* dayCounter, Calendar* calendar, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int interpolator, int approximator, int approximatorArg, QlError **e); QlDefaultProbabilityTermStructure* qlInterpolatedHazardRateCurve(unsigned datesLen, int* dates, unsigned hazardRatesLen, double* hazardRates, DayCounter* dayCounter, Calendar* cal, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int interpolator, int approximator, int approximatorArg, int extrapolate, QlError **e);@@ -349,8 +352,14 @@ double qlDefaultProbabilityHelperImpliedQuoteOn(QlDefaultProbabilityHelper *o, QlDefaultProbabilityTermStructure *curve, QlError **e); QlDefaultProbabilityHelper* qlSpreadCdsHelper(QlQuote* runningSpread, int, int, int settlementDays, Calendar* calendar, int frequency, int paymentConvention, int rule, DayCounter* dayCounter, double recoveryRate, QlYieldTermStructure* discountCurve, int settlesAccrual, int paysAtDefaultTime, int startDate, DayCounter* lastPeriodDayCounter, int rebatesAccrual, int model, int tradeDate, QlError **e); QlDefaultProbabilityHelper* qlUpfrontCdsHelper(QlQuote* upfront, double runningSpread, int, int, int settlementDays, Calendar* calendar, int frequency, int paymentConvention, int rule, DayCounter* dayCounter, double recoveryRate, QlYieldTermStructure* discountCurve, unsigned upfrontSettlementDays, int settlesAccrual, int paysAtDefaultTime, int startDate, DayCounter* lastPeriodDayCounter, int rebatesAccrual, int model, int tradeDate, QlError **e);- QlDefaultProbabilityTermStructure* qlPiecewiseDefaultCurve(int referenceDate, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e);- QlDefaultProbabilityTermStructure* qlPiecewiseDefaultCurve1(unsigned settlementDays, Calendar *calendar, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e);+ QlPiecewiseDefaultCurve* qlPiecewiseDefaultCurve(int referenceDate, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e);+ QlPiecewiseDefaultCurve* qlPiecewiseDefaultCurve1(unsigned settlementDays, Calendar *calendar, unsigned instrumentsLen, QlDefaultProbabilityHelper** instruments, DayCounter* dayCounter, unsigned jumpsLen, QlQuote** jumps, unsigned jDatesLen, int* jumpDates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e);+ void qlFreePiecewiseDefaultCurve(QlPiecewiseDefaultCurve *o);+ QlDefaultProbabilityTermStructure* qlPiecewiseDefaultCurveAsDefaultProbabilityTermStructure(QlPiecewiseDefaultCurve *o);+ void qlPiecewiseDefaultCurveNodes(QlPiecewiseDefaultCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e);+ void qlFreePiecewiseYieldCurve(QlPiecewiseYieldCurve *o);+ QlYieldTermStructure *qlPiecewiseYieldCurveAsYieldTermStructure(QlPiecewiseYieldCurve *o);+ void qlPiecewiseYieldCurveNodes(QlPiecewiseYieldCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e); double qlDefaultProbabilityTermStructureDefaultDensity1(QlDefaultProbabilityTermStructure* o, double t, int extrapolate, QlError **e); double qlDefaultProbabilityTermStructureDefaultDensity(QlDefaultProbabilityTermStructure* o, int d, int extrapolate, QlError **e);@@ -424,10 +433,16 @@ QlYearOnYearInflationSwap* qlYearOnYearInflationSwapHelperSwap(QlYearOnYearInflationSwapHelper* o, QlError **e); // seasKind: -1 none, 0 MultiplicativePriceSeasonality, 1 KerkhofSeasonality.- QlZeroInflationTermStructure* qlPiecewiseZeroInflationCurve(int referenceDate, int baseDate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlZeroCouponInflationSwapHelper** instruments,+ QlPiecewiseZeroInflationCurve* qlPiecewiseZeroInflationCurve(int referenceDate, int baseDate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlZeroCouponInflationSwapHelper** instruments, int seasKind, int seasBaseDate, int seasFreq, unsigned seasLen, double *seasFactors, int interpolator, int approximator, int approximatorArg, QlError **e);- QlYoYInflationTermStructure* qlPiecewiseYoYInflationCurve(int referenceDate, int baseDate, double baseYoYRate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlYearOnYearInflationSwapHelper** instruments,+ QlPiecewiseYoYInflationCurve* qlPiecewiseYoYInflationCurve(int referenceDate, int baseDate, double baseYoYRate, int frequency, DayCounter* dayCounter, unsigned instrumentsLen, QlYearOnYearInflationSwapHelper** instruments, int seasKind, int seasBaseDate, int seasFreq, unsigned seasLen, double *seasFactors, int interpolator, int approximator, int approximatorArg, QlError **e);+ void qlFreePiecewiseZeroInflationCurve(QlPiecewiseZeroInflationCurve *o);+ QlZeroInflationTermStructure* qlPiecewiseZeroInflationCurveAsZeroInflationTermStructure(QlPiecewiseZeroInflationCurve *o);+ void qlPiecewiseZeroInflationCurveNodes(QlPiecewiseZeroInflationCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e);+ void qlFreePiecewiseYoYInflationCurve(QlPiecewiseYoYInflationCurve *o);+ QlYoYInflationTermStructure* qlPiecewiseYoYInflationCurveAsYoYInflationTermStructure(QlPiecewiseYoYInflationCurve *o);+ void qlPiecewiseYoYInflationCurveNodes(QlPiecewiseYoYInflationCurve *o, unsigned *daysLen, int **days, unsigned *valuesLen, double **values, QlError **e); QlYoYInflationTermStructure* qlInterpolatedYoYInflationCurve(int referenceDate, unsigned datesLen, int *dates, double *rates, int frequency, DayCounter* dayCounter, int seasKind, int seasBaseDate, int seasFreq, unsigned seasLen, double *seasFactors, int interpolator, int approximator, int approximatorArg, QlError **e); QlZeroInflationTermStructure* qlInterpolatedZeroInflationCurve(int referenceDate, unsigned datesLen, int *dates, double *rates, int frequency, DayCounter* dayCounter,@@ -440,43 +455,43 @@ QlRateHelper *qlDepositRateHelper(QlQuote *quote, int, int, unsigned fixDays, Calendar *calendar, int conv, int eom, DayCounter *dayCount, QlError **e); QlBondHelper *qlFixedRateBondHelper(QlQuote *quote, unsigned settlDays, double face, Schedule *sched, unsigned cLen, double *coupons, DayCounter *dayCount, int conv, double redemption, int issue, QlError **e); QlBondHelper *qlCPIBondHelper(QlQuote *quote, unsigned settlementDays, double faceAmount, double baseCPI, int obsLagLen, int obsLagUnit, QlZeroInflationIndex* index, int observationInterpolation, Schedule *schedule, unsigned couponsLen, double *coupons, DayCounter *accrualDayCounter, int paymentConvention, int issueDate, Calendar *paymentCalendar, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurve1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, int extrapolate, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurve1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, int extrapolate, QlError **e); // Full-arity counterparts of the two above, additionally taking every IterativeBootstrap // constructor parameter (ql/termstructures/iterativebootstrap.hpp). Separate entry points // rather than nine more params on the narrow ones, so the narrow Haskell bindings keep // their signatures -- see QuantLib/Internal/Common.chs's IterativeBootstrapOpts. // accuracy/minValue/maxValue take qlNullReal() for "upstream's default".- QlYieldTermStructure *qlPiecewiseYieldCurveFull(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveFull1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, int extrapolate, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveFull(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveFull1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, int extrapolate, QlError **e); // GlobalBootstrap entry point with fixed Discount/LogLinear dispatch.- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed1(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed1(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e); // Same shape as qlPiecewiseYieldCurveGlobalBootstrap1, hardcoding trait=SimpleZeroYield/ // interpolator=Linear instead -- QuantLib-SWIG's only bound GlobalBootstrap combination // (GlobalLinearSimpleZeroCurve).- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap2(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed2(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap2(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed2(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e); // ForwardRate/Linear and ZeroYield/Linear GlobalBootstrap variants.- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap4(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap5(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed4(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed5(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap4(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap5(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed4(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed5(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, double accuracy, unsigned weightsLen, double *weights, int extrapolate, QlCallback* initialGuess, QlError **e); // trait=SimpleZeroYield/interpolator=Linear via GlobalBootstrap's functor-callback // constructor (canned AdditionalErrors/AdditionalDates -- see qlTermStructureAux.cpp). // additionalDatesLen must equal additionalRateLen - 2.- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrap3(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, unsigned additionalRateLen, QlRateHelper **additionalRatehelpers, unsigned additionalDatesLen, int *additionalDates, double accuracy, int extrapolate, unsigned weightsLen, double* weights, QlCallback* initialGuess, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFixed3(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, unsigned additionalRateLen, QlRateHelper **additionalRatehelpers, unsigned additionalDatesLen, int *additionalDates, double accuracy, int extrapolate, unsigned weightsLen, double* weights, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrap3(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, unsigned additionalRateLen, QlRateHelper **additionalRatehelpers, unsigned additionalDatesLen, int *additionalDates, double accuracy, int extrapolate, unsigned weightsLen, double* weights, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveGlobalBootstrapFixed3(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, unsigned additionalRateLen, QlRateHelper **additionalRatehelpers, unsigned additionalDatesLen, int *additionalDates, double accuracy, int extrapolate, unsigned weightsLen, double* weights, QlCallback* initialGuess, QlError **e); // Dedicated LocalBootstrap entry point: interpolator is always ConvexMonotone (the only // upstream interpolator LocalBootstrap works with -- see qlTermStructureAux.cpp), so trait is // the only Haskell-visible dispatch axis here; localisation/forcePositive/accuracy are // LocalBootstrap's own constructor params, quadraticity/monotonicity/convexForcePositive are // ConvexMonotone's.- QlYieldTermStructure *qlPiecewiseYieldCurveLocalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, unsigned localisation, int forcePositive, double accuracy, double quadraticity, double monotonicity, int convexForcePositive, int extrapolate, QlError **e);- QlYieldTermStructure *qlPiecewiseYieldCurveLocalBootstrapFixed(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, unsigned localisation, int forcePositive, double accuracy, double quadraticity, double monotonicity, int convexForcePositive, int extrapolate, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveLocalBootstrap1(unsigned settl, Calendar *cal, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, unsigned localisation, int forcePositive, double accuracy, double quadraticity, double monotonicity, int convexForcePositive, int extrapolate, QlError **e);+ QlPiecewiseYieldCurve *qlPiecewiseYieldCurveLocalBootstrapFixed(int date, unsigned rateLen, QlRateHelper **ratehelpers, DayCounter *dayCount, unsigned quoteLen, QlQuote **quotes, unsigned datesLen, int *dates, int trait, unsigned localisation, int forcePositive, double accuracy, double quadraticity, double monotonicity, int convexForcePositive, int extrapolate, QlError **e); QlMultiCurve *qlMultiCurve(double accuracy, QlError **e); void qlFreeMultiCurve(QlMultiCurve *o);- QlYieldTermStructure *qlMultiCurveAddBootstrappedCurve(QlMultiCurve *mc, QlRelinkableYieldTermStructure *internalHandle, QlYieldTermStructure *curve, QlError **e);+ QlYieldTermStructure *qlMultiCurveAddBootstrappedCurve(QlMultiCurve *mc, QlRelinkableYieldTermStructure *internalHandle, QlPiecewiseYieldCurve *curve, QlError **e); QlYieldTermStructure *qlMultiCurveAddNonBootstrappedCurve(QlMultiCurve *mc, QlRelinkableYieldTermStructure *internalHandle, QlYieldTermStructure *curve, QlError **e); QlRateHelper *qlIborIborBasisSwapRateHelper(QlQuote *basis, int tenorLen, int tenorUnit, unsigned settlementDays, Calendar *calendar, int convention, int endOfMonth, QlIborIndex *baseIndex, QlIborIndex *otherIndex, QlYieldTermStructure *discountHandle, int bootstrapBaseCurve, int useIndexedCoupons, int rule, int paymentLag, QlStubIndexSelection* baseStub, QlStubIndexSelection* otherStub, QlError **e);@@ -530,6 +545,7 @@ QlRateHelper* qlOvernightIndexFutureRateHelperAsRateHelper(QlOvernightIndexFutureRateHelper *o); double qlOvernightIndexFutureRateHelperConvexityAdjustment(QlOvernightIndexFutureRateHelper *o, QlError **e); QlRateHelper* qlSofrFutureRateHelper(QlQuote* price, int month, int year, int freq, QlQuote* convexityAdjustment, int pillar, int customPillarDate, QlError **e);+ int qlRateHelperPillarDate(QlRateHelper* o, QlError **e); double qlRateHelperImpliedQuote(QlRateHelper* o, QlError **e); double qlRateHelperImpliedQuoteOn(QlRateHelper* o, QlYieldTermStructure* curve, QlError **e); QlBond* qlBondHelperBond(QlBondHelper* o, QlError **e);@@ -594,8 +610,8 @@ QlYieldTermStructure* qlImpliedTermStructure(QlYieldTermStructure* x0, int referenceDate, QlError **e); QlYieldTermStructure* qlPiecewiseZeroSpreadedTermStructure(QlYieldTermStructure* x0, unsigned spreadsLen, QlQuote** spreads, unsigned datesLen, int* dates, int comp, int freq, int interpolator, int approximator, int approximatorArg, QlError **e); QlYieldTermStructure* qlPiecewiseForwardSpreadedTermStructure(QlYieldTermStructure* x0, unsigned spreadsLen, QlQuote** spreads, unsigned datesLen, int* dates, int interpolator, int approximator, int approximatorArg, QlError **e);- QlYieldTermStructure* qlPiecewiseSpreadYieldCurve(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, int extrapolate, QlError **e);- QlYieldTermStructure* qlPiecewiseSpreadYieldCurveGlobalBootstrap(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, double accuracy, unsigned weightsLen, double* weights, int extrapolate, QlCallback* initialGuess, QlError **e);+ QlPiecewiseYieldCurve* qlPiecewiseSpreadYieldCurve(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, int interpolator, int approximator, int approximatorArg, double accuracy, double minValue, double maxValue, unsigned maxAttempts, double maxFactor, double minFactor, int dontThrow, unsigned dontThrowSteps, unsigned maxEvaluations, int extrapolate, QlError **e);+ QlPiecewiseYieldCurve* qlPiecewiseSpreadYieldCurveGlobalBootstrap(QlYieldTermStructure* baseCurve, unsigned rateLen, QlRateHelper** helpers, double accuracy, unsigned weightsLen, double* weights, int extrapolate, QlCallback* initialGuess, QlError **e); QlYieldTermStructure* qlQuantoTermStructure(QlYieldTermStructure* underlyingDividendTS, QlYieldTermStructure* riskFreeTS, QlYieldTermStructure* foreignRiskFreeTS, QlBlackVolTermStructure* underlyingBlackVolTS, double strike, QlBlackVolTermStructure* exchRateBlackVolTS, double exchRateATMlevel, double underlyingExchRateCorrelation, QlError **e); QlYieldTermStructure* qlUltimateForwardTermStructure(QlYieldTermStructure* x0, QlQuote* lastLiquidForwardRate, QlQuote* ultimateForwardRate, int fspLen, int fspUnit, double alpha, int roundingDigits, int compounding, int frequency, QlError **e); QlYieldTermStructure* qlInterpolatedSpreadDiscountCurve(QlYieldTermStructure* baseCurve, unsigned dfsLen, double *dfs, unsigned datesLen, int *dates, int interpolator, int approximator, int approximatorArg, QlError **e);@@ -682,8 +698,6 @@ void qlFreeYoYInflationIndex(QlYoYInflationIndex *o); QlInflationIndex* qlYoYInflationIndexAsInflationIndex(QlYoYInflationIndex *o); - double qlZeroInflationIndexFixing(QlZeroInflationIndex* o, int fixingDate, QlError **e);- double qlYoYInflationIndexFixing(QlYoYInflationIndex* o, int fixingDate, QlError **e); int qlZeroInflationIndexNeedsForecast(QlZeroInflationIndex* o, int fixingDate, QlError **e); int qlYoYInflationIndexNeedsForecast(QlYoYInflationIndex* o, int fixingDate, QlError **e); @@ -736,7 +750,7 @@ double strike, int obsLagLen, int obsLagUnit, int extrapolate, QlError **e); /* YoYCapFloorTermPriceSurface */- QlYoYCapFloorTermPriceSurface *qlYoYCapFloorTermPriceSurface(unsigned fixingDays,+ QlYoYCapFloorTermPriceSurface *qlYoYCapFloorTermPriceSurface(int booked, unsigned fixingDays, int yyLagLen, int yyLagUnit, QlYoYInflationIndex *yii, int interpolationType, QlYieldTermStructure *nominal, DayCounter *dc, Calendar *cal, int bdc, unsigned cStrikesLen, double *cStrikes, unsigned fStrikesLen, double *fStrikes,@@ -765,20 +779,10 @@ stripper nor the per-strike PiecewiseYoYOptionletVolatilityCurve/YoYOptionletHelper it builds internally are ever exposed: nothing in upstream reaches them from outside YoYOptionletStripper::initialize, so there is nothing for a Haskell binding to return. */- QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurfaceBlack(- unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc,- QlYoYCapFloorTermPriceSurface *capFloorPrices, QlYoYInflationIndex *index,- QlYieldTermStructure *nominalTs, double slope,- int interpolator, int approximator, int approximatorArg, QlError **e);- QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurfaceUnitDisplacedBlack(- unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc,- QlYoYCapFloorTermPriceSurface *capFloorPrices, QlYoYInflationIndex *index,- QlYieldTermStructure *nominalTs, double slope,- int interpolator, int approximator, int approximatorArg, QlError **e);- QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurfaceBachelier(- unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc,+ QlYoYOptionletVolatilitySurface *qlKInterpolatedYoYOptionletVolatilitySurface(+ int model, unsigned settlementDays, Calendar *cal, int bdc, DayCounter *dc, QlYoYCapFloorTermPriceSurface *capFloorPrices, QlYoYInflationIndex *index,- QlYieldTermStructure *nominalTs, double slope,+ QlYieldTermStructure *nominalTs, double slope, int useBracket, double lower, double upper, int interpolator, int approximator, int approximatorArg, QlError **e); QlYieldTermStructure* qlImpliedTermStructureMoving(QlYieldTermStructure* curve, unsigned days, Calendar* calendar, QlError **e); QlRateHelper* qlOvernightOvernightBasisSwapRateHelper(QlQuote* basis, int tenorLen, int tenorUnit, unsigned settlementDays, Calendar* calendar, int convention, int endOfMonth, QlOvernightIndex* baseIndex, QlOvernightIndex* otherIndex, QlYieldTermStructure* discount, int bootstrapBaseCurve, int paymentLag, int paymentFrequency, int baseAveragingMethod, int otherAveragingMethod, int telescopicValueDates, int rule, QlError **e);
cbits/qlTermStructureAux.cpp view
@@ -1,3 +1,4 @@+#include <cmath> #include <ql/shared_ptr.hpp> using QuantLib::ext::shared_ptr; #include "qlTermStructureAux.h"@@ -72,15 +73,24 @@ // Args is the entry-point-specific prefix (a Date, or settlementDays + Calendar) followed by // instruments/dayCounter/jumps/jumpDates; every PiecewiseYieldCurve constructor ends with the // interpolator and the bootstrapper, so those two go last in the lambda below.+// Keep the concrete curve's nodes() and MultiCurve contributor reachable behind the erased handle.+template <class CurveType>+PiecewiseYieldCurveHandle *retainNodes(const shared_ptr<CurveType>& curve) {+ const QuantLib::MultiCurveBootstrapContributor* contributor = nullptr;+ if constexpr (std::is_base_of_v<QuantLib::MultiCurveBootstrapProvider, CurveType>)+ contributor = curve->multiCurveBootstrapContributor();+ return new PiecewiseYieldCurveHandle(curve, [curve]{ return curve->nodes(); }, contributor);+}+ template <class... Args>-YieldTermStructure *dispatchTrait(int trait, int interpolator, int approximator, int approximatorArg,+PiecewiseYieldCurveHandle *dispatchTrait(int trait, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& b, Args&&... args) {- auto makeForTrait = [&](auto t) -> YieldTermStructure* {+ auto makeForTrait = [&](auto t) -> PiecewiseYieldCurveHandle* { using Trait = typename decltype(t)::type;- return dispatchInterpolation<YieldTermStructure*>(interpolator, approximator, approximatorArg,+ return dispatchInterpolation<PiecewiseYieldCurveHandle*>(interpolator, approximator, approximatorArg, [&](auto i) { using CurveType = PiecewiseYieldCurve<Trait, decltype(i)>;- return new CurveType(std::forward<Args>(args)..., i, makeIterativeBootstrap<CurveType>(b));+ return retainNodes(ext::make_shared<CurveType>(std::forward<Args>(args)..., i, makeIterativeBootstrap<CurveType>(b))); }); }; switch (trait) {@@ -135,11 +145,12 @@ // for LocalBootstrap below) so each trait/interpolator combination is one dispatch arm instead of // a hand-duplicated block. template <class Trait, class Interp, class... Args>-YieldTermStructure *makeGlobalBootstrapCurve(const Interp& interp, double accuracy,+PiecewiseYieldCurveHandle *makeGlobalBootstrapCurve(const Interp& interp, double accuracy, const std::vector<double>& instrumentWeights, [[maybe_unused]] const QlCallback& initialGuess, Args&&... args) { using CurveType = PiecewiseYieldCurve<Trait, Interp, QuantLib::GlobalBootstrap>;- return new CurveType(std::forward<Args>(args)..., interp,- typename CurveType::bootstrap_type(accuracy, nullptr, nullptr, instrumentWeights QL144_ARGS(bootstrapInitialGuess(initialGuess))));+ static_assert(std::is_base_of_v<QuantLib::MultiCurveBootstrapProvider, CurveType>, "MultiCurve members must retain their contributor");+ return retainNodes(ext::make_shared<CurveType>(std::forward<Args>(args)..., interp,+ typename CurveType::bootstrap_type(accuracy, nullptr, nullptr, instrumentWeights QL144_ARGS(bootstrapInitialGuess(initialGuess))))); } // GlobalBootstrap is wired up only for the combinations concrete use cases have asked for --@@ -149,7 +160,7 @@ // not the full trait x interpolator matrix; CLAUDE.md is explicit about not building dispatch for // hypothetical future combinations. template <class... Args>-YieldTermStructure *dispatchTraitGlobalBootstrap(int trait, int interpolator, double accuracy,+PiecewiseYieldCurveHandle *dispatchTraitGlobalBootstrap(int trait, int interpolator, double accuracy, const std::vector<double>& instrumentWeights, [[maybe_unused]] const QlCallback& initialGuess, Args&&... args) { switch (trait) { case hasquant::Discount:@@ -192,7 +203,7 @@ // instrumentWeights constructor and this functor constructor are different GlobalBootstrap // overloads entirely, not more parameters on the same one. template <class... Args>-YieldTermStructure *piecewiseYieldCurveGlobalBootstrapFull(+PiecewiseYieldCurveHandle *piecewiseYieldCurveGlobalBootstrapFull( const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -210,15 +221,16 @@ " additionalHelpers and " << additionalDates.size() << " additionalDates, expected " << (additionalHelpers.size() - 2) << " additionalDates)"); using CurveType = PiecewiseYieldCurve<QuantLib::SimpleZeroYield, QuantLib::Linear, QuantLib::GlobalBootstrap>;+ static_assert(std::is_base_of_v<QuantLib::MultiCurveBootstrapProvider, CurveType>, "MultiCurve members must retain their contributor"); // CurveType::bootstrap_type(...) naming order -- see the comment on the plain-constructor // GlobalBootstrap branch in qlPiecewiseYieldCurveAux1, same [temp.inst] reason.- return new CurveType(std::forward<Args>(reference)..., instr, dayCount, jumps, jumpDates,+ return retainNodes(ext::make_shared<CurveType>(std::forward<Args>(reference)..., instr, dayCount, jumps, jumpDates, QuantLib::Linear(), CurveType::bootstrap_type(additionalHelpers, AdditionalDates(additionalDates),- AdditionalErrors(additionalHelpers), accuracy, nullptr, nullptr, nullptr, instrumentWeights QL144_ARGS(bootstrapInitialGuess(initialGuess))));+ AdditionalErrors(additionalHelpers), accuracy, nullptr, nullptr, nullptr, instrumentWeights QL144_ARGS(bootstrapInitialGuess(initialGuess))))); } -YieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFullAux(const Date& date,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveGlobalBootstrapFullAux(const Date& date, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates, const std::vector<shared_ptr<RateHelper> >& additionalHelpers,@@ -227,7 +239,7 @@ additionalHelpers, additionalDates, accuracy, instrumentWeights, initialGuess, date); } -YieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFullAux(unsigned settl,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveGlobalBootstrapFullAux(unsigned settl, const Calendar &cal, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -246,17 +258,17 @@ // Discount is excluded: its guesses produce invalid discount factors with // ConvexMonotone/LocalBootstrap. The supported traits bootstrap ordinary deposit rates. template <class Trait, class... Args>-YieldTermStructure *makeCurveLocalBootstrap(const ConvexMonotone& interp, Size localisation,+PiecewiseYieldCurveHandle *makeCurveLocalBootstrap(const ConvexMonotone& interp, Size localisation, bool forcePositive, double accuracy, Args&&... args) { using CurveType = PiecewiseYieldCurve<Trait, QuantLib::ConvexMonotone, QuantLib::LocalBootstrap>; // CurveType::bootstrap_type(...) naming order -- see the comment on the GlobalBootstrap branch // in qlPiecewiseYieldCurveAux1, same [temp.inst] reasoning applied defensively here too.- return new CurveType(std::forward<Args>(args)..., interp,- typename CurveType::bootstrap_type(localisation, forcePositive, accuracy));+ return retainNodes(ext::make_shared<CurveType>(std::forward<Args>(args)..., interp,+ typename CurveType::bootstrap_type(localisation, forcePositive, accuracy))); } template <class... Args>-YieldTermStructure *dispatchTraitLocalBootstrap(int trait, const ConvexMonotone& interp,+PiecewiseYieldCurveHandle *dispatchTraitLocalBootstrap(int trait, const ConvexMonotone& interp, Size localisation, bool forcePositive, double accuracy, Args&&... args) { switch (trait) { case hasquant::ForwardRate:@@ -274,7 +286,7 @@ } } -YieldTermStructure *qlPiecewiseYieldCurveLocalBootstrapAux1(unsigned settl, const Calendar &cal,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveLocalBootstrapAux1(unsigned settl, const Calendar &cal, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -284,7 +296,7 @@ localisation, forcePositive, accuracy, settl, cal, instr, dayCount, jumps, jumpDates); } -YieldTermStructure *qlPiecewiseYieldCurveLocalBootstrapAux(const Date& date,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveLocalBootstrapAux(const Date& date, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -295,7 +307,7 @@ } // extracted some template-heavy stuff into a separate file to speed up the compilation-YieldTermStructure *qlPiecewiseYieldCurveAux(const Date &date,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveAux(const Date &date, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -305,23 +317,22 @@ date, instr, dayCount, jumps, jumpDates); } -YieldTermStructure *qlPiecewiseYieldCurveAux1(unsigned settl, const Calendar &cal,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveAux1(unsigned settl, const Calendar &cal, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates, int trait, int interpolator, int approximator, int approximatorArg, int bootstrap, double accuracy, const std::vector<double>& instrumentWeights, const QlIterativeBootstrapOpts& bootstrapOpts, [[maybe_unused]] const QlCallback& initialGuess) {- if (bootstrap == 1) {+ if (bootstrap == 1) return dispatchTraitGlobalBootstrap(trait, interpolator, accuracy, instrumentWeights, initialGuess, settl, cal, instr, dayCount, jumps, jumpDates);- } return dispatchTrait(trait, interpolator, approximator, approximatorArg, bootstrapOpts, settl, cal, instr, dayCount, jumps, jumpDates); } -YieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapAux(const Date& date,+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveGlobalBootstrapAux(const Date& date, const std::vector<shared_ptr<RateHelper> >& instr, const DayCounter& dayCount, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -430,26 +441,26 @@ }); } -YieldTermStructure *qlPiecewiseSpreadYieldCurveAux(+PiecewiseYieldCurveHandle *qlPiecewiseSpreadYieldCurveAux( const Handle<YieldTermStructure>& baseCurve, const std::vector<shared_ptr<RateHelper> >& instr, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& b) {- return dispatchInterpolation<YieldTermStructure*>(interpolator, approximator, approximatorArg,+ return dispatchInterpolation<PiecewiseYieldCurveHandle*>(interpolator, approximator, approximatorArg, [&](auto i) { using CurveType = PiecewiseSpreadYieldCurve<QuantLib::Discount, decltype(i)>;- return new CurveType(baseCurve, instr, i, makeIterativeBootstrap<CurveType>(b));+ return retainNodes(ext::make_shared<CurveType>(baseCurve, instr, i, makeIterativeBootstrap<CurveType>(b))); }); } // Bootstrap spelled through CurveType::bootstrap_type, as in makeGlobalBootstrapCurve.-YieldTermStructure *qlPiecewiseSpreadYieldCurveGlobalBootstrapAux(+PiecewiseYieldCurveHandle *qlPiecewiseSpreadYieldCurveGlobalBootstrapAux( const Handle<YieldTermStructure>& baseCurve, const std::vector<shared_ptr<RateHelper> >& instr, double accuracy, const std::vector<double>& instrumentWeights, [[maybe_unused]] const QlCallback& initialGuess) { using CurveType = PiecewiseSpreadYieldCurve<QuantLib::Discount, QuantLib::LogLinear, QuantLib::GlobalBootstrap>;- return new CurveType(baseCurve, instr, QuantLib::LogLinear(),- typename CurveType::bootstrap_type(accuracy, nullptr, nullptr, instrumentWeights QL144_ARGS(bootstrapInitialGuess(initialGuess))));+ return retainNodes(ext::make_shared<CurveType>(baseCurve, instr, QuantLib::LogLinear(),+ typename CurveType::bootstrap_type(accuracy, nullptr, nullptr, instrumentWeights QL144_ARGS(bootstrapInitialGuess(initialGuess))))); } // some credit stuff@@ -528,19 +539,21 @@ // The trait x interpolator product, with the entry-point-specific constructor prefix forwarded // as a variadic pack -- same shape as dispatchTrait's for PiecewiseYieldCurve above. template <class... Args>-DefaultProbabilityTermStructure *makePiecewiseDefaultCurve(int trait, int interpolator,+PiecewiseDefaultCurveHandle *makePiecewiseDefaultCurve(int trait, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& b, Args&&... args) {- return dispatchDefaultTrait<DefaultProbabilityTermStructure*>(trait, [&](auto t) {+ return dispatchDefaultTrait<PiecewiseDefaultCurveHandle*>(trait, [&](auto t) { using Trait = typename decltype(t)::type;- return dispatchInterpolation<DefaultProbabilityTermStructure*>(interpolator, approximator, approximatorArg,+ return dispatchInterpolation<PiecewiseDefaultCurveHandle*>(interpolator, approximator, approximatorArg, [&](auto i) { using CurveType = PiecewiseDefaultCurve<Trait, decltype(i)>;- return new CurveType(std::forward<Args>(args)..., i, makeIterativeBootstrap<CurveType>(b));+ auto curve = ext::make_shared<CurveType>(std::forward<Args>(args)..., i, makeIterativeBootstrap<CurveType>(b));+ // PiecewiseDefaultCurve::nodes runs the bootstrap first.+ return new PiecewiseDefaultCurveHandle{curve, [curve]{ return curve->nodes(); }}; }); }); } -DefaultProbabilityTermStructure* qlPiecewiseDefaultCurveAux(const Date &referenceDate,+PiecewiseDefaultCurveHandle* qlPiecewiseDefaultCurveAux(const Date &referenceDate, const std::vector<shared_ptr<DefaultProbabilityHelper> >& instruments, DayCounter& dayCounter, const std::vector<Handle<Quote> >& jumps, const std::vector<Date>& jumpDates,@@ -550,7 +563,7 @@ referenceDate, instruments, dayCounter, jumps, jumpDates); } -DefaultProbabilityTermStructure* qlPiecewiseDefaultCurveAux1(unsigned settlementDays,+PiecewiseDefaultCurveHandle* qlPiecewiseDefaultCurveAux1(unsigned settlementDays, const Calendar& calendar, const std::vector<shared_ptr<DefaultProbabilityHelper> >& instruments, DayCounter& dayCounter,@@ -583,7 +596,7 @@ // The 1.0e-14 / 1.0e-12 accuracies below are upstream's own defaults, spelled explicitly because // the interpolator follows them (piecewisezeroinflationcurve.hpp / piecewiseyoyinflationcurve.hpp).-ZeroInflationTermStructure *qlPiecewiseZeroInflationCurveAux(+PiecewiseZeroInflationCurveHandle *qlPiecewiseZeroInflationCurveAux( const Date &referenceDate, const Date &baseDate, Frequency frequency,@@ -591,14 +604,15 @@ const std::vector<shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > >& instruments, const shared_ptr<Seasonality>& seasonality, int interpolator, int approximator, int approximatorArg) {- return dispatchInterpolation<ZeroInflationTermStructure*>(interpolator, approximator, approximatorArg,+ return dispatchInterpolation<PiecewiseZeroInflationCurveHandle*>(interpolator, approximator, approximatorArg, [&](auto i) {- return new PiecewiseZeroInflationCurve<decltype(i)>(referenceDate, baseDate, frequency,+ auto curve = ext::make_shared<PiecewiseZeroInflationCurve<decltype(i)>>(referenceDate, baseDate, frequency, dayCounter, instruments, seasonality, 1.0e-14, i);+ return new PiecewiseZeroInflationCurveHandle{curve, [curve]{ return curve->nodes(); }}; }); } -YoYInflationTermStructure *qlPiecewiseYoYInflationCurveAux(+PiecewiseYoYInflationCurveHandle *qlPiecewiseYoYInflationCurveAux( const Date &referenceDate, const Date &baseDate, Rate baseYoYRate,@@ -607,10 +621,11 @@ const std::vector<shared_ptr<BootstrapHelper<YoYInflationTermStructure> > >& instruments, const shared_ptr<Seasonality>& seasonality, int interpolator, int approximator, int approximatorArg) {- return dispatchInterpolation<YoYInflationTermStructure*>(interpolator, approximator, approximatorArg,+ return dispatchInterpolation<PiecewiseYoYInflationCurveHandle*>(interpolator, approximator, approximatorArg, [&](auto i) {- return new PiecewiseYoYInflationCurve<decltype(i)>(referenceDate, baseDate, baseYoYRate,+ auto curve = ext::make_shared<PiecewiseYoYInflationCurve<decltype(i)>>(referenceDate, baseDate, baseYoYRate, frequency, dayCounter, instruments, seasonality, 1.0e-12, i);+ return new PiecewiseYoYInflationCurveHandle{curve, [curve]{ return curve->nodes(); }}; }); } @@ -696,9 +711,45 @@ }); } +// Keep booked price grids independent of later process-clock changes.+template <class I2D, class I1D>+class FixedStartYoyPriceSurface : public InterpolatedYoYCapFloorTermPriceSurface<I2D, I1D> {+ using Base = InterpolatedYoYCapFloorTermPriceSurface<I2D, I1D>;+ Date reference_;+public:+ template <class... Args>+ explicit FixedStartYoyPriceSurface(Args&&... args)+ : Base(std::forward<Args>(args)...), reference_(Base::referenceDate()) {+ const Date start = Settings::instance().evaluationDate();+ this->unregisterWith(Settings::instance().evaluationDate());+ const auto frequency = this->yoyIndex()->frequency();+ const auto interpolation = this->indexIsInterpolated() ? CPI::Linear : CPI::Flat;+ const Size years = (Size)std::lround(this->timeFromReference(reference_ + this->cfMaturities_.back()));+ std::vector<shared_ptr<BootstrapHelper<YoYInflationTermStructure>>> helpers;+ for (Size year = 1; year <= years; ++year) {+ const Date maturity = this->nominalTS_->referenceDate() + Period(year, Years);+ const Handle<Quote> quote(ext::make_shared<SimpleQuote>(this->atmYoYSwapRate(maturity)));+ // Preserve the native moving constructor's pillar, including interpolated observations.+ const YearOnYearInflationSwapHelper original(quote, this->observationLag(), maturity,+ this->calendar(), this->bdc_, this->dayCounter(), this->yoyIndex(), interpolation,+ this->nominalTS_);+ helpers.push_back(ext::make_shared<YearOnYearInflationSwapHelper>(quote,+ this->observationLag(), start, maturity, this->calendar(), this->bdc_,+ this->dayCounter(), this->yoyIndex(), interpolation, this->nominalTS_,+ Pillar::CustomDate, original.pillarDate()));+ }+ auto curve = ext::make_shared<PiecewiseYoYInflationCurve<Linear>>(+ this->nominalTS_->referenceDate(), this->yoy_->baseDate(),+ this->atmYoYSwapRate(reference_), frequency, this->dayCounter(), helpers);+ curve->recalculate();+ this->yoy_ = std::move(curve);+ }+ const Date& referenceDate() const override { return reference_; }+};+ // Dispatch both interpolator axes: the 2-D price grid and the inner 1-D per-maturity curve. YoYCapFloorTermPriceSurface *qlYoYCapFloorTermPriceSurfaceAux(- Natural fixingDays, const Period &yyLag, const shared_ptr<YoYInflationIndex> &yii,+ bool booked, Natural fixingDays, const Period &yyLag, const shared_ptr<YoYInflationIndex> &yii, CPI::InterpolationType interpolation, const Handle<YieldTermStructure> &nominal, const DayCounter &dc, const Calendar &cal, BusinessDayConvention bdc, const std::vector<Rate> &cStrikes, const std::vector<Rate> &fStrikes,@@ -708,9 +759,13 @@ using I2D = typename decltype(i2d)::type; return dispatchInterpolation<YoYCapFloorTermPriceSurface*>(interpolator1D, approximator, approximatorArg, [&](auto i) {- return new InterpolatedYoYCapFloorTermPriceSurface<I2D, decltype(i)>(fixingDays, yyLag, yii,+ if (booked)+ return static_cast<YoYCapFloorTermPriceSurface*>(new FixedStartYoyPriceSurface<I2D, decltype(i)>(+ fixingDays, yyLag, yii, interpolation, nominal, dc, cal, bdc,+ cStrikes, fStrikes, cfMaturities, cPrice, fPrice, I2D(), i));+ return static_cast<YoYCapFloorTermPriceSurface*>(new InterpolatedYoYCapFloorTermPriceSurface<I2D, decltype(i)>(fixingDays, yyLag, yii, interpolation, nominal, dc, cal, bdc, cStrikes, fStrikes, cfMaturities, cPrice, fPrice,- I2D(), i);+ I2D(), i)); }); }); }@@ -720,16 +775,166 @@ // never passes one) -- only the surface's own K-direction interpolator (factory1D_) takes an // explicit instance, so only that one needs the Cubic/LogCubic approximator-specific // construction.+/*+ Copyright (C) 2009 Chris Kenyon++ This file is part of QuantLib, a free-software/open-source library+ for financial quantitative analysts and developers - http://quantlib.org/++ QuantLib is free software: you can redistribute it and/or modify it+ under the terms of the QuantLib license. You should have received a+ copy of the license along with this program; if not, please email+ <quantlib-dev@lists.sf.net>. The license is also available online at+ <https://www.quantlib.org/license.shtml>.++ This program is distributed in the hope that it will be useful, but WITHOUT+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS+ FOR A PARTICULAR PURPOSE. See the license for more details.+*/++// Adapt the native initialization pipeline with configurable root bounds. template <class Interpolator1D>+class BracketedYoyOptionletStripper : public InterpolatedYoYOptionletStripper<Interpolator1D> {+ using Base = InterpolatedYoYOptionletStripper<Interpolator1D>;+ using ObjectiveFunction = typename Base::ObjectiveFunction;+ using Base::YoYCapFloorTermPriceSurface_;+ using Base::p_;+ using Base::lag_;+ using Base::frequency_;+ using Base::indexIsInterpolated_;+ using Base::volCurves_;+ Real lower_, upper_;+ public:+ BracketedYoyOptionletStripper(Real lower, Real upper) : lower_(lower), upper_(upper) {}+ void initialize(const shared_ptr<YoYCapFloorTermPriceSurface>& s,+ const shared_ptr<YoYInflationCapFloorEngine>& p,+ Real slope) const override {+ YoYCapFloorTermPriceSurface_ = s;+ p_ = p;+ lag_ = YoYCapFloorTermPriceSurface_->observationLag();+ frequency_ = YoYCapFloorTermPriceSurface_->frequency();+ indexIsInterpolated_ = YoYCapFloorTermPriceSurface_->indexIsInterpolated();+ Natural fixingDays_ = YoYCapFloorTermPriceSurface_->fixingDays();+ Natural settlementDays = 0; // always+ Calendar cal = YoYCapFloorTermPriceSurface_->calendar();+ BusinessDayConvention bdc =+ YoYCapFloorTermPriceSurface_->businessDayConvention();+ DayCounter dc = YoYCapFloorTermPriceSurface_->dayCounter();++ // switch from caps to floors when out of floors+ Rate maxFloor = YoYCapFloorTermPriceSurface_->floorStrikes().back();+ YoYInflationCapFloor::Type useType = YoYInflationCapFloor::Floor;+ Period TPmin = YoYCapFloorTermPriceSurface_->maturities().front();+ // create a "fake index" based on Generic, this should work+ // provided that the lag and frequency are correct+ RelinkableHandle<YoYInflationTermStructure> hYoY(+ YoYCapFloorTermPriceSurface_->YoYTS());+ ext::shared_ptr<YoYInflationIndex> anIndex(+ new YYGenericCPI(frequency_,+ false, lag_,+ Currency(), hYoY));++ // strip each K separatly+ for (Size i=0; i<YoYCapFloorTermPriceSurface_->strikes().size(); i++) {+ Rate K = YoYCapFloorTermPriceSurface_->strikes()[i];+ if (K > maxFloor) useType = YoYInflationCapFloor::Cap;++ // solve for the initial point on the vol curve+ Brent solver;+ Real solverTolerance_ = 1e-7;+ // these are VOLATILITY guesses (always +)+ Real lo = lower_, hi = upper_;+ Real guess = lo + (hi-lo)/2.0;+ Real found;+ Real priceToMatch =+ (useType == YoYInflationCapFloor::Cap ?+ YoYCapFloorTermPriceSurface_->capPrice(TPmin, K) :+ YoYCapFloorTermPriceSurface_->floorPrice(TPmin, K));++ try{+ found = solver.solve(+ ObjectiveFunction(useType, slope, K, lag_, fixingDays_,+ anIndex, YoYCapFloorTermPriceSurface_,+ p_, priceToMatch),+ solverTolerance_, guess, lo, hi );+ } catch( std::exception &e) {+ QL_FAIL("failed to find solution here because: " << e.what());+ }++ // ***create helpers***+ Real notional = 10000; // work in bps+ std::vector<ext::shared_ptr<BootstrapHelper<YoYOptionletVolatilitySurface> > > helperInstruments;+ std::vector<ext::shared_ptr<YoYOptionletHelper> > helpers;+ for (Size j = 0; j < YoYCapFloorTermPriceSurface_->maturities().size(); j++){+ Period Tp = YoYCapFloorTermPriceSurface_->maturities()[j];++ Real nextPrice =+ (useType == YoYInflationCapFloor::Cap ?+ YoYCapFloorTermPriceSurface_->capPrice(Tp, K) :+ YoYCapFloorTermPriceSurface_->floorPrice(Tp, K));++ Handle<Quote> quote1(ext::shared_ptr<Quote>(+ new SimpleQuote( nextPrice )));+ // helper should be an integer number of periods away,+ // this is enforced by rounding+ Size nT = (Size)floor(s->timeFromReference(s->yoyOptionDateFromTenor(Tp))+0.5);+ helpers.push_back(ext::shared_ptr<YoYOptionletHelper>(+ new YoYOptionletHelper(quote1, notional, useType,+ lag_,+ dc, cal,+ fixingDays_,+ anIndex, CPI::Flat,+ K, nT, p_)));++ ext::shared_ptr<ConstantYoYOptionletVolatility> yoyVolBLACK(+ new ConstantYoYOptionletVolatility(found, settlementDays,+ cal, bdc, dc,+ lag_, frequency_,+ false,+ // -100% to +300%+ -1.0,3.0));++ helpers[j]->setTermStructure(+ // gets underlying pointer & removes const+ const_cast<ConstantYoYOptionletVolatility*>(+ yoyVolBLACK.get()));+ helperInstruments.push_back(helpers[j]);+ }+ // ***bootstrap***+ // this is the artificial vol at zero so that first section works+ Real Tmin = s->timeFromReference(s->yoyOptionDateFromTenor(TPmin));+ Volatility baseYoYVolatility = found - slope * Tmin * found;+ Rate eps = std::max(K, 0.02) / 1000.0;+ Rate minStrike = K-eps;+ Rate maxStrike = K+eps;+ ext::shared_ptr<+ PiecewiseYoYOptionletVolatilityCurve<Interpolator1D> > testPW(+ new PiecewiseYoYOptionletVolatilityCurve<Interpolator1D>(+ settlementDays, cal, bdc, dc, lag_,+ frequency_, indexIsInterpolated_,+ minStrike, maxStrike,+ baseYoYVolatility,+ helperInstruments) );+ testPW->recalculate();+ volCurves_.push_back(testPW);+ }+ }+};++template <class Interpolator1D> YoYOptionletVolatilitySurface *makeKInterpolatedYoYOptionletVolatilitySurface( unsigned settlementDays, const Calendar &cal, BusinessDayConvention bdc, const DayCounter &dc, const shared_ptr<YoYCapFloorTermPriceSurface> &capFloorPrices, const shared_ptr<YoYInflationCapFloorEngine> &engine, double slope,- const Interpolator1D &interpolator) {+ const Interpolator1D &interpolator, bool useBracket, double lower, double upper) {+ shared_ptr<YoYOptionletStripper> stripper;+ if (useBracket)+ stripper = shared_ptr<YoYOptionletStripper>(new BracketedYoyOptionletStripper<Interpolator1D>(lower, upper));+ else+ stripper = shared_ptr<YoYOptionletStripper>(new InterpolatedYoYOptionletStripper<Interpolator1D>()); return new KInterpolatedYoYOptionletVolatilitySurface<Interpolator1D>( settlementDays, cal, bdc, dc, capFloorPrices->observationLag(), capFloorPrices, engine,- shared_ptr<YoYOptionletStripper>(new InterpolatedYoYOptionletStripper<Interpolator1D>()),- slope, interpolator);+ stripper, slope, interpolator); } // Not written in terms of dispatchInterpolation, unlike everything else in this file: that@@ -738,10 +943,12 @@ unsigned settlementDays, const Calendar &cal, BusinessDayConvention bdc, const DayCounter &dc, const shared_ptr<YoYCapFloorTermPriceSurface> &capFloorPrices, const shared_ptr<YoYInflationCapFloorEngine> &engine, double slope,- int interpolator1D, int approximator, int approximatorArg) {+ int interpolator1D, int approximator, int approximatorArg, bool useBracket, double lower, double upper) {+ QL_REQUIRE(!useBracket || (std::isfinite(lower) && std::isfinite(upper) && 0 < lower && lower < upper),+ "YoY initial volatility bracket must be finite, positive and ordered"); auto make = [&](auto i) -> YoYOptionletVolatilitySurface* { return makeKInterpolatedYoYOptionletVolatilitySurface(settlementDays, cal, bdc, dc,- capFloorPrices, engine, slope, i);+ capFloorPrices, engine, slope, i, useBracket, lower, upper); }; switch (interpolator1D) { case hasquant::BackwardFlat: return make(BackwardFlat());
cbits/qlTermStructureAux.h view
@@ -43,7 +43,21 @@ unsigned dontThrowSteps, maxEvaluations; }; -QuantLib::YieldTermStructure *qlPiecewiseYieldCurveAux(+// Node pairs of a bootstrapped curve, read through a closure over its concrete instantiation.+using QlCurveNodes = std::vector<std::pair<QuantLib::Date, QuantLib::Real>>;++struct PiecewiseYieldCurveHandle {+ QuantLib::Handle<QuantLib::YieldTermStructure> curve;+ std::function<QlCurveNodes()> nodesFn;+ // The curve's own bootstrapper when it can join a MultiCurve, else null; owned by the curve.+ const QuantLib::MultiCurveBootstrapContributor* contributor;+ PiecewiseYieldCurveHandle(const QuantLib::ext::shared_ptr<QuantLib::YieldTermStructure>& base,+ std::function<QlCurveNodes()> nodes, const QuantLib::MultiCurveBootstrapContributor* member)+ : curve(base), nodesFn(std::move(nodes)), contributor(member) {}+ void enableExtrapolation() { curve->enableExtrapolation(); }+};++PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveAux( const QuantLib::Date &date, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -52,7 +66,7 @@ int trait, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& bootstrapOpts); -QuantLib::YieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapAux(+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveGlobalBootstrapAux( const QuantLib::Date &date, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -73,7 +87,7 @@ // The Haskell `piecewiseYieldCurve` dispatcher selects the matching C shim for each // `Bootstrap` constructor. This integer therefore remains limited to 0 and 1; local bootstrap // uses its separate shim.-QuantLib::YieldTermStructure *qlPiecewiseYieldCurveAux1(+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveAux1( unsigned settl, const QuantLib::Calendar &cal, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -87,7 +101,7 @@ // GlobalBootstrap's functor-callback constructor (additionalHelpers/additionalDates, with // AdditionalErrors/AdditionalDates constructed internally -- see qlTermStructureAux.cpp). // additionalDates.size() must equal additionalHelpers.size() - 2 (QL_REQUIRE'd inside).-QuantLib::YieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFullAux(+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveGlobalBootstrapFullAux( const QuantLib::Date& date, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -97,7 +111,7 @@ const std::vector<QuantLib::Date>& additionalDates, double accuracy, const std::vector<double>& instrumentWeights, const QlCallback& initialGuess = {}); -QuantLib::YieldTermStructure *qlPiecewiseYieldCurveGlobalBootstrapFullAux(+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveGlobalBootstrapFullAux( unsigned settl, const QuantLib::Calendar &cal, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -114,7 +128,7 @@ // with -- see qlTermStructureAux.cpp for why -- so it's implicit, not a Haskell-visible choice; // quadraticity/monotonicity/convexForcePositive are its own constructor params, distinct from // localisation/forcePositive/accuracy (LocalBootstrap's own).-QuantLib::YieldTermStructure *qlPiecewiseYieldCurveLocalBootstrapAux1(+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveLocalBootstrapAux1( unsigned settl, const QuantLib::Calendar &cal, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -123,7 +137,7 @@ int trait, QuantLib::Size localisation, bool forcePositive, double accuracy, double quadraticity, double monotonicity, bool convexForcePositive); -QuantLib::YieldTermStructure *qlPiecewiseYieldCurveLocalBootstrapAux(+PiecewiseYieldCurveHandle *qlPiecewiseYieldCurveLocalBootstrapAux( const QuantLib::Date& date, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, const QuantLib::DayCounter& dayCount,@@ -190,19 +204,24 @@ int interpolator, int approximator, int approximatorArg); // PiecewiseSpreadYieldCurve<Discount, Interpolator, IterativeBootstrap>.-QuantLib::YieldTermStructure *qlPiecewiseSpreadYieldCurveAux(+PiecewiseYieldCurveHandle *qlPiecewiseSpreadYieldCurveAux( const QuantLib::Handle<QuantLib::YieldTermStructure>& baseCurve, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& bootstrapOpts); // PiecewiseSpreadYieldCurve<Discount, LogLinear, GlobalBootstrap>.-QuantLib::YieldTermStructure *qlPiecewiseSpreadYieldCurveGlobalBootstrapAux(+PiecewiseYieldCurveHandle *qlPiecewiseSpreadYieldCurveGlobalBootstrapAux( const QuantLib::Handle<QuantLib::YieldTermStructure>& baseCurve, const std::vector<QuantLib::ext::shared_ptr<QuantLib::RateHelper> >& instr, double accuracy, const std::vector<double>& instrumentWeights, const QlCallback& initialGuess = {}); // some credit stuff+// A bootstrapped curve's type-erased base and a nodes closure over its trait and interpolator.+struct PiecewiseDefaultCurveHandle {+ QuantLib::ext::shared_ptr<QuantLib::DefaultProbabilityTermStructure> curve;+ std::function<QlCurveNodes()> nodesFn;+}; QuantLib::DefaultProbabilityTermStructure *qlInterpolatedDefaultDensityCurveAux( const std::vector<QuantLib::Date>& dates, const std::vector<double>& densities,@@ -240,14 +259,14 @@ const std::vector<QuantLib::Date>& jumpDates, int interpolator, int approximator, int approximatorArg); -QuantLib::DefaultProbabilityTermStructure* qlPiecewiseDefaultCurveAux(const QuantLib::Date &referenceDate,+PiecewiseDefaultCurveHandle* qlPiecewiseDefaultCurveAux(const QuantLib::Date &referenceDate, const std::vector<QuantLib::ext::shared_ptr<QuantLib::DefaultProbabilityHelper> >& instruments, QuantLib::DayCounter& dayCounter, const std::vector<QuantLib::Handle<QuantLib::Quote> >& jumps, const std::vector<QuantLib::Date>& jumpDates, int trait,int interpolator, int approximator, int approximatorArg, const QlIterativeBootstrapOpts& bootstrapOpts); -QuantLib::DefaultProbabilityTermStructure* qlPiecewiseDefaultCurveAux1(unsigned settlementDays,+PiecewiseDefaultCurveHandle* qlPiecewiseDefaultCurveAux1(unsigned settlementDays, const QuantLib::Calendar& calendar, const std::vector<QuantLib::ext::shared_ptr<QuantLib::DefaultProbabilityHelper> >& instruments, QuantLib::DayCounter& dayCounter,@@ -266,7 +285,17 @@ QuantLib::LatentModelIntegrationType::LatentModelIntegrationType integralType, QuantLib::Size nVariables, const std::vector<QuantLib::Integer>& tOrders); -QuantLib::ZeroInflationTermStructure *qlPiecewiseZeroInflationCurveAux(+// A bootstrapped inflation curve and its (date, rate) nodes, read after bootstrapping.+struct PiecewiseZeroInflationCurveHandle {+ QuantLib::ext::shared_ptr<QuantLib::ZeroInflationTermStructure> curve;+ std::function<QlCurveNodes()> nodesFn;+};+struct PiecewiseYoYInflationCurveHandle {+ QuantLib::ext::shared_ptr<QuantLib::YoYInflationTermStructure> curve;+ std::function<QlCurveNodes()> nodesFn;+};++PiecewiseZeroInflationCurveHandle *qlPiecewiseZeroInflationCurveAux( const QuantLib::Date &referenceDate, const QuantLib::Date &baseDate, QuantLib::Frequency frequency,@@ -275,7 +304,7 @@ const QuantLib::ext::shared_ptr<QuantLib::Seasonality>& seasonality, int interpolator, int approximator, int approximatorArg); -QuantLib::YoYInflationTermStructure *qlPiecewiseYoYInflationCurveAux(+PiecewiseYoYInflationCurveHandle *qlPiecewiseYoYInflationCurveAux( const QuantLib::Date &referenceDate, const QuantLib::Date &baseDate, QuantLib::Rate baseYoYRate,@@ -326,7 +355,7 @@ // Two interpolator axes: the 2-D cap/floor price grid, and the 1-D per-maturity curve. QuantLib::YoYCapFloorTermPriceSurface *qlYoYCapFloorTermPriceSurfaceAux(- QuantLib::Natural fixingDays, const QuantLib::Period &yyLag,+ bool booked, QuantLib::Natural fixingDays, const QuantLib::Period &yyLag, const QuantLib::ext::shared_ptr<QuantLib::YoYInflationIndex> &yii, QuantLib::CPI::InterpolationType interpolation, const QuantLib::Handle<QuantLib::YieldTermStructure> &nominal,@@ -343,7 +372,7 @@ const QuantLib::DayCounter &dc, const QuantLib::ext::shared_ptr<QuantLib::YoYCapFloorTermPriceSurface> &capFloorPrices, const QuantLib::ext::shared_ptr<QuantLib::YoYInflationCapFloorEngine> &engine, double slope,- int interpolator1D, int approximator, int approximatorArg);+ int interpolator1D, int approximator, int approximatorArg, bool useBracket, double lower, double upper); // ZabrSmileSection<Evaluation> is templated over the evaluation-tag axis (4 type-only tags, no // runtime state) -- dispatched here rather than in qlTermStructure.cpp, same rule as every other
cbits/qlTypesC2HS.h view
@@ -262,6 +262,10 @@ typedef struct QlYoYInflationCouponPricer QlYoYInflationCouponPricer; typedef struct QlYoYInflationIndex QlYoYInflationIndex; typedef struct QlYoYInflationTermStructure QlYoYInflationTermStructure;+typedef struct QlPiecewiseYoYInflationCurve QlPiecewiseYoYInflationCurve;+typedef struct QlPiecewiseZeroInflationCurve QlPiecewiseZeroInflationCurve;+typedef struct QlPiecewiseYieldCurve QlPiecewiseYieldCurve;+typedef struct QlPiecewiseDefaultCurve QlPiecewiseDefaultCurve; typedef struct QlYoYOptionletVolatilitySurface QlYoYOptionletVolatilitySurface; typedef struct QlZeroCouponInflationSwap QlZeroCouponInflationSwap; typedef struct QlZeroCouponInflationSwapHelper QlZeroCouponInflationSwapHelper;
cbits/qlaux.h view
@@ -336,6 +336,7 @@ class NoConstraint; class NonstandardSwap; class NonstandardSwaption;+ class PiecewiseBlackVarianceSurface; class FloatFloatSwap; class FloatFloatSwaption; class OISRateHelper;@@ -410,6 +411,9 @@ class YoYCapFloorTermPriceSurface; class YoYInflationCapFloor; class YoYInflationCouponPricer;+ class YoYInflationBlackCapFloorEngine;+ class YoYInflationUnitDisplacedBlackCapFloorEngine;+ class YoYInflationBachelierCapFloorEngine; class YoYInflationIndex; class YoYInflationTermStructure; class YoYOptionletVolatilitySurface;@@ -708,6 +712,7 @@ using QuantLib::NoConstraint; using QuantLib::NonstandardSwap; using QuantLib::NonstandardSwaption;+using QuantLib::PiecewiseBlackVarianceSurface; using QuantLib::FloatFloatSwap; using QuantLib::FloatFloatSwaption; using QuantLib::OISRateHelper;@@ -787,6 +792,9 @@ using QuantLib::YoYCapFloorTermPriceSurface; using QuantLib::YoYInflationCapFloor; using QuantLib::YoYInflationCouponPricer;+using QuantLib::YoYInflationBlackCapFloorEngine;+using QuantLib::YoYInflationUnitDisplacedBlackCapFloorEngine;+using QuantLib::YoYInflationBachelierCapFloorEngine; using QuantLib::YoYInflationIndex; using QuantLib::YoYInflationTermStructure; using QuantLib::YoYOptionletVolatilitySurface;@@ -1139,6 +1147,19 @@ using QlYoYInflationCouponPricer = shared_ptr<YoYInflationCouponPricer>; using QlYoYInflationIndex = shared_ptr<YoYInflationIndex>; using QlYoYInflationTermStructure = shared_ptr<YoYInflationTermStructure>;+// PiecewiseYoYInflationCurve<Interpolator> and PiecewiseZeroInflationCurve<Interpolator> have no+// common concrete type with nodes(); like ZabrInterpolatedSmileSectionHandle, each handle keeps+// the type-erased curve and a nodes closure over the instantiation (qlTermStructureAux.h).+struct PiecewiseYoYInflationCurveHandle;+struct PiecewiseZeroInflationCurveHandle;+using QlPiecewiseYoYInflationCurve = shared_ptr<PiecewiseYoYInflationCurveHandle>;+using QlPiecewiseZeroInflationCurve = shared_ptr<PiecewiseZeroInflationCurveHandle>;+// PiecewiseDefaultCurve<Traits, Interpolator> likewise: the handle keeps the type-erased curve and+// a nodes closure over its trait and interpolator.+struct PiecewiseYieldCurveHandle;+using QlPiecewiseYieldCurve = shared_ptr<PiecewiseYieldCurveHandle>;+struct PiecewiseDefaultCurveHandle;+using QlPiecewiseDefaultCurve = shared_ptr<PiecewiseDefaultCurveHandle>; // A vol structure is a Handle, same reasoning as QlOptionletVolatilityStructure above. using QlYoYOptionletVolatilitySurface = Handle<YoYOptionletVolatilitySurface>; using QlZeroCouponInflationSwap = shared_ptr<ZeroCouponInflationSwap>;@@ -1412,6 +1433,7 @@ QL_TRACE_NAME(PaymentTerm) QL_TRACE_NAME(Payoff) QL_TRACE_NAME(PercentageStrikePayoff)+QL_TRACE_NAME(PiecewiseBlackVarianceSurface) QL_TRACE_NAME(PiecewiseTimeDependentHestonModel) QL_TRACE_NAME(PlainVanillaPayoff) QL_TRACE_NAME(PolymorphicPathGenerator)@@ -1663,6 +1685,14 @@ QL_TRACE_NAME(QlYoYInflationCouponPricer) QL_TRACE_NAME(QlYoYInflationIndex) QL_TRACE_NAME(QlYoYInflationTermStructure)+QL_TRACE_NAME(QlPiecewiseYoYInflationCurve)+QL_TRACE_NAME(QlPiecewiseZeroInflationCurve)+QL_TRACE_NAME(PiecewiseYoYInflationCurveHandle)+QL_TRACE_NAME(PiecewiseZeroInflationCurveHandle)+QL_TRACE_NAME(QlPiecewiseYieldCurve)+QL_TRACE_NAME(PiecewiseYieldCurveHandle)+QL_TRACE_NAME(QlPiecewiseDefaultCurve)+QL_TRACE_NAME(PiecewiseDefaultCurveHandle) QL_TRACE_NAME(QlYoYOptionletVolatilitySurface) QL_TRACE_NAME(QlZeroCouponInflationSwap) QL_TRACE_NAME(QlZeroCouponSwap)@@ -1731,6 +1761,9 @@ QL_TRACE_NAME(YoYCapFloorTermPriceSurface) QL_TRACE_NAME(YoYInflationCapFloor) QL_TRACE_NAME(YoYInflationCouponPricer)+QL_TRACE_NAME(YoYInflationBlackCapFloorEngine)+QL_TRACE_NAME(YoYInflationUnitDisplacedBlackCapFloorEngine)+QL_TRACE_NAME(YoYInflationBachelierCapFloorEngine) QL_TRACE_NAME(YoYInflationIndex) QL_TRACE_NAME(YoYInflationTermStructure) QL_TRACE_NAME(YoYOptionletVolatilitySurface)
hasquant.cabal view
@@ -1,7 +1,7 @@ cabal-version: 2.2 name: hasquant-version: 0.8.0.0+version: 0.9.0.0 synopsis: Bindings to QuantLib description: Haskell bindings to the QuantLib C++ library. hasquant provides pricing, curve-building, and risk primitives, including financial@@ -34,6 +34,8 @@ cbits/qlaux.h cbits/qlCallback.h cbits/qlCheckedFdEngine.h+ cbits/qlShapedHazardCurve.h+ cbits/qlConditionalSurvivalCurve.h cbits/qlExactMeanH1HwEngine.h cbits/qlEnumC2HS.h cbits/qlEnumObjects.h
test/example/QuantLib/Example/Bond.hs view
@@ -132,6 +132,7 @@ --Abcd --df <- discount ts (fromGregorian 2011 08 03) True+ base <- asYieldTermStructure ts return MarketData { targetCal = targetCal' , nyseCal = nyseCal'@@ -143,7 +144,7 @@ , thirty360Europeandc = thirty360Europeandc' , settlDate = settlDate' , todaysDate = todaysDate'- , discountCurve = ts+ , discountCurve = base } buildBonds :: MarketData -> IO (Bond, Bond, Bond, PricingEngine)
test/example/QuantLib/Example/FRA.hs view
@@ -33,9 +33,9 @@ setEvaluationDate $ Just todaysDate eu3m <- I.iborIndex I.Euribor3M Nothing fraCalendar <- fixingCalendar eu3m- let fixDays = I.fixingDays eu3m- convention = I.businessDayConvention eu3m- eom = I.endOfMonth eu3m+ fixDays <- I.fixingDays eu3m+ convention <- I.businessDayConvention eu3m+ eom <- I.endOfMonth eu3m settleDate <- advance fraCalendar todaysDate (fromIntegral fixDays, Days) Following False fraQuotes <- mapM simpleQuote quotes
test/example/QuantLib/Example/FittedBondCurve.hs view
@@ -123,9 +123,10 @@ let (instrA, instrB) = unzip helpers - ts0 <- TS.piecewiseYieldCurve (TS.SettlementDays curveSettleDays cal) (fromList instrB) dc []+ piecewise <- TS.piecewiseYieldCurve (TS.SettlementDays curveSettleDays cal) (fromList instrB) dc [] (TS.Iterative TS.Discount LogLinear TS.defaultIterativeBootstrapOpts) False + ts0 <- TS.asYieldTermStructure piecewise curves <- fitCurves cal dc instrA rs <- rates ts0 dc bondSettle evalDate curves instrA return (rs, ts0, instrA, instrB, curves)@@ -143,9 +144,10 @@ step3 :: Day -> DayCounter -> Calendar -> Day -> [TS.BondHelper] -> [TS.RateHelper] -> IO (Rate, TS.YieldTermStructure, [TS.FittedBondDiscountCurve]) step3 evalDate dc cal bondSettle iA iB = do- ts00 <- TS.piecewiseYieldCurve (TS.SettlementDays curveSettleDays cal) (fromList iB) dc []+ piecewise <- TS.piecewiseYieldCurve (TS.SettlementDays curveSettleDays cal) (fromList iB) dc [] (TS.Iterative TS.Discount LogLinear TS.defaultIterativeBootstrapOpts) False + ts00 <- TS.asYieldTermStructure piecewise curves <- fitCurves cal dc iA rs <- rates ts00 dc bondSettle evalDate curves iA return (rs, ts00, curves)
test/example/QuantLib/Example/Gaussian1dModels.hs view
@@ -174,7 +174,7 @@ npv3 <- npv swaption3 -- Add a 100bp credit spread and regenerate the basket.- _ <- setValue oasQuote 0.01+ setValue oasQuote 0.01 basket5 <- calibrationBasket swaption3 swapBase swaptionVol MaturityStrikeByDeltaGamma forM_ basket5 (`Model.setPricingEngine` swaptionEngine) calibrateVolatilitiesIterative gsrModel basket5 lmMethod lmEndCriteria Nothing []
test/example/QuantLib/Example/InflationInstruments.hs view
@@ -8,7 +8,7 @@ import Control.Monad(forM_) import qualified QuantLib.CashFlow as CF import QuantLib.Currency(currency, Ccy(GBP))-import QuantLib.Index(addFixing)+import QuantLib.Index(addFixing, fixing) import qualified QuantLib.Index.InterestRate as I import QuantLib.Index.Inflation import QuantLib.InterestRate(Compounding(Continuous, Compounded), interestRate)@@ -160,7 +160,7 @@ floatSchedule <- schedule (Just evalDate) maturity5Y (6, Months) cal Unadjusted Unadjusted Backward False Nothing Nothing fixedSchedule <- schedule (Just evalDate) maturity5Y (6, Months) cal Unadjusted Unadjusted Backward False Nothing Nothing floatIdx <- I.iborIndex (I.GbpLibor (6, Months)) (Just nominalCurve)- baseCPI0 <- fixing idx1 evalDate+ baseCPI0 <- fixing idx1 evalDate False let cpiSwapCtx = CpiSwapContext { cpiSwapDc = dc , cpiSwapFloatSchedule = floatSchedule
test/example/QuantLib/Example/LiborMarketModelMC.hs view
@@ -56,7 +56,8 @@ Context.setEvaluationDate (Just evalDate) dc <- dayCounter (Actual360 False) emptyIndex <- iborIndex Euribor1Y Nothing- firstPillar <- advance cal evalDate (fromIntegral (Ibor.fixingDays emptyIndex), Days) Following False+ fixDays <- Ibor.fixingDays emptyIndex+ firstPillar <- advance cal evalDate (fromIntegral fixDays, Days) Following False rTS <- interpolatedZeroCurve (fromList [(firstPillar, 0.01), (curveEndDate, 0.08)]) dc cal [] Linear idx <- iborIndex Euribor1Y (Just rTS) @@ -65,7 +66,7 @@ volDates <- fixingDates volProcess volDc <- dayCounter ActualActualISDA capletVol <- Vol.capletVarianceCurve evalDate- (fromList (zip (take (fromIntegral len) (drop 1 volDates)) capletVols)) volDc ShiftedLognormal 0.0+ (fromList (zip (take (fromIntegral len) (drop 1 volDates)) capletVols)) volDc ShiftedLognormal 0.0 False process <- liborForwardModelProcess len idx parameterization <- lfmHullWhiteParameterization process capletVol emptyCorrelation 1
test/example/QuantLib/Example/Replication.hs view
@@ -4,7 +4,7 @@ Result(..) , run ) where-import Control.Monad(void, foldM)+import Control.Monad(foldM) import Data.Time.Calendar import QuantLib.Instrument@@ -109,7 +109,7 @@ putn <- europeanOption innerPayoff innerExercise >>= asOneAssetOption >>= asOption >>= asInstrument setPricingEngine putn engine setEvaluationDate $ Just killDate- void $ setValue underlyingQuote barrier+ setValue underlyingQuote barrier portfolioValue <- composite p >>= npv putValue <- npv putn return (putn, -portfolioValue / putValue)
test/example/QuantLib/Example/Repo.hs view
@@ -5,7 +5,7 @@ , run ) where -import Control.Monad(void, when)+import Control.Monad(when) import System.IO (hPutStrLn, stderr) import QuantLib.Instrument@@ -103,7 +103,7 @@ (0, Days) bondCalendar Unadjusted False bondDayCountConvention -- liftM2 setPricingEngine (asInstrument b) (discountingBondEngine bondCurve Nothing)] discountingBondEngine bondCurve Nothing >>= setPricingEngine b- void $ yieldFromPrice b (bondCleanPrice, Clean) bondDayCountConvention IR.Compounded bondCouponFrequency repoSettlementDate 1e-8 100 >>= setValue bondQuote+ yieldFromPrice b (bondCleanPrice, Clean) bondDayCountConvention IR.Compounded bondCouponFrequency repoSettlementDate 1e-8 100 >>= setValue bondQuote repoQuote <- simpleQuote repoRate repoCurve <- flatForward (ReferenceDate repoSettlementDate) repoQuote repoDayCountConvention repoCompounding repoCompoundFreq
test/example/QuantLib/Example/ShortRateModels.hs view
@@ -122,8 +122,8 @@ ccy <- IR.currency index cal <- fixingCalendar index dc <- IR.dayCounter index- let conv = IR.businessDayConvention index- eom = IR.endOfMonth index+ conv <- IR.businessDayConvention index+ eom <- IR.endOfMonth index index0 <- IR.iborIndex (IR.Ibor "Euribor" tenr 0 ccy cal conv eom dc) (Just ts) runCalibration model index0 ts [] 0.0482063 0.00582687
test/example/QuantLib/Example/Swap.hs view
@@ -5,7 +5,7 @@ , IterationResult(..) , run ) where-import Control.Monad(void, forM)+import Control.Monad(forM) import Data.Time.Calendar import Data.List.NonEmpty(fromList) @@ -81,7 +81,7 @@ i1 <- forM [depoSwapTS, depoFutSwapTS, depoFraSwapTS] (\ts -> valuateSwap settleDate ts ts) let market5YQuote = swapQuotes !! 2- void $ setValue market5YQuote 0.0460+ setValue market5YQuote 0.0460 i2 <- forM [depoSwapTS, depoFutSwapTS, depoFraSwapTS] (\ts -> valuateSwap settleDate ts ts)
test/hspec/QuantLib/Spec/CashFlow/FxReset.hs view
@@ -82,7 +82,7 @@ CF.fixingDependencies plain >>= \dependencies -> CF.fixingDependencies wrapped `shouldReturn` dependencies Context.collectGarbage CF.amount coupon >>= near 1e-10 (rawAmount * fx)- _ <- setValue spot 1.2+ setValue spot 1.2 CF.amount coupon >>= near 1e-10 (rawAmount * fx * 1.2 / 1.1) it "uses historical direct, inverse and triangulated exchange rates" $ Context.keepingSettingsGc $
test/hspec/QuantLib/Spec/Commodity.hs view
@@ -75,7 +75,7 @@ pt <- paymentTerm "Trade + 2 days" TradeDate 2 cal let d = 3 `january` 2024 expected <- adjust cal (addDays 2 d) Following- paymentTermGetPaymentDate pt d `shouldReturn` expected+ paymentTermPaymentDate pt d `shouldReturn` expected describe "Quantity" $ do it "rounds the amount per the unit of measure's rounding convention, unit/type unchanged" $ do
test/hspec/QuantLib/Spec/Credit.hs view
@@ -2,8 +2,9 @@ import Control.Monad(forM, forM_, unless) import Test.Hspec+import Data.List(isInfixOf, uncons) import Data.List.NonEmpty(fromList)-import Data.Time.Calendar(fromGregorian, addDays, addGregorianYearsClip)+import Data.Time.Calendar(Day, fromGregorian, addDays, addGregorianYearsClip) import QuantLib.Currency(currency, Ccy(..)) import QuantLib.Time.Calendar(calendar, adjust, CalendarConstructor(..), BusinessDayConvention(..))@@ -11,8 +12,8 @@ import qualified QuantLib.Time.Schedule as Schedule import QuantLib.InterestRate(Compounding(..)) import QuantLib.Math(Interpolation(..))-import QuantLib.Quote(simpleQuote, setValue)-import QuantLib.TermStructure(allowsExtrapolation)+import QuantLib.Quote(SimpleQuote, simpleQuote, setValue)+import QuantLib.TermStructure(allowsExtrapolation, referenceDate, setExtrapolation, maxDate) import QuantLib.TermStructure.Credit import QuantLib.TermStructure.Yield(flatForward, interpolatedDiscountCurve) import QuantLib.Instrument(setPricingEngine, PricingModel(..))@@ -24,14 +25,189 @@ import QuantLib.Spec.Helpers(closePrec, quantLibAtMost143, unsupportedQuantLib144) -- |Builds a small pool/basket/Gaussian-LHP-loss-model chain and checks the loss model actually--- wired up -- 'basketNotional' alone can't tell (it's a plain constructor echo, computed before--- any loss model is consulted), so the discriminating check is 'basketExpectedTrancheLoss', which+-- wired up -- 'notional' alone can't tell (it's a plain constructor echo, computed before+-- any loss model is consulted), so the discriminating check is 'expectedTrancheLoss', which -- throws if no loss model is attached. Fixture shape follows -- ~/Src/QuantLib/test-suite/cdo.cpp (an EUR corporate default key, a single shared flat hazard -- curve, five equal-notional names); numeric golden-value coverage against that fixture is -- the 'SyntheticCDO' test below. spec :: Spec spec = do+ describe "conditional survival views" $ do+ it "retains native survival, density and hazard geometry for every shift family" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ day n = addDays (365 * n) ref+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (ReferenceDate ref) q dc+ s1 <- simpleQuote 0.001+ s2 <- simpleQuote 0.003+ forM_ [ParallelHazardShift s1, RelativeHazardShift s2,+ KeyRateHazardShifts (fromList [(day 1,s1), (day 3,s2), (day 5,s1)]),+ BucketHazardShifts (fromList [(day 1,s1), (day 3,s2)])] $ \shift -> do+ original <- shiftedHazardRateCurve base shift+ view <- conditionalSurvivalCurve original (day 1)+ referenceDate view `shouldReturn` day 1+ originalMaximum <- maxDate original+ maxDate view `shouldReturn` originalMaximum+ normalization <- survivalProbability original (DatePoint (day 1)) False+ forM_ [day 1,day 2,day 4,day 6] $ \target -> do+ originalSurvival <- survivalProbability original (DatePoint target) False+ survivalProbability view (DatePoint target) False >>= (`shouldSatisfy` closePrec (originalSurvival / normalization) 1e-13)+ density <- defaultDensity original (DatePoint target) False+ defaultDensity view (DatePoint target) False >>= (`shouldSatisfy` closePrec (density / normalization) 1e-13)+ hazard <- hazardRate original (DatePoint target) False+ hazardRate view (DatePoint target) False >>= (`shouldSatisfy` closePrec hazard 1e-13)++ it "keeps analytic accumulated bucket survival on the translated clock" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ day n = addDays (365 * n) ref+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (ReferenceDate ref) q dc+ s1 <- simpleQuote 0.001+ s2 <- simpleQuote 0.003+ original <- shiftedHazardRateCurve base (BucketHazardShifts (fromList [(day 1,s1), (day 3,s2)]))+ view <- conditionalSurvivalCurve original (day 1)+ survivalProbability view (TimePoint 0) False `shouldReturn` 1+ survivalProbability view (TimePoint 2) False >>= (`shouldSatisfy` closePrec (exp (-0.046)) 1e-14)+ survivalProbability view (TimePoint 3) False >>= (`shouldSatisfy` closePrec (exp (-0.066)) 1e-14)+ hazardRate view (TimePoint 0) False >>= (`shouldSatisfy` closePrec 0.023 1e-14)+ hazardRate view (TimePoint 2) False >>= (`shouldSatisfy` closePrec 0.02 1e-14)++ it "owns its original curve and observes live quote changes after GC" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ s <- simpleQuote 0.001+ view <- do+ base <- flatHazardRate (ReferenceDate ref) q dc+ shifted <- shiftedHazardRateCurve base (KeyRateHazardShifts (fromList [(addDays 730 ref,s)]))+ conditionalSurvivalCurve shifted (addDays 365 ref)+ Context.collectGarbage+ setValue q 0.03+ setValue s 0.002+ survivalProbability view (TimePoint 2) False >>= (`shouldSatisfy` closePrec (exp (-0.064)) 1e-14)++ it "preserves extrapolation permission and rejects invalid reference normalizations" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ has message e = message `isInfixOf` show (e :: Context.Error)+ dc <- dayCounter Actual365FixedStandard+ cal <- calendar Null+ base <- interpolatedHazardRateCurve (fromList [(ref,0.02),(addDays 365 ref,0.02)]) dc cal+ ([] :: [(Day,SimpleQuote)]) Linear False+ conditionalSurvivalCurve base (addDays (-1) ref) `shouldThrow` has "must not precede"+ conditionalSurvivalCurve base (addDays 366 ref) `shouldThrow` has "within the original curve support"+ view <- conditionalSurvivalCurve base (addDays 180 ref)+ allowsExtrapolation view `shouldReturn` False+ survivalProbability view (TimePoint 2) False `shouldThrow` has "past max curve time"+ setExtrapolation base True+ extrapolated <- conditionalSurvivalCurve base (addDays 180 ref)+ allowsExtrapolation extrapolated `shouldReturn` True+ survivalProbability extrapolated (TimePoint 2) False >>= (`shouldSatisfy` closePrec (exp (-0.04)) 1e-14)+ q <- simpleQuote 1.0e6+ zeroSurvival <- flatHazardRate (ReferenceDate ref) q dc+ conditionalSurvivalCurve zeroSurvival (addDays 365 ref) `shouldThrow` has "normalization must be positive and finite"+ setValue q 0.02+ updated <- conditionalSurvivalCurve zeroSurvival (addDays 365 ref)+ setValue q 1.0e6+ hazardRate updated (TimePoint 1) False `shouldThrow` has "normalization must be positive and finite"+ jump <- simpleQuote 0.9+ withJump <- interpolatedHazardRateCurve (fromList [(ref,0.02),(addDays 730 ref,0.02)]) dc cal+ [(addDays 365 ref,jump)] Linear False+ conditionalSurvivalCurve withJump (addDays 180 ref) `shouldThrow` has "scheduled-jump metadata"++ describe "live hazard shift shapes" $ do+ it "keeps parallel and relative shifts on the native wrappers" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (ReferenceDate ref) q dc+ s <- simpleQuote 0.001+ parallelCurve <- shiftedHazardRateCurve base (ParallelHazardShift s)+ relative <- shiftedHazardRateCurve base (RelativeHazardShift s)+ hazardRate parallelCurve (TimePoint 2) False `shouldReturn` 0.021+ hazardRate relative (TimePoint 2) False `shouldReturn` (0.02 * 1.001)+ let quadratureScale = pi / (96 * sin (pi / 96))+ survivalProbability parallelCurve (TimePoint 2) False >>= (`shouldSatisfy` closePrec (exp (-0.042 * quadratureScale)) 1e-14)++ it "integrates linear shifts exactly and observes base and node quotes after GC" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ day n = addDays (365 * n) ref+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (ReferenceDate ref) q dc+ s1 <- simpleQuote 0.001+ s2 <- simpleQuote 0.003+ curve <- shiftedHazardRateCurve base (KeyRateHazardShifts (fromList [(day 1,s1), (day 3,s2), (day 5,s1)]))+ Context.collectGarbage+ forM_ [(0,0.021), (0.5,0.021), (1,0.021), (2,0.022), (3,0.023), (4,0.022), (7,0.021)] $ \(t,h) ->+ hazardRate curve (TimePoint t) False >>= (`shouldSatisfy` closePrec h 1e-14)+ survivalProbability curve (TimePoint 2) False >>= (`shouldSatisfy` closePrec (exp (-0.0425)) 1e-14)+ survivalProbability curve (TimePoint 6) False >>= (`shouldSatisfy` closePrec (exp (-0.13)) 1e-14)+ setValue s2 0.001+ hazardRate curve (TimePoint 2) False >>= (`shouldSatisfy` closePrec 0.021 1e-14)+ setValue q 0.03+ survivalProbability curve (TimePoint 2) False >>= (`shouldSatisfy` closePrec (exp (-0.062)) 1e-14)++ it "gives shared boundaries to the next bucket and retains accumulated survival" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ day n = addDays (365 * n) ref+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (ReferenceDate ref) q dc+ s1 <- simpleQuote 0.001+ s2 <- simpleQuote 0.003+ curve <- shiftedHazardRateCurve base (BucketHazardShifts (fromList [(day 1,s1), (day 3,s2)]))+ forM_ [(0,0.021), (0.999,0.021), (1,0.023), (2.999,0.023), (3,0.02), (4,0.02)] $ \(t,h) ->+ hazardRate curve (TimePoint t) False >>= (`shouldSatisfy` closePrec h 1e-14)+ survivalProbability curve (TimePoint 4) False >>= (`shouldSatisfy` closePrec (exp (-0.087)) 1e-14)+ left <- survivalProbability curve (TimePoint (1 - 1e-10)) False+ right <- survivalProbability curve (TimePoint (1 + 1e-10)) False+ abs (left - right) `shouldSatisfy` (< 1e-10)+ setValue s1 (-0.02)+ setValue s2 (-0.02)+ forM_ [0.002,0.017,0.02,0.5,1,2] $ \t -> do+ hazardRate curve (TimePoint t) False `shouldReturn` 0+ probability <- survivalProbability curve (TimePoint t) False+ probability `shouldSatisfy` (\x -> x <= 1 && closePrec 1 1e-15 x)++ it "refreshes grid times when the underlying reference date moves" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ Context.setEvaluationDate (Just ref)+ cal <- calendar Null+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (SettlementDays 0 cal) q dc+ s1 <- simpleQuote 0.001+ s2 <- simpleQuote 0.003+ let start = addDays 365 ref+ end = addDays 1095 ref+ curve <- shiftedHazardRateCurve base (KeyRateHazardShifts (fromList [(start,s1), (end,s2)]))+ hazardRate curve (DatePoint start) False >>= (`shouldSatisfy` closePrec 0.021 1e-14)+ Context.setEvaluationDate (Just (addDays 30 ref))+ hazardRate curve (DatePoint start) False >>= (`shouldSatisfy` closePrec 0.021 1e-14)+ hazardRate curve (DatePoint end) False >>= (`shouldSatisfy` closePrec 0.023 1e-14)++ it "rejects invalid grids, non-finite operands and negative hazards" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ end = addDays 365 ref+ has message e = message `isInfixOf` show (e :: Context.Error)+ dc <- dayCounter Actual365FixedStandard+ q <- simpleQuote 0.02+ base <- flatHazardRate (ReferenceDate ref) q dc+ s <- simpleQuote (-0.03)+ shiftedHazardRateCurve base (KeyRateHazardShifts (fromList [(ref,s)])) `shouldThrow` has "after the reference date"+ shiftedHazardRateCurve base (BucketHazardShifts (fromList [(end,s), (end,s)])) `shouldThrow` has "after the reference date"+ parallelCurve <- shiftedHazardRateCurve base (ParallelHazardShift s)+ hazardRate parallelCurve (TimePoint 0.5) False `shouldThrow` has "nonnegative"+ survivalProbability parallelCurve (TimePoint 2) False `shouldThrow` has "nonnegative"+ curve <- shiftedHazardRateCurve base (BucketHazardShifts (fromList [(end,s)]))+ hazardRate curve (TimePoint 0.5) False `shouldThrow` has "nonnegative"+ survivalProbability curve (TimePoint 2) False `shouldThrow` has "nonnegative"+ setValue s (1/0)+ hazardRate curve (TimePoint 0.5) False `shouldThrow` has "spreads must be finite"+ describe "portfolio credit scaffolding (Pool, Issuer, Basket, GaussianLHPLossModel)" $ do it "wires a basket to a Gaussian LHP loss model over a small pool" $ Context.keepingSettingsGc $ do let refDate = fromGregorian 2006 8 31@@ -54,12 +230,12 @@ b <- basket refDate (fromList [(n, notionalPerName) | n <- names]) p 0.0 1.0 FaceValue lossModel - notional <- basketNotional (trancheBasketAsBasket b)- notional `shouldBe` notionalPerName * fromIntegral (length names)+ total <- notional (trancheBasketAsBasket b)+ total `shouldBe` notionalPerName * fromIntegral (length names) let futureDate = addGregorianYearsClip 5 refDate- etl <- basketExpectedTrancheLoss b futureDate- etl `shouldSatisfy` (\x -> x > 0 && x < notional)+ etl <- expectedTrancheLoss b futureDate+ etl `shouldSatisfy` (\x -> x > 0 && x < total) -- Ports test-suite/cdo.cpp's testHW, data set 1 only (corr=0.1, the "gaussian" branch of -- hwData7): a 100-name pool, the Gaussian LHP loss model (the only loss model hasquant@@ -182,7 +358,7 @@ gaussCorrelQuote <- simpleQuote 0.0 gaussNtds <- buildNtds gaussCorrelQuote mapM_ (\(j, corr) -> do- _ <- setValue gaussCorrelQuote corr+ setValue gaussCorrelQuote corr mapM_ (\(rank, spreads) -> do fair <- (* 1e4) <$> ntdFairPremium (gaussNtds !! (rank - 1)) let expected = spreads !! j@@ -240,25 +416,25 @@ bb = trancheBasketAsBasket b -- No default has been recorded on the pool, so the live notional never drops.- full <- basketNotional bb- remaining <- basketRemainingNotional bb futureDate+ full <- notional bb+ remaining <- remainingNotional bb futureDate remaining `shouldBe` full -- GaussianLHPLossModel's expectedRecovery is just the recovery quote passed in.- rr <- basketRecoveryRate bb futureDate 0+ rr <- recoveryRate bb futureDate 0 rr `shouldSatisfy` closePrec recovery 1.0e-12 -- Certain to lose at least 0% of the tranche.- p0 <- basketProbOverLoss b futureDate 0.0+ p0 <- probOverLoss b futureDate 0.0 p0 `shouldSatisfy` closePrec 1.0 1.0e-6 -- percentile is a monotone non-decreasing function of its probability argument.- pctLo <- basketPercentile b futureDate 0.5- pctHi <- basketPercentile b futureDate 0.95+ pctLo <- percentile b futureDate 0.5+ pctHi <- percentile b futureDate 0.95 pctLo `shouldSatisfy` (<= pctHi) -- expected shortfall past a percentile is never below that percentile itself.- es <- basketExpectedShortfall b futureDate 0.95+ es <- expectedShortfall b futureDate 0.95 es `shouldSatisfy` (>= pctHi) -- Reuses the nth-to-default Gaussian fixture (10 names, correlation 0.3) to check@@ -291,16 +467,16 @@ let futureDate = addGregorianYearsClip 5 refDate -- Self-correlation is always 1 (E[1_i*1_i] = p_i, per the closed form).- selfCorr <- basketDefaultCorrelation b futureDate 0 0+ selfCorr <- defaultCorrelation b futureDate 0 0 selfCorr `shouldSatisfy` closePrec 1.0 1.0e-9 -- Certain to have at least 0 defaults.- p0 <- basketProbAtLeastNEvents b 0 futureDate+ p0 <- probAtLeastNEvents b 0 futureDate p0 `shouldSatisfy` closePrec 1.0 1.0e-6 -- probAtLeastNEvents is non-increasing in n.- p1 <- basketProbAtLeastNEvents b 1 futureDate- p2 <- basketProbAtLeastNEvents b 2 futureDate+ p1 <- probAtLeastNEvents b 1 futureDate+ p2 <- probAtLeastNEvents b 2 futureDate (p0 >= p1 && p1 >= p2) `shouldBe` True describe "default-probability curves" $ do@@ -456,6 +632,39 @@ setPricingEngine cds engine computed <- fairSpread cds computed `shouldSatisfy` closePrec quotedSpread 1.0e-6+ -- the interpolated curve of the bootstrap's trait on its nodes is the same curve+ nodes <- bootstrappedNodes curve+ map fst nodes `shouldSatisfy` ((== Just refDate) . fmap fst . uncons)+ length nodes `shouldBe` length spreads + 1+ rebuilt <- case trait of+ HazardRate -> interpolatedHazardRateCurve (fromList nodes) helperDc cal [] interpolation False+ DefaultDensity -> interpolatedDefaultDensityCurve (fromList nodes) helperDc cal [] interpolation False+ SurvivalProbability -> interpolatedSurvivalProbabilityCurve (fromList nodes) helperDc cal [] interpolation False+ forM_ [addDays k refDate | k <- [0, 45, 365, 400, 1000, 1825]] $ \d -> do+ expected <- survivalProbability curve (DatePoint d) False+ survivalProbability rebuilt (DatePoint d) False >>= (`shouldBe` expected)++ it "reconstructs default nodes with their separate jump factors" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2015 6 15+ Context.setEvaluationDate (Just ref)+ cal <- calendar TARGET+ dc <- dayCounter Actual365FixedStandard+ discountQuote <- simpleQuote 0.03+ nominal <- flatForward (ReferenceDate ref) discountQuote dc Continuous Annual+ helpers <- forM [1,2,3,5] $ \n -> do+ q <- simpleQuote 0.02+ spreadCdsHelper q (n, Years) 1 cal Quarterly Following TwentiethIMM dc 0.4 nominal True True Nothing dc True Midpoint Nothing+ jump <- simpleQuote 0.995+ let jumps = [(addDays 550 ref, jump)]+ curve <- piecewiseDefaultCurve (ReferenceDate ref) (fromList helpers) dc jumps HazardRate BackwardFlat defaultIterativeBootstrapOpts False+ nodes <- bootstrappedNodes curve+ rebuilt <- interpolatedHazardRateCurve (fromList nodes) dc cal jumps BackwardFlat False+ omitted <- interpolatedHazardRateCurve (fromList nodes) dc cal [] BackwardFlat False+ forM_ ([365,550,551,730] :: [Integer]) $ \n -> do+ expected <- survivalProbability curve (DatePoint (addDays n ref)) False+ survivalProbability rebuilt (DatePoint (addDays n ref)) False >>= (`shouldSatisfy` closePrec expected 1e-6)+ expected <- survivalProbability curve (TimePoint 2) False+ survivalProbability omitted (TimePoint 2) False >>= (\x -> abs (x - expected) `shouldSatisfy` (> 0.001)) it "supports retry/fallback settings for a distressed inverted spread curve" $ Context.keepingSettingsGc $ do let asof = fromGregorian 2020 4 1
test/hspec/QuantLib/Spec/Examples.hs view
@@ -118,7 +118,7 @@ sch <- schedule (Just issue) maturity (1, Years) c Unadjusted Unadjusted Backward False Nothing Nothing b <- B.fixedRateBond 2 1000 sch [0.05] dc Following 100 (Just issue) c (0, Days) c Unadjusted False dc- B.maturityDate b `shouldReturn` Just (fromGregorian 2013 1 1)+ B.maturityDate b `shouldReturn` fromGregorian 2013 1 1 describe "Amortizing bonds" $ do it "AmortizingFixedRateBond reproduces upstream's sinking-fund pmt values" $ do
test/hspec/QuantLib/Spec/Index/Commodity.hs view
@@ -21,7 +21,7 @@ usd <- commoditySettingsCurrency cal <- calendar TARGET idx <- CommodityIndex.commodityIndex "HO empty index" ho usd bbl cal 1000 Nothing- CommodityIndex.isEmpty idx `shouldBe` True+ CommodityIndex.isEmpty idx `shouldReturn` True it "forecasts a forward price from a forward curve" $ do ho <- commodityType "HO" "Heating Oil"@@ -44,7 +44,7 @@ let d0 = 2 `january` 2024 -- a TARGET business day (Jan 1st is a holiday) bracket_ (clearFixings idx) (clearFixings idx) $ do addFixing idx d0 72.5 False- CommodityIndex.isEmpty idx `shouldBe` False+ CommodityIndex.isEmpty idx `shouldReturn` False CommodityIndex.lastQuoteDate idx `shouldReturn` d0 fixing idx d0 False `shouldReturn` 72.5
test/hspec/QuantLib/Spec/Index/Inflation.hs view
@@ -16,7 +16,7 @@ -- A date decades before the availability lag can only be served from a stored fixing. needsForecast idx (fromGregorian 1990 1 1) `shouldReturn` False yoy <- yoyInflationIndexFromZero idx Nothing- yoyNeedsForecast yoy (fromGregorian 1990 1 1) `shouldReturn` False+ needsForecast yoy (fromGregorian 1990 1 1) `shouldReturn` False -- The constructors accept any Frequency, but needsForecast reaches inflationPeriod, which -- QL_FAILs outside Annual..Monthly. Nothing on the Haskell side constrains the frequency, so@@ -26,7 +26,7 @@ idx <- unsupportedIndex needsForecast idx (fromGregorian 1990 1 1) `shouldThrow` anyException yoy <- yoyInflationIndexFromZero idx Nothing- yoyNeedsForecast yoy (fromGregorian 1990 1 1) `shouldThrow` anyException+ needsForecast yoy (fromGregorian 1990 1 1) `shouldThrow` anyException where mkIndex freq = do uk <- region UKRegion
test/hspec/QuantLib/Spec/Instrument/Forward.hs view
@@ -61,7 +61,7 @@ let sourceNominal = 100.0 targetNominal = 112.34 fwd <- fxForward sourceNominal usd targetNominal eur maturity True 2 cal- let r = fxForwardRate fwd+ r <- fxForwardRate fwd r `shouldSatisfy` closePrec (targetNominal / sourceNominal) 1e-12 -- vim: set ft=haskell ff=unix ts=8 sts=2 sw=2 et:
test/hspec/QuantLib/Spec/Instrument/InflationCapFloor.hs view
@@ -36,7 +36,7 @@ -- same globally shared index-name fixing store -- QuantLib's fixing store is keyed by index -- name, and hspec runs specs in random order, so any shared name is a latent cross-test -- conflict.-customYoYIndex :: Maybe YoYInflationTermStructure -> IO YoYInflationIndex+customYoYIndex :: Maybe (GenYoYInflationTermStructure y) -> IO YoYInflationIndex customYoYIndex mts = do gbp <- currency GBP r <- customRegion "InflationCapFloor Test" "ICFT"
test/hspec/QuantLib/Spec/Instrument/MtmCrossCurrency.hs view
@@ -1,10 +1,9 @@ module QuantLib.Spec.Instrument.MtmCrossCurrency (spec) where -import Control.Monad(forM, forM_, void)+import Control.Monad(forM, forM_) import qualified Data.List.NonEmpty as NE import QuantLib.Math(Interpolation(..)) import Data.Time.Calendar(Day, fromGregorian, addGregorianYearsClip)-import qualified Data.Vector.Storable as V import Test.Hspec import qualified QuantLib.Context as Context import QuantLib.Time.Calendar@@ -67,19 +66,19 @@ npv par >>= near 0.02 0 rates <- fxResetRates payer notionals <- fxResetNotionals payer- V.length rates `shouldBe` 20- V.length notionals `shouldBe` V.length rates+ length rates `shouldBe` 20+ length notionals `shouldBe` length rates let notional = if resetBase then 10000000 / 1.1 else 10000000- forM_ (zip (V.toList rates) (V.toList notionals)) $ \(rate, nominal) -> near 1e-6 (notional * rate) nominal+ forM_ (zip rates notionals) $ \(rate, nominal) -> near 1e-6 (notional * rate) nominal _ <- legCurrency payer 0 inCcyLegNpv payer 0 >>= (`shouldSatisfy` (\v -> not (isNaN v || isInfinite v))) inCcyLegBps payer 1 >>= (`shouldSatisfy` (/= 0)) npvDateDiscounts payer 0 `shouldReturn` 1 fxResetRates payer >>= \old -> do- _ <- setValue spot 1.2+ setValue spot 1.2 changed <- fxResetRates payer changed `shouldSatisfy` (/= old)- void (setValue spot 1.1)+ setValue spot 1.1 it "projects resets at value dates and respects spot settlement overrides" $ Context.keepingSettingsGc $ do let today = fromGregorian 2024 7 1@@ -113,7 +112,7 @@ eurStartDf <- discount eurCurve (DatePoint start) False usdStartDf <- discount usdCurve (DatePoint start) False rates <- fxResetRates swap- case V.toList rates of+ case rates of first:_ -> near 1e-10 (1.1 * usdSpotDf / eurSpotDf * eurStartDf / usdStartDf) first [] -> expectationFailure "no FX reset rates" explicit <- discountingMtmCrossCurrencyBasisSwapEngine usd usdCurve eur eurCurve spot Nothing Nothing Nothing (Just valueDate)@@ -145,8 +144,9 @@ quote <- simpleQuote basis mtmCrossCurrencyBasisSwapRateHelper quote (years, Years) 2 cal Following False eurIndex usdIndex collateral collateralBase basisBase resetBase Nothing 0 Nothing 2 (Just cal) Nothing Nothing Nothing- curve <- piecewiseYieldCurve (ReferenceDate today) (NE.fromList helpers) dc []+ piecewise <- piecewiseYieldCurve (ReferenceDate today) (NE.fromList helpers) dc [] (Iterative Discount LogLinear defaultIterativeBootstrapOpts) True+ curve <- asYieldTermStructure piecewise let eurDiscount = if collateralBase then eurForecast else curve usdDiscount = if collateralBase then curve else usdForecast engine <- discountingMtmCrossCurrencyBasisSwapEngine usd usdDiscount eur eurDiscount spot Nothing Nothing Nothing Nothing
test/hspec/QuantLib/Spec/InterestRateAndCashFlow.hs view
@@ -302,7 +302,7 @@ indexed <- CF.indexedCashFlow 100.0 idx baseDate fixingDate' paymentDate False growth <- CF.indexedCashFlow 100.0 idx baseDate fixingDate' paymentDate True CF.amount simple `shouldReturn` 10.0- CF.date simple `shouldBe` paymentDate+ CF.date simple `shouldReturn` paymentDate CF.baseFixing indexed >>= (`shouldSatisfy` closePrec 100.0 1.0e-12) CF.indexFixing indexed >>= (`shouldSatisfy` closePrec 120.0 1.0e-12) fixedCoupon <- CF.fixedRateCoupon accrualEnd 100.0 0.05 dc paymentDate accrualEnd Nothing Nothing Nothing@@ -365,7 +365,7 @@ zeroAmount <- CF.amount zero cpiAmount <- CF.amount cpi equityAmount <- CF.amount equity- CF.date equity `shouldBe` paymentDate+ CF.date equity `shouldReturn` paymentDate CF.baseFixing equity >>= (`shouldSatisfy` closePrec 80.0 1.0e-12) CF.indexFixing equity >>= (`shouldSatisfy` closePrec 100.0 1.0e-12) listCloseRel id [120.0, 120.0, 125.0] 1.0e-12 [zeroAmount, cpiAmount, equityAmount] `shouldBe` True@@ -437,8 +437,7 @@ price `shouldSatisfy` closePrec (amount * disc) 1e-10 -- No CMS-style timing adjustment applies to a plain Ibor coupon.- convexityAdjustment <- CF.convexityAdjustment coupon- convexityAdjustment `shouldSatisfy` closePrec 0.0 1e-12+ CF.convexityAdjustment coupon >>= (`shouldSatisfy` closePrec 0.0 1e-12) -- Caplet/floorlet put-call parity at a common effective strike: the price difference -- must equal the (undiscounted) intrinsic value of the underlying swaplet relative to@@ -862,17 +861,12 @@ strippedRate <- CF.rate stripped (cappedRate + strippedRate) `shouldSatisfy` closePrec plainRate 1.0e-10 - let isCap = CF.isCap stripped- isFloor = CF.isFloor stripped- isCollar = CF.isCollar stripped- isCap `shouldBe` True- isFloor `shouldBe` False- isCollar `shouldBe` False+ CF.isCap stripped `shouldReturn` True+ CF.isFloor stripped `shouldReturn` False+ CF.isCollar stripped `shouldReturn` False - let cap' = CF.capRate stripped- effCap = CF.effectiveCap stripped- cap' `shouldBe` capStrike- effCap `shouldBe` capStrike+ CF.capRate stripped `shouldReturn` capStrike+ CF.effectiveCap stripped `shouldReturn` capStrike -- Ported from test-suite/overnightindexedcoupon.cpp's 'CommonVars' fixture: a SOFR index -- seeded with two blocks of real historical fixings (Jun-Aug 2019, Oct-Nov 2021), default@@ -954,6 +948,12 @@ length dates' `shouldSatisfy` (> 0) expected <- mapM (\d -> fixing sofr d False) dates' fixings `shouldBe` expected+ fractions <- CF.fixingAccrualFractions pastCoupon+ let ends = drop 1 dates' ++ [18 `november` 2021]+ expectedFractions = [fromIntegral (diffDays end start) / 360 | (start, end) <- zip dates' ends]+ fractions `shouldBe` expectedFractions+ product (zipWith (\r dt -> 1 + r * dt) fixings expectedFractions) - 1+ `shouldSatisfy` closePrec (0.000987136104 * 31 / 360) 1e-12 it "AverageBMACoupon fixingDates/indexFixings agree with the coupon's own seeded fixings" $ bracket_ clearAllFixingHistories clearAllFixingHistories $ Context.keepingSettingsGc $ do@@ -1184,7 +1184,7 @@ end = addGregorianMonthsClip 6 start spread = 0.001 sch <- mrSchedule cal start end- let fixingDaysN = Ibor.fixingDays euribor+ fixingDaysN <- Ibor.fixingDays euribor subs <- mrExpected cal dc euribor fixingDaysN spread sch let expected = product [1 + a * r | (r, a) <- subs] - 1 @@ -1193,6 +1193,10 @@ Nothing Nothing dc Nothing fixingDates <- CF.fixingDates testCpn length fixingDates `shouldBe` length subs+ fractions <- CF.fixingAccrualFractions testCpn+ length fractions `shouldBe` length subs+ and (zipWith (`closePrec` 1e-12) (map snd subs) fractions)+ `shouldBe` True pricer <- CF.compoundingMultipleResetsPricer CF.setFloatingRateCouponPricer testCpn pricer actual <- CF.amount testCpn@@ -1210,7 +1214,7 @@ end = addGregorianMonthsClip 6 start spread = 0.001 sch <- mrSchedule cal start end- let fixingDaysN = Ibor.fixingDays euribor+ fixingDaysN <- Ibor.fixingDays euribor subs <- mrExpected cal dc euribor fixingDaysN spread sch let expected = sum [a * r | (r, a) <- subs] @@ -1262,10 +1266,15 @@ -- than against a golden value, since both entry points must agree to FP precision on the -- exact same fixture. describe "cash flow analytics" $ do- let mkFixedLeg = do+ let -- one regular period spanning today: a start of today less 2 months would be a day off+ -- the end's backward roll whenever the end clips to a shorter month (an end on Feb 28+ -- rolls back to Aug 28, not Aug 29), and make the coupon an irregular stub+ mkSchedule td cal = let end = addGregorianMonthsClip 4 td in+ schedule (Just $ addGregorianMonthsClip (-6) end) end (6, Months) cal Unadjusted Unadjusted Backward False Nothing Nothing+ mkFixedLeg = do td <- Context.evaluationDate cal <- calendar TARGET- sch <- schedule (Just $ addGregorianMonthsClip (-2) td) (addGregorianMonthsClip 4 td) (6, Months) cal Unadjusted Unadjusted Backward False Nothing Nothing+ sch <- mkSchedule td cal dc <- dayCounter (Actual360 False) cpn <- IR.interestRate 0.03 dc IR.Simple Annual l <- CF.fixedRateLeg sch [100.0] [cpn] Following dc cal@@ -1377,7 +1386,7 @@ atm <- CF.atmRate l curve False Nothing Nothing n1 cal <- calendar TARGET- sch2 <- schedule (Just $ addGregorianMonthsClip (-2) td) (addGregorianMonthsClip 4 td) (6, Months) cal Unadjusted Unadjusted Backward False Nothing Nothing+ sch2 <- mkSchedule td cal cpnAtm <- IR.interestRate atm dc IR.Simple Annual lAtm <- CF.fixedRateLeg sch2 [100.0] [cpnAtm] Following dc cal nAtm <- CF.npv lAtm (CF.DiscountingCurve curve) False Nothing Nothing@@ -1477,8 +1486,8 @@ it "direct cappedFlooredCmsCoupon agrees between numerical and analytic Hagan pricers" $ Context.keepingSettingsGc $ do (_, dc, _, atmVol, meanRevQ, _, swapIdx, startDate, endDate) <- mkFixture- let fixingDays = Ibor.fixingDays swapIdx- coupon = CF.cappedFlooredCmsCoupon endDate 1.0 startDate endDate fixingDays swapIdx+ fixingDays <- Ibor.fixingDays swapIdx+ let coupon = CF.cappedFlooredCmsCoupon endDate 1.0 startDate endDate fixingDays swapIdx 1.0 0.0 Nothing Nothing (Just startDate) (Just endDate) dc False Nothing Preceding numerical <- CF.numericHaganPricer atmVol CF.NonParallelShifts meanRevQ 0.0 1.0 1.0e-6 1.0e100 couponNumerical <- coupon@@ -1497,8 +1506,8 @@ it "direct capped/floored CMS coupons satisfy put-call parity" $ Context.keepingSettingsGc $ do (_, dc, _, atmVol, meanRevQ, _, swapIdx, startDate, endDate) <- mkFixture- let fixingDays = Ibor.fixingDays swapIdx- strike = 0.03+ fixingDays <- Ibor.fixingDays swapIdx+ let strike = 0.03 coupon mCap mFloor = CF.cappedFlooredCmsCoupon endDate 1.0 startDate endDate fixingDays swapIdx 1.0 0.0 mCap mFloor (Just startDate) (Just endDate) dc False Nothing Preceding priced mCap mFloor = do@@ -1518,8 +1527,8 @@ Context.keepingSettingsGc $ do (cal, dc, curve, atmVol, meanRevQ, _, swapIdx, startDate, endDate) <- mkFixture pricer <- CF.analyticHaganPricer atmVol CF.NonParallelShifts meanRevQ- let fixingDays = Ibor.fixingDays swapIdx- coupon = CF.cmsCoupon endDate 1.0 startDate endDate fixingDays swapIdx+ fixingDays <- Ibor.fixingDays swapIdx+ let coupon = CF.cmsCoupon endDate 1.0 startDate endDate fixingDays swapIdx 1.0 0.0 Nothing Nothing dc False Nothing Preceding plain <- coupon CF.setFloatingRateCouponPricer plain pricer
test/hspec/QuantLib/Spec/Model.hs view
@@ -514,7 +514,8 @@ Context.setEvaluationDate (Just evalDate) dc <- dayCounter (Actual360 False) emptyIndex <- IR.iborIndex IR.Euribor6M Nothing- firstPillar <- advance cal evalDate (fromIntegral (IR.fixingDays emptyIndex), Days) Following False+ fixDays <- IR.fixingDays emptyIndex+ firstPillar <- advance cal evalDate (fromIntegral fixDays, Days) Following False rTS <- interpolatedZeroCurve (fromList [(firstPillar, 0.039), (curveEndDate, 0.041)]) dc cal [] Linear idx <- IR.iborIndex IR.Euribor6M (Just rTS) process <- Process.liborForwardModelProcess size idx
test/hspec/QuantLib/Spec/Model/RoughHeston.hs view
@@ -90,7 +90,7 @@ case engines of engine:_ -> do priceBefore <- roughHestonPriceVanillaPayoff engine (PlainVanillaPayoff Call 100) (TimePoint 1)- _ <- setValue spot 110+ setValue spot 110 priceAfter <- roughHestonPriceVanillaPayoff engine (PlainVanillaPayoff Call 100) (TimePoint 1) priceAfter `shouldSatisfy` (> priceBefore) Model.setParams model [0.05, 0.4, 0.3, -0.6, 0.03, 0.2]
test/hspec/QuantLib/Spec/PricingEngine.hs view
@@ -1190,13 +1190,13 @@ optInst <- asOneAssetOption opt setPricingEngine optInst engine forM_ innerCases $ \(q, r, v, fxr, fxv, corr) -> do- _ <- setValue spotQ u- _ <- setValue qRateQ q- _ <- setValue rRateQ r- _ <- setValue volQ v- _ <- setValue fxRateQ fxr- _ <- setValue fxVolQ fxv- _ <- setValue corrQ corr+ setValue spotQ u+ setValue qRateQ q+ setValue rRateQ r+ setValue volQ v+ setValue fxRateQ fxr+ setValue fxVolQ fxv+ setValue corrQ corr val <- npv optInst when (val > u * 1.0e-5) $ do calcDelta <- delta optInst@@ -1210,46 +1210,46 @@ calcQlambda <- qlambda opt let du = u * 1.0e-4- _ <- setValue spotQ (u + du); valueP <- npv optInst; deltaP <- delta optInst- _ <- setValue spotQ (u - du); valueM <- npv optInst; deltaM <- delta optInst- _ <- setValue spotQ u+ setValue spotQ (u + du); valueP <- npv optInst; deltaP <- delta optInst+ setValue spotQ (u - du); valueM <- npv optInst; deltaM <- delta optInst+ setValue spotQ u let expDelta = (valueP - valueM) / (2 * du) expGamma = (deltaP - deltaM) / (2 * du) let dr = r * 1.0e-4- _ <- setValue rRateQ (r + dr); rValueP <- npv optInst- _ <- setValue rRateQ (r - dr); rValueM <- npv optInst- _ <- setValue rRateQ r+ setValue rRateQ (r + dr); rValueP <- npv optInst+ setValue rRateQ (r - dr); rValueM <- npv optInst+ setValue rRateQ r let expRho = (rValueP - rValueM) / (2 * dr) let dq = q * 1.0e-4- _ <- setValue qRateQ (q + dq); qValueP <- npv optInst- _ <- setValue qRateQ (q - dq); qValueM <- npv optInst- _ <- setValue qRateQ q+ setValue qRateQ (q + dq); qValueP <- npv optInst+ setValue qRateQ (q - dq); qValueM <- npv optInst+ setValue qRateQ q let expDivRho = (qValueP - qValueM) / (2 * dq) let dv = v * 1.0e-4- _ <- setValue volQ (v + dv); vValueP <- npv optInst- _ <- setValue volQ (v - dv); vValueM <- npv optInst- _ <- setValue volQ v+ setValue volQ (v + dv); vValueP <- npv optInst+ setValue volQ (v - dv); vValueM <- npv optInst+ setValue volQ v let expVega = (vValueP - vValueM) / (2 * dv) let dfxr = fxr * 1.0e-4- _ <- setValue fxRateQ (fxr + dfxr); fxrValueP <- npv optInst- _ <- setValue fxRateQ (fxr - dfxr); fxrValueM <- npv optInst- _ <- setValue fxRateQ fxr+ setValue fxRateQ (fxr + dfxr); fxrValueP <- npv optInst+ setValue fxRateQ (fxr - dfxr); fxrValueM <- npv optInst+ setValue fxRateQ fxr let expQrho = (fxrValueP - fxrValueM) / (2 * dfxr) let dfxv = fxv * 1.0e-4- _ <- setValue fxVolQ (fxv + dfxv); fxvValueP <- npv optInst- _ <- setValue fxVolQ (fxv - dfxv); fxvValueM <- npv optInst- _ <- setValue fxVolQ fxv+ setValue fxVolQ (fxv + dfxv); fxvValueP <- npv optInst+ setValue fxVolQ (fxv - dfxv); fxvValueM <- npv optInst+ setValue fxVolQ fxv let expQvega = (fxvValueP - fxvValueM) / (2 * dfxv) let dcorr = corr * 1.0e-4- _ <- setValue corrQ (corr + dcorr); corrValueP <- npv optInst- _ <- setValue corrQ (corr - dcorr); corrValueM <- npv optInst- _ <- setValue corrQ corr+ setValue corrQ (corr + dcorr); corrValueP <- npv optInst+ setValue corrQ (corr - dcorr); corrValueM <- npv optInst+ setValue corrQ corr let expQlambda = (corrValueP - corrValueM) / (2 * dcorr) dTyears <- yearFraction dc (addDays (-1) today') (addDays 1 today') Nothing Nothing@@ -1334,13 +1334,13 @@ optInst <- asOneAssetOption opt setPricingEngine optInst engine forM_ innerCases $ \(q, r, v, fxr, fxv, corr) -> do- _ <- setValue spotQ u- _ <- setValue qRateQ q- _ <- setValue rRateQ r- _ <- setValue volQ v- _ <- setValue fxRateQ fxr- _ <- setValue fxVolQ fxv- _ <- setValue corrQ corr+ setValue spotQ u+ setValue qRateQ q+ setValue rRateQ r+ setValue volQ v+ setValue fxRateQ fxr+ setValue fxVolQ fxv+ setValue corrQ corr val <- npv optInst when (val > u * 1.0e-5) $ do calcDelta <- delta optInst@@ -1354,46 +1354,46 @@ calcQlambda <- qlambda opt let du = u * 1.0e-4- _ <- setValue spotQ (u + du); valueP <- npv optInst; deltaP <- delta optInst- _ <- setValue spotQ (u - du); valueM <- npv optInst; deltaM <- delta optInst- _ <- setValue spotQ u+ setValue spotQ (u + du); valueP <- npv optInst; deltaP <- delta optInst+ setValue spotQ (u - du); valueM <- npv optInst; deltaM <- delta optInst+ setValue spotQ u let expDelta = (valueP - valueM) / (2 * du) expGamma = (deltaP - deltaM) / (2 * du) let dr = r * 1.0e-4- _ <- setValue rRateQ (r + dr); rValueP <- npv optInst- _ <- setValue rRateQ (r - dr); rValueM <- npv optInst- _ <- setValue rRateQ r+ setValue rRateQ (r + dr); rValueP <- npv optInst+ setValue rRateQ (r - dr); rValueM <- npv optInst+ setValue rRateQ r let expRho = (rValueP - rValueM) / (2 * dr) let dq = q * 1.0e-4- _ <- setValue qRateQ (q + dq); qValueP <- npv optInst- _ <- setValue qRateQ (q - dq); qValueM <- npv optInst- _ <- setValue qRateQ q+ setValue qRateQ (q + dq); qValueP <- npv optInst+ setValue qRateQ (q - dq); qValueM <- npv optInst+ setValue qRateQ q let expDivRho = (qValueP - qValueM) / (2 * dq) let dv = v * 1.0e-4- _ <- setValue volQ (v + dv); vValueP <- npv optInst- _ <- setValue volQ (v - dv); vValueM <- npv optInst- _ <- setValue volQ v+ setValue volQ (v + dv); vValueP <- npv optInst+ setValue volQ (v - dv); vValueM <- npv optInst+ setValue volQ v let expVega = (vValueP - vValueM) / (2 * dv) let dfxr = fxr * 1.0e-4- _ <- setValue fxRateQ (fxr + dfxr); fxrValueP <- npv optInst- _ <- setValue fxRateQ (fxr - dfxr); fxrValueM <- npv optInst- _ <- setValue fxRateQ fxr+ setValue fxRateQ (fxr + dfxr); fxrValueP <- npv optInst+ setValue fxRateQ (fxr - dfxr); fxrValueM <- npv optInst+ setValue fxRateQ fxr let expQrho = (fxrValueP - fxrValueM) / (2 * dfxr) let dfxv = fxv * 1.0e-4- _ <- setValue fxVolQ (fxv + dfxv); fxvValueP <- npv optInst- _ <- setValue fxVolQ (fxv - dfxv); fxvValueM <- npv optInst- _ <- setValue fxVolQ fxv+ setValue fxVolQ (fxv + dfxv); fxvValueP <- npv optInst+ setValue fxVolQ (fxv - dfxv); fxvValueM <- npv optInst+ setValue fxVolQ fxv let expQvega = (fxvValueP - fxvValueM) / (2 * dfxv) let dcorr = corr * 1.0e-4- _ <- setValue corrQ (corr + dcorr); corrValueP <- npv optInst- _ <- setValue corrQ (corr - dcorr); corrValueM <- npv optInst- _ <- setValue corrQ corr+ setValue corrQ (corr + dcorr); corrValueP <- npv optInst+ setValue corrQ (corr - dcorr); corrValueM <- npv optInst+ setValue corrQ corr let expQlambda = (corrValueP - corrValueM) / (2 * dcorr) dTyears <- yearFraction dc (addDays (-1) today') (addDays 1 today') Nothing Nothing@@ -1713,7 +1713,7 @@ rQ <- simpleQuote (0.0 :: Double) rTS <- flatForward (ReferenceDate today') rQ dc Continuous Annual forM_ cases $ \(barType, ty, barrier, strike, corr, r, expected) -> do- _ <- setValue rQ r+ setValue rQ r s1Q <- simpleQuote (100.0 :: Double) q1Q <- simpleQuote (0.0 :: Double) v1Q <- simpleQuote (0.2 :: Double)@@ -1994,7 +1994,7 @@ let exDate = addDays (round (0.5 * 360 :: Double)) evalDate eng <- mcAmericanBasketEngine PseudoRandom procArr (Just 52) Nothing False True (Just 10000) Nothing Nothing 1 (Just 2500) 2 Monomial forM_ rows $ \(s, expected, tol) -> do- _ <- setValue spot1 s+ setValue spot1 s let payoff = plainVanillaPayoff (PlainVanillaPayoff Put 100.0) basket = Max payoff opt <- basketOption basket (American (Just evalDate) exDate False)@@ -2097,12 +2097,12 @@ npv0 <- npv opt let eps = 1.0- _ <- setValue spot1 (s1 + eps)- _ <- setValue spot2 (s2 + eps)+ setValue spot1 (s1 + eps)+ setValue spot2 (s2 + eps) npvUp <- npv opt - _ <- setValue spot1 (s1 - eps)- _ <- setValue spot2 (s2 - eps)+ setValue spot1 (s1 - eps)+ setValue spot2 (s2 - eps) npvDown <- npv opt let expectedDelta = (npvUp - npvDown) / (2 * eps)@@ -2298,9 +2298,9 @@ fmap concat $ forM [0.0, 0.05, 0.2] $ \rate -> do- _ <- setValue rQ rate+ setValue rQ rate forM [75.0, 90.0, 100.0, 105.0, 175.0] $ \spot -> do- _ <- setValue s2Q spot+ setValue s2Q spot setPricingEngine opt fd2d fdNPV <- npv opt setPricingEngine opt kirk
test/hspec/QuantLib/Spec/Process.hs view
@@ -38,7 +38,7 @@ import QuantLib.Time.Schedule(dayCounter, yearFraction, DayCounterConstructor(..), Frequency(..), TimeUnit(..)) import QuantLib.InterestRate(Compounding(..), VolatilityType(..), rate) import QuantLib.Quote(simpleQuote, setValue)-import QuantLib.TermStructure.Yield(Reference(..), TermPoint(..), flatForward, forwardRateBetweenTimes, discount, YieldTermStructure, interpolatedZeroCurve)+import QuantLib.TermStructure.Yield(Reference(..), TermPoint(..), RateInterval(..), flatForward, forwardRate, discount, YieldTermStructure, interpolatedZeroCurve) import QuantLib.Instrument(npv, setPricingEngine) import QuantLib.Instrument.Option(europeanOption, impliedVolatility, StrikedPayoff(PlainVanilla), PlainVanillaPayoff(..), OptionType(..), Exercise(European), EuropeanExercise(..)) import qualified QuantLib.Process as Process@@ -74,6 +74,11 @@ it "accepts matching boxed and contiguous shapes, including an empty matrix" $ do fmap matrixData (boxedRealMatrix 2 2 [1, 2, 3, 4]) `shouldBe` Right [1, 2, 3, 4] fmap realMatrixData (realMatrixFromVector 0 0 V.empty) `shouldBe` Right V.empty+ it "preserves matrix Show output after making the inspectors ordinary functions" $ do+ fmap show (boxedRealMatrix 1 2 [1, 2]) `shouldBe`+ Right "Matrix {matrixRows = 1, matrixColumns = 2, matrixData = [1.0,2.0]}"+ fmap show (realMatrixFromVector 1 2 (V.fromList [1, 2])) `shouldBe`+ Right "RealMatrix {realMatrixRows = 1, realMatrixColumns = 2, realMatrixData = [1.0,2.0]}" it "rejects mismatched and overflowed shapes" $ do boxedRealMatrix 2 2 [1, 2, 3] `shouldBe` Left "Data length 3 does not match dimensions 2x2" realMatrixFromVector 2 2 (V.fromList [1, 2, 3]) `shouldBe` Left "Data length 3 does not match dimensions 2x2"@@ -234,13 +239,13 @@ Context.setEvaluationDate (Just evalDate) dc <- dayCounter (Actual360 False) emptyIndex <- iborIndex Euribor6M Nothing- firstPillar <- advance cal evalDate (fromIntegral (Ibor.fixingDays emptyIndex), Days) Following False+ firstPillar <- Ibor.fixingDays emptyIndex >>= \n -> advance cal evalDate (fromIntegral n, Days) Following False rTS <- interpolatedZeroCurve (fromList [(firstPillar, 0.039), (curveEndDate, 0.041)]) dc cal [] Linear idx <- iborIndex Euribor6M (Just rTS) process <- liborForwardModelProcess size idx fixingDates <- Process.fixingDates process fixingTimes <- Process.fixingTimes process- capletVol <- Vol.capletVarianceCurve evalDate (fromList $ zip (take 9 $ drop 1 fixingDates) capletVols) dc ShiftedLognormal 0.0+ capletVol <- Vol.capletVarianceCurve evalDate (fromList $ zip (take 9 $ drop 1 fixingDates) capletVols) dc ShiftedLognormal 0.0 False let emptyCorrelation = either error id $ boxedRealMatrix 0 0 [] parameterization <- lfmHullWhiteParameterization process capletVol emptyCorrelation 1 covar <- lfmHullWhiteCovariance parameterization 0.0 []@@ -279,7 +284,7 @@ Context.setEvaluationDate (Just evalDate) dc <- dayCounter (Actual360 False) emptyIndex <- iborIndex Euribor6M Nothing- firstPillar <- advance cal evalDate (fromIntegral (Ibor.fixingDays emptyIndex), Days) Following False+ firstPillar <- Ibor.fixingDays emptyIndex >>= \n -> advance cal evalDate (fromIntegral n, Days) Following False rTS <- interpolatedZeroCurve (fromList [(firstPillar, 0.039), (curveEndDate, 0.041)]) dc cal [] Linear idx <- iborIndex Euribor6M (Just rTS) process <- liborForwardModelProcess size idx@@ -295,7 +300,7 @@ -- the process is only simulable once a covariance parameterization is installed fixingDates <- Process.fixingDates process- capletVol <- Vol.capletVarianceCurve evalDate (fromList (map (, 0.15) (take 9 (drop 1 fixingDates)))) dc ShiftedLognormal 0.0+ capletVol <- Vol.capletVarianceCurve evalDate (fromList (map (, 0.15) (take 9 (drop 1 fixingDates)))) dc ShiftedLognormal 0.0 False let emptyCorrelation = either error id $ boxedRealMatrix 0 0 [] parameterization <- lfmHullWhiteParameterization process capletVol emptyCorrelation 1 setCovarParam process parameterization@@ -318,7 +323,7 @@ process <- g2Process 0.1 0.01 0.2 0.013 (-0.5) (Just curve) let t = 2.0 phiBefore <- phi process t- _ <- setValue rateQ 0.05+ setValue rateQ 0.05 phiAfter <- phi process t (phiAfter - phiBefore) `shouldSatisfy` closePrec 0.03 1.0e-10 @@ -852,7 +857,7 @@ helper <- Model.hestonModelHelper (months, Months) nullCal s0 strike vol rTS qTS Model.ImpliedVolError Model.setPricingEngine helper truthEngine price <- Model.modelValue helper- _ <- Model.impliedVolatility helper price 1.0e-12 1000 0.01 2.0 >>= setValue vol+ Model.impliedVolatility helper price 1.0e-12 1000 0.01 2.0 >>= setValue vol pure helper | months <- [6, 12, 24], strike <- [90, 100, 110] ] fitted <- modelOf (0.06, 1.0, 0.04, 0.3, -0.3)@@ -973,7 +978,7 @@ setForwardMeasureTime hwFwd 10.0 mapM_ (\t -> do- fwdIR <- forwardRateBetweenTimes rTS t t Continuous NoFrequency True+ fwdIR <- forwardRate rTS (RateBetweenTimes t t) Continuous NoFrequency True let alfa = (sigma / a) * (1 - exp (-a * t)) expected = 0.5 * alfa * alfa + rate fwdIR plain <- Process.alpha hw t@@ -1022,7 +1027,7 @@ -- reference independent of G2Process. referencePhi :: YieldTermStructure -> Double -> Double -> Double -> Double -> Double -> Double -> IO Double referencePhi curve t a sigma b eta rho = do- fwdIR <- forwardRateBetweenTimes curve t t Continuous NoFrequency True+ fwdIR <- forwardRate curve (RateBetweenTimes t t) Continuous NoFrequency True let fwd = rate fwdIR temp1 = sigma * (1 - exp (-a * t)) / a temp2 = eta * (1 - exp (-b * t)) / b
test/hspec/QuantLib/Spec/Quote.hs view
@@ -1,19 +1,26 @@ module QuantLib.Spec.Quote (spec) where import Control.Monad(forM_)+import Data.Time.Calendar(Day, diffDays) import Test.Hspec import QuantLib.Quote import qualified QuantLib.Context as Context import QuantLib.Time.Calendar(calendar, CalendarConstructor(TARGET), advance, BusinessDayConvention(Following))-import QuantLib.Time.Schedule(dayCounter, DayCounterConstructor(ActualActualISDA), Frequency(Annual), TimeUnit(Years))+import QuantLib.Time.Date(december)+import QuantLib.Time.Schedule(dayCounter, DayCounterConstructor(ActualActualISDA, Actual365FixedStandard), Frequency(Annual), TimeUnit(Years)) import qualified QuantLib.InterestRate as IR import QuantLib.Index(fixing) import QuantLib.Index.InterestRate(iborIndex, IborConstructor(Euribor1Y))-import QuantLib.TermStructure.Yield(Reference(..), flatForward)-import QuantLib.PricingEngine(blackFormula)-import QuantLib.Instrument.Option(OptionType(Call))+import QuantLib.TermStructure(TermPoint(DatePoint))+import QuantLib.TermStructure.Yield(Reference(..), flatForward, discount, relinkableYieldTermStructure)+import qualified QuantLib.TermStructure.Yield as Yield+import QuantLib.TermStructure.Volatility(CalendarReference(CalendarReferenceDate), blackConstantVol)+import QuantLib.Process(blackScholesMertonProcess, ProcessDiscretization(EulerDiscretization))+import QuantLib.Instrument(npv, setPricingEngine)+import QuantLib.PricingEngine(blackFormula, analyticEuropeanEngine)+import QuantLib.Instrument.Option(OptionType(Call), vanillaOption, PlainVanillaPayoff(..), StrikedPayoff(PlainVanilla), EuropeanExercise(..), Exercise(European)) import QuantLib.Spec.Helpers(closePrec) -- The three upstream unary functions from test-suite/quotes.cpp:testDerived, and its values.@@ -30,13 +37,12 @@ -- Ported from quotes.cpp:testObservable's core mechanic (the value round-trip); the -- Flag/registerWith observer-notification check in that test has no hasquant binding. describe "SimpleQuote" $- it "round-trips value/setValue, with setValue returning the change" $ do+ it "round-trips value/setValue" $ do q <- simpleQuote 0.0 value q `shouldReturn` 0.0- setValue q 3.14 `shouldReturn` 3.14+ setValue q 3.14 value q `shouldReturn` 3.14- diff <- setValue q 1.0- diff `shouldSatisfy` closePrec (1.0 - 3.14) 1.0e-9+ setValue q 1.0 value q `shouldReturn` 1.0 -- quotes.cpp:testDerived. Both entry points against the same three functions/values.@@ -47,7 +53,7 @@ me <- simpleQuote 0.0 derived <- derivedQuote op me operand forM_ values $ \v -> do- _ <- setValue me v+ setValue me v x <- value derived x `shouldSatisfy` closePrec (f v) 1.0e-10 @@ -56,7 +62,7 @@ me <- simpleQuote 0.0 withDerivedQuote f me $ \derived -> forM_ values $ \v -> do- _ <- setValue me v+ setValue me v x <- value derived x `shouldSatisfy` closePrec (f v) 1.0e-10 @@ -68,8 +74,8 @@ me2 <- simpleQuote 0.0 composite <- compositeQuote op me1 me2 forM_ values $ \v -> do- _ <- setValue me1 v- _ <- setValue me2 (v + 1)+ setValue me1 v+ setValue me2 (v + 1) x <- value composite x `shouldSatisfy` closePrec (f v (v + 1)) 1.0e-10 @@ -79,8 +85,8 @@ me2 <- simpleQuote 0.0 withCompositeQuote f me1 me2 $ \composite -> forM_ values $ \v -> do- _ <- setValue me1 v- _ <- setValue me2 (v + 1)+ setValue me1 v+ setValue me2 (v + 1) x <- value composite x `shouldSatisfy` closePrec (f v (v + 1)) 1.0e-10 @@ -121,10 +127,10 @@ spread <- simpleQuote 0.0005 q <- compositeQuote QuoteAdd base spread value q `shouldReturn` 0.0305- _ <- setValue base 0.04+ setValue base 0.04 v1 <- value q v1 `shouldSatisfy` closePrec 0.0405 1.0e-12- _ <- setValue spread 0.001+ setValue spread 0.001 v2 <- value q v2 `shouldSatisfy` closePrec 0.041 1.0e-12 @@ -168,7 +174,7 @@ priceQuote <- simpleQuote price q <- impliedStdDevQuote Call forwardQuote priceQuote strike guess 1.0e-10 100 stdev0 <- value q- _ <- setValue priceQuote 0.011+ setValue priceQuote 0.011 stdev1 <- value q stdev1 `shouldNotSatisfy` closePrec stdev0 1.0e-6 repriced <- blackFormula Call strike forwardRate stdev1 1.0 0.0@@ -208,12 +214,93 @@ expected <- fixing idx fixingDate True v <- value q v `shouldSatisfy` closePrec expected 1.0e-15- _ <- setValue forwardQuote 0.04+ setValue forwardQuote 0.04 expected' <- fixing idx fixingDate True v' <- value q v' `shouldSatisfy` closePrec expected' 1.0e-15 v' `shouldNotSatisfy` closePrec v 1.0e-9 Context.collectGarbage++ -- A settlement-dated spot S_V and its cash value S_d at the evaluation date d. Expected values+ -- come from the flat continuous rates directly, not from the curves' discount factors.+ describe "FX cash spot quote" $ do+ let settle = 2 :: Word+ spotV = 1.25+ rd = 0.05+ rf = 0.01+ yf :: Day -> Day -> Double+ yf from to = fromIntegral (diffDays to from) / 365+ expectedCash d v s = s * exp (-(rd - rf) * yf d v)+ withMarket d k = Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just d)+ dc <- dayCounter Actual365FixedStandard+ cal <- calendar TARGET+ spot <- simpleQuote spotV+ rdQ <- simpleQuote rd+ rfQ <- simpleQuote rf+ dom <- flatForward (ReferenceDate d) rdQ dc IR.Continuous Annual+ for <- flatForward (ReferenceDate d) rfQ dc IR.Continuous Annual+ k dc cal spot rdQ dom for+ it "discounts a settlement spot back over the spot lag, across a holiday" $+ -- 23 Dec 2026 + 2 TARGET days skips Christmas and the weekend: V = 28 Dec 2026.+ withMarket (23 `december` 2026) $ \_ cal spot _ dom for -> do+ let d = 23 `december` 2026+ v = 28 `december` 2026+ cash <- fxCashSpotQuote spot dom for cal settle >>= value+ cash `shouldSatisfy` closePrec (expectedCash d v spotV) 1.0e-14+ cash `shouldSatisfy` (< spotV)+ -- The forward to the settlement date reproduces the quoted spot.+ pfV <- discount for (DatePoint v) False+ pdV <- discount dom (DatePoint v) False+ (cash * pfV / pdV) `shouldSatisfy` closePrec spotV 1.0e-14+ it "returns the settlement spot itself with no lag on a business day" $+ withMarket (23 `december` 2026) $ \_ cal spot _ dom for ->+ (fxCashSpotQuote spot dom for cal 0 >>= value) `shouldReturn` spotV+ it "follows the spot, a curve's rate and a relink, and restores exactly" $+ withMarket (23 `december` 2026) $ \dc cal spot rdQ dom for -> do+ domHandle <- relinkableYieldTermStructure (Just dom)+ q <- fxCashSpotQuote spot domHandle for cal settle+ base <- value q+ setValue spot 1.30+ value q >>= (`shouldSatisfy` (/= base))+ setValue spot spotV+ setValue rdQ 0.06+ value q >>= (`shouldSatisfy` (/= base))+ setValue rdQ rd+ value q `shouldReturn` base+ flatQ <- simpleQuote rf+ flatDom <- flatForward (ReferenceDate (23 `december` 2026)) flatQ dc IR.Continuous Annual+ Yield.linkTo domHandle flatDom+ value q `shouldReturn` spotV+ Yield.linkTo domHandle dom+ value q `shouldReturn` base+ it "recomputes the settlement date when the evaluation date rolls" $+ withMarket (22 `december` 2026) $ \_ cal spot _ dom for -> do+ q <- fxCashSpotQuote spot dom for cal settle+ -- From 22 Dec, V = 24 Dec; from 23 Dec, V = 28 Dec.+ value q >>= (`shouldSatisfy` closePrec (expectedCash (22 `december` 2026) (24 `december` 2026) spotV) 1.0e-14)+ Context.setEvaluationDate (Just (23 `december` 2026))+ value q >>= (`shouldSatisfy` closePrec (expectedCash (23 `december` 2026) (28 `december` 2026) spotV) 1.0e-14)+ it "notifies a cached option price when a curve it reads moves" $+ withMarket (23 `december` 2026) $ \dc cal spot rdQ dom for -> do+ -- The process discounts on curves of its own, so only the quote reads rdQ.+ q <- fxCashSpotQuote spot dom for cal settle+ let d = 23 `december` 2026+ procRd <- simpleQuote rd+ procRf <- simpleQuote rf+ procDom <- flatForward (ReferenceDate d) procRd dc IR.Continuous Annual+ procFor <- flatForward (ReferenceDate d) procRf dc IR.Continuous Annual+ volQ <- simpleQuote 0.10+ vol <- blackConstantVol (CalendarReferenceDate d) cal volQ dc+ process <- blackScholesMertonProcess q procFor procDom vol EulerDiscretization False+ option <- vanillaOption (PlainVanilla (PlainVanillaPayoff Call 1.25)) (European (EuropeanExercise (23 `december` 2027)))+ analyticEuropeanEngine process Nothing >>= setPricingEngine option+ basePv <- npv option+ setValue rdQ 0.07+ movedPv <- npv option+ movedPv `shouldSatisfy` (< basePv)+ setValue rdQ rd+ npv option `shouldReturn` basePv describe "FuturesConvAdjustmentQuote" $ it "futuresValue reports the futures quote's own value, independent of volatility/meanReversion" $ do
test/hspec/QuantLib/Spec/TermStructure.hs view
@@ -12,8 +12,8 @@ import Data.Time.Calendar import Data.Maybe(catMaybes)-import Data.List(isInfixOf, nub)-import Data.List.NonEmpty(NonEmpty, fromList)+import Data.List(isInfixOf, nub, uncons)+import Data.List.NonEmpty(NonEmpty(..), fromList) import qualified Data.Vector.Storable as V import QuantLib.Time.Date@@ -47,6 +47,31 @@ spec :: Spec spec = do+ describe "rate helper pillar dates" $+ it "computes pillars without a curve and moves only relative-date helpers" $ Context.keepingSettingsGc $ do+ let origin = fromGregorian 2025 1 2+ futureStart = fromGregorian 2025 10 1+ Context.setEvaluationDate (Just origin)+ cal <- calendar TARGET+ dc <- dayCounter (Actual360 False)+ q <- Quote.simpleQuote 0.03+ price <- Quote.simpleQuote 97+ index <- iborIndex (Euribor (3, Months)) Nothing+ deposit <- depositRateHelper q (DepositTenor (3, Months) 2 cal ModifiedFollowing False dc)+ fra <- fraRateHelper q (FraMonthsFromIndex 3 index) LastRelevantDate Nothing True+ future <- futuresRateHelper price (FuturesFromIndex futureStart index) Nothing Custom+ spot <- advance cal origin (2, Days) Following False+ depEnd <- advance cal spot (3, Months) ModifiedFollowing False+ fraEnd <- advance cal depEnd (3, Months) ModifiedFollowing False+ futureEnd <- advance cal futureStart (3, Months) ModifiedFollowing False+ rateHelperPillarDate deposit `shouldReturn` depEnd+ rateHelperPillarDate fra `shouldReturn` fraEnd+ rateHelperPillarDate future `shouldReturn` futureEnd+ Context.setEvaluationDate (Just (addDays 7 origin))+ moved <- rateHelperPillarDate fra+ moved `shouldSatisfy` (> fraEnd)+ rateHelperPillarDate future `shouldReturn` futureEnd+ describe "QuantLib 1.44 curves and helpers" $ do it "moves the implied reference date and preserves discount ratios" $ Context.keepingSettingsGc $ do let today' = fromGregorian 2024 1 2@@ -116,7 +141,7 @@ (GlobalDiscountLogLinear 1e-12 [] (Just guess)) False Context.collectGarbage discount curve (TimePoint 0.2) False >>= (`shouldSatisfy` (> 0))- _ <- Quote.setValue q 0.04+ Quote.setValue q 0.04 discount curve (TimePoint 0.2) False >>= (`shouldSatisfy` (> 0)) seen <- readIORef calls seen `shouldBe` if quantLibAtMost143 then [] else [(3,0), (3,3)]@@ -147,7 +172,7 @@ ==> monadicIO $ do run $ (Quote.simpleQuote val >>= \q -> Quote.value q) `shouldReturn` val describe "yield term structure" $ do- let setup :: IO (Calendar, Word, YieldTermStructure)+ let setup :: IO (Calendar, Word, PiecewiseYieldCurve) setup = do let settlementDays = 2 depositData = [@@ -185,6 +210,57 @@ ts <- piecewiseYieldCurve (ReferenceDate settlement) (fromList (deposits ++ swaps)) actual360dc [] (Iterative Discount LogLinear defaultIterativeBootstrapOpts) False return (cal, settlementDays, ts)+ it "rebuilds a bootstrapped curve from its nodes" $ Context.keepingSettingsGc $ do+ cal <- calendar TARGET+ today' <- today >>= \d -> adjust cal d Following+ Context.setEvaluationDate (Just today')+ dc <- dayCounter (Actual360 False)+ helpers <- mapM (\(t, r) -> Quote.simpleQuote (r :: Double) >>= \q -> depositRateHelper q (DepositTenor t 2 cal ModifiedFollowing True dc))+ [((3, Months), 0.045), ((6, Months), 0.046), ((1, Years), 0.047), ((2, Years), 0.049)]+ forM_ ([(Discount, LogLinear), (Discount, Linear), (ZeroYield, Linear), (ForwardRate, BackwardFlat), (SimpleZeroYield, Linear), (Discount, Cubic (NaturalSpline False))] :: [(BootstrapTrait, Interpolation)]) $ \(trait, interpolation) -> do+ curve <- piecewiseYieldCurve (SettlementDays 0 cal) (fromList helpers) dc [] (Iterative trait interpolation defaultIterativeBootstrapOpts) True+ nodes <- bootstrappedNodes curve+ map fst nodes `shouldSatisfy` ((== Just today') . fmap fst . uncons)+ length nodes `shouldBe` length helpers + 1+ rebuilt <- case trait of+ Discount -> interpolatedDiscountCurve (fromList nodes) dc cal [] interpolation False+ ZeroYield -> interpolatedZeroCurve (fromList nodes) dc cal [] interpolation+ ForwardRate -> interpolatedForwardCurve (fromList nodes) dc cal [] interpolation+ SimpleZeroYield -> interpolatedSimpleZeroCurve (fromList nodes) dc cal [] interpolation+ forM_ [addDays k today' | k <- [0, 45, 180, 400, 700]] $ \d -> do+ expected <- discount curve (DatePoint d) False+ discount rebuilt (DatePoint d) False >>= (`shouldBe` expected)++ it "reconstructs jump-bearing nodes and a globally bootstrapped curve" $ Context.keepingSettingsGc $ do+ let ref = fromGregorian 2025 1 2+ Context.setEvaluationDate (Just ref)+ cal <- calendar Null+ dc <- dayCounter Actual365FixedStandard+ quotes <- mapM Quote.simpleQuote [0.04, 0.045, 0.05]+ helpers <- sequence [depositRateHelper q (DepositTenor (n, Years) 0 cal Unadjusted False dc) | (n,q) <- zip [1,2,3] quotes]+ jump <- Quote.simpleQuote 0.99+ let jumps = [(addDays 550 ref, jump)]+ forM_ ([ReferenceDate ref, SettlementDays 0 cal] :: [Reference]) $ \reference -> do+ curve <- piecewiseYieldCurve reference (fromList helpers) dc jumps (Iterative Discount LogLinear defaultIterativeBootstrapOpts) False+ nodes <- bootstrappedNodes curve+ rebuilt <- interpolatedDiscountCurve (fromList nodes) dc cal jumps LogLinear False+ omitted <- interpolatedDiscountCurve (fromList nodes) dc cal [] LogLinear False+ forM_ ([365, 550, 551, 730] :: [Integer]) $ \n -> do+ expected <- discount curve (DatePoint (addDays n ref)) False+ discount rebuilt (DatePoint (addDays n ref)) False >>= (`shouldSatisfy` closePrec expected 1e-6)+ expected <- discount curve (TimePoint 2) False+ discount omitted (TimePoint 2) False >>= (\x -> abs (x - expected) `shouldSatisfy` (> 0.001))+ Quote.setValue jump 0.98+ updated <- bootstrappedNodes curve+ updated `shouldNotBe` nodes+ Quote.setValue jump 0.99+ pure ()+ global <- piecewiseYieldCurve (ReferenceDate ref) (fromList helpers) dc [] (GlobalDiscountLogLinear 1e-12 [] Nothing) False+ globalNodes <- bootstrappedNodes global+ rebuiltGlobal <- interpolatedDiscountCurve (fromList globalNodes) dc cal [] LogLinear False+ forM_ ([200, 365, 550, 900] :: [Integer]) $ \n -> do+ expected <- discount global (DatePoint (addDays n ref)) False+ discount rebuiltGlobal (DatePoint (addDays n ref)) False >>= (`shouldSatisfy` closePrec expected 1e-6) it "referenceChange" $ Context.keepingSettingsGc $ do let ds = [10, 30, 60, 120, 360, 720] (_calendar, settlementDays, _ts) <- setup@@ -229,8 +305,8 @@ ts <- flatForward (ReferenceDate refDate) flatRate dc IR.Continuous Annual zeroAtDate <- IR.rate <$> zeroRate ts (RateAtDate endDate dc) IR.Continuous NoFrequency False zeroAtTime <- IR.rate <$> zeroRate ts (RateAtTime 1.0) IR.Continuous NoFrequency False- forwardBetweenDates <- IR.rate <$> forwardRate ts refDate endDate dc IR.Continuous NoFrequency False- forwardBetweenTimes <- IR.rate <$> forwardRateBetweenTimes ts 0.0 1.0 IR.Continuous NoFrequency False+ forwardBetweenDates <- IR.rate <$> forwardRate ts (RateBetweenDates refDate endDate dc) IR.Continuous NoFrequency False+ forwardBetweenTimes <- IR.rate <$> forwardRate ts (RateBetweenTimes 0.0 1.0) IR.Continuous NoFrequency False let results :: [Double] results = [zeroAtDate, zeroAtTime, forwardBetweenDates, forwardBetweenTimes] mapM_ (`shouldSatisfy` closePrec expected tolerance) results@@ -238,7 +314,7 @@ -- The day counter is the caller's, not the curve's: the same compound factor over the same -- interval reports a different rate under Actual360. act360 <- dayCounter (Actual360 False)- forwardAct360 <- IR.rate <$> forwardRate ts refDate endDate act360 IR.Continuous NoFrequency False+ forwardAct360 <- IR.rate <$> forwardRate ts (RateBetweenDates refDate endDate act360) IR.Continuous NoFrequency False forwardAct360 `shouldSatisfy` closePrec (expected * 360 / 365) tolerance it "implied" $@@ -264,8 +340,8 @@ refDate <- asTermStructure ts >>= referenceDate let testDate = addGregorianYearsClip 5 refDate actual360dc <- dayCounter (Actual360 False)- forward <- IR.rate <$> forwardRate ts testDate testDate actual360dc IR.Continuous NoFrequency False- spreadedForward <- IR.rate <$> forwardRate spreaded testDate testDate actual360dc IR.Continuous NoFrequency False+ forward <- IR.rate <$> forwardRate ts (RateBetweenDates testDate testDate actual360dc) IR.Continuous NoFrequency False+ spreadedForward <- IR.rate <$> forwardRate spreaded (RateBetweenDates testDate testDate actual360dc) IR.Continuous NoFrequency False (forward - (spreadedForward - val)) `shouldSatisfy` (<= 1.0e-10) it "z-spreaded" $@@ -294,7 +370,7 @@ c2 <- flatForward (ReferenceDate refDate) q2 dc IR.Continuous NoFrequency withCompositeZeroYieldStructure (-) c1 c2 IR.Continuous NoFrequency $ \composite -> do initial <- IR.rate <$> zeroRate composite (RateAtDate queryDate dc) IR.Continuous NoFrequency False- _ <- Quote.setValue q1 0.04+ Quote.setValue q1 0.04 updated <- IR.rate <$> zeroRate composite (RateAtDate queryDate dc) IR.Continuous NoFrequency False initial `shouldSatisfy` closePrec 0.02 (1.0e-6 * 0.02) updated `shouldSatisfy` closePrec 0.03 (1.0e-6 * 0.03)@@ -382,7 +458,7 @@ (cal, _settlementDays, ts) <- setup todayD <- Context.evaluationDate let businessDays n = advance cal todayD (n, Days) Following False- instFwd curve t = IR.rate <$> forwardRateBetweenTimes curve t t IR.Continuous NoFrequency True+ instFwd curve t = IR.rate <$> forwardRate curve (RateBetweenTimes t t) IR.Continuous NoFrequency True q2 <- Quote.simpleQuote 0.02 q3 <- Quote.simpleQuote 0.03 q4 <- Quote.simpleQuote 0.04@@ -437,8 +513,18 @@ curve <- piecewiseSpreadYieldCurve ts (fromList (map fst hs)) bootstrap True _ <- discount curve (DatePoint (addGregorianYearsClip 1 refDate)) True mapM_ (\(h, r) -> impliedQuote h >>= (`shouldSatisfy` closePrec r 1.0e-8)) hs+ nodes <- bootstrappedNodes curve+ map fst (take 1 nodes) `shouldBe` [refDate]+ let interpolation = case bootstrap of+ SpreadIterative i _ -> i+ SpreadGlobalLogLinear{} -> LogLinear+ held <- interpolatedSpreadDiscountCurve ts (fromList nodes) interpolation+ Context.collectGarbage+ forM_ ([0.1,1,2.7,7.3,20,35,50] :: [Double]) $ \t -> do+ expected <- discount curve (TimePoint t) True+ discount held (TimePoint t) True >>= (`shouldSatisfy` closePrec expected 1.0e-12) pure curve- flatFwd curve t1 t2 = IR.rate <$> forwardRateBetweenTimes curve t1 t2 IR.Continuous NoFrequency True+ flatFwd curve t1 t2 = IR.rate <$> forwardRate curve (RateBetweenTimes t1 t2) IR.Continuous NoFrequency True logLinear <- repricing (SpreadIterative LogLinear defaultIterativeBootstrapOpts) _ <- repricing (SpreadIterative Linear defaultIterativeBootstrapOpts) _ <- repricing (SpreadGlobalLogLinear 1.0e-10 [] Nothing)@@ -507,13 +593,13 @@ ois <- overnightIborIndex Sofr Nothing oisSwap <- oisRateHelper (OisTenor 2 (1, Years) (0, Days)) q ois Nothing >>= helperInstrument- (Swap.asSwap oisSwap >>= Swap.maturityDate) `shouldReturn` Just (4 `january` 2025)+ (Swap.asSwap oisSwap >>= Swap.maturityDate) `shouldReturn` (4 `january` 2025) ccy <- currency EUR ibor <- iborIndex (Ibor "dummy" (6, Months) 2 ccy cal ModifiedFollowing False actual360dc) Nothing vanilla <- swapRateHelper q (SwapRateTenor (5, Years) cal Annual Unadjusted thirty360dc ibor (0, Days) Nothing Nothing) Nothing Nothing LastRelevantDate Nothing False Nothing Nothing >>= helperInstrument- (Swap.asSwap vanilla >>= Swap.maturityDate) `shouldReturn` Just (4 `january` 2029)+ (Swap.asSwap vanilla >>= Swap.maturityDate) `shouldReturn` (4 `january` 2029) bondMaturity <- advance cal (2 `january` 2024) (5, Years) Unadjusted False sch <- schedule (Just (2 `january` 2024)) bondMaturity (1, Years) cal Unadjusted Unadjusted@@ -521,7 +607,7 @@ price <- Quote.simpleQuote 100.0 bond <- fixedRateBondHelper price 3 100.0 sch [0.04] thirty360dc Following 100.0 Nothing >>= helperInstrument- Bond.maturityDate bond `shouldReturn` Just bondMaturity+ Bond.maturityDate bond `shouldReturn` bondMaturity -- Which fixings a bootstrapped curve reads from the store. The curve itself cannot say: -- PiecewiseYieldCurve is a template with no instruments accessor and an Observer does not@@ -884,10 +970,10 @@ adjQuote <- Quote.simpleQuote 0.0012 adjQuoteG <- Quote.asQuote adjQuote rhAdj <- overnightIndexFutureRateHelper price valueDate maturityDate ois (Just adjQuoteG) AveragingCompound LastRelevantDate Nothing- adj <- overnightIndexFutureRateHelperConvexityAdjustment rhAdj+ adj <- convexityAdjustment rhAdj adj `shouldSatisfy` closePrec 0.0012 1.0e-12 rhNone <- overnightIndexFutureRateHelper price valueDate maturityDate ois Nothing AveragingCompound LastRelevantDate Nothing- none <- overnightIndexFutureRateHelperConvexityAdjustment rhNone+ none <- convexityAdjustment rhNone none `shouldBe` 0.0 describe "futures rate helper" $@@ -901,10 +987,10 @@ adjQuote <- Quote.simpleQuote 0.0007 adjQuoteG <- Quote.asQuote adjQuote fhAdj <- futuresRateHelper price (FuturesMonths immDate' 3 cal ModifiedFollowing True actual360dc) (Just adjQuoteG) IMM- adj <- futuresRateHelperConvexityAdjustment fhAdj+ adj <- convexityAdjustment fhAdj adj `shouldSatisfy` closePrec 0.0007 1.0e-12 fhNone <- futuresRateHelper price (FuturesMonths immDate' 3 cal ModifiedFollowing True actual360dc) Nothing IMM- none <- futuresRateHelperConvexityAdjustment fhNone+ none <- convexityAdjustment fhNone none `shouldBe` 0.0 describe "futures rate helper terms" $ do@@ -1311,6 +1397,27 @@ npvAfter <- npv capfl abs (npvAfter - npvBefore) `shouldSatisfy` (> 0.5) + -- A caplet variance curve whose every node has the same volatility is that constant+ -- volatility, before its first node by its variance interpolation and after its last+ -- only when it extrapolates: the 5-year cap's last caplets fix after the last node.+ it "a caplet variance curve extrapolates its last volatility only when asked" $+ Context.keepingSettingsGc $ do+ let refDate = 11 `december` 2012+ Context.setEvaluationDate (Just refDate)+ (capfl, _) <- mkCap+ expected <- npv capfl+ (_, discountH, _) <- setupSwap+ dc <- dayCounter Actual365FixedStandard+ let nodes = (11 `december` 2013, 0.20) :| [(11 `december` 2014, 0.20)]+ priceOn extrapolate = do+ curve <- Vol.capletVarianceCurve refDate nodes dc IR.ShiftedLognormal 0 extrapolate+ eng <- blackCapFloorEngineFromVolatilityStructure discountH curve+ setPricingEngine capfl eng+ npv capfl+ got <- priceOn True+ abs (got - expected) `shouldSatisfy` (<= 1e-8 * abs expected)+ priceOn False `shouldThrow` anyException+ -- OptionletStripper1 strips a quoted CapFloorTermVolSurface into caplet/floorlet vols, -- immediately wrapped behind StrippedOptionletAdapter (an OptionletVolatilityStructure). -- Self-consistency check (upstream: optionletstripper.cpp's testFlatTermVolatilityStripping1,@@ -1382,7 +1489,7 @@ `shouldReturn` volFromSurface curveVolQ <- mapM (const (Quote.simpleQuote 0.18)) tenors- capVolCurve <- Vol.capFloorTermVolCurve (Vol.CalendarSettlementDays 0) cal Following (fromList $ zipWith (\(n, u) q -> (n, u, q)) tenors curveVolQ) dc+ capVolCurve <- Vol.capFloorTermVolCurve (Vol.CalendarSettlementDays 0) cal Following (fromList $ zip tenors curveVolQ) dc volFromCurve <- Vol.capFloorVolatility capVolCurve (Vol.OptionTenor (5, Years)) 0.05 False volFromCurve `shouldBe` 0.18 curveDates <- Vol.capFloorTermVolCurveOptionDates capVolCurve@@ -1463,7 +1570,7 @@ let volMatrix = either error id $ objectMatrix 10 3 (replicate 30 flatVolQ) capVolSurface <- Vol.capFloorTermVolSurface (Vol.CalendarSettlementDays 0) cal Following tenors [0.02, 0.05, 0.08] volMatrix dc curveVolQs <- mapM (const (Quote.simpleQuote 0.18)) tenors- capVolCurve <- Vol.capFloorTermVolCurve (Vol.CalendarSettlementDays 0) cal Following (fromList $ zipWith (\(n, u) q -> (n, u, q)) tenors curveVolQs) dc+ capVolCurve <- Vol.capFloorTermVolCurve (Vol.CalendarSettlementDays 0) cal Following (fromList $ zip tenors curveVolQs) dc stripper1 <- Vol.optionletStripper capVolSurface idx Nothing 1.0e-6 100 (Just discountH) IR.ShiftedLognormal 0 False Nothing 0@@ -1512,7 +1619,7 @@ _ <- Vol.abcdEndCriteria curve ks <- Vol.abcdKs curve length ks `shouldBe` 10- returnedTenors <- Vol.abcdAtmVolCurveOptionTenors curve+ returnedTenors <- Vol.abcdOptionTenors curve length returnedTenors `shouldBe` 10 optionDates <- Vol.abcdOptionDates curve optionTimes <- Vol.abcdOptionTimes curve@@ -1532,7 +1639,7 @@ forM_ remainingVariances $ \v -> v `shouldSatisfy` closePrec expectedVariance 1.0e-8 [] -> expectationFailure "expected ATM variance results" - -- SabrVolSurface's own sabrVolatilitySpreads(Date) linearly interpolates the raw quoted+ -- SabrVolSurface's own sabrVolSurfaceVolatilitySpreads(Date) linearly interpolates the raw quoted -- vol-spread quotes across optionTenors -- at a date that lands exactly on a grid tenor, -- that interpolation is the identity, so with flat spread quotes the surface must echo the -- input value back exactly. Real self-consistency check, not a hand-derived value.@@ -1550,13 +1657,13 @@ spreadQs <- mapM (const (Quote.simpleQuote 0.02)) [1 .. (5 * 3 :: Int)] let volSpreads = either error id $ objectMatrix 5 3 spreadQs surf <- Vol.sabrVolSurface idx atmCurve (fromList tenors) (fromList spreads) volSpreads- vs <- Vol.sabrVolatilitySpreads surf (Vol.SabrVolatilitySpreadsTenor (tenors !! 2))+ vs <- Vol.sabrVolSurfaceVolatilitySpreads surf (Vol.SabrVolatilitySpreadsTenor (tenors !! 2)) length vs `shouldBe` 3 vs `shouldSatisfy` all (\v -> abs (v - 0.02) < 1.0e-8) _ <- Vol.sabrVolSurfaceIndex surf d <- Vol.sabrVolSurfaceOptionDateFromTenor surf (3, Years) d `shouldSatisfy` (> 11 `december` 2012)- vsAtDate <- Vol.sabrVolatilitySpreads surf (Vol.SabrVolatilitySpreadsDate d)+ vsAtDate <- Vol.sabrVolSurfaceVolatilitySpreads surf (Vol.SabrVolatilitySpreadsDate d) vsAtDate `shouldSatisfy` all (\v -> abs (v - 0.02) < 1.0e-8) t <- yearFraction dc (11 `december` 2012) d Nothing Nothing _ <- Vol.blackVolSurfaceSmileSection surf (Vol.OptionTenor (3, Years)) False@@ -1942,12 +2049,20 @@ -- additionalDates for GlobalSimpleZeroLinearFull below: deliberately not coincident -- with the primary monthly pillars, same reasoning as the GlobalBootstrapFull test above. extraDates <- mapM (\d -> advance cal settleFix (d, Days) ModifiedFollowing True) [45, 75, 105 :: Int]- let checkCurve curve = mapM_ (\i -> do+ let checkCurve :: PiecewiseYieldCurve -> IO ()+ checkCurve curve = mapM_ (\i -> do pillar <- advance cal settleFix (i, Months) ModifiedFollowing True let tau = fromIntegral (diffDays pillar settleFix) / 360 :: Double df <- discount curve (DatePoint pillar) False df `shouldSatisfy` closePrec (1 / (1 + qVal * tau)) tolerance- ) ([1 .. 5] :: [Int])+ ) ([1 .. 5] :: [Int]) >> checkNodes curve+ -- Every bootstrapper keeps its nodes: the reference date, then increasing pillars.+ checkNodes :: PiecewiseYieldCurve -> IO ()+ checkNodes curve = do+ nodeDates <- map fst <$> bootstrappedNodes curve+ take 1 nodeDates `shouldBe` [settleFix]+ length nodeDates `shouldSatisfy` (>= 6)+ and (zipWith (<) nodeDates (drop 1 nodeDates)) `shouldBe` True checkReference reference = do piecewiseYieldCurve reference helpers euriborDC [] (Iterative ForwardRate Linear defaultIterativeBootstrapOpts) False >>= checkCurve piecewiseYieldCurve reference helpers euriborDC [] (GlobalDiscountLogLinear 1.0e-10 [] Nothing) False >>= checkCurve@@ -1989,7 +2104,7 @@ -- expiring exactly at a grid node must reprice identically under the piecewise surface and -- under a flat blackConstantVol at that node's own vol, since both surfaces have the same -- variance there.- describe "BlackVolTermStructure blackVol/blackVolVariance/blackForwardVol/blackForwardVariance/minStrike/maxStrike" $+ describe "BlackVolTermStructure blackVol/blackVariance/blackForwardVol/blackForwardVariance/minStrike/maxStrike" $ it "agree between DatePoint/TimePoint and DateInterval/TimeInterval coordinates, and expose generic strike bounds" $ Context.keepingSettingsGc $ do let refDate = 11 `december` 2012@@ -2007,8 +2122,8 @@ volAtDate <- Vol.blackVol surface (DatePoint d1) strike False volAtTime <- Vol.blackVol surface (TimePoint t1) strike False volAtDate `shouldSatisfy` closePrec volAtTime tolerance- varAtDate <- Vol.blackVolVariance surface (DatePoint d1) strike False- varAtTime <- Vol.blackVolVariance surface (TimePoint t1) strike False+ varAtDate <- Vol.blackVariance surface (DatePoint d1) strike False+ varAtTime <- Vol.blackVariance surface (TimePoint t1) strike False varAtDate `shouldSatisfy` closePrec varAtTime tolerance -- constant-vol identity: variance = vol^2 * t varAtDate `shouldSatisfy` closePrec (0.20 * 0.20 * t1) tolerance@@ -2019,7 +2134,7 @@ fwdVarTimes <- Vol.blackForwardVariance surface (TimeInterval t1 t2) strike False fwdVarDates `shouldSatisfy` closePrec fwdVarTimes tolerance -- upstream identity: forward variance between two points is the variance difference- varAtD2 <- Vol.blackVolVariance surface (DatePoint d2) strike False+ varAtD2 <- Vol.blackVariance surface (DatePoint d2) strike False fwdVarDates `shouldSatisfy` closePrec (varAtD2 - varAtDate) tolerance -- BlackConstantVol::minStrike/maxStrike return QL_MIN_REAL/QL_MAX_REAL: exercise the -- generic 'HasStrikeBounds (GenVolatilityTermStructure v)' instance through a real@@ -2058,14 +2173,95 @@ , 0.20, nodeVol , 0.35, 0.32 ]- piecewise <- Vol.piecewiseBlackVarianceSurface refDate [otherDate, nodeDate]- [80, 100, 120] volMatrix dc+ piecewise <- Vol.piecewiseBlackVarianceSurface refDate+ (Vol.VarianceGrid [otherDate, nodeDate] [80, 100, 120] volMatrix) dc False q <- Quote.simpleQuote nodeVol flat <- Vol.blackConstantVol (Vol.CalendarReferenceDate refDate) cal q dc npvPiecewise <- mkNpv piecewise npvFlat <- mkNpv flat npvPiecewise `shouldSatisfy` closePrec npvFlat tolerance + describe "piecewise Black variance surface from strike slices" $ do+ -- Upstream's testRaggedStrikeGrids/testExtrapolation fixtures (piecewiseblackvariancesurface.cpp),+ -- with section variances computed here from linear vol interpolation in strike.+ let refDate = 15 `january` 2026+ d1 = 15 `july` 2026+ dMid = 15 `october` 2026+ d2 = 15 `january` 2027+ yf d = fromIntegral (diffDays d refDate) / 365 :: Double+ linear nodes k = case [(k0, v0, k1, v1) | ((k0, v0), (k1, v1)) <- zip nodes (drop 1 nodes), k <= k1] of+ (k0, v0, k1, v1) : _ -> v0 + (v1 - v0) * (k - k0) / (k1 - k0)+ [] -> let ((k0, v0), (k1, v1)) = (nodes !! (length nodes - 2), last nodes)+ in v0 + (v1 - v0) * (k - k0) / (k1 - k0)+ sectionVar nodes d k = linear nodes k ^ (2 :: Int) * yf d+ strikes1 = [(80, 0.30), (100, 0.20), (120, 0.18)] :: [(Double, Double)]+ strikes2 = [(70, 0.35), (90, 0.25), (110, 0.22), (130, 0.20)] :: [(Double, Double)]+ ragged = Vol.VarianceSlices [(d1, fromList strikes1), (d2, fromList strikes2)]+ tolerance = 1.0e-12+ outsideRange = \case+ Context.CPlusPlusException message -> "outside the range" `isInfixOf` message+ _ -> False+ it "reprices each slice at its own strikes and refuses a strike outside an enclosing slice" $+ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just refDate)+ dc <- dayCounter Actual365FixedStandard+ surface <- Vol.piecewiseBlackVarianceSurface refDate ragged dc False+ forM_ ([(d1, strikes1), (d2, strikes2)] :: [(Day, [(Double, Double)])]) $ \(d, nodes) -> forM_ nodes $ \(k, v) ->+ Vol.blackVariance surface (DatePoint d) k False+ >>= (`shouldSatisfy` closePrec (v * v * yf d) tolerance)+ -- 75 lies in the second slice's strikes but not the first's.+ Vol.blackVariance surface (DatePoint dMid) 75 False `shouldThrow` outsideRange+ -- The query's own extrapolation flag does not reach the section range check.+ Vol.blackVariance surface (DatePoint dMid) 75 True `shouldThrow` outsideRange+ it "interpolates total variance across slices with different strike sets when extrapolating" $+ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just refDate)+ dc <- dayCounter Actual365FixedStandard+ surface <- Vol.piecewiseBlackVarianceSurface refDate ragged dc True+ let alpha = (yf dMid - yf d1) / (yf d2 - yf d1)+ var1 = sectionVar strikes1 d1 75+ var2 = sectionVar strikes2 d2 75+ Vol.blackVariance surface (DatePoint dMid) 75 False+ >>= (`shouldSatisfy` closePrec (var1 + (var2 - var1) * alpha) tolerance)+ forM_ ([70, 80, 90, 100, 110, 120, 130] :: [Double]) $ \k -> do+ vars <- mapM (\d -> Vol.blackVariance surface (DatePoint d) k False) ([d1, dMid, d2] :: [Day])+ and (zipWith (\a b -> a <= b + tolerance) vars (drop 1 vars)) `shouldBe` True+ it "keeps the last slice's volatility flat beyond its date" $+ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just refDate)+ dc <- dayCounter Actual365FixedStandard+ surface <- Vol.piecewiseBlackVarianceSurface refDate+ (Vol.VarianceSlices [(d1, [(90, 0.20), (110, 0.20)]), (d2, [(90, 0.30), (110, 0.30)])]) dc True+ let beyond = 15 `january` 2028+ Vol.blackVariance surface (DatePoint beyond) 100 True+ >>= (`shouldSatisfy` closePrec (0.09 * yf beyond) tolerance)+ Vol.blackVol surface (DatePoint beyond) 100 True >>= (`shouldSatisfy` closePrec 0.30 tolerance)+ it "reads the next slice at an interior expiry, so only extrapolation admits a wing quoted there alone" $+ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just refDate)+ dc <- dayCounter Actual365FixedStandard+ let wide = [(60, 0.32), (100, 0.20), (140, 0.24)] :: [(Double, Double)]+ nodes = Vol.VarianceSlices+ [(d1, [(70, 0.30), (130, 0.22)]), (dMid, fromList wide), (d2, [(80, 0.26), (120, 0.21)])]+ strict <- Vol.piecewiseBlackVarianceSurface refDate nodes dc False+ Vol.blackVol strict (DatePoint dMid) 65 False `shouldThrow` \case+ Context.CPlusPlusException message -> "outside the range of smile section 2" `isInfixOf` message+ _ -> False+ extrapolating <- Vol.piecewiseBlackVarianceSurface refDate nodes dc True+ Vol.blackVol extrapolating (DatePoint dMid) 65 False+ >>= (`shouldSatisfy` closePrec (linear wide 65) tolerance)+ it "refuses slices that cannot be interpolated" $+ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just refDate)+ dc <- dayCounter Actual365FixedStandard+ let refused fragment nodes = Vol.piecewiseBlackVarianceSurface refDate (Vol.VarianceSlices nodes) dc False+ `shouldThrow` \case+ Context.CPlusPlusException message -> fragment `isInfixOf` message+ _ -> False+ refused "at least 2" [(d1, [(100, 0.2)])]+ refused "strictly increasing" [(d1, [(100, 0.2), (100, 0.25)])]+ refused "must be after reference date" [(refDate, [(90, 0.2), (110, 0.2)])]+ describe "extended Black variance surface" $ it "rejects QuantLib <= 1.43 before entering its out-of-bounds implementation" $ Context.keepingSettingsGc $ do@@ -2403,21 +2599,21 @@ -- trigger calibration (lazy -- see the shim comment on qlSabrSwaptionVolatilityCube) _ <- Vol.swaptionVolatility cube (Vol.OptionDate (10 `december` 2013)) (Vol.SwapTenor (2, Years)) 0.03 False let n = fromIntegral (length optionTenors * length swapTenors)- sparse <- Vol.sparseSabrParameters cube+ sparse <- Vol.sabrSparseParameters cube realMatrixRows sparse `shouldBe` n -- 2 metadata columns (swapLength, optionTime) + 4 SABR params + forward/error/maxError/endCriteria realMatrixColumns sparse `shouldBe` 10- -- denseSabrParameters is only ever populated when the cube was built with+ -- sabrDenseParameters is only ever populated when the cube was built with -- isAtmCalibrated = True (see the ctor body: denseParameters_ is never assigned -- otherwise, staying at its empty default-Cube state) -- assert that documented- -- behavior rather than a populated shape. volCubeAtmCalibrated, by contrast, is always- -- set to a copy of marketVolCube_ regardless of isAtmCalibrated, so it's populated here.- dense <- Vol.denseSabrParameters cube+ -- behavior rather than a populated shape. sabrVolCubeAtmCalibrated, by contrast, is always+ -- set to a copy of sabrMarketVolCube_ regardless of isAtmCalibrated, so it's populated here.+ dense <- Vol.sabrDenseParameters cube realMatrixRows dense `shouldBe` 0- market <- Vol.marketVolCube cube+ market <- Vol.sabrMarketVolCube cube realMatrixRows market `shouldBe` n realMatrixColumns market `shouldBe` (fromIntegral (length strikeSpreads) + 2)- atmCalibrated <- Vol.volCubeAtmCalibrated cube+ atmCalibrated <- Vol.sabrVolCubeAtmCalibrated cube realMatrixRows atmCalibrated `shouldBe` n realMatrixColumns atmCalibrated `shouldBe` (fromIntegral (length strikeSpreads) + 2) -- alpha/nu are positive, rho within [-1,1] at every calibrated node (columns 2,4,5, 0-indexed)
test/hspec/QuantLib/Spec/TermStructure/Commodity.hs view
@@ -33,7 +33,7 @@ ccy <- Curve.currency curve ccy `shouldBe` usd Curve.nodes curve `shouldReturn` zip dates prices- Curve.isEmpty curve `shouldBe` False+ Curve.isEmpty curve `shouldReturn` False it "has no basis curve until one is set, and finds it afterwards" $ do ho <- commodityType "HO" "Heating Oil"
test/hspec/QuantLib/Spec/TermStructure/Inflation.hs view
@@ -109,7 +109,7 @@ curve <- piecewiseZeroInflationCurve evalDate baseDate' Monthly dc (fromList helpers) Nothing Linear forM_ quotes $ \(n, rate) -> do fresh <- helperAt 0 n- zeroCouponInflationSwapImpliedQuoteOn fresh curve >>= (`shouldSatisfy` closePrec rate 1.0e-8)+ impliedQuoteOn fresh curve >>= (`shouldSatisfy` closePrec rate 1.0e-8) it "a year-on-year helper reads its swap rate on a curve it did not bootstrap" $ Context.keepingSettingsGc $ do Context.setEvaluationDate (Just evalDate)@@ -132,7 +132,58 @@ curve <- piecewiseYoyInflationCurve evalDate baseDate' 0.03 Monthly dc (fromList helpers) Nothing Linear forM_ quotes $ \(n, rate) -> do fresh <- helperAt 0 n- yearOnYearInflationSwapImpliedQuoteOn fresh curve >>= (`shouldSatisfy` closePrec rate 1.0e-8)+ impliedQuoteOn fresh curve >>= (`shouldSatisfy` closePrec rate 1.0e-8)++ it "a bootstrapped zero curve's nodes rebuild it, seasonality included" $ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just evalDate)+ gbp <- currency GBP+ r <- customRegion "InflationSwapHelper Test" "ISHT"+ cal <- calendar Null+ dc <- dayCounter Actual365FixedStandard+ zii0 <- customZeroInflationIndex "ISHT Zero" r False Monthly (1, Months) gbp Nothing+ fixingDates <- mapM (\n -> advance cal evalDate (n, Months) Unadjusted False) [-96 .. 12 :: Int]+ forM_ (zip [1 :: Double ..] fixingDates) $ \(i, d) -> addFixing zii0 d (100.0 + i * 0.1) False+ helpers <- mapM (\(n, rate) -> do+ m <- advance cal evalDate (n, Years) Unadjusted False+ q <- simpleQuote rate+ zeroCouponInflationSwapHelper q (2, Months) (InflationSwapToMaturity m) cal Unadjusted dc zii0 CPIFlat LastRelevantDate Nothing)+ [(2, 0.03), (5, 0.028), (10, 0.025) :: (Int, Double)]+ baseDate' <- advance cal evalDate (-2, Months) Unadjusted False+ let seasonality = Just (MultiplicativePriceSeasonality baseDate' Monthly [1.0, 1.01, 1.02, 1.015, 1.005, 0.995, 0.99, 0.985, 0.99, 1.0, 1.005, 1.01])+ curve <- piecewiseZeroInflationCurve evalDate baseDate' Monthly dc (fromList helpers) seasonality Linear+ nodes <- bootstrappedNodes curve+ map fst nodes `shouldSatisfy` \ds -> length ds == 4 && take 1 ds == [baseDate'] && and (zipWith (<) ds (drop 1 ds))+ rebuilt <- interpolatedZeroInflationCurve evalDate (fromList nodes) Monthly dc seasonality Linear+ forM_ [6, 18, 30, 66, 114 :: Integer] $ \k -> do+ let d = addGregorianMonthsClip k evalDate+ expected <- zeroRate curve d False+ zeroRate rebuilt d False `shouldReturn` expected++ it "a bootstrapped year-on-year curve's nodes rebuild it" $ Context.keepingSettingsGc $ do+ Context.setEvaluationDate (Just evalDate)+ gbp <- currency GBP+ r <- customRegion "InflationSwapHelper Test" "ISHT"+ cal <- calendar Null+ dc <- dayCounter Actual365FixedStandard+ yii0 <- customYoyInflationIndex "ISHT YoY" r False Monthly (1, Months) gbp Nothing+ fixingDates <- mapM (\n -> advance cal evalDate (n, Months) Unadjusted False) [-96 .. 12 :: Int]+ forM_ (zip [1 :: Double ..] fixingDates) $ \(i, d) -> addFixing yii0 d (0.03 + i * 0.0001) False+ nominalQ <- simpleQuote 0.02+ nominalCurve <- flatForward (ReferenceDate evalDate) nominalQ dc IR.Continuous Annual+ helpers <- mapM (\(n, rate) -> do+ m <- advance cal evalDate (n, Years) Unadjusted False+ q <- simpleQuote rate+ yearOnYearInflationSwapHelper q (3, Months) (InflationSwapToMaturity m) cal Unadjusted dc yii0 CPIFlat nominalCurve LastRelevantDate Nothing)+ [(2, 0.03), (5, 0.028) :: (Int, Double)]+ baseDate' <- advance cal evalDate (-2, Months) Unadjusted False+ curve <- piecewiseYoyInflationCurve evalDate baseDate' 0.03 Monthly dc (fromList helpers) Nothing Linear+ nodes <- bootstrappedNodes curve+ map fst nodes `shouldSatisfy` \ds -> length ds == 3 && take 1 ds == [baseDate']+ rebuilt <- interpolatedYoyInflationCurve evalDate (fromList nodes) Monthly dc Nothing Linear+ forM_ [6, 18, 42 :: Integer] $ \k -> do+ let d = addGregorianMonthsClip k evalDate+ expected <- yoyRate curve d False+ yoyRate rebuilt d False `shouldReturn` expected -- The shim once mapped the interpolation with `== 0 ? Flat : Linear`, but CPIFlat is 1, so every -- helper interpolated linearly and these two curves were the same.
test/hspec/QuantLib/Spec/TermStructure/InflationVolatility.hs view
@@ -1,6 +1,8 @@-module QuantLib.Spec.TermStructure.InflationVolatility (spec) where+module QuantLib.Spec.TermStructure.InflationVolatility (spec, setup) where +import Control.Exception (SomeException, displayException) import Control.Monad(forM_, zipWithM_)+import Data.List (isInfixOf) import Data.Time.Calendar(addDays, addGregorianYearsClip) import Data.List.NonEmpty(fromList) import qualified Data.Vector.Storable as V@@ -128,7 +130,7 @@ let fixingDays = 0 yyLag = (3, Months)- priceSurfEU <- yoyCapFloorTermPriceSurface fixingDays yyLag yoyIndexEU CPILinear nominalEUR dc cal ModifiedFollowing+ priceSurfEU <- yoyCapFloorTermPriceSurface BookedAtEvaluationDate fixingDays yyLag yoyIndexEU CPILinear nominalEUR dc cal ModifiedFollowing cStrikesEU fStrikesEU cfMaturitiesEU capPricesEU floorPricesEU Bicubic (Cubic Kruger) return (eval, cal, dc, nominalEUR, yoyIndexEU, priceSurfEU)@@ -136,6 +138,15 @@ spec :: Spec spec = do describe "YoY optionlet stripper (KInterpolatedYoYOptionletVolatilitySurface)" $ do+ it "booked ATM helpers survive a clock after their first maturity" $ Context.keepingSettingsGc $ do+ (eval, _, _, _, _, prices) <- setup+ rates <- yoyCapFloorAtmYoySwapDateRates prices+ ratesBefore <- mapM (\(date, _) -> yoyCapFloorAtmYoyRate prices date Nothing True) rates+ Context.setEvaluationDate (Just (addGregorianYearsClip 2 eval))+ Context.setEvaluationDate (Just eval)+ ratesAfter <- mapM (\(date, _) -> yoyCapFloorAtmYoyRate prices date Nothing True) rates+ zipWithM_ (\a b -> abs (a-b) `shouldSatisfy` (< 1e-12)) ratesBefore ratesAfter+ it "interpolatedYoyInflationCurve: a non-Linear interpolation builds and differs between nodes" $ Context.keepingSettingsGc $ do let eval = 23 `november` 2007 Context.setEvaluationDate (Just eval)@@ -156,8 +167,8 @@ it "matches an independent C++ reprise of upstream's testYoYPriceSurfaceToVol fixture" $ Context.keepingSettingsGc $ do (_, cal, dc, nominalEUR, yoyIndexEU, priceSurfEU) <- setup - yoySurf <- kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack 0 cal ModifiedFollowing dc- priceSurfEU yoyIndexEU nominalEUR (-0.5) Linear+ yoySurf <- kInterpolatedYoyOptionletVolatilitySurface YoyUnitDisplacedBlack 0 cal ModifiedFollowing dc+ priceSurfEU yoyIndexEU nominalEUR (-0.5) Nothing Linear strikes <- yoyCapFloorStrikes priceSurfEU baseDate <- yoyCapFloorBaseDate priceSurfEU@@ -212,7 +223,7 @@ zii <- zeroInflationIndex EUHICP yoyIndexEU <- yoyInflationIndexFromZero zii (Just yoyEU) - priceSurf <- yoyCapFloorTermPriceSurface 0 (3, Months) yoyIndexEU CPILinear nominalEUR dc cal ModifiedFollowing+ priceSurf <- yoyCapFloorTermPriceSurface MovingStart 0 (3, Months) yoyIndexEU CPILinear nominalEUR dc cal ModifiedFollowing cStrikesEU fStrikesEU cfMaturitiesEU capPricesEU floorPricesEU Bilinear Linear ((rate1st, _):_) <- yoyCapFloorAtmYoySwapDateRates priceSurf rate <- yoyCapFloorAtmYoySwapRate priceSurf rate1st True@@ -224,11 +235,31 @@ -- LogCubic case in qlInflationVol.cpp's dispatchKInterpolatedYoYOptionletVolatilitySurface). -- This sparse fixture does not converge under Cubic; BackwardFlat exercises another -- interpolator without derivative estimation.- it "kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack: a non-Linear interpolation builds and queries" $ Context.keepingSettingsGc $ do+ it "explicit YoY root brackets retain native default prices and validate bounds" $ Context.keepingSettingsGc $ do+ (_, cal, dc, nominalEUR, index, prices) <- setup+ let invalidBracket :: SomeException -> Bool+ invalidBracket exception = "bracket must be finite, positive and ordered" `isInfixOf` displayException exception+ strip bracket = kInterpolatedYoyOptionletVolatilitySurface YoyUnitDisplacedBlack 0 cal ModifiedFollowing dc+ prices index nominalEUR (-0.5) bracket Linear+ native <- strip Nothing+ explicit <- strip (Just (1e-5, 0.08))+ wider <- strip (Just (1e-6, 0.2))+ base <- yoyCapFloorBaseDate prices+ date <- advance cal base (3, Years) Unadjusted False+ strikes <- yoyCapFloorStrikes prices+ forM_ strikes $ \strike -> do+ reference <- yoyOptionletVolatility native date strike Nothing True+ forM_ [explicit, wider] $ \surface -> do+ actual <- yoyOptionletVolatility surface date strike Nothing True+ abs (actual - reference) `shouldSatisfy` (<= 1e-6 * max 1 (abs reference))+ forM_ [(0, 0.08), (-1, 0.08), (0.08, 0.08), (0.1, 0.08), (0/0, 0.08), (1e-5, 1/0)] $ \bounds ->+ strip (Just bounds) `shouldThrow` invalidBracket++ it "kInterpolatedYoyOptionletVolatilitySurface YoyUnitDisplacedBlack: a non-Linear interpolation builds and queries" $ Context.keepingSettingsGc $ do (_, cal, dc, nominalEUR, yoyIndexEU, priceSurfEU) <- setup - yoySurf <- kInterpolatedYoyOptionletVolatilitySurfaceUnitDisplacedBlack 0 cal ModifiedFollowing dc- priceSurfEU yoyIndexEU nominalEUR (-0.5) BackwardFlat+ yoySurf <- kInterpolatedYoyOptionletVolatilitySurface YoyUnitDisplacedBlack 0 cal ModifiedFollowing dc+ priceSurfEU yoyIndexEU nominalEUR (-0.5) Nothing BackwardFlat (strike1st: _) <- yoyCapFloorStrikes priceSurfEU baseDate <- yoyCapFloorBaseDate priceSurfEU
tools/ql-methods-1.43.txt view
@@ -433,7 +433,7 @@ |x|ql/cashflows/lineartsrpricer.hpp|Real PriceHelper::operator()(Real strike) const; |v|ql/cashflows/multipleresetscoupon.hpp|MultipleResetsCoupon::MultipleResetsCoupon(const Date & paymentDate, Real nominal, const Schedule & resetSchedule, Natural fixingDays, const ext::shared_ptr<IborIndex> & index, Real gearing = 1.0, Rate couponSpread = 0.0, Rate rateSpread = 0.0, const Date & refPeriodStart = Date(), const Date & refPeriodEnd = Date(), const DayCounter & dayCounter = DayCounter(), const Date & exCouponDate = Date()); |v|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Date> & MultipleResetsCoupon::fixingDates() const;-|x|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Time> & MultipleResetsCoupon::dt() const;+|v|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Time> & MultipleResetsCoupon::dt() const; |x|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Date> & MultipleResetsCoupon::valueDates() const; |x|ql/cashflows/multipleresetscoupon.hpp|Spread MultipleResetsCoupon::rateSpread() const; | |ql/cashflows/multipleresetscoupon.hpp|Rate MultipleResetsPricer::swapletPrice() const;@@ -463,7 +463,7 @@ | |ql/cashflows/multipleresetscoupon.hpp|MultipleResetsLeg & MultipleResetsLeg::withAveragingMethod(RateAveraging::Type averagingMethod); |v|ql/cashflows/overnightindexedcoupon.hpp|OvernightIndexedCoupon::OvernightIndexedCoupon(const Date & paymentDate, Real nominal, const Date & startDate, const Date & endDate, const ext::shared_ptr<OvernightIndex> & overnightIndex, Real gearing = 1.0, Spread spread = 0.0, const Date & refPeriodStart = Date(), const Date & refPeriodEnd = Date(), const DayCounter & dayCounter = DayCounter(), bool telescopicValueDates = false, RateAveraging::Type averagingMethod = RateAveraging::Compound, Natural lookbackDays = Null<Natural>(), Natural lockoutDays = 0, bool applyObservationShift = false, bool compoundSpread = false, const Date & rateComputationStartDate = Date(), const Date & rateComputationEndDate = Date(), const Date & exCouponDate = Date(), const ext::optional<Integer> & roundingPrecision = ext::nullopt); |v|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Date> & OvernightIndexedCoupon::fixingDates() const;-|x|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Time> & OvernightIndexedCoupon::dt() const;+|v|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Time> & OvernightIndexedCoupon::dt() const; |v|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Rate> & OvernightIndexedCoupon::indexFixings() const; |x|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Date> & OvernightIndexedCoupon::valueDates() const; |x|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Date> & OvernightIndexedCoupon::interestDates() const;@@ -7975,7 +7975,7 @@ | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::earliestDate() const; | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::maturityDate() const; | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::latestRelevantDate() const;-| |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::pillarDate() const;+|v|ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::pillarDate() const; | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::latestDate() const; | |ql/termstructures/bootstraphelper.hpp|void BootstrapHelper::accept(AcyclicVisitor &); | |ql/termstructures/bootstraphelper.hpp|RelativeDateBootstrapHelper::RelativeDateBootstrapHelper<TS>(const std::variant<Spread, Handle<Quote>> & quote, bool updateDates = true);@@ -8070,7 +8070,7 @@ | |ql/termstructures/credit/piecewisedefaultcurve.hpp|const std::vector<Time> & PiecewiseDefaultCurve::times() const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|const std::vector<Date> & PiecewiseDefaultCurve::dates() const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|const std::vector<Real> & PiecewiseDefaultCurve::data() const;-| |ql/termstructures/credit/piecewisedefaultcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseDefaultCurve::nodes() const;+|v|ql/termstructures/credit/piecewisedefaultcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseDefaultCurve::nodes() const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|void update(); | |ql/termstructures/credit/piecewisedefaultcurve.hpp|Probability survivalProbabilityImpl(Time t) const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|Real defaultDensityImpl(Time t) const;@@ -8184,7 +8184,7 @@ | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|const std::vector<Time> & times() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|const std::vector<Date> & dates() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|const std::vector<Real> & data() const;-| |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const;+|v|ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|void performCalculations() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|Rate yoyRateImpl(Time t) const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|void update();@@ -8195,7 +8195,7 @@ | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|const std::vector<Time> & times() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|const std::vector<Date> & dates() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|const std::vector<Real> & data() const;-| |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const;+|v|ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|void performCalculations() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|Rate zeroRateImpl(Time t) const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|void update();@@ -8430,7 +8430,7 @@ | |ql/termstructures/volatility/equityfx/localvoltermstructure.hpp|void LocalVolTermStructure::accept(AcyclicVisitor &); |v|ql/termstructures/volatility/equityfx/noexceptlocalvolsurface.hpp|NoExceptLocalVolSurface::NoExceptLocalVolSurface(const Handle<BlackVolTermStructure> & blackTS, const Handle<YieldTermStructure> & riskFreeTS, const Handle<YieldTermStructure> & dividendTS, const Handle<Quote> & underlying, Real illegalLocalVolOverwrite); |x|ql/termstructures/volatility/equityfx/noexceptlocalvolsurface.hpp|NoExceptLocalVolSurface::NoExceptLocalVolSurface(const Handle<BlackVolTermStructure> & blackTS, const Handle<YieldTermStructure> & riskFreeTS, const Handle<YieldTermStructure> & dividendTS, Real underlying, Real illegalLocalVolOverwrite);-| |ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|PiecewiseBlackVarianceSurface::PiecewiseBlackVarianceSurface(const Date & referenceDate, const std::vector<Date> & dates, std::vector<ext::shared_ptr<SmileSection>> smileSections, DayCounter dayCounter = DayCounter());+|u|ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|PiecewiseBlackVarianceSurface::PiecewiseBlackVarianceSurface(const Date & referenceDate, const std::vector<Date> & dates, std::vector<ext::shared_ptr<SmileSection>> smileSections, DayCounter dayCounter = DayCounter()); | |ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|PiecewiseBlackVarianceSurface::PiecewiseBlackVarianceSurface(const Date & referenceDate, const Date & date, ext::shared_ptr<SmileSection> smileSection, DayCounter dayCounter = DayCounter()); |v|ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|static ext::shared_ptr<PiecewiseBlackVarianceSurface> PiecewiseBlackVarianceSurface::makeFromGrid(const Date & referenceDate, const std::vector<Date> & dates, const std::vector<Real> & strikes, const Matrix & blackVols, const DayCounter & dc = DayCounter()); |?|ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|DayCounter dayCounter() const;@@ -9124,7 +9124,7 @@ |x|ql/termstructures/yield/piecewiseyieldcurve.hpp|const std::vector<Time> & PiecewiseYieldCurve::times() const; |x|ql/termstructures/yield/piecewiseyieldcurve.hpp|const std::vector<Date> & PiecewiseYieldCurve::dates() const; |x|ql/termstructures/yield/piecewiseyieldcurve.hpp|const std::vector<Real> & PiecewiseYieldCurve::data() const;-|x|ql/termstructures/yield/piecewiseyieldcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseYieldCurve::nodes() const;+|v|ql/termstructures/yield/piecewiseyieldcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseYieldCurve::nodes() const; | |ql/termstructures/yield/piecewiseyieldcurve.hpp|void update(); | |ql/termstructures/yield/piecewiseyieldcurve.hpp|DiscountFactor discountImpl(Time t) const; | |ql/termstructures/yield/piecewiseyieldcurve.hpp|void performCalculations() const;
tools/ql-methods-1.44.txt view
@@ -431,7 +431,7 @@ |x|ql/cashflows/lineartsrpricer.hpp|Real PriceHelper::operator()(Real strike) const; |v|ql/cashflows/multipleresetscoupon.hpp|MultipleResetsCoupon::MultipleResetsCoupon(const Date & paymentDate, Real nominal, const Schedule & resetSchedule, Natural fixingDays, const ext::shared_ptr<IborIndex> & index, Real gearing = 1.0, Rate couponSpread = 0.0, Rate rateSpread = 0.0, const Date & refPeriodStart = Date(), const Date & refPeriodEnd = Date(), const DayCounter & dayCounter = DayCounter(), const Date & exCouponDate = Date()); |v|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Date> & MultipleResetsCoupon::fixingDates() const;-|x|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Time> & MultipleResetsCoupon::dt() const;+|v|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Time> & MultipleResetsCoupon::dt() const; |x|ql/cashflows/multipleresetscoupon.hpp|const std::vector<Date> & MultipleResetsCoupon::valueDates() const; |x|ql/cashflows/multipleresetscoupon.hpp|Spread MultipleResetsCoupon::rateSpread() const; | |ql/cashflows/multipleresetscoupon.hpp|Rate MultipleResetsPricer::swapletPrice() const;@@ -461,7 +461,7 @@ | |ql/cashflows/multipleresetscoupon.hpp|MultipleResetsLeg & MultipleResetsLeg::withAveragingMethod(RateAveraging::Type averagingMethod); |v|ql/cashflows/overnightindexedcoupon.hpp|OvernightIndexedCoupon::OvernightIndexedCoupon(const Date & paymentDate, Real nominal, const Date & startDate, const Date & endDate, const ext::shared_ptr<OvernightIndex> & overnightIndex, Real gearing = 1.0, Spread spread = 0.0, const Date & refPeriodStart = Date(), const Date & refPeriodEnd = Date(), const DayCounter & dayCounter = DayCounter(), bool telescopicValueDates = false, RateAveraging::Type averagingMethod = RateAveraging::Compound, Natural lookbackDays = Null<Natural>(), Natural lockoutDays = 0, bool applyObservationShift = false, bool compoundSpread = false, const Date & rateComputationStartDate = Date(), const Date & rateComputationEndDate = Date(), const Date & exCouponDate = Date(), const std::optional<Integer> & roundingPrecision = std::nullopt); |v|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Date> & OvernightIndexedCoupon::fixingDates() const;-|x|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Time> & OvernightIndexedCoupon::dt() const;+|v|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Time> & OvernightIndexedCoupon::dt() const; |v|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Rate> & OvernightIndexedCoupon::indexFixings() const; |x|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Date> & OvernightIndexedCoupon::valueDates() const; |x|ql/cashflows/overnightindexedcoupon.hpp|const std::vector<Date> & OvernightIndexedCoupon::interestDates() const;@@ -7910,7 +7910,7 @@ | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::earliestDate() const; | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::maturityDate() const; | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::latestRelevantDate() const;-| |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::pillarDate() const;+|v|ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::pillarDate() const; | |ql/termstructures/bootstraphelper.hpp|Date BootstrapHelper::latestDate() const; | |ql/termstructures/bootstraphelper.hpp|void BootstrapHelper::accept(AcyclicVisitor &); | |ql/termstructures/bootstraphelper.hpp|RelativeDateBootstrapHelper::RelativeDateBootstrapHelper<TS>(const std::variant<Spread, Handle<Quote>> & quote, bool updateDates = true);@@ -8005,7 +8005,7 @@ | |ql/termstructures/credit/piecewisedefaultcurve.hpp|const std::vector<Time> & PiecewiseDefaultCurve::times() const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|const std::vector<Date> & PiecewiseDefaultCurve::dates() const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|const std::vector<Real> & PiecewiseDefaultCurve::data() const;-| |ql/termstructures/credit/piecewisedefaultcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseDefaultCurve::nodes() const;+|v|ql/termstructures/credit/piecewisedefaultcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseDefaultCurve::nodes() const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|void update(); | |ql/termstructures/credit/piecewisedefaultcurve.hpp|Probability survivalProbabilityImpl(Time t) const; | |ql/termstructures/credit/piecewisedefaultcurve.hpp|Real defaultDensityImpl(Time t) const;@@ -8118,7 +8118,7 @@ | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|const std::vector<Time> & times() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|const std::vector<Date> & dates() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|const std::vector<Real> & data() const;-| |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const;+|v|ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|void performCalculations() const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|Rate yoyRateImpl(Time t) const; | |ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp|void update();@@ -8129,7 +8129,7 @@ | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|const std::vector<Time> & times() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|const std::vector<Date> & dates() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|const std::vector<Real> & data() const;-| |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const;+|v|ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|std::vector<std::pair<Date, Real>> nodes() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|void performCalculations() const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|Rate zeroRateImpl(Time t) const; | |ql/termstructures/inflation/piecewisezeroinflationcurve.hpp|void update();@@ -8362,7 +8362,7 @@ | |ql/termstructures/volatility/equityfx/localvoltermstructure.hpp|void LocalVolTermStructure::accept(AcyclicVisitor &); |v|ql/termstructures/volatility/equityfx/noexceptlocalvolsurface.hpp|NoExceptLocalVolSurface::NoExceptLocalVolSurface(const Handle<BlackVolTermStructure> & blackTS, const Handle<YieldTermStructure> & riskFreeTS, const Handle<YieldTermStructure> & dividendTS, const Handle<Quote> & underlying, Real illegalLocalVolOverwrite); |x|ql/termstructures/volatility/equityfx/noexceptlocalvolsurface.hpp|NoExceptLocalVolSurface::NoExceptLocalVolSurface(const Handle<BlackVolTermStructure> & blackTS, const Handle<YieldTermStructure> & riskFreeTS, const Handle<YieldTermStructure> & dividendTS, Real underlying, Real illegalLocalVolOverwrite);-| |ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|PiecewiseBlackVarianceSurface::PiecewiseBlackVarianceSurface(const Date & referenceDate, const std::vector<Date> & dates, std::vector<ext::shared_ptr<SmileSection>> smileSections, DayCounter dayCounter = DayCounter());+|u|ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|PiecewiseBlackVarianceSurface::PiecewiseBlackVarianceSurface(const Date & referenceDate, const std::vector<Date> & dates, std::vector<ext::shared_ptr<SmileSection>> smileSections, DayCounter dayCounter = DayCounter()); | |ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|PiecewiseBlackVarianceSurface::PiecewiseBlackVarianceSurface(const Date & referenceDate, const Date & date, ext::shared_ptr<SmileSection> smileSection, DayCounter dayCounter = DayCounter()); |v|ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|static ext::shared_ptr<PiecewiseBlackVarianceSurface> PiecewiseBlackVarianceSurface::makeFromGrid(const Date & referenceDate, const std::vector<Date> & dates, const std::vector<Real> & strikes, const Matrix & blackVols, const DayCounter & dc = DayCounter()); |?|ql/termstructures/volatility/equityfx/piecewiseblackvariancesurface.hpp|DayCounter dayCounter() const;@@ -9053,7 +9053,7 @@ |x|ql/termstructures/yield/piecewiseyieldcurve.hpp|const std::vector<Time> & PiecewiseYieldCurve::times() const; |x|ql/termstructures/yield/piecewiseyieldcurve.hpp|const std::vector<Date> & PiecewiseYieldCurve::dates() const; |x|ql/termstructures/yield/piecewiseyieldcurve.hpp|const std::vector<Real> & PiecewiseYieldCurve::data() const;-|x|ql/termstructures/yield/piecewiseyieldcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseYieldCurve::nodes() const;+|v|ql/termstructures/yield/piecewiseyieldcurve.hpp|std::vector<std::pair<Date, Real>> PiecewiseYieldCurve::nodes() const; | |ql/termstructures/yield/piecewiseyieldcurve.hpp|void update(); | |ql/termstructures/yield/piecewiseyieldcurve.hpp|DiscountFactor discountImpl(Time t) const; | |ql/termstructures/yield/piecewiseyieldcurve.hpp|void performCalculations() const;