Logo
Fully annotated reference manual - version 1.8.12
Loading...
Searching...
No Matches
Namespaces | Classes | Typedefs | Enumerations | Functions
QuantExt Namespace Reference

Namespaces

namespace  CommodityAveragePriceOptionMomementMatching
 
namespace  CrossAssetAnalytics
 
namespace  CrossAssetModelTypes
 
namespace  DateUtilities
 
namespace  detail
 
namespace  tag
 
namespace  ZeroInflation
 

Classes

class  AccrualBondRepoEngine
 Accrual Bond Repo Engine. More...
 
class  AdjustedDefaultCurve
 
class  AmcCalculator
 
class  AmendedCalendar
 Amended calendar. More...
 
class  AnalyticBarrierEngine
 Wrapper engine for the QuantLib engine to take settlement delay into account. More...
 
class  AnalyticCashSettledEuropeanEngine
 Pricing engine for cash settled European vanilla options using analytical formulae. More...
 
class  AnalyticCcLgmFxOptionEngine
 Analytic cc lgm fx option engine. More...
 
class  AnalyticDigitalAmericanEngine
 Analytic pricing engine for American vanilla options with digital payoff. More...
 
class  AnalyticDigitalAmericanKOEngine
 Analytic pricing engine for American Knock-out options with digital payoff. More...
 
class  AnalyticDkCpiCapFloorEngine
 Analytic dk cpi cap floor engine. More...
 
class  AnalyticDoubleBarrierBinaryEngine
 Analytic pricing engine for double barrier binary options. More...
 
class  AnalyticDoubleBarrierEngine
 Wrapper engine for the QuantLib engine to take settlement delay into account. More...
 
class  AnalyticEuropeanEngine
 Pricing engine for European vanilla options using analytical formulae. More...
 
class  AnalyticEuropeanEngineDeltaGamma
 Pricing engine for European vanilla options using analytical formulae. More...
 
class  AnalyticEuropeanForwardEngine
 Pricing engine for European vanilla forward options using analytical formulae. More...
 
class  AnalyticJyCpiCapFloorEngine
 
class  AnalyticJyYoYCapFloorEngine
 
class  AnalyticLgmCdsOptionEngine
 
class  AnalyticLgmSwaptionEngine
 Analytic LGM swaption engine for european exercise. More...
 
class  AnalyticOutperformanceOptionEngine
 Pricing engine for European outperformance options using analytical formulae. More...
 
class  AnalyticXAssetLgmEquityOptionEngine
 Analytic cross-asset lgm equity option engine. More...
 
class  AnnuityMapping
 
class  AnnuityMappingBuilder
 
class  ApoFutureSurface
 Average future price option (APO) surface derived from a future option surface. More...
 
class  Ascot
 ascot More...
 
class  AtmAdjustedSmileSection
 
class  Austria
 
class  AverageFuturePriceHelper
 
class  AverageFXLinked
 
class  AverageFXLinkedCashFlow
 Average FX Linked cash-flow. More...
 
class  AverageOffPeakPowerHelper
 
class  AverageOIS
 Average overnight index swap. More...
 
class  AverageOISRateHelper
 Average OIS Rate Helper. More...
 
class  AverageONIndexedCoupon
 average overnight coupon More...
 
class  AverageONIndexedCouponPricer
 Pricer for average overnight indexed coupons. More...
 
class  AverageONLeg
 helper class building a sequence of overnight coupons More...
 
class  AverageSpotPriceHelper
 
class  BachelierCPICashFlowPricer
 Bachelier CPI CashFlow Pricer. More...
 
class  BachelierCPICouponPricer
 
class  BachelierSwaptionEngineDeltaGamma
 Normal Bachelier-formula swaption engine. More...
 
class  BalanceGuaranteedSwap
 Balance Guaranteed Swap. More...
 
class  BaroneAdesiWhaleyApproximationEngine
 
class  BaseCorrelationQuote
 market element whose value depends on two other market element More...
 
class  BaseCorrelationTermStructure
 
class  BasicCpuFramework
 
class  BasisTwoSwapHelper
 Basis Two Swap Helper. More...
 
class  Basket
 
class  BEHICP
 Belgium HICP index. More...
 
class  Belgium
 
class  BelgiumRegion
 Belgium as geographical/economic region. More...
 
class  BicubicFlat
 BiCubicSpline-interpolation and flat extrapolation factory More...
 
class  BilinearFlat
 BiLinear-interpolation and flat extrapolation factory More...
 
class  BinomialConvertibleEngine
 Binomial Tsiveriotis-Fernandes engine for convertible bonds. More...
 
class  BlackAverageBMACouponPricer
 
class  BlackAverageONIndexedCouponPricer
 Black averaged overnight coupon pricer. More...
 
class  BlackBondOptionEngine
 Black-formula bond option engine. More...
 
class  BlackCdsOptionEngine
 
class  BlackCPICashFlowPricer
 Black CPI CashFlow Pricer. More...
 
class  BlackCPICouponPricer
 
class  BlackIborQuantoCouponPricer
 
class  BlackIndexCdsOptionEngine
 
class  BlackInvertedVolTermStructure
 Black volatility surface that inverts an existing surface. More...
 
class  BlackMonotoneVarVolTermStructure
 Black volatility surface that monotonises the variance in an existing surface. More...
 
class  BlackMultiLegOptionEngine
 
class  BlackMultiLegOptionEngineBase
 
class  BlackNonstandardSwaptionFromMultilegOptionEngine
 
class  BlackOvernightIndexedCouponPricer
 Black compounded overnight coupon pricer. More...
 
class  BlackScholesModelWrapper
 
class  BlackSwaptionEngineDeltaGamma
 Shifted Lognormal Black-formula swaption engine. More...
 
class  BlackSwaptionFromMultilegOptionEngine
 
class  BlackTriangulationATMVolTermStructure
 Black volatility surface that implies an ATM vol based on triangulation. More...
 
class  BlackVarianceCurve3
 Black volatility curve modeled as variance curve. More...
 
class  BlackVarianceSurfaceMoneyness
 Abstract Black volatility surface based on moneyness (moneyness defined in subclasses) More...
 
class  BlackVarianceSurfaceMoneynessForward
 
class  BlackVarianceSurfaceMoneynessSpot
 
class  BlackVarianceSurfaceSparse
 
class  BlackVarianceSurfaceStdDevs
 
class  BlackVolatilityConstantSpread
 Cube that combines an ATM matrix and vol spreads from a cube. More...
 
class  BlackVolatilitySurfaceAbsolute
 
class  BlackVolatilitySurfaceBFRR
 
class  BlackVolatilitySurfaceDelta
 
class  BlackVolatilitySurfaceProxy
 Wrapper class for a BlackVolTermStructure that allows us to proxy one equity vol surface off another. More...
 
class  BlackVolatilityWithATM
 Wrapper class for a BlackVolTermStructure that easily exposes ATM vols. More...
 
class  BlackVolFromCreditVolWrapper
 
class  BMAIndexWrapper
 
class  BOEBaseRateIndex
 Bank of England Base Rate index. More...
 
class  BondBasket
 Bond Basket. More...
 
class  BondFuturesIndex
 Bond Futures Index. More...
 
class  BondIndex
 Bond Index. More...
 
class  BondOption
 Bond option class. More...
 
class  BondRepo
 Bond repo instrument. More...
 
class  BondTRS
 Bond TRS class. More...
 
class  BondTRSCashFlow
 bond trs cashflow More...
 
class  BondTRSLeg
 helper class building a sequence of bond trs cashflows More...
 
class  BondYieldShiftedCurveTermStructure
 
class  BRLCdi
 BRL-CDI index. More...
 
class  BRLCdiCouponPricer
 BRL CDI coupon pricer. More...
 
class  BRLCdiRateHelper
 
class  BRLCdiSwap
 Standard BRL CDI swap. More...
 
class  BucketedDistribution
 Represents a bucketed probability distibution. More...
 
class  Bucketing
 
class  CACPI
 Canadian CPI index. More...
 
class  CanadaRegion
 Canada as geographical/economic region. More...
 
class  CapFlooredAverageBMACouponPricer
 capped floored averaged indexed coupon pricer base class More...
 
class  CapFlooredAverageONIndexedCouponPricer
 capped floored averaged indexed coupon pricer base class More...
 
class  CapFloorHelper
 
class  CapFloorTermVolCurve
 
class  CapFloorTermVolSurface
 Cap/floor term-volatility surface. More...
 
class  CapFloorTermVolSurfaceExact
 Cap/floor smile volatility surface. More...
 
class  CapFloorTermVolSurfaceSparse
 Cap/floor smile volatility surface sparse. More...
 
struct  CapFloorVolatilityEUR
 
class  CappedFlooredAverageBMACoupon
 
class  CappedFlooredAverageONIndexedCoupon
 capped floored overnight indexed coupon More...
 
class  CappedFlooredCPICashFlow
 Capped or floored CPI cashflow. More...
 
class  CappedFlooredCPICoupon
 Capped or floored CPI coupon. More...
 
class  CappedFlooredCPICouponPricer
 
class  CappedFlooredOvernightIndexedCoupon
 capped floored overnight indexed coupon More...
 
class  CappedFlooredOvernightIndexedCouponPricer
 capped floored overnight indexed coupon pricer base class More...
 
class  CappedFlooredYoYInflationCoupon
 
class  CarrMadanMarginalProbability
 
class  CarrMadanMarginalProbabilitySafeStrikes
 
class  CarrMadanSurface
 
class  Cash
 
struct  CashFlowResults
 
class  CashflowRow
 Class representing the row of a cashflow table. More...
 
class  CashFlows
 cashflow-analysis functions in addition to those in QuantLib More...
 
class  CashflowTable
 Class representing the contents of a cashflow table. More...
 
class  CashSettledEuropeanOption
 
class  CBO
 
class  CdsOption
 CDS option. More...
 
class  CdsOptionHelper
 CDS option helper. More...
 
class  CHFSaron
 CHF SARON rate More...
 
class  CHFTois
 CHF TOIS rate More...
 
class  CirppConstantParametrization
 CIR++ Constant Parametrization. More...
 
class  CirppConstantWithFellerParametrization
 CIR++ Constant Parametrization. More...
 
class  CirppImpliedDefaultTermStructure
 
class  CirppParametrization
 CIR++ Parametrization. More...
 
class  CliquetOption
 
struct  CloseEnoughComparator
 
class  CLPCamara
 
class  CmbCoupon
 CMB coupon class. More...
 
class  CmbCouponPricer
 Base pricer for vanilla CMB coupons. More...
 
class  CmbLeg
 helper class building a sequence of capped/floored cmb coupons More...
 
class  CME
 
class  CmsCapHelper
 
class  CmsSpreadCouponPricer2
 base pricer for vanilla CMS spread coupons with a correlation surface More...
 
class  CNHHibor
 CNH-HIBOR index. More...
 
class  CNHShibor
 CNH-SHIBOR index. More...
 
class  CNYRepoFix
 CNY-CNREPOFIX=CFXS-Reuters index. More...
 
class  CommodityAverageBasisPriceCurve
 Commodity average basis price curve. More...
 
class  CommodityAveragePriceOption
 Commodity Average Price Option. More...
 
class  CommodityAveragePriceOptionAnalyticalEngine
 
class  CommodityAveragePriceOptionBaseEngine
 
class  CommodityAveragePriceOptionMonteCarloEngine
 
class  CommodityBasisFutureIndex
 Commodity Basis Future Index. More...
 
class  CommodityBasisPriceCurve
 Commodity basis price curve. More...
 
class  CommodityBasisPriceCurveWrapper
 
class  CommodityBasisPriceTermStructure
 
class  CommodityCashFlow
 
class  CommodityForward
 
class  CommodityFuturesIndex
 
class  CommodityIndex
 Commodity Index. More...
 
class  CommodityIndexedAverageCashFlow
 
class  CommodityIndexedAverageLeg
 Helper class building a sequence of commodity indexed average cashflows. More...
 
class  CommodityIndexedCashFlow
 Cash flow dependent on a single commodity spot price or futures settlement price on a given pricing date. More...
 
class  CommodityIndexedLeg
 Helper class building a sequence of commodity indexed cashflows. More...
 
class  CommodityModel
 
class  CommodityOptionSurfaceStripper
 
class  CommoditySchwartzFutureOptionEngine
 Commodity options on prompt future (with maturity=expiry) priced in the Schwartz model. More...
 
class  CommoditySchwartzModel
 
class  CommoditySchwartzParametrization
 COM Schwartz parametrization. More...
 
class  CommoditySchwartzStateProcess
 COM Schwartz model one-factor state process. More...
 
class  CommoditySpotIndex
 
class  CommoditySpreadOption
 Commodity Spread Option. More...
 
class  CommoditySpreadOptionAnalyticalEngine
 
class  CommoditySwaptionBaseEngine
 Commodity Swaption Engine base class. More...
 
class  CommoditySwaptionEngine
 Commodity Swaption Analytical Engine. More...
 
class  CommoditySwaptionMonteCarloEngine
 Commodity Swaption Monte Carlo Engine. More...
 
class  CompiledFormula
 helper class representing a formula with variables given by an id v More...
 
class  CompoEquityIndex
 
class  CompositeIndex
 
class  CompositeVectorQuote
 
class  ComputationGraph
 
class  ComputeContext
 
class  ComputeEnvironment
 
class  ComputeFramework
 
class  ComputeFrameworkRegistry
 
class  ConfigurableCurrency
 Configurable currency class. More...
 
class  Constant
 Constant-interpolation factory and traits More...
 
class  ConstantCPIVolatility
 
class  ConstantInterpolation
 Constant interpolation More...
 
class  ConstantLossLatentmodel
 
class  ConstantLossModel
 
class  ConstantMaturityBondIndex
 Constant Maturity Bond Index. More...
 
class  ConstantSmileSection
 
class  ConstantSpreadSmileSection
 
class  ConvertibleBond
 convertible bond More...
 
class  ConvertibleBond2
 
class  COPIbr
 COP-IBR index. More...
 
class  CORRA
 CORRA rate More...
 
class  CORRATerm
 
class  CorrelationTermStructure
 Correlation term structure. More...
 
class  CorrelationValue
 Wrapper class that extracts a value at a given time from the term structure. More...
 
struct  CovarianceSalvage
 
class  CPIBachelierCapFloorEngine
 
class  CPIBlackCapFloorEngine
 
class  CPICapFloorEngine
 Basse Class for Black / Bachelier CPI cap floor pricing engines. More...
 
class  CpiCapFloorHelper
 CPI cap floor helper. More...
 
class  CPICoupon
 
class  CPILeg
 Helper class building a sequence of capped/floored CPI coupons. More...
 
class  CPIPriceVolatilitySurface
 Stripped zero inflation volatility structure. More...
 
struct  CPIPriceVolatilitySurfaceDefaultValues
 
class  CPIVolatilitySurface
 
class  CrCirpp
 Cox-Ingersoll-Ross ++ credit model class. More...
 
class  CrCirppStateProcess
 CIR++ Model State Process. More...
 
class  CreditCurve
 
class  CreditLinkedSwap
 
class  CreditVolCurve
 
class  CreditVolCurveWrapper
 
class  CrossAssetModel
 Cross Asset Model. More...
 
class  CrossAssetModelImpliedEqVolTermStructure
 Cross Asset Model Implied EQ Term Structure. More...
 
class  CrossAssetModelImpliedFxVolTermStructure
 Cross Asset Model Implied FX Term Structure. More...
 
class  CrossAssetStateProcess
 Cross Asset Model State Process. More...
 
class  CrossCcyBasisMtMResetSwap
 Cross currency basis MtM resettable swap. More...
 
class  CrossCcyBasisMtMResetSwapHelper
 Cross Ccy Basis MtM Reset Swap Rate Helper. More...
 
class  CrossCcyBasisSwap
 Cross currency basis swap. More...
 
class  CrossCcyBasisSwapHelper
 Cross Ccy Basis Swap Rate Helper. More...
 
class  CrossCcyFixFloatMtMResetSwap
 Cross currency fix float MtM resettable swap. More...
 
class  CrossCcyFixFloatMtMResetSwapHelper
 Cross Ccy Fix Float MtM Reset Swap Rate Helper. More...
 
class  CrossCcyFixFloatSwap
 
class  CrossCcyFixFloatSwapHelper
 Cross currency fix vs. float swap helper. More...
 
class  CrossCcySwap
 Cross currency swap. More...
 
class  CrossCcySwapEngine
 Cross currency swap engine. More...
 
class  CrossCurrencyPriceTermStructure
 Cross currency price term structure. More...
 
class  CrossCurrencySwap
 Cross currency swap. More...
 
class  CrStateParametrization
 Credit State Parametrization. More...
 
class  CubicFlat
 Cubic interpolation and flat extrapolation factory and traits. More...
 
struct  CurrencyComparator
 
class  CurrencySwap
 Currency Interest Rate Swap More...
 
class  Cyprus
 Cyprus Calendar. More...
 
class  CZKPribor
 CZK-PRIBOR index. More...
 
class  DatedBRLCdiRateHelper
 
class  DatedOISRateHelper
 Rate helper for bootstrapping using Overnight Indexed Swaps. More...
 
class  DatedStrippedOptionlet
 Stripped Optionlet Surface. More...
 
class  DatedStrippedOptionletAdapter
 Adapter class for turning a DatedStrippedOptionletBase object into an OptionletVolatilityStructure. More...
 
class  DatedStrippedOptionletBase
 Stripped Optionlet base class interface. More...
 
class  DECPI
 German CPI index. More...
 
class  DefaultableEquityJumpDiffusionModel
 
class  DefaultableEquityJumpDiffusionModelBuilder
 
class  DefaultLatentModel
 Default event Latent Model. More...
 
class  DefaultLossModel
 
class  DEMLibor
 DEM-LIBOR index. More...
 
class  DenmarkRegion
 Denmark as geographical/economic region. More...
 
class  Deposit
 Deposit Instrument. More...
 
class  DepositEngine
 
class  DerivedPriceQuote
 Helper class so that the spot price can be pulled from the price curve each time the spot price is requested. More...
 
class  DifferentialEvolution_MT
 
class  DiscountingBondRepoEngine
 Discounting Bond Repo Engine. More...
 
class  DiscountingBondTRSEngine
 Discounting Bond TRS Engine. More...
 
class  DiscountingCommodityForwardEngine
 Discounting commodity forward engine. More...
 
class  DiscountingCreditLinkedSwapEngine
 
class  DiscountingCurrencySwapEngine
 Discounting CurrencySwap Engine More...
 
class  DiscountingCurrencySwapEngineDeltaGamma
 Discounting currency swap engine providing analytical deltas and gammas. More...
 
class  DiscountingEquityForwardEngine
 Discounting Equity Forward Engine. More...
 
class  DiscountingForwardBondEngine
 Discounting Forward Bond Engine. More...
 
class  DiscountingFxForwardEngine
 Discounting FX Forward Engine. More...
 
class  DiscountingFxForwardEngineDeltaGamma
 Discounting FX Forward Engine providing analytical deltas and gammas. More...
 
class  DiscountingRiskyBondEngine
 Discounting Risky Bond Engine. More...
 
class  DiscountingRiskyBondEngineMultiState
 
class  DiscountingSwapEngineDeltaGamma
 Discounting swap engine providing analytical deltas and gammas. More...
 
class  DiscountingSwapEngineMultiCurve
 Discounting Swap Engine - Multi Curve. More...
 
class  DiscountRatioModifiedCurve
 
class  DiscreteDistribution
 Discrete Distribution. More...
 
class  DiscretizedConvertible
 
class  Distributionpair
 Distributionpair is a helper class for DiscretDistribution. More...
 
struct  Dividend
 
class  DividendManager
 global repository for past dividends More...
 
class  DKCPI
 DK CPI index. More...
 
class  DkImpliedYoYInflationTermStructure
 
class  DkImpliedZeroInflationTermStructure
 
class  DKKCibor
 DKK-CIBOR index. More...
 
class  DKKCita
 DKK CITA More...
 
class  DKKOis
 DKK OIS More...
 
class  DurationAdjustedCmsCoupon
 
class  DurationAdjustedCmsCouponTsrPricer
 
class  DurationAdjustedCmsLeg
 
class  DynamicBlackVolTermStructure
 Takes a BlackVolTermStructure with fixed reference date and turns it into a floating reference date term structure. More...
 
class  DynamicCPIVolatilitySurface
 Converts a CPIVolatilityStructure with fixed reference date into a floating reference date term structure. More...
 
class  DynamicOptionletVolatilityStructure
 Converts OptionletVolatilityStructure with fixed reference date into a floating reference date term structure. More...
 
class  DynamicSwaptionVolatilityMatrix
 Takes a SwaptionVolatilityMatrix with fixed reference date and turns it into a floating reference date term. More...
 
class  DynamicYoYOptionletVolatilitySurface
 Converts YoYOptionletVolatilitySurface with fixed reference date into a floating reference date term structure. More...
 
class  EqBsConstantParametrization
 EQ Black Scholes parametrization. More...
 
class  EqBsParametrization
 EQ Black Scholes parametrizations. More...
 
class  EqBsPiecewiseConstantParametrization
 EQ Black Scholes constant parametrization. More...
 
class  EqFxIndexBase
 Equity Index. More...
 
class  EquityCoupon
 equity coupon More...
 
class  EquityCouponPricer
 Pricer for equity coupons. More...
 
class  EquityForward
 
class  EquityForwardCurveStripper
 
class  EquityIndex2
 Equity Index. More...
 
class  EquityLeg
 helper class building a sequence of equity coupons More...
 
class  EquityMarginCoupon
 equity coupon More...
 
class  EquityMarginCouponPricer
 Pricer for equity margin coupons. More...
 
class  EquityMarginLeg
 helper class building a sequence of equity margin coupons More...
 
class  EquityOptionSurfaceStripper
 
class  ESCPI
 Spain CPI index. More...
 
class  ExceptionQuote
 A dummy quote class that throws an exception when value is called. More...
 
class  ExtendedConstantLossLatentModel
 
class  ExtendedConstantLossModel
 
class  ExternalRandomVariable
 
class  FallbackIborIndex
 
class  FallbackOvernightIndex
 
class  FdConvertibleBondEvents
 
class  FdDefaultableEquityJumpDiffusionConvertibleBondEngine
 
class  FdmBlackScholesMesher
 
class  FdmBlackScholesOp
 
class  FdmDefaultableEquityJumpDiffusionFokkerPlanckOp
 
class  FdmDefaultableEquityJumpDiffusionOp
 
class  FdmLgmOp
 
class  FdmQuantoHelper
 
struct  Filter
 
class  FixedBMASwap
 swap paying a fixed rate against BMA coupons More...
 
class  FixedRateFXLinkedNotionalCoupon
 
class  FlatCorrelation
 Flat correlation structure. More...
 
class  FlatExtrapolation
 Flat extrapolation given a base interpolation. More...
 
class  FlatForwardDividendCurve
 
class  FlexiSwap
 Flexi-Swap with global notional bounds. More...
 
class  FloatingAnnuityCoupon
 floating annuity coupon More...
 
class  FloatingAnnuityNominal
 
class  FloatingRateFXLinkedNotionalCoupon
 
class  FormulaBasedCoupon
 formula based coupon class More...
 
class  FormulaBasedCouponPricer
 base pricer for formula based coupons More...
 
class  FormulaBasedIndex
 formula based index class More...
 
class  FormulaBasedLeg
 helper class building a sequence of formula based coupons More...
 
class  ForwardBond
 Forward Bond class. More...
 
class  ForwardBondTypePayoff
 Class for forward type payoffs. More...
 
class  France
 
class  FRCPI
 French CPI index. More...
 
class  FutureExpiryCalculator
 Base class for classes that perform date calculations for future contracts. More...
 
class  FutureOptionHelper
 Future Option Helper. More...
 
class  FuturePriceHelper
 
class  FxBlackVannaVolgaVolatilitySurface
 Fx Black vanna volga volatility surface. More...
 
class  FxBlackVolatilitySurface
 Fx Black volatility surface. More...
 
class  FxBsConstantParametrization
 FX Black Scholes parametrization. More...
 
class  FxBsModel
 
class  FxBsParametrization
 FX Black Scholes parametrizations. More...
 
class  FxBsPiecewiseConstantParametrization
 FX Black Scholes constant parametrization. More...
 
class  FxEqOptionHelper
 FxEq Option Helper. More...
 
class  FxForward
  FX Forward More...
 
class  FxIndex
 FX Index. More...
 
class  FXLinked
 Base class for FX Linked cashflows. More...
 
class  FXLinkedCashFlow
 FX Linked cash-flow. More...
 
class  FxModel
 
class  FxRateQuote
 
class  FxSmileSection
 
class  FxSpotQuote
 
class  Gaussian1dCrossAssetAdaptor
 Gaussian 1d Cross Asset adaptor. More...
 
class  GaussianLHPLossModel
 
class  GeneralisedReplicatingVarianceSwapEngine
 
class  GeneratorDefaultProbabilityTermStructure
 Default probability term structure implied from a transition matrix. More...
 
class  GenericIborIndex
 Generic Ibor Index. More...
 
class  GenericIndex
 Generic Index. More...
 
class  GenericSwaption
 Swaption class with QuantLib::Swap underlying More...
 
class  GermanyRegion
 Germany as geographical/economic region. More...
 
class  Greece
 Greece Calendar. More...
 
class  HazardSpreadedDefaultTermStructure
 Hazard Spreaded Default Term Structure. More...
 
class  HermiteFlat
 Hermite interpolation and flat extrapolation factory and traits. More...
 
class  HKDHibor
 HKD-HIBOR index. More...
 
class  HKDHonia
 HKD-HONIA index. More...
 
class  HomogeneousPoolLossModel
 Default loss distribution convolution for finite homogeneous pool. More...
 
class  HUFBubor
 HUF-BUBOR index. More...
 
class  HullWhiteBucketing
 
class  HwConstantParametrization
 HW nF Parametrization with m driving Brownian motions and constant reversion, vol. More...
 
class  HwModel
 
class  HwParametrization
 HW nF Parametrization with m driving Brownian motions. More...
 
class  IborFallbackCurve
 
class  IborFraCoupon
 Coupon paying a Forward rate aggreement payoff with and ibor-type index underlying More...
 
class  IborIndexWithFixingOverride
 wrapper for ibor index wit individiual trade level fixings More...
 
class  ICE
 
class  IDRIdrfix
 IDR-IDRFIX index. More...
 
class  IDRJibor
 IDR-JIBOR index. More...
 
class  ILSTelbor
 ILS-TELBOR index. More...
 
class  ImmFraRateHelper
 
class  ImpliedDefaultTermStructure
 
class  IndexCdsOption
 Index CDS option instrument. More...
 
class  IndexCdsOptionBaseEngine
 
class  IndexCdsTrancheEngine
 
class  IndexCreditDefaultSwap
 
class  IndexedCoupon
 indexed coupon More...
 
class  IndexedCouponLeg
 indexed coupon leg More...
 
class  IndexWrappedCashFlow
 indexed cashflow More...
 
class  InfDkVectorised
 
class  InfJyParameterization
 
class  InflationCashFlowPricer
 Base class for CPI CashFLow and Coupon pricers. More...
 
class  InflationIndexObserver
 Inflation Index observer. More...
 
class  InhomogeneousPoolLossModel
 Default loss distribution convolution for finite non homogeneous pool. More...
 
class  INRMiborOis
 INR-MIBOROIS index. More...
 
class  INRMifor
 INR-MIFOR index. More...
 
class  InterpolatedBaseCorrelationTermStructure
 
class  InterpolatedCapFloorTermVolCurve
 Interpolated cap floor term volatility curve. More...
 
class  InterpolatedCorrelationCurve
 CorrelationTermStructure based on interpolation of correlations. More...
 
class  InterpolatedCPIVolatilitySurface
 Interpolated zero inflation volatility structure. More...
 
class  InterpolatedDiscountCurve
 InterpolatedDiscountCurve based on loglinear interpolation of DiscountFactors. More...
 
class  InterpolatedDiscountCurve2
 InterpolatedDiscountCurve2 as in QuantLib, but with floating discount quotes and floating reference date. More...
 
class  InterpolatedHazardRateCurve
 DefaultProbabilityTermStructure based on interpolation of hazard rates. More...
 
class  InterpolatedOptionletCurve
 
class  InterpolatedPriceCurve
 Interpolated price curve. More...
 
class  InterpolatedSmileSection
 
class  InterpolatedSurvivalProbabilityCurve
 DefaultProbabilityTermStructure based on interpolation of survival probabilities. More...
 
class  InterpolatedYoYCapFloorTermPriceSurface
 Interpolated YoY Inflation Cap floor term price surface. More...
 
class  InterpolatingCPICapFloorEngine
 
class  InterpolatingCreditVolCurve
 
class  IntrinsicAscotEngine
 Intrinsic engine for Ascots. More...
 
class  Ireland
 Ireland Calendars. More...
 
class  IrHwStateProcess
 Ir HW State Process. More...
 
class  IrLgm1fStateProcess
 Ir Lgm 1f State Process. More...
 
class  IrModel
 
class  IslamicWeekendsOnly
 Islamic Weekends-only calendar. More...
 
class  Israel
 Israel calendar. More...
 
class  IterativeBootstrap
 
class  JPYEYTIBOR
 JPY Euroyen TIBOR index More...
 
class  JyImpliedYoYInflationTermStructure
 
class  JyImpliedZeroInflationTermStructure
 
class  JyYoYInflationCouponPricer
 JY pricer for YoY inflation coupons. More...
 
class  KienitzLawsonSwayneSabrPdeDensity
 
class  KInterpolatedYoYOptionletVolatilitySurface
 K-interpolated YoY optionlet volatility. More...
 
class  KRWCd
 KRW-CD index. More...
 
class  KRWKoribor
 KRW-KORIBOR index. More...
 
class  Lgm1fConstantParametrization
 LGM 1F Constant Parametrization. More...
 
class  Lgm1fParametrization
 LGM 1F Parametrization. More...
 
class  Lgm1fPiecewiseConstantHullWhiteAdaptor
 LGM 1f Piecewise Constant Hull White Adaptor. More...
 
class  Lgm1fPiecewiseConstantParametrization
 LGM 1F Piecewise Constant Parametrization. More...
 
class  Lgm1fPiecewiseLinearParametrization
 Lgm 1f Piecewise Linear Parametrization. More...
 
class  LgmBackwardSolver
 Interface for LGM1F backward solver. More...
 
struct  LgmCalibrationData
 
struct  LgmCalibrationInfo
 
class  LgmConvolutionSolver
 Numerical convolution solver for the LGM model. More...
 
class  LgmConvolutionSolver2
 Numerical convolution solver for the LGM model. More...
 
class  LgmFdSolver
 Numerical FD solver for the LGM model. More...
 
class  LgmImpliedDefaultTermStructure
 Lgm Implied Default Term Structure. More...
 
class  LgmImpliedYieldTermStructure
 Lgm Implied Yield Term Structure. More...
 
class  LgmImpliedYtsFwdFwdCorrected
 Lgm Implied Yts Fwd Corrected. More...
 
class  LgmImpliedYtsSpotCorrected
 Lgm Implied Yts Spot Corrected. More...
 
class  LgmVectorised
 
class  LinearAnnuityMapping
 
class  LinearAnnuityMappingBuilder
 
class  LinearFlat
 Linear-interpolation and flat extrapolation factory and traits More...
 
class  LinearGaussMarkovModel
 Linear Gauss Morkov Model. More...
 
class  LinkableCalibratedModel
 Calibrated model class with linkable parameters. More...
 
class  LogLinearFlat
 Linear-interpolation and flat extrapolation factory and traits More...
 
class  LognormalCmsSpreadPricer
 CMS spread - coupon pricer. More...
 
class  LogQuadratic
 log-quadratic interpolation factory and traits More...
 
class  LogQuadraticInterpolation
 log-quadratic interpolation between discrete points More...
 
class  LogQuote
 Class for storing logs of quotes for log-linear interpolation. More...
 
class  LossModelConditionalDist
 
class  Luxembourg
 
class  MakeAverageOIS
 helper class More...
 
class  MakeCreditDefaultSwap
 helper class More...
 
class  MakeFixedBMASwap
 
class  MakeOISCapFloor
 
class  MakeSubPeriodsSwap
 
class  MarketObserver
 Observer class for Model Builders. More...
 
class  Mauritius
 Mauritius calendar. More...
 
class  McCamCurrencySwapEngine
 
class  McCamFxForwardEngine
 
class  McCamFxOptionEngine
 
struct  McEngineStats
 
class  MCGaussianFormulaBasedCouponPricer
 Formula based coupon pricer. More...
 
class  McLgmNonstandardSwaptionEngine
 
class  McLgmSwapEngine
 
class  McLgmSwaptionEngine
 
class  McMultiLegBaseEngine
 
class  McMultiLegOptionEngine
 
class  MDD
 Modify Distrete Distribution. More...
 
class  MidPointCDOEngine
 CDO base engine taking schedule steps. More...
 
class  MidPointCdsEngineMultiState
 
class  MidPointIndexCdsEngine
 
class  ModelBuilder
 
class  ModelImpliedPriceTermStructure
 COM Implied Price Term Structure. More...
 
class  ModelImpliedYieldTermStructure
 IR Implied Yield Term Structure. More...
 
class  ModelImpliedYtsFwdFwdCorrected
 Model Implied Yts Fwd Corrected. More...
 
class  ModelImpliedYtsSpotCorrected
 Lgm Implied Yts Spot Corrected. More...
 
class  MonteCarloCBOEngine
 CBO engine, Monte Carlo for the sample payoff. More...
 
class  MultiCcyCompositeInstrument
 Composite instrument More...
 
class  MultiLegOption
 
class  MultiPathGeneratorBase
 Multi Path Generator Base. More...
 
class  MultiPathGeneratorBurley2020Sobol
 Instantiation of MultiPathGenerator with standard LowDiscrepancy traits. More...
 
class  MultiPathGeneratorBurley2020SobolBrownianBridge
 Instantiation using Burley2020SobolBrownianGenerator from models/marketmodels/browniangenerators. More...
 
class  MultiPathGeneratorFactory
 Standard implementation for path generator factory. More...
 
class  MultiPathGeneratorMersenneTwister
 Instantiation of MultiPathGenerator with standard PseudoRandom traits. More...
 
class  MultiPathGeneratorMersenneTwisterAntithetic
 
class  MultiPathGeneratorSobol
 Instantiation of MultiPathGenerator with standard LowDiscrepancy traits. More...
 
class  MultiPathGeneratorSobolBrownianBridge
 Instantiation using SobolBrownianGenerator from models/marketmodels/browniangenerators. More...
 
class  MultiPathGeneratorSobolBrownianBridgeBase
 Base class for instantiations using brownian generators from models/marketmodels/browniangenerators. More...
 
class  MultiPathVariateGeneratorBase
 
class  MultiPathVariateGeneratorBurley2020Sobol
 
class  MultiPathVariateGeneratorBurley2020SobolBrownianBridge
 
class  MultiPathVariateGeneratorMersenneTwister
 
class  MultiPathVariateGeneratorMersenneTwisterAntithetic
 
class  MultiPathVariateGeneratorSobol
 
class  MultiPathVariateGeneratorSobolBrownianBridge
 
class  MultiPathVariateGeneratorSobolBrownianBridgeBase
 
class  MultiSectionDefaultCurve
 multi section default ts More...
 
class  MXNTiie
 MXN-TIIE index. More...
 
class  MYRKlibor
 MYR-KLIBOR index. More...
 
class  NadarayaWatson
 Nadaraya Watson regression. More...
 
class  NegativeCorrelationTermStructure
 Wrapper class that inverts the correlation. More...
 
class  Netherlands
 
struct  NoCovarianceSalvage
 Implementation that does not change the input matrix. More...
 
class  NOKNibor
 NOK-NIBOR index. More...
 
class  NonStandardBachelierYoYInflationCouponPricer
 Bachelier-formula pricer for capped/floored yoy inflation coupons. More...
 
class  NonStandardBlackYoYInflationCouponPricer
 Black-formula pricer for capped/floored yoy inflation coupons. More...
 
class  NonStandardCappedFlooredYoYInflationCoupon
 Capped or floored inflation coupon. More...
 
class  NonStandardUnitDisplacedBlackYoYInflationCouponPricer
 Unit-Displaced-Black-formula pricer for capped/floored yoy inflation coupons. More...
 
class  NonStandardYoYInflationCoupon
 Coupon paying a YoY-inflation type index More...
 
class  NonStandardYoYInflationCouponPricer
 base pricer for capped/floored YoY inflation coupons More...
 
class  NonStandardYoYInflationLeg
 
class  NormalSABR
 SABR interpolation factory and traits More...
 
class  NormalSABRInterpolation
 SABR smile interpolation between discrete volatility points. More...
 
class  NormalSabrSmileSection
 
class  Nowa
 
class  NullInstrument
 
class  NumericalIntegrationIndexCdsOptionEngine
 
class  NumericLgmBgsFlexiSwapEngine
 Numerical engine for balance guaranteed swaps using a flexi swap proxy in the LGM model. More...
 
class  NumericLgmFlexiSwapEngine
 
class  NumericLgmFlexiSwapEngineBase
 Numerical engine for flexi swaps in the LGM model. More...
 
class  NumericLgmMultiLegOptionEngine
 
class  NumericLgmMultiLegOptionEngineBase
 
class  NumericLgmNonstandardSwaptionEngine
 
class  NumericLgmSwaptionEngine
 
class  NZDBKBM
 NZD-BKBM index. More...
 
class  OffPeakPowerIndex
 Off peak power index. More...
 
class  OICCBSHelper
 Rate helper for bootstrapping over Overnight Indexed CC Basis Swap Spreads. More...
 
class  OISCapFloorHelper
 
class  OISRateHelper
 Rate helper for bootstrapping using Overnight Indexed Swaps. More...
 
class  OpenClFramework
 
class  OptimizationMethod_MT
 Abstract class for constrained optimization method. More...
 
class  OptionInterpolator2d
 
class  OptionInterpolatorBase
 Option surface interpolator base. More...
 
class  OptionletStripper
 
class  OptionletStripper1
 
class  OptionletStripper2
 
class  OptionletStripperWithAtm
 
struct  OptionletTraits
 Traits class that is needed for Bootstrap classes to work More...
 
class  OptionPriceSurface
 
class  OptionSurfaceStripper
 Abstract base class for the option stripper. More...
 
class  OutperformanceOption
 Outperformance option. More...
 
class  OvernightFallbackCurve
 
class  OvernightIndexedCoupon
 overnight coupon More...
 
class  OvernightIndexedCouponPricer
 OvernightIndexedCoupon pricer. More...
 
class  OvernightIndexedCrossCcyBasisSwap
 Basis swap: compounded overnight rate in ccy 1 vs. compounded overnight rate in ccy 2. More...
 
class  OvernightIndexedCrossCcyBasisSwapEngine
 
class  OvernightIndexWithFixingOverride
 
class  OvernightLeg
 helper class building a sequence of overnight coupons More...
 
class  PairwiseVarianceSwap
 Pairwise Variance swap. More...
 
class  PairwiseVarianceSwapEngine
 
class  ParametricVolatility
 
class  ParametricVolatilitySmileSection
 
class  Parametrization
 Parametrization. More...
 
class  PathGeneratorFactory
 Base class for path generator factories. More...
 
class  Payment
 Payment Instrument. More...
 
class  PaymentDiscountingEngine
 Payment discounting engine. More...
 
class  Peru
 
class  Philippines
 
class  PHPPhiref
 PHP-PHIREF index. More...
 
class  PiecewiseAtmOptionletCurve
 
class  PiecewiseConstantHelper1
 Piecewise Constant Helper 1. More...
 
class  PiecewiseConstantHelper11
 Piecewise Constant Helper 11. More...
 
class  PiecewiseConstantHelper2
 Piecewise Constant Helper2. More...
 
class  PiecewiseConstantHelper3
 Piecewise Constant Helper 3. More...
 
class  PiecewiseOptionletCurve
 
class  PiecewiseOptionletStripper
 
class  PiecewisePriceCurve
 Piecewise price term structure. More...
 
class  PiecewiseZeroInflationCurve
 Piecewise zero-inflation term structure. More...
 
class  PLNPolonia
 PLN-POLONIA index. More...
 
class  PoolLossModel
 
class  PriceTermStructure
 Price term structure. More...
 
class  PriceTermStructureAdapter
 Adapter class for turning a PriceTermStructure in to a YieldTermStructure. More...
 
struct  PriceTraits
 Traits class that is needed for Bootstrap classes to work. More...
 
class  PrimeIndex
 USD-Prime index. More...
 
class  Problem_MT
 Constrained optimization problem. More...
 
class  ProjectedBufferedMultiPathGenerator
 
class  ProjectedBufferedMultiPathGeneratorFactory
 
class  ProjectedVariateMultiPathGenerator
 
class  ProjectedVariatePathGeneratorFactory
 
class  ProxyCreditVolCurve
 
class  ProxyOptionletVolatility
 
class  ProxySwaptionVolatility
 
class  PseudoParameter
 Parameter that accesses CalibratedModel. More...
 
class  Quadratic
 Quadratic-interpolation factory and traits More...
 
class  QuadraticInterpolation
 Quadratic interpolation between discrete points More...
 
struct  RandomVariable
 
class  randomvariable_output_pattern
 
class  randomvariable_output_size
 
class  RandomVariableLsmBasisSystem
 
struct  RandomVariableOpCode
 
struct  RandomVariableStats
 
class  RebatedExercise
 Rebated exercise with exercise dates != notification dates and arbitrary period. More...
 
class  RepresentativeFxOptionMatcher
 
class  RepresentativeSwaptionMatcher
 
class  RiskParticipationAgreement
 
class  RiskParticipationAgreementTLock
 
class  RUBKeyRate
 RUB-KEYRATE index. More...
 
class  RussiaModified
 Russian calendars. More...
 
class  SabrParametricVolatility
 
class  SabrStrippedOptionletAdapter
 
class  SAibor
 SAR-SAIBOR index. More...
 
class  SavedObservableSettings
 
class  ScaledCashFlow
 scalable cashflow More...
 
class  ScaledCoupon
 scalable coupon More...
 
class  SECPI
 SE CPI index. More...
 
class  SEKSior
 SEK SIOR More...
 
class  SEKStibor
 SEK-STIBOR index. More...
 
class  SEKStina
 SEK STINA More...
 
class  SGDSibor
 SGD-SIBOR index. More...
 
class  SGDSor
 SGD-SOR index. More...
 
class  SKKBribor
 SKK-BRIBOR index. More...
 
class  SofrTerm
 Sofr term index, see https://www.cmegroup.com/market-data/cme-group-benchmark-administration/term-sofr.html# More...
 
class  SoftCallability
 callability leaving to the holder the possibility to convert More...
 
struct  Solver1DOptions
 
class  SoniaTerm
 Sonia term index, see https://www.bankofengland.co.uk/-/media/boe/files/markets/benchmarks/rfr/rfrwg-term-sonia-reference-rate-summary.pdf# More...
 
class  Sora
 SGD SORA rate More...
 
class  Spain
 
class  SpainRegion
 Spain as geographical/economic region. More...
 
struct  SpectralCovarianceSalvage
 Implementation that uses the spectral method. More...
 
class  SpreadedBaseCorrelationCurve
 Spreaded Base Correlation Curve. More...
 
class  SpreadedBlackVolatilityCurve
 Spreaded Black volatility curve modeled as variance curve. More...
 
class  SpreadedBlackVolatilitySurfaceLogMoneynessForward
 Black volatility surface based on forward log moneyness. More...
 
class  SpreadedBlackVolatilitySurfaceLogMoneynessSpot
 Spreaded Black volatility surface based on spot log moneyness. More...
 
class  SpreadedBlackVolatilitySurfaceMoneyness
 Abstract Spreaded Black volatility surface based on moneyness (moneyness defined in subclasses) More...
 
class  SpreadedBlackVolatilitySurfaceMoneynessForward
 Black volatility surface based on forward moneyness. More...
 
class  SpreadedBlackVolatilitySurfaceMoneynessForwardAbsolute
 Spreaded Black volatility surface based on absolute forward moneyness. More...
 
class  SpreadedBlackVolatilitySurfaceMoneynessSpot
 Spreaded Black volatility surface based on spot moneyness. More...
 
class  SpreadedBlackVolatilitySurfaceMoneynessSpotAbsolute
 Spreaded Black volatility surface based on absolute spot moneyness. More...
 
class  SpreadedBlackVolatilitySurfaceStdDevs
 Black volatility surface based on std devs (standardised log moneyness) More...
 
class  SpreadedCorrelationCurve
 Spreaded Correlation Curve. More...
 
class  SpreadedCPIVolatilitySurface
 
class  SpreadedCreditVolCurve
 
class  SpreadedDiscountCurve
 
class  SpreadedOptionletVolatility
 
class  SpreadedOptionletVolatility2
 
class  SpreadedPriceTermStructure
 Spreaded Price term structure. More...
 
class  SpreadedSmileSection
 
class  SpreadedSmileSection2
 
class  SpreadedSurvivalProbabilityTermStructure
 Spreaded Default Term Structure, the spread is given in terms of loglinearly interpolated survival probabilities. More...
 
class  SpreadedSwaptionVolatility
 
class  SpreadedYoYInflationCurve
 
class  SpreadedYoYVolatilitySurface
 
class  SpreadedZeroInflationCurve
 
class  StabilisedGLLS
 Numerically stabilised general linear least squares. More...
 
class  StaticallyCorrectedYieldTermStructure
 Statically Corrected Yield Term Structure. More...
 
class  Stats
 helper class for the MonteCarloCBOEngine More...
 
class  StrippedCappedFlooredCPICashFlow
 Stripped capped or floored CPI cashflow. More...
 
class  StrippedCappedFlooredCPICoupon
 
class  StrippedCappedFlooredCPICouponLeg
 
class  StrippedCappedFlooredYoYInflationCoupon
 
class  StrippedCappedFlooredYoYInflationCouponLeg
 
class  StrippedCPIVolatilitySurface
 Stripped zero inflation volatility structure. More...
 
struct  StrippedCPIVolSurfaceDefaultValues
 
class  StrippedOptionletAdapter
 
class  StrippedOptionletAdapter2
 
class  StrippedYoYInflationOptionletVol
 
class  SubPeriodsCoupon1
 Sub-periods coupon. More...
 
class  SubPeriodsCouponPricer1
 Pricer for sub-period coupons. More...
 
class  SubPeriodsLeg1
 helper class building a sequence of sub-period coupons More...
 
class  SubPeriodsSwap
 Single currency sub periods swap. More...
 
class  SubPeriodsSwapHelper
 Rate helper for bootstrapping using Sub Periods Swaps. More...
 
struct  SurvivalProbability
 Survival probability curve traits. More...
 
class  SurvivalProbabilityCurve
 DefaultProbabilityTermStructure based on interpolation of survival probability quotes. More...
 
class  SwapConventions
 
struct  SwaptionConventionsEUR
 
struct  SwaptionData
 
class  SwaptionSabrCube
 
class  SwaptionVolatilityConstantSpread
 Swaption cube that combines an ATM matrix and vol spreads from a cube. More...
 
class  SwaptionVolatilityConverter
 Class that converts a supplied SwaptionVolatilityStructure to one of another type with possibly different shifts. More...
 
struct  SwaptionVolatilityEUR
 
class  SwaptionVolCube2
 
class  SwaptionVolCubeWithATM
 Wrapper class for a SwaptionVolatilityCube that easily and efficiently exposes ATM vols. More...
 
class  SwedenRegion
 Sweden as geographical/economic region. More...
 
class  Switzerland
 Swiss calendar. More...
 
class  SyntheticCDO
 Synthetic Collateralized Debt Obligation. More...
 
class  TenorBasisSwap
 Single currency tenor basis swap. More...
 
class  TenorBasisSwapHelper
 Rate helper for bootstrapping using Libor tenor basis swaps. More...
 
class  TermInterpolatedDefaultCurve
 
class  TermRateIndex
 
class  THBBibor
 THB-BIBOR index/. More...
 
class  THBThor
 THB-THOR index. More...
 
class  Tonar
 JPY TONAR rate More...
 
class  TonarTerm
 
struct  Tranche
 Collateralized Bond Obligation, Cash Flow CBO. More...
 
class  TRSCashFlow
 bond trs cashflow More...
 
class  TRSLeg
 helper class building a sequence of trs cashflows More...
 
class  TsiveriotisFernandesLattice
 Binomial lattice approximating the Tsiveriotis-Fernandes model. More...
 
class  TWDTaibor
 TWD-TAIBOR index. More...
 
class  UnitedArabEmirates
 Islamic Weekends-only calendar. More...
 
class  USDAmbor
 USD-AMBOR index. More...
 
class  USDAmeribor
 AMERIBOR overnight rate. More...
 
class  VanillaCrossCurrencySwap
 Vanilla cross currency interest rate swap. More...
 
class  VanillaForwardOption
 Vanilla Forward option on a single asset. More...
 
class  VannaVolgaSmileSection
 
struct  Variances
 
class  VarianceSwap2
 Variance swap. More...
 
class  VolatilityFromVarianceSwapEngine
 
class  WeightedYieldTermStructure
 weighted yield term structure More...
 
class  Wmr
 
class  XAGCurrency
 Troy ounce of Silver. More...
 
class  XAUCurrency
 Troy ounce of Gold. More...
 
class  XPDCurrency
 Troy ounce of Palladium. More...
 
class  XPTCurrency
 Troy ounce of Platinum. More...
 
class  YearCounter
 Year counter for when we want a whole number year fraction. More...
 
struct  YieldCurveEUR
 
class  YieldPlusDefaultYieldTermStructure
 yield plus default yield term structure More...
 
class  YoYCapFloorHelper
 
class  YoYInflationBachelierCapFloorEngine
 Unit Displaced Black-formula inflation cap/floor engine (standalone, i.e. no coupon pricer) More...
 
class  YoYInflationBlackCapFloorEngine
 Black-formula inflation cap/floor engine (standalone, i.e. no coupon pricer) More...
 
class  YoYInflationCapFloorEngine
 Base YoY inflation cap/floor engine. More...
 
class  YoYInflationCoupon
 
class  YoYInflationCurveObserverMoving
 Inflation term structure based on the interpolation of zero rates. More...
 
class  YoYInflationCurveObserverStatic
 Inflation term structure based on the interpolation of zero rates. More...
 
class  YoYInflationIndexWrapper
 Wrapper that creates a yoy from a zc index. More...
 
class  yoyInflationLeg
 
class  YoYInflationModelTermStructure
 
class  YoYInflationOptionletVolStripper
 
class  YoYInflationUnitDisplacedBlackCapFloorEngine
 Unit Displaced Black-formula inflation cap/floor engine (standalone, i.e. no coupon pricer) More...
 
class  YoYSwapHelper
 
class  ZeroFixedCoupon
 
class  ZeroInflationCurveObserverMoving
 Inflation term structure based on the interpolation of zero rates, with floating reference date. More...
 
class  ZeroInflationCurveObserverStatic
 Inflation term structure based on the interpolation of zero rates. More...
 
class  ZeroInflationIndexWrapper
 Wrapper that changes the interpolation of an underlying ZC inflation index. More...
 
class  ZeroInflationModelTermStructure
 
class  ZeroInflationTraits
 Bootstrap traits to use for PiecewiseZeroInflationCurve. More...
 

Typedefs

using ExternalRandomVariableOp = std::function< ExternalRandomVariable(const std::vector< const ExternalRandomVariable * > &)>
 
using ExternalRandomVariableGrad = std::function< std::vector< ExternalRandomVariable >(const std::vector< const ExternalRandomVariable * > &, const ExternalRandomVariable *)>
 
using RandomVariableOp = std::function< RandomVariable(const std::vector< const RandomVariable * > &)>
 
using RandomVariableGrad = std::function< std::vector< RandomVariable >(const std::vector< const RandomVariable * > &, const RandomVariable *)>
 
using RandomVariableOpNodeRequirements = std::function< std::pair< std::vector< bool >, bool >(const std::size_t)>
 
typedef CirppConstantWithFellerParametrization< YieldTermStructure > IrCirppConstantWithFellerParametrization
 
typedef CirppConstantWithFellerParametrization< DefaultProbabilityTermStructure > CrCirppConstantWithFellerParametrization
 
typedef CirppConstantParametrization< YieldTermStructure > IrCirppConstantParametrization
 
typedef CirppConstantParametrization< DefaultProbabilityTermStructure > CrCirppConstantParametrization
 
typedef CirppParametrization< DefaultProbabilityTermStructure > CrCirppParametrization
 
typedef CirppParametrization< YieldTermStructure > IrCirppParametrization
 
typedef ConstantLossLatentmodel< GaussianCopulaPolicy > GaussianConstantLossLM
 
typedef ConstantLossLatentmodel< TCopulaPolicy > TConstantLossLM
 
typedef Lgm1fParametrization< DefaultProbabilityTermStructure > CrLgm1fParametrization
 
typedef Lgm1fConstantParametrization< DefaultProbabilityTermStructure > CrLgm1fConstantParametrization
 
typedef Lgm1fPiecewiseConstantHullWhiteAdaptor< DefaultProbabilityTermStructure > CrLgm1fPiecewiseConstantHullWhiteADaptor
 
typedef Lgm1fPiecewiseConstantParametrization< DefaultProbabilityTermStructure > CrLgm1fPiecewiseConstantParametrization
 
typedef Lgm1fPiecewiseLinearParametrization< DefaultProbabilityTermStructure > CrLgm1fPiecewiseLinearParametrization
 
typedef DefaultLatentModel< GaussianCopulaPolicy > GaussianDefProbLM
 
typedef DefaultLatentModel< TCopulaPolicy > TDefProbLM
 
typedef ExtendedConstantLossLatentModel< GaussianCopulaPolicy > ExtendedGaussianConstantLossLM
 
typedef HomogeneousPoolLossModel< GaussianCopulaPolicy > HomogGaussPoolLossModel
 
typedef HomogeneousPoolLossModel< TCopulaPolicy > HomogTPoolLossModel
 
typedef HwConstantParametrization< YieldTermStructure > IrHwConstantParametrization
 
typedef HwParametrization< YieldTermStructure > IrHwParametrization
 
typedef Lgm1fParametrization< ZeroInflationTermStructure > InfDkParametrization
 
typedef Lgm1fConstantParametrization< ZeroInflationTermStructure > InfDkConstantParametrization
 
typedef Lgm1fPiecewiseConstantHullWhiteAdaptor< ZeroInflationTermStructure > InfDkPiecewiseConstantHullWhiteAdaptor
 
typedef Lgm1fPiecewiseConstantParametrization< ZeroInflationTermStructure > InfDkPiecewiseConstantParametrization
 
typedef Lgm1fPiecewiseLinearParametrization< ZeroInflationTermStructure > InfDkPiecewiseLinearParametrization
 
typedef InhomogeneousPoolLossModel< GaussianCopulaPolicy > IHGaussPoolLossModel
 
typedef InhomogeneousPoolLossModel< TCopulaPolicy > IHStudentPoolLossModel
 
typedef Lgm1fConstantParametrization< YieldTermStructure > IrLgm1fConstantParametrization
 
typedef Lgm1fParametrization< YieldTermStructure > IrLgm1fParametrization
 
typedef Lgm1fPiecewiseConstantHullWhiteAdaptor< YieldTermStructure > IrLgm1fPiecewiseConstantHullWhiteAdaptor
 
typedef Lgm1fPiecewiseConstantParametrization< YieldTermStructure > IrLgm1fPiecewiseConstantParametrization
 
typedef Lgm1fPiecewiseLinearParametrization< YieldTermStructure > IrLgm1fPiecewiseLinearParametrization
 
typedef LinearGaussMarkovModel LGM
 
typedef PoolLossModel< GaussianCopulaPolicy > GaussPoolLossModel
 
typedef PoolLossModel< TCopulaPolicy > StudentPoolLossModel
 
typedef QuantLib::BootstrapHelper< PriceTermStructurePriceHelper
 
typedef InterpolatedBaseCorrelationTermStructure< QuantLib::Bilinear > BilinearBaseCorrelationCurve
 
typedef RelativeDateBootstrapHelper< YieldTermStructure > RelativeDateRateHelper
 
typedef InterpolatedCorrelationCurve< BackwardFlat > BackwardFlatCorrelationCurve
 
typedef InterpolatedCorrelationCurve< Linear > PiecewiseLinearCorrelationCurve
 
typedef InterpolatedOptionletCurve< QuantLib::Linear > OptionletCurve
 
typedef std::vector< std::vector< QuantLib::ext::shared_ptr< QuantLib::CapFloor > > > CapFloorMatrix
 

Enumerations

enum class  CommodityQuantityFrequency {
  PerCalculationPeriod , PerCalendarDay , PerPricingDay , PerHour ,
  PerHourAndCalendarDay
}
 Enumeration indicating the frequency associated with a commodity quantity. More...
 
enum class  EquityReturnType { Price , Total , Absolute , Dividend }
 
enum class  RandomVariableRegressionMethod { QR , SVD }
 
enum  SequenceType {
  MersenneTwister , MersenneTwisterAntithetic , Sobol , Burley2020Sobol ,
  SobolBrownianBridge , Burley2020SobolBrownianBridge
}
 
enum  Stickyness { StickyStrike , StickyLogMoneyness , StickyAbsoluteMoneyness }
 Stickiness. More...
 
enum  ReactionToTimeDecay { ConstantVariance , ForwardForwardVariance }
 Reaction to Time Decay. More...
 
enum  YieldCurveRollDown { ConstantDiscounts , ForwardForward }
 Yield Curve Roll Down. More...
 
enum  PriceQuotePreference { Cap , Floor , CapFloor }
 

Functions

template<class T >
void backwardDerivatives (const ComputationGraph &g, std::vector< T > &values, std::vector< T > &derivatives, const std::vector< std::function< std::vector< T >(const std::vector< const T * > &, const T *)> > &grad, std::function< void(T &)> deleter={}, const std::vector< bool > &keepNodes={}, const std::vector< std::function< T(const std::vector< const T * > &)> > &fwdOps={}, const std::vector< std::function< std::pair< std::vector< bool >, bool >(const std::size_t)> > &fwdOpRequiresNodesForDerivatives={}, const std::vector< bool > &fwdKeepNodes={}, const std::size_t conditionalExpectationOpId=0, const std::function< T(const std::vector< const T * > &)> &conditionalExpectation={})
 
std::size_t cg_const (ComputationGraph &g, const double value)
 
std::size_t cg_insert (ComputationGraph &g, const std::string &label)
 
std::size_t cg_var (ComputationGraph &g, const std::string &name, const ComputationGraph::VarDoesntExist v)
 
std::size_t cg_add (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_subtract (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_negative (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::size_t cg_mult (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_div (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_conditionalExpectation (ComputationGraph &g, const std::size_t regressand, const std::vector< std::size_t > &regressor, const std::size_t filter, const std::string &label)
 
std::size_t cg_indicatorEq (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_indicatorGt (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_indicatorGeq (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_min (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_max (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_abs (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::size_t cg_exp (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::size_t cg_sqrt (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::size_t cg_log (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::size_t cg_pow (ComputationGraph &g, const std::size_t a, const std::size_t b, const std::string &label)
 
std::size_t cg_normalCdf (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::size_t cg_normalPdf (ComputationGraph &g, const std::size_t a, const std::string &label)
 
std::vector< ExternalRandomVariableOpgetExternalRandomVariableOps ()
 
std::vector< ExternalRandomVariableGradgetExternalRandomVariableGradients ()
 
bool isDeterministicAndZero (const ExternalRandomVariable &x)
 
template<class T >
void forwardDerivatives (const ComputationGraph &g, const std::vector< T > &values, std::vector< T > &derivatives, const std::vector< std::function< std::vector< T >(const std::vector< const T * > &, const T *)> > &grad, std::function< void(T &)> deleter={}, const std::vector< bool > &keepNodes={}, const std::size_t conditionalExpectationOpId=0, const std::function< T(const std::vector< const T * > &)> &conditionalExpectation={})
 
template<class T >
void forwardEvaluation (const ComputationGraph &g, std::vector< T > &values, const std::vector< std::function< T(const std::vector< const T * > &)> > &ops, std::function< void(T &)> deleter={}, bool keepValuesForDerivatives=true, const std::vector< std::function< std::pair< std::vector< bool >, bool >(const std::size_t)> > &opRequiresNodesForDerivatives={}, const std::vector< bool > &keepNodes={}, const std::size_t startNode=0, const std::size_t endNode=ComputationGraph::nan, const bool redBlockReconstruction=false)
 
template<class T >
std::string ssaForm (const ComputationGraph &g, const std::vector< std::string > &opCodeLabels, const std::vector< T > &values, const std::vector< T > &values2)
 
template std::string ssaForm (const ComputationGraph &g, const std::vector< std::string > &opCodeLabels, const std::vector< double > &values, const std::vector< double > &values2)
 
template std::string ssaForm (const ComputationGraph &g, const std::vector< std::string > &opCodeLabels, const std::vector< RandomVariable > &values, const std::vector< RandomVariable > &values2)
 
set< Date > pricingDates (const Date &s, const Date &e, const Calendar &pricingCalendar, bool excludeStart, bool includeEnd, bool useBusinessDays)
 
bool isPricingDate (const Date &d, const Calendar &pricingCalendar, bool useBusinessDays)
 
std::set< QuantLib::Date > pricingDates (const QuantLib::Date &start, const QuantLib::Date &end, const QuantLib::Calendar &pricingCalendar, bool excludeStart, bool includeEnd, bool useBusinessDays=true)
 Get the set of valid pricing dates in a period. More...
 
bool isPricingDate (const QuantLib::Date &d, const QuantLib::Calendar &pricingCalendar, bool useBusinessDays=true)
 Check if a date is a pricing date. More...
 
void setCouponPricer (const Leg &leg, const QuantLib::ext::shared_ptr< FloatingRateCouponPricer > &)
 Set Coupon Pricer. More...
 
void setCouponPricers (const Leg &leg, const std::vector< QuantLib::ext::shared_ptr< FloatingRateCouponPricer > > &)
 Set Coupon Pricers. More...
 
std::ostream & operator<< (std::ostream &out, EquityReturnType t)
 
EquityReturnType parseEquityReturnType (const std::string &str)
 
Leg makeFloatingAnnuityNominalLeg (const Leg &floatingAnnuityLeg)
 
QuantLib::ext::shared_ptr< CashFlow > unpackIndexedCouponOrCashFlow (const QuantLib::ext::shared_ptr< CashFlow > &c)
 
QuantLib::ext::shared_ptr< CouponunpackIndexedCoupon (const QuantLib::ext::shared_ptr< Coupon > &c)
 
QuantLib::ext::shared_ptr< CashFlow > unpackIndexWrappedCashFlow (const QuantLib::ext::shared_ptr< CashFlow > &c)
 
Real getIndexedCouponOrCashFlowMultiplier (const QuantLib::ext::shared_ptr< CashFlow > &c)
 
std::vector< std::tuple< Date, QuantLib::ext::shared_ptr< Index >, Real > > getIndexedCouponOrCashFlowFixingDetails (const QuantLib::ext::shared_ptr< CashFlow > &c)
 
Real jyExpectedIndexRatio (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, Size index, Time S, Time T, bool indexIsInterpolated)
 
QuantLib::Real jyExpectedIndexRatio (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, QuantLib::Size index, QuantLib::Time S, QuantLib::Time T, bool indexIsInterpolated)
 
std::ostream & operator<< (std::ostream &os, ConfigurableCurrency::Type ccytype)
 
bool isMetal (const Currency &currency)
 
bool isMetal (const QuantLib::Currency &currency)
 Check if a given currency is a metal. More...
 
void applyDividends (const std::set< Dividend > &dividends)
 Utility to write a set of dividends in the dividend manager's history. More...
 
bool operator< (const Dividend &d1, const Dividend &d2)
 
bool operator== (const Dividend &d1, const Dividend &d)
 Compare dividends. More...
 
std::ostream & operator<< (std::ostream &out, Dividend dividend)
 
Real sum (const Cash &c, const Cash &d)
 
Real sumDiscounted (const Cash &c, const Cash &d)
 
std::ostream & operator<< (std::ostream &out, const CashFlowResults &t)
 
CashFlowResults standardCashFlowResults (const QuantLib::ext::shared_ptr< CashFlow > &c, const Real multiplier, const std::string &type, const Size legNo, const Currency &currency, const Handle< YieldTermStructure > &discountCurve)
 
CashFlowResults populateCashFlowResultsFromCashflow (const QuantLib::ext::shared_ptr< QuantLib::CashFlow > &c, const QuantLib::Real multiplier, const QuantLib::Size legNo, const QuantLib::Currency &currency)
 
CashFlowResults standardCashFlowResults (const QuantLib::ext::shared_ptr< QuantLib::CashFlow > &c, const QuantLib::Real multiplier=1.0, const std::string &type="Unspecified", const QuantLib::Size legNo=0, const QuantLib::Currency &currency=QuantLib::Currency(), const QuantLib::Handle< QuantLib::YieldTermStructure > &discountCurve=QuantLib::Handle< QuantLib::YieldTermStructure >())
 
 MakeCreditDefaultSwap::operator QuantLib::ext::shared_ptr< QuantExt::CreditDefaultSwap > () const
 
Leg getOisCapFloorUnderlying (const Leg &oisCapFloor)
 get the underlying ON coupons from an OIS cf More...
 
std::vector< std::pair< Real, Real > > getOisCapFloorStrikes (const Leg &oisCapFloor)
 get the (cap, floor) - strikes from an OIS cf More...
 
QuantLib::SparseMatrix inverse (QuantLib::SparseMatrix m)
 
Matrix blockMatrixInverse (const Matrix &A, const std::vector< Size > &blockIndices)
 
QuantLib::SparseMatrix blockMatrixInverse (const QuantLib::SparseMatrix &A, const std::vector< Size > &blockIndices)
 
Real modifiedMaxNorm (const QuantLib::SparseMatrix &A)
 
QuantLib::Matrix blockMatrixInverse (const QuantLib::Matrix &A, const std::vector< QuantLib::Size > &blockIndices)
 
QuantLib::SparseMatrix blockMatrixInverse (const QuantLib::SparseMatrix &A, const std::vector< QuantLib::Size > &blockIndices)
 
BucketedDistribution operator+ (const BucketedDistribution &lhs, const BucketedDistribution &rhs)
 Sum probabilities in two bucketed distributions with equal buckets. More...
 
BucketedDistribution operator* (Real factor, const BucketedDistribution &rhs)
 
BucketedDistribution operator* (const BucketedDistribution &lhs, QuantLib::Real factor)
 
BucketedDistribution operator* (QuantLib::Real factor, const BucketedDistribution &rhs)
 Multiply probabilities in bucketed distribution by factor. More...
 
CompiledFormula operator+ (CompiledFormula x, const CompiledFormula &y)
 
CompiledFormula operator- (CompiledFormula x, const CompiledFormula &y)
 
CompiledFormula operator* (CompiledFormula x, const CompiledFormula &y)
 
CompiledFormula operator/ (CompiledFormula x, const CompiledFormula &y)
 
CompiledFormula unaryOp (CompiledFormula x, CompiledFormula::Operator op)
 
CompiledFormula binaryOp (CompiledFormula x, const CompiledFormula &y, CompiledFormula::Operator op)
 
CompiledFormula gtZero (CompiledFormula x)
 
CompiledFormula geqZero (CompiledFormula x)
 
CompiledFormula abs (CompiledFormula x)
 
CompiledFormula exp (CompiledFormula x)
 
CompiledFormula log (CompiledFormula x)
 
CompiledFormula max (CompiledFormula x, const CompiledFormula &y)
 
CompiledFormula min (CompiledFormula x, const CompiledFormula &y)
 
CompiledFormula pow (CompiledFormula x, const CompiledFormula &y)
 
template<class T >
T * createComputeFrameworkCreator ()
 
Real deltaVar (const Matrix &omega, const Array &delta, const Real p, const CovarianceSalvage &sal=NoCovarianceSalvage())
 function that computes a delta VaR More...
 
Real deltaGammaVarNormal (const Matrix &omega, const Array &delta, const Matrix &gamma, const Real p, const CovarianceSalvage &sal=NoCovarianceSalvage())
 function that computes a delta-gamma normal VaR More...
 
Real deltaGammaVarCornishFisher (const Matrix &omega, const Array &delta, const Matrix &gamma, const Real p, const CovarianceSalvage &sal)
 
Real deltaGammaVarSaddlepoint (const Matrix &omega, const Array &delta, const Matrix &gamma, const Real p, const CovarianceSalvage &sal)
 
template<class RNG >
Real deltaGammaVarMc (const Matrix &omega, const Array &delta, const Matrix &gamma, const Real p, const Size paths, const Size seed, const CovarianceSalvage &sal=NoCovarianceSalvage())
 function that computes a delta-gamma VaR using Monte Carlo (single quantile) More...
 
template<class RNG >
std::vector< Real > deltaGammaVarMc (const Matrix &omega, const Array &delta, const Matrix &gamma, const std::vector< Real > &p, const Size paths, const Size seed, const CovarianceSalvage &sal=NoCovarianceSalvage())
 function that computes a delta-gamma VaR using Monte Carlo (multiple quantiles) More...
 
bool operator< (const Distributionpair &p1, const Distributionpair &p2)
 
bool operator> (const Distributionpair &p1, const Distributionpair &p2)
 
void fillIncompleteMatrix (Matrix &mat, bool interpRows, Real blank)
 function that fills a matrix More...
 
template<class I1 , class I2 >
Real kendallRankCorrelation (I1 begin1, I1 end1, I2 begin2)
 
bool supports_Logm ()
 
bool supports_Expm ()
 
QuantLib::Matrix Logm (const QuantLib::Matrix &m)
 
QuantLib::Matrix Expm (const QuantLib::Matrix &m)
 
bool operator== (const Filter &a, const Filter &b)
 
bool operator!= (const Filter &a, const Filter &b)
 
Filter operator&& (Filter x, const Filter &y)
 
Filter operator|| (Filter x, const Filter &y)
 
Filter equal (Filter x, const Filter &y)
 
Filter operator! (Filter x)
 
void checkTimeConsistency (const RandomVariable &x, const RandomVariable &y)
 
bool operator== (const RandomVariable &a, const RandomVariable &b)
 
bool operator!= (const RandomVariable &a, const RandomVariable b)
 
RandomVariable operator+ (RandomVariable x, const RandomVariable &y)
 
RandomVariable operator- (RandomVariable x, const RandomVariable &y)
 
RandomVariable operator* (RandomVariable x, const RandomVariable &y)
 
RandomVariable operator/ (RandomVariable x, const RandomVariable &y)
 
RandomVariable max (RandomVariable x, const RandomVariable &y)
 
RandomVariable min (RandomVariable x, const RandomVariable &y)
 
RandomVariable pow (RandomVariable x, const RandomVariable &y)
 
RandomVariable operator- (RandomVariable x)
 
RandomVariable abs (RandomVariable x)
 
RandomVariable exp (RandomVariable x)
 
RandomVariable log (RandomVariable x)
 
RandomVariable sqrt (RandomVariable x)
 
RandomVariable sin (RandomVariable x)
 
RandomVariable cos (RandomVariable x)
 
RandomVariable normalCdf (RandomVariable x)
 
RandomVariable normalPdf (RandomVariable x)
 
Filter close_enough (const RandomVariable &x, const RandomVariable &y)
 
bool close_enough_all (const RandomVariable &x, const RandomVariable &y)
 
RandomVariable conditionalResult (const Filter &f, RandomVariable x, const RandomVariable &y)
 
RandomVariable indicatorEq (RandomVariable x, const RandomVariable &y, const Real trueVal, const Real falseVal)
 
RandomVariable indicatorGt (RandomVariable x, const RandomVariable &y, const Real trueVal, const Real falseVal, const Real eps)
 
RandomVariable indicatorGeq (RandomVariable x, const RandomVariable &y, const Real trueVal, const Real falseVal, const Real eps)
 
Filter operator< (const RandomVariable &x, const RandomVariable &y)
 
Filter operator<= (const RandomVariable &x, const RandomVariable &y)
 
Filter operator> (const RandomVariable &x, const RandomVariable &y)
 
Filter operator>= (const RandomVariable &x, const RandomVariable &y)
 
RandomVariable applyFilter (RandomVariable x, const Filter &f)
 
RandomVariable applyInverseFilter (RandomVariable x, const Filter &f)
 
Matrix pcaCoordinateTransform (const std::vector< const RandomVariable * > &regressor, const Real varianceCutoff)
 
std::vector< RandomVariableapplyCoordinateTransform (const std::vector< const RandomVariable * > &regressor, const Matrix &transform)
 
std::vector< const RandomVariable * > vec2vecptr (const std::vector< RandomVariable > &values)
 
Array regressionCoefficients (RandomVariable r, std::vector< const RandomVariable * > regressor, const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > &basisFn, const Filter &filter, const RandomVariableRegressionMethod regressionMethod, const std::string &debugLabel)
 
RandomVariable conditionalExpectation (const std::vector< const RandomVariable * > &regressor, const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > &basisFn, const Array &coefficients)
 
RandomVariable conditionalExpectation (const RandomVariable &r, const std::vector< const RandomVariable * > &regressor, const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > &basisFn, const Filter &filter, const RandomVariableRegressionMethod regressionMethod)
 
RandomVariable expectation (const RandomVariable &r)
 
RandomVariable variance (const RandomVariable &r)
 
RandomVariable covariance (const RandomVariable &r, const RandomVariable &s)
 
RandomVariable black (const RandomVariable &omega, const RandomVariable &t, const RandomVariable &strike, const RandomVariable &forward, const RandomVariable &impliedVol)
 
RandomVariable indicatorDerivative (const RandomVariable &x, const double eps)
 
std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > multiPathBasisSystem (Size dim, Size order, QuantLib::LsmBasisSystem::PolynomialType type, Size basisSystemSizeBound)
 
bool operator!= (const RandomVariable &a, const RandomVariable &b)
 
bool isDeterministicAndZero (const RandomVariable &x)
 
std::ostream & operator<< (std::ostream &out, const randomvariable_output_size &r)
 
std::ostream & operator<< (std::ostream &out, const randomvariable_output_pattern &p)
 
std::ostream & operator<< (std::ostream &out, const Filter &f)
 
std::ostream & operator<< (std::ostream &out, const RandomVariable &r)
 
std::vector< std::string > getRandomVariableOpLabels ()
 
std::vector< RandomVariableOpgetRandomVariableOps (const Size size, const Size regressionOrder, QuantLib::LsmBasisSystem::PolynomialType polynomType, const double eps, QuantLib::Real regressionVarianceCutoff)
 
std::vector< RandomVariableGradgetRandomVariableGradients (const Size size, const Size regressionOrder, const QuantLib::LsmBasisSystem::PolynomialType polynomType, const double eps, const Real regressionVarianceCutoff)
 
std::vector< RandomVariableOpNodeRequirementsgetRandomVariableOpNodeRequirements ()
 
std::vector< RandomVariableGradgetRandomVariableGradients (const Size size, const Size regressionOrder=2, const QuantLib::LsmBasisSystem::PolynomialType polynomType=QuantLib::LsmBasisSystem::Monomial, const double eps=0.2, QuantLib::Real regressionVarianceCutoff=Null< Real >())
 
std::vector< Size > stopLightBoundsTabulated (const std::vector< Real > &stopLightP, const Size observations, const Size numberOfDays, const Real p)
 
std::vector< Size > stopLightBounds (const std::vector< Real > &stopLightP, const Size observations, const Size numberOfDays, const Real p, const Size numberOfPortfolios, const Matrix &correlation, const Size samples, const Size seed, const SalvagingAlgorithm::Type salvaging, const Size exceptions, Real *cumProb)
 
std::vector< Size > stopLightBounds (const std::vector< Real > &stopLightP, const Size observations, const Real p, const Size exceptions, Real *cumProb)
 
std::vector< std::pair< Size, std::vector< Size > > > generateStopLightBoundTable (const std::vector< Size > &observations, const std::vector< Real > &stopLightP, const Size samples, const Size seed, const Size numberOfDays, const Real p)
 
Real Trace (const Matrix &m)
 
void interpolateVariatesWithBrownianBridge (const std::vector< QuantLib::Real > &times, std::vector< std::vector< QuantExt::RandomVariable > > &variates, const Size seed)
 
QuantLib::ext::shared_ptr< MultiPathGeneratorBasemakeMultiPathGenerator (const SequenceType s, const QuantLib::ext::shared_ptr< StochasticProcess > &process, const TimeGrid &timeGrid, const BigNatural seed, const SobolBrownianGenerator::Ordering ordering=SobolBrownianGenerator::Steps, const SobolRsg::DirectionIntegers directionIntegers=SobolRsg::JoeKuoD7)
 Make function for path generators. More...
 
std::ostream & operator<< (std::ostream &out, const SequenceType s)
 Output function. More...
 
QuantLib::ext::shared_ptr< MultiPathVariateGeneratorBasemakeMultiPathVariateGenerator (const SequenceType s, const Size dimension, const Size timeSteps, const BigNatural seed, const SobolBrownianGenerator::Ordering ordering, const SobolRsg::DirectionIntegers directionIntegers)
 
template<class CarrMadanMarginalProbabilityClass >
std::string arbitrageAsString (const CarrMadanMarginalProbabilityClass &cm)
 
template std::string arbitrageAsString (const CarrMadanMarginalProbability &cm)
 
template std::string arbitrageAsString (const CarrMadanMarginalProbabilitySafeStrikes &cm)
 
std::string arbitrageAsString (const CarrMadanSurface &cm)
 
std::ostream & operator<< (std::ostream &out, const CrossAssetModel::AssetType &type)
 
Handle< ZeroInflationTermStructure > inflationTermStructure (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, Size index)
 
QuantLib::Handle< QuantLib::ZeroInflationTermStructure > inflationTermStructure (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, QuantLib::Size index)
 Utility function to return a handle to the inflation term structure given the inflation index. More...
 
Real exactBachelierImpliedVolatility (Option::Type optionType, Real strike, Real forward, Real tte, Real bachelierPrice, Real discount)
 
Real inflationGrowth (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, Size index, Time S, Time T, Real irState, Real rrState, bool indexIsInterpolated)
 
QuantLib::Real inflationGrowth (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, QuantLib::Size index, QuantLib::Time S, QuantLib::Time T, QuantLib::Real irState, QuantLib::Real rrState, bool indexIsInterpolated)
 
std::map< std::string, boost::any > getAdditionalResultsMap (const LgmCalibrationInfo &info)
 
Real normalSabrVolatility (Rate strike, Rate forward, Time expiryTime, Real alpha, Real nu, Real rho)
 
Real normalSabrAlphaFromAtmVol (Rate forward, Time expiryTime, Real atmVol, Real nu, Real rho)
 
Real normalFreeBoundarySabrPrice (Rate strike, Rate forward, Time expiryTime, Real alpha, Real nu, Real rho)
 
Real normalFreeBoundarySabrVolatility (Rate strike, Rate forward, Time expiryTime, Real alpha, Real nu, Real rho)
 
QuantLib::ext::shared_ptr< CrossAssetModelgetProjectedCrossAssetModel (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, const std::vector< std::pair< CrossAssetModel::AssetType, Size > > &selectedComponents, std::vector< Size > &projectedStateProcessIndices)
 
std::vector< Size > getStateProcessProjection (const QuantLib::ext::shared_ptr< CrossAssetModel > &model, const QuantLib::ext::shared_ptr< CrossAssetModel > &projectedModel)
 
void sanitiseTransitionMatrix (Matrix &m)
 
void checkTransitionMatrix (const Matrix &t)
 check if the matrix is a transition matrix, i.e. row sums are 1 and entries are non-negative More...
 
void checkGeneratorMatrix (const Matrix &g)
 check if the matrix is a generator matirx, i.e. row sums are 0 and non-diagonal elements are non-negative More...
 
Matrix generator (const Matrix &t, const Real horizon)
 
template<class I >
std::vector< Real > creditStateBoundaries (const I &begin, const I &end)
 compute N(0,1) credit state boundaries More...
 
void print (Distribution &dist, std::string fileName)
 
Real getCallPriceAmount (const FdConvertibleBondEvents::CallData &cd, Real notional, Real accruals)
 
Real interpolateValueFromPlanes (const Real conversionRatio, const std::vector< Array > &value, const std::vector< Real > &stochasticConversionRatios, const Size j)
 
RandomVariable getRebatePv (const LgmVectorised &lgm, const Real t, const RandomVariable &x, const Handle< YieldTermStructure > &discountCurve, const QuantLib::ext::shared_ptr< RebatedExercise > &exercise, const Date &d)
 
Real getStrikeFromDelta (Option::Type optionType, Real delta, DeltaVolQuote::DeltaType dt, Real spot, Real domDiscount, Real forDiscount, QuantLib::ext::shared_ptr< BlackVolTermStructure > vol, Real t, Real accuracy, Size maxIterations)
 
Real getAtmStrike (DeltaVolQuote::DeltaType dt, DeltaVolQuote::AtmType at, Real spot, Real domDiscount, Real forDiscount, QuantLib::ext::shared_ptr< BlackVolTermStructure > vol, Real t, Real accuracy, Size maxIterations)
 
ostream & operator<< (std::ostream &out, CapFloorHelper::Type type)
 In order to convert CapFloorHelper::Type to string. More...
 
ostream & operator<< (std::ostream &out, CapFloorHelper::QuoteType type)
 In order to convert CapFloorHelper::QuoteType to string. More...
 
ostream & operator<< (std::ostream &out, CapFloorTermVolSurfaceExact::InterpolationMethod method)
 In order to convert CapFloorTermVolSurface::InterpolationMethod to string. More...
 
std::ostream & operator<< (std::ostream &out, const Stickyness &t)
 
std::ostream & operator<< (std::ostream &out, const ReactionToTimeDecay &t)
 
std::ostream & operator<< (std::ostream &out, const YieldCurveRollDown &t)
 
Date getImmDate (Date asof, Size i)
 
bool operator< (const ParametricVolatility::MarketSmile &s, const ParametricVolatility::MarketSmile &t)
 
Real getOisAtmLevel (const QuantLib::ext::shared_ptr< OvernightIndex > &on, const Date &fixingDate, const Period &rateComputationPeriod)
 
Real getBMAAtmLevel (const QuantLib::ext::shared_ptr< BMAIndex > &bma, const Date &fixingDate, const Period &rateComputationPeriod)
 
QuantLib::ext::shared_ptr< CashFlow > makeCommodityCashflowForBasisFuture (const QuantLib::Date &start, const QuantLib::Date &end, const QuantLib::ext::shared_ptr< CommodityIndex > &baseIndex, const QuantLib::ext::shared_ptr< FutureExpiryCalculator > &baseFec, bool baseIsAveraging, const QuantLib::Date &paymentDate)
 Make a commodity indexed cashflow. More...
 
Time inflationTime (const Date &date, const QuantLib::ext::shared_ptr< InflationTermStructure > &inflationTs, bool indexIsInterpolated, const DayCounter &dayCounter)
 
Real inflationGrowth (const Handle< ZeroInflationTermStructure > &ts, Time t, const DayCounter &dc, bool indexIsInterpolated)
 
Real inflationGrowth (const Handle< ZeroInflationTermStructure > &ts, Time t, bool indexIsInterpolated)
 
Real inflationLinkedBondQuoteFactor (const QuantLib::ext::shared_ptr< QuantLib::Bond > &bond)
 
void addInflationIndexToMap (std::map< std::tuple< std::string, QuantLib::CPI::InterpolationType, QuantLib::Frequency, QuantLib::Period >, QuantLib::ext::shared_ptr< QuantLib::ZeroInflationIndex > > &inflationIndices, const QuantLib::ext::shared_ptr< QuantLib::Index > &index, QuantLib::CPI::InterpolationType interpolation, Frequency couponFrequency, Period observationLag)
 
std::map< std::tuple< std::string, QuantLib::CPI::InterpolationType, QuantLib::Frequency, QuantLib::Period >, QuantLib::ext::shared_ptr< QuantLib::ZeroInflationIndex > > extractAllInflationUnderlyingFromBond (const QuantLib::ext::shared_ptr< QuantLib::Bond > &bond)
 
QuantLib::Time inflationTime (const QuantLib::Date &date, const QuantLib::ext::shared_ptr< QuantLib::InflationTermStructure > &inflationTs, bool indexIsInterpolated, const QuantLib::DayCounter &dayCounter=QuantLib::DayCounter())
 
QuantLib::Real inflationGrowth (const QuantLib::Handle< QuantLib::ZeroInflationTermStructure > &ts, QuantLib::Time t, const QuantLib::DayCounter &dc, bool indexIsInterpolated)
 
QuantLib::Real inflationGrowth (const QuantLib::Handle< QuantLib::ZeroInflationTermStructure > &ts, QuantLib::Time t, bool indexIsInterpolated)
 
template<typename T >
std::tuple< Size, Size, Real > interpolationIndices (const T &x, const Real v)
 
Real periodToTime (const Period &p)
 
QuantLib::Period implyIndexTerm (const Date &startDate, const Date &endDate)
 
QuantLib::Date lowerDate (const Real t, const QuantLib::Date &refDate, const QuantLib::DayCounter &dc)
 
QuantLib::Period tenorFromLength (const QuantLib::Real length)
 
QuantLib::Integer daylightSavingCorrection (const std::string &location, const QuantLib::Date &start, const QuantLib::Date &end)
 
QuantLib::Real periodToTime (const QuantLib::Period &p)
 
QuantLib::Period implyIndexTerm (const QuantLib::Date &startDate, const QuantLib::Date &endDate)
 
QuantLib::Date lowerDate (const QuantLib::Real t, const QuantLib::Date &refDate, const QuantLib::DayCounter &dc)
 

Typedef Documentation

◆ ExternalRandomVariableOp

using ExternalRandomVariableOp = std::function<ExternalRandomVariable(const std::vector<const ExternalRandomVariable*>&)>

Definition at line 54 of file external_randomvariable_ops.hpp.

◆ ExternalRandomVariableGrad

using ExternalRandomVariableGrad = std::function<std::vector<ExternalRandomVariable>( const std::vector<const ExternalRandomVariable*>&, const ExternalRandomVariable*)>

Definition at line 59 of file external_randomvariable_ops.hpp.

◆ RandomVariableOp

using RandomVariableOp = std::function<RandomVariable(const std::vector<const RandomVariable*>&)>

Definition at line 36 of file randomvariable_ops.hpp.

◆ RandomVariableGrad

using RandomVariableGrad = std::function<std::vector<RandomVariable>(const std::vector<const RandomVariable*>&, const RandomVariable*)>

Definition at line 46 of file randomvariable_ops.hpp.

◆ RandomVariableOpNodeRequirements

using RandomVariableOpNodeRequirements = std::function<std::pair<std::vector<bool>, bool>(const std::size_t)>

Definition at line 57 of file randomvariable_ops.hpp.

◆ IrCirppConstantWithFellerParametrization

Definition at line 159 of file cirppconstantfellerparametrization.hpp.

◆ CrCirppConstantWithFellerParametrization

Definition at line 160 of file cirppconstantfellerparametrization.hpp.

◆ IrCirppConstantParametrization

Definition at line 116 of file cirppconstantparametrization.hpp.

◆ CrCirppConstantParametrization

typedef CirppConstantParametrization<DefaultProbabilityTermStructure> CrCirppConstantParametrization

Definition at line 117 of file cirppconstantparametrization.hpp.

◆ CrCirppParametrization

typedef CirppParametrization<DefaultProbabilityTermStructure> CrCirppParametrization

Definition at line 61 of file cirppparametrization.hpp.

◆ IrCirppParametrization

typedef CirppParametrization<YieldTermStructure> IrCirppParametrization

Definition at line 62 of file cirppparametrization.hpp.

◆ GaussianConstantLossLM

typedef ConstantLossLatentmodel<GaussianCopulaPolicy> GaussianConstantLossLM

Definition at line 83 of file constantlosslatentmodel.hpp.

◆ TConstantLossLM

typedef ConstantLossLatentmodel<TCopulaPolicy> TConstantLossLM

Definition at line 84 of file constantlosslatentmodel.hpp.

◆ CrLgm1fParametrization

typedef Lgm1fParametrization<DefaultProbabilityTermStructure> CrLgm1fParametrization

Definition at line 39 of file crlgm1fparametrization.hpp.

◆ CrLgm1fConstantParametrization

typedef Lgm1fConstantParametrization<DefaultProbabilityTermStructure> CrLgm1fConstantParametrization

Definition at line 41 of file crlgm1fparametrization.hpp.

◆ CrLgm1fPiecewiseConstantHullWhiteADaptor

Definition at line 44 of file crlgm1fparametrization.hpp.

◆ CrLgm1fPiecewiseConstantParametrization

Definition at line 46 of file crlgm1fparametrization.hpp.

◆ CrLgm1fPiecewiseLinearParametrization

Definition at line 48 of file crlgm1fparametrization.hpp.

◆ GaussianDefProbLM

typedef DefaultLatentModel<GaussianCopulaPolicy> GaussianDefProbLM

Definition at line 285 of file defaultprobabilitylatentmodel.hpp.

◆ TDefProbLM

typedef DefaultLatentModel<TCopulaPolicy> TDefProbLM

Definition at line 286 of file defaultprobabilitylatentmodel.hpp.

◆ ExtendedGaussianConstantLossLM

Definition at line 111 of file extendedconstantlosslatentmodel.hpp.

◆ HomogGaussPoolLossModel

typedef HomogeneousPoolLossModel<GaussianCopulaPolicy> HomogGaussPoolLossModel

Definition at line 113 of file homogeneouspooldef.hpp.

◆ HomogTPoolLossModel

Definition at line 114 of file homogeneouspooldef.hpp.

◆ IrHwConstantParametrization

Definition at line 102 of file hwconstantparametrization.hpp.

◆ IrHwParametrization

typedef HwParametrization<YieldTermStructure> IrHwParametrization

Definition at line 91 of file hwparametrization.hpp.

◆ InfDkParametrization

typedef Lgm1fParametrization<ZeroInflationTermStructure> InfDkParametrization

Definition at line 38 of file infdkparametrization.hpp.

◆ InfDkConstantParametrization

typedef Lgm1fConstantParametrization<ZeroInflationTermStructure> InfDkConstantParametrization

Definition at line 40 of file infdkparametrization.hpp.

◆ InfDkPiecewiseConstantHullWhiteAdaptor

Definition at line 42 of file infdkparametrization.hpp.

◆ InfDkPiecewiseConstantParametrization

Definition at line 44 of file infdkparametrization.hpp.

◆ InfDkPiecewiseLinearParametrization

Definition at line 46 of file infdkparametrization.hpp.

◆ IHGaussPoolLossModel

typedef InhomogeneousPoolLossModel<GaussianCopulaPolicy> IHGaussPoolLossModel

Definition at line 121 of file inhomogeneouspooldef.hpp.

◆ IHStudentPoolLossModel

Definition at line 122 of file inhomogeneouspooldef.hpp.

◆ IrLgm1fConstantParametrization

Definition at line 116 of file irlgm1fconstantparametrization.hpp.

◆ IrLgm1fParametrization

typedef Lgm1fParametrization<YieldTermStructure> IrLgm1fParametrization

Definition at line 137 of file irlgm1fparametrization.hpp.

◆ IrLgm1fPiecewiseConstantHullWhiteAdaptor

◆ IrLgm1fPiecewiseConstantParametrization

Definition at line 172 of file irlgm1fpiecewiseconstantparametrization.hpp.

◆ IrLgm1fPiecewiseLinearParametrization

Definition at line 177 of file irlgm1fpiecewiselinearparametrization.hpp.

◆ LGM

Definition at line 164 of file lgm.hpp.

◆ GaussPoolLossModel

typedef PoolLossModel<GaussianCopulaPolicy> GaussPoolLossModel

Definition at line 105 of file poollossmodel.hpp.

◆ StudentPoolLossModel

typedef PoolLossModel<TCopulaPolicy> StudentPoolLossModel

Definition at line 106 of file poollossmodel.hpp.

◆ PriceHelper

typedef QuantLib::BootstrapHelper< PriceTermStructure > PriceHelper

Definition at line 34 of file averagefuturepricehelper.hpp.

◆ BilinearBaseCorrelationCurve

Definition at line 178 of file basecorrelationstructure.hpp.

◆ RelativeDateRateHelper

typedef RelativeDateBootstrapHelper<YieldTermStructure> RelativeDateRateHelper

Definition at line 34 of file immfraratehelper.hpp.

◆ BackwardFlatCorrelationCurve

Definition at line 141 of file interpolatedcorrelationcurve.hpp.

◆ PiecewiseLinearCorrelationCurve

Definition at line 142 of file interpolatedcorrelationcurve.hpp.

◆ CapFloorMatrix

typedef std::vector<std::vector<QuantLib::ext::shared_ptr<QuantLib::CapFloor> > > CapFloorMatrix

Definition at line 37 of file optionletstripper1.hpp.

Enumeration Type Documentation

◆ CommodityQuantityFrequency

enum class CommodityQuantityFrequency
strong

Enumeration indicating the frequency associated with a commodity quantity.

Enumerator
PerCalculationPeriod 
PerCalendarDay 
PerPricingDay 
PerHour 
PerHourAndCalendarDay 

Definition at line 39 of file commoditycashflow.hpp.

◆ EquityReturnType

enum class EquityReturnType
strong
Enumerator
Price 
Total 
Absolute 
Dividend 

Definition at line 44 of file equitycoupon.hpp.

◆ RandomVariableRegressionMethod

enum class RandomVariableRegressionMethod
strong

◆ SequenceType

Enumerator
MersenneTwister 
MersenneTwisterAntithetic 
Sobol 
Burley2020Sobol 
SobolBrownianBridge 
Burley2020SobolBrownianBridge 

Definition at line 37 of file multipathgeneratorbase.hpp.

◆ PriceQuotePreference

Function Documentation

◆ backwardDerivatives()

void backwardDerivatives ( const ComputationGraph g,
std::vector< T > &  values,
std::vector< T > &  derivatives,
const std::vector< std::function< std::vector< T >(const std::vector< const T * > &, const T *)>  ,
grad,
std::function< void(T &)>  deleter = {},
const std::vector< bool > &  keepNodes = {},
const std::vector< std::function< T(const std::vector< const T * > &)>  ,
fwdOps = {},
const std::vector< std::function< std::pair< std::vector< bool >, bool >(const std::size_t)> > &  fwdOpRequiresNodesForDerivatives = {},
const std::vector< bool > &  fwdKeepNodes = {},
const std::size_t  conditionalExpectationOpId = 0,
const std::function< T(const std::vector< const T * > &)> &  conditionalExpectation = {} 
)

Definition at line 34 of file backwardderivatives.hpp.

36 {}, const std::vector<bool>& keepNodes = {},
37 const std::vector<std::function<T(const std::vector<const T*>&)>>& fwdOps = {},
38 const std::vector<std::function<std::pair<std::vector<bool>, bool>(const std::size_t)>>&
39 fwdOpRequiresNodesForDerivatives = {},
40 const std::vector<bool>& fwdKeepNodes = {}, const std::size_t conditionalExpectationOpId = 0,
41 const std::function<T(const std::vector<const T*>&)>& conditionalExpectation = {}) {
42
43 if (g.size() == 0)
44 return;
45
46 std::size_t redBlockId = 0;
47
48 // loop over the nodes in the graph in reverse order
49
50 for (std::size_t node = g.size() - 1; node > 0; --node) {
51
52 if (g.redBlockId(node) != redBlockId) {
53
54 // delete the values in the previous red block
55
56 if (deleter && redBlockId > 0) {
57 auto range = g.redBlockRanges()[redBlockId - 1];
58 QL_REQUIRE(range.second != ComputationGraph::nan,
59 "backwardDerivatives(): red block " << redBlockId << " was not closed.");
60 for (std::size_t n = range.first; n < range.second; ++n) {
61 if (g.redBlockId(n) == redBlockId && !fwdKeepNodes[n])
62 deleter(values[n]);
63 }
64 }
65
66 // populate the values in the current red block
67
68 if (g.redBlockId(node) > 0) {
69 auto range = g.redBlockRanges()[g.redBlockId(node) - 1];
70 QL_REQUIRE(range.second != ComputationGraph::nan,
71 "backwardDerivatives(): red block " << g.redBlockId(node) << " was not closed.");
72 forwardEvaluation(g, values, fwdOps, deleter, true, fwdOpRequiresNodesForDerivatives, fwdKeepNodes,
73 range.first, range.second, true);
74 }
75
76 // update the red block id
77
78 redBlockId = g.redBlockId(node);
79 }
80
81 if (!g.predecessors(node).empty() && !isDeterministicAndZero(derivatives[node])) {
82
83 // propagate the derivative at a node to its predecessors
84
85 std::vector<const T*> args(g.predecessors(node).size());
86 for (std::size_t arg = 0; arg < g.predecessors(node).size(); ++arg) {
87 args[arg] = &values[g.predecessors(node)[arg]];
88 }
89
90 QL_REQUIRE(derivatives[node].initialised(),
91 "backwardDerivatives(): derivative at active node " << node << " is not initialized.");
92
93 if (g.opId(node) == conditionalExpectationOpId && conditionalExpectation) {
94
95 // expected stochastic automatic differentiaion, Fries, 2017
96 args[0] = &derivatives[node];
97 derivatives[g.predecessors(node)[0]] += conditionalExpectation(args);
98
99 } else {
100
101 auto gr = grad[g.opId(node)](args, &values[node]);
102
103 for (std::size_t p = 0; p < g.predecessors(node).size(); ++p) {
104 QL_REQUIRE(derivatives[g.predecessors(node)[p]].initialised(),
105 "backwardDerivatives: derivative at node "
106 << g.predecessors(node)[p] << " not initialized, which is an active predecessor of "
107 << node);
108 QL_REQUIRE(gr[p].initialised(),
109 "backwardDerivatives: gradient at node "
110 << node << " (opId " << g.opId(node) << ") not initialized at component " << p
111 << " but required to push to predecessor " << g.predecessors(node)[p]);
112 derivatives[g.predecessors(node)[p]] += derivatives[node] * gr[p];
113 }
114 }
115 }
116
117 // then check if we can delete the node
118
119 if (deleter) {
120
121 // is the node marked as to be kept?
122
123 if (!keepNodes.empty() && keepNodes[node])
124 continue;
125
126 // apply the deleter
127
128 deleter(derivatives[node]);
129 }
130
131 } // for node
132}
const std::vector< std::size_t > & predecessors(const std::size_t node) const
std::size_t redBlockId(const std::size_t node) const
const std::vector< std::pair< std::size_t, std::size_t > > & redBlockRanges() const
std::size_t opId(const std::size_t node) const
bool isDeterministicAndZero(const ExternalRandomVariable &x)
RandomVariable conditionalExpectation(const std::vector< const RandomVariable * > &regressor, const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > &basisFn, const Array &coefficients)
void forwardEvaluation(const ComputationGraph &g, std::vector< T > &values, const std::vector< std::function< T(const std::vector< const T * > &)> > &ops, std::function< void(T &)> deleter={}, bool keepValuesForDerivatives=true, const std::vector< std::function< std::pair< std::vector< bool >, bool >(const std::size_t)> > &opRequiresNodesForDerivatives={}, const std::vector< bool > &keepNodes={}, const std::size_t startNode=0, const std::size_t endNode=ComputationGraph::nan, const bool redBlockReconstruction=false)
+ Here is the caller graph for this function:

◆ cg_const()

std::size_t cg_const ( ComputationGraph g,
const double  value 
)

Definition at line 187 of file computationgraph.cpp.

187{ return g.constant(value); }
std::size_t constant(const double c)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cg_insert()

std::size_t cg_insert ( ComputationGraph g,
const std::string &  label 
)

Definition at line 189 of file computationgraph.cpp.

189{ return g.insert(label); }
std::size_t insert(const std::string &label=std::string())
+ Here is the call graph for this function:

◆ cg_var()

std::size_t cg_var ( ComputationGraph g,
const std::string &  name,
const ComputationGraph::VarDoesntExist  v 
)

Definition at line 191 of file computationgraph.cpp.

191 {
192 return g.variable(name, v);
193}
std::size_t variable(const std::string &name, const VarDoesntExist v=VarDoesntExist::Throw)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cg_add()

std::size_t cg_add ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 195 of file computationgraph.cpp.

195 {
196 if (g.isConstant(a) && g.isConstant(b))
197 return cg_const(g, g.constantValue(a) + g.constantValue(b));
198 if (g.isConstant(a) && QuantLib::close_enough(g.constantValue(a), 0.0))
199 return b;
200 if (g.isConstant(b) && QuantLib::close_enough(g.constantValue(b), 0.0))
201 return a;
202 return g.insert({a, b}, RandomVariableOpCode::Add, label);
203}
double constantValue(const std::size_t node) const
bool isConstant(const std::size_t node) const
std::size_t cg_const(ComputationGraph &g, const double value)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cg_subtract()

std::size_t cg_subtract ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 205 of file computationgraph.cpp.

205 {
206 if (a == b)
207 return cg_const(g, 0.0);
208 if (g.isConstant(a) && g.isConstant(b))
209 return cg_const(g, g.constantValue(a) - g.constantValue(b));
210 if (g.isConstant(a) && QuantLib::close_enough(g.constantValue(a), 0.0))
211 return cg_negative(g, b);
212 if (g.isConstant(b) && QuantLib::close_enough(g.constantValue(b), 0.0))
213 return a;
214 return g.insert({a, b}, RandomVariableOpCode::Subtract, label);
215}
std::size_t cg_negative(ComputationGraph &g, const std::size_t a, const std::string &label)
+ Here is the call graph for this function:

◆ cg_negative()

std::size_t cg_negative ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 217 of file computationgraph.cpp.

217 {
218 if (g.isConstant(a))
219 return cg_const(g, -g.constantValue(a));
220 return g.insert({a}, RandomVariableOpCode::Negative, label);
221}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cg_mult()

std::size_t cg_mult ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 223 of file computationgraph.cpp.

223 {
224 if (g.isConstant(a) && g.isConstant(b))
225 return cg_const(g, g.constantValue(a) * g.constantValue(b));
226 if (g.isConstant(a) && QuantLib::close_enough(g.constantValue(a), 1.0))
227 return b;
228 if (g.isConstant(b) && QuantLib::close_enough(g.constantValue(b), 1.0))
229 return a;
230 if ((g.isConstant(a) && QuantLib::close_enough(g.constantValue(a), 0.0)) ||
231 (g.isConstant(b) && QuantLib::close_enough(g.constantValue(b), 0.0)))
232 return cg_const(g, 0.0);
233 return g.insert({a, b}, RandomVariableOpCode::Mult, label);
234}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cg_div()

std::size_t cg_div ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 236 of file computationgraph.cpp.

236 {
237 if (a == b)
238 return cg_const(g, 1.0);
239 if (g.isConstant(a) && g.isConstant(b))
240 return cg_const(g, g.constantValue(a) / g.constantValue(b));
241 if (g.isConstant(b) && QuantLib::close_enough(g.constantValue(b), 1.0))
242 return a;
243 if (g.isConstant(a) && QuantLib::close_enough(g.constantValue(a), 0.0))
244 return cg_const(g, 0.0);
245 return g.insert({a, b}, RandomVariableOpCode::Div, label);
246}
+ Here is the call graph for this function:

◆ cg_conditionalExpectation()

std::size_t cg_conditionalExpectation ( ComputationGraph g,
const std::size_t  regressand,
const std::vector< std::size_t > &  regressor,
const std::size_t  filter,
const std::string &  label 
)

Definition at line 248 of file computationgraph.cpp.

250 {
251 if (g.isConstant(regressand))
252 return regressand;
253 std::vector<size_t> args;
254 args.push_back(regressand);
255 args.push_back(filter);
256 args.insert(args.end(), regressor.begin(), regressor.end());
257 return g.insert(args, RandomVariableOpCode::ConditionalExpectation, label);
258}
+ Here is the call graph for this function:

◆ cg_indicatorEq()

std::size_t cg_indicatorEq ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 260 of file computationgraph.cpp.

260 {
261 if (g.isConstant(a) && g.isConstant(b))
262 return cg_const(g, QuantLib::close_enough(g.constantValue(a), g.constantValue(b)) ? 1.0 : 0.0);
263 return g.insert({a, b}, RandomVariableOpCode::IndicatorEq, label);
264}
+ Here is the call graph for this function:

◆ cg_indicatorGt()

std::size_t cg_indicatorGt ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 266 of file computationgraph.cpp.

266 {
267 if (g.isConstant(a) && g.isConstant(b))
268 return cg_const(g, g.constantValue(a) > g.constantValue(b) &&
269 !QuantLib::close_enough(g.constantValue(a), g.constantValue(b))
270 ? 1.0
271 : 0.0);
272 return g.insert({a, b}, RandomVariableOpCode::IndicatorGt, label);
273}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cg_indicatorGeq()

std::size_t cg_indicatorGeq ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 275 of file computationgraph.cpp.

275 {
276 if (g.isConstant(a) && g.isConstant(b))
277 return cg_const(g, g.constantValue(a) > g.constantValue(b) ||
278 QuantLib::close_enough(g.constantValue(a), g.constantValue(b))
279 ? 1.0
280 : 0.0);
281 return g.insert({a, b}, RandomVariableOpCode::IndicatorGeq, label);
282}
+ Here is the call graph for this function:

◆ cg_min()

std::size_t cg_min ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 284 of file computationgraph.cpp.

284 {
285 if (g.isConstant(a) && g.isConstant(b))
286 return cg_const(g, std::min(g.constantValue(a), g.constantValue(b)));
287 return g.insert({a, b}, RandomVariableOpCode::Min, label);
288}
+ Here is the call graph for this function:

◆ cg_max()

std::size_t cg_max ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 290 of file computationgraph.cpp.

290 {
291 if (g.isConstant(a) && g.isConstant(b))
292 return cg_const(g, std::max(g.constantValue(a), g.constantValue(b)));
293 return g.insert({a, b}, RandomVariableOpCode::Max, label);
294}
+ Here is the call graph for this function:

◆ cg_abs()

std::size_t cg_abs ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 296 of file computationgraph.cpp.

296 {
297 if (g.isConstant(a))
298 return cg_const(g, std::abs(g.constantValue(a)));
299 return g.insert({a}, RandomVariableOpCode::Abs, label);
300}
+ Here is the call graph for this function:

◆ cg_exp()

std::size_t cg_exp ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 302 of file computationgraph.cpp.

302 {
303 if (g.isConstant(a))
304 return cg_const(g, std::exp(g.constantValue(a)));
305 return g.insert({a}, RandomVariableOpCode::Exp, label);
306}
+ Here is the call graph for this function:

◆ cg_sqrt()

std::size_t cg_sqrt ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 308 of file computationgraph.cpp.

308 {
309 if (g.isConstant(a))
310 return cg_const(g, std::sqrt(g.constantValue(a)));
311 return g.insert({a}, RandomVariableOpCode::Sqrt, label);
312}
+ Here is the call graph for this function:

◆ cg_log()

std::size_t cg_log ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 314 of file computationgraph.cpp.

314 {
315 if (g.isConstant(a))
316 return cg_const(g, std::log(g.constantValue(a)));
317 return g.insert({a}, RandomVariableOpCode::Log, label);
318}
+ Here is the call graph for this function:

◆ cg_pow()

std::size_t cg_pow ( ComputationGraph g,
const std::size_t  a,
const std::size_t  b,
const std::string &  label 
)

Definition at line 320 of file computationgraph.cpp.

320 {
321 if (g.isConstant(a) && g.isConstant(b))
322 return cg_const(g, std::pow(g.constantValue(a), g.constantValue(b)));
323 return g.insert({a, b}, RandomVariableOpCode::Pow, label);
324}
+ Here is the call graph for this function:

◆ cg_normalCdf()

std::size_t cg_normalCdf ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 326 of file computationgraph.cpp.

326 {
327 static const boost::math::normal_distribution<double> n;
328 if (g.isConstant(a))
329 return cg_const(g, boost::math::cdf(n, g.constantValue(a)));
330 return g.insert({a}, RandomVariableOpCode::NormalCdf, label);
331}
+ Here is the call graph for this function:

◆ cg_normalPdf()

std::size_t cg_normalPdf ( ComputationGraph g,
const std::size_t  a,
const std::string &  label 
)

Definition at line 333 of file computationgraph.cpp.

333 {
334 static const boost::math::normal_distribution<double> n;
335 if (g.isConstant(a))
336 return cg_const(g, boost::math::pdf(n, g.constantValue(a)));
337 return g.insert({a}, RandomVariableOpCode::NormalPdf, label);
338}
+ Here is the call graph for this function:

◆ getExternalRandomVariableOps()

std::vector< ExternalRandomVariableOp > getExternalRandomVariableOps ( )

Definition at line 58 of file external_randomvariable_ops.cpp.

58 {
59 std::vector<ExternalRandomVariableOp> ops;
60
61 // None = 0
62 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) -> ExternalRandomVariable {
63 QL_FAIL("ExternRandomVariable does not support op None");
64 });
65
66 // Add = 1
67 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
68 return ExternalRandomVariable(RandomVariableOpCode::Add, args);
69 });
70
71 // Subtract = 2
72 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
73 return ExternalRandomVariable(RandomVariableOpCode::Subtract, args);
74 });
75
76 // Negative = 3
77 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
78 return ExternalRandomVariable(RandomVariableOpCode::Negative, args);
79 });
80
81 // Mult = 4
82 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
83 return ExternalRandomVariable(RandomVariableOpCode::Mult, args);
84 });
85
86 // Div = 5
87 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
88 return ExternalRandomVariable(RandomVariableOpCode::Div, args);
89 });
90
91 // ConditionalExpectation = 6
92 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
93 return ExternalRandomVariable(RandomVariableOpCode::ConditionalExpectation, args);
94 });
95
96 // IndicatorEq = 7
97 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
98 return ExternalRandomVariable(RandomVariableOpCode::IndicatorEq, args);
99 });
100
101 // IndicatorGt = 8
102 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
103 return ExternalRandomVariable(RandomVariableOpCode::IndicatorGt, args);
104 });
105
106 // IndicatorGeq = 9
107 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
108 return ExternalRandomVariable(RandomVariableOpCode::IndicatorGeq, args);
109 });
110
111 // Min = 10
112 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
113 return ExternalRandomVariable(RandomVariableOpCode::Min, args);
114 });
115
116 // Max = 11
117 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
118 return ExternalRandomVariable(RandomVariableOpCode::Max, args);
119 });
120
121 // Abs = 12
122 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
123 return ExternalRandomVariable(RandomVariableOpCode::Abs, args);
124 });
125
126 // Exp = 13
127 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
128 return ExternalRandomVariable(RandomVariableOpCode::Exp, args);
129 });
130
131 // Sqrt = 14
132 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
133 return ExternalRandomVariable(RandomVariableOpCode::Sqrt, args);
134 });
135
136 // Log = 15
137 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
138 return ExternalRandomVariable(RandomVariableOpCode::Log, args);
139 });
140
141 // Pow = 16
142 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
143 return ExternalRandomVariable(RandomVariableOpCode::Pow, args);
144 });
145
146 // NormalCdf = 17
147 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
148 return ExternalRandomVariable(RandomVariableOpCode::NormalCdf, args);
149 });
150
151 // NormalPdf = 18
152 ops.push_back([](const std::vector<const ExternalRandomVariable*>& args) {
153 return ExternalRandomVariable(RandomVariableOpCode::NormalPdf, args);
154 });
155
156 return ops;
157}

◆ getExternalRandomVariableGradients()

std::vector< ExternalRandomVariableGrad > getExternalRandomVariableGradients ( )

Definition at line 159 of file external_randomvariable_ops.cpp.

159{ return {}; }

◆ isDeterministicAndZero() [1/2]

bool isDeterministicAndZero ( const ExternalRandomVariable x)

Definition at line 50 of file external_randomvariable_ops.hpp.

50 {
51 return false;
52}

◆ forwardDerivatives()

void forwardDerivatives ( const ComputationGraph g,
const std::vector< T > &  values,
std::vector< T > &  derivatives,
const std::vector< std::function< std::vector< T >(const std::vector< const T * > &, const T *)>  ,
grad,
std::function< void(T &)>  deleter = {},
const std::vector< bool > &  keepNodes = {},
const std::size_t  conditionalExpectationOpId = 0,
const std::function< T(const std::vector< const T * > &)> &  conditionalExpectation = {} 
)

Definition at line 35 of file forwardderivatives.hpp.

37 {}, const std::vector<bool>& keepNodes = {},
38 const std::size_t conditionalExpectationOpId = 0,
39 const std::function<T(const std::vector<const T*>&)>& conditionalExpectation = {}) {
40
41 if (g.size() == 0)
42 return;
43
44 // loop over the nodes in the graph in forward order
45
46 for (std::size_t node = 0; node < g.size(); ++node) {
47 if (!g.predecessors(node).empty()) {
48
49 // propagate the derivatives from predecessors of a node to the node
50
51 std::vector<const T*> args(g.predecessors(node).size());
52 for (std::size_t arg = 0; arg < g.predecessors(node).size(); ++arg) {
53 args[arg] = &values[g.predecessors(node)[arg]];
54 }
55
56 if (g.opId(node) == conditionalExpectationOpId && conditionalExpectation) {
57
58 args[0] = &derivatives[g.predecessors(node)[0]];
59 derivatives[node] = conditionalExpectation(args);
60
61 } else {
62
63 auto gr = grad[g.opId(node)](args, &values[node]);
64
65 for (std::size_t p = 0; p < g.predecessors(node).size(); ++p) {
66 derivatives[node] += derivatives[g.predecessors(node)[p]] * gr[p];
67 }
68 }
69
70 // the check if we can delete the predecessors
71
72 if (deleter) {
73 for (std::size_t arg = 0; arg < g.predecessors(node).size(); ++arg) {
74 std::size_t p = g.predecessors(node)[arg];
75
76 // is the node no longer needed for other target nodes?
77
78 if (g.maxNodeRequiringArg(p) > node)
79 continue;
80
81 // is the node marked as to be kept ?
82
83 if (!keepNodes.empty() && keepNodes[p])
84 continue;
85
86 // apply the deleter
87
88 deleter(derivatives[p]);
89
90 } // for arg over g.predecessors
91 } // if deleter
92 } // if !g.predecessors empty
93 } // for node
94}
std::size_t maxNodeRequiringArg(const std::size_t node) const
+ Here is the caller graph for this function:

◆ forwardEvaluation()

void forwardEvaluation ( const ComputationGraph g,
std::vector< T > &  values,
const std::vector< std::function< T(const std::vector< const T * > &)>  ,
ops,
std::function< void(T &)>  deleter = {},
bool  keepValuesForDerivatives = true,
const std::vector< std::function< std::pair< std::vector< bool >, bool >(const std::size_t)> > &  opRequiresNodesForDerivatives = {},
const std::vector< bool > &  keepNodes = {},
const std::size_t  startNode = 0,
const std::size_t  endNode = ComputationGraph::nan,
const bool  redBlockReconstruction = false 
)

Definition at line 32 of file forwardevaluation.hpp.

34 {}, bool keepValuesForDerivatives = true,
35 const std::vector<std::function<std::pair<std::vector<bool>, bool>(const std::size_t)>>&
36 opRequiresNodesForDerivatives = {},
37 const std::vector<bool>& keepNodes = {}, const std::size_t startNode = 0,
38 const std::size_t endNode = ComputationGraph::nan, const bool redBlockReconstruction = false) {
39
40 std::vector<bool> keepNodesDerivatives;
41 if (deleter && keepValuesForDerivatives)
42 keepNodesDerivatives = std::vector<bool>(g.size(), false);
43
44 // loop over the nodes in the graph in ascending order
45
46 for (std::size_t node = startNode; node < (endNode == ComputationGraph::nan ? g.size() : endNode); ++node) {
47
48 // if a node is computed by an op applied to predecessors ...
49
50 if (!g.predecessors(node).empty()) {
51
52 // evaluate the node
53
54 std::vector<const T*> args(g.predecessors(node).size());
55 for (std::size_t arg = 0; arg < g.predecessors(node).size(); ++arg) {
56 args[arg] = &values[g.predecessors(node)[arg]];
57 }
58 values[node] = ops[g.opId(node)](args);
59
60 QL_REQUIRE(values[node].initialised(), "forwardEvaluation(): value at active node "
61 << node << " is not initialized, opId = " << g.opId(node));
62
63 // then check if we can delete the predecessors
64
65 if (deleter) {
66 for (std::size_t arg = 0; arg < g.predecessors(node).size(); ++arg) {
67 std::size_t p = g.predecessors(node)[arg];
68
69 if (!keepNodesDerivatives.empty()) {
70
71 // is the node required to compute derivatives, then add it to the keep nodes vector
72
73 if (opRequiresNodesForDerivatives[g.opId(p)](args.size()).second ||
74 opRequiresNodesForDerivatives[g.opId(node)](args.size()).first[arg])
75 keepNodesDerivatives[p] = true;
76 }
77
78 // is the node no longer needed for the forward evaluation?
79
80 if (g.maxNodeRequiringArg(p) > node)
81 continue;
82
83 // is the node marked as to be kept ?
84
85 if ((!keepNodes.empty() && keepNodes[p]) ||
86 (!keepNodesDerivatives.empty() && keepNodesDerivatives[p] &&
87 (g.redBlockId(p) == 0 || redBlockReconstruction)))
88 continue;
89
90 // apply the deleter
91
92 deleter(values[p]);
93
94 } // for arg over g.predecessors
95 } // if deleter
96 } // if !g.predecessors empty
97 } // for node
98}
+ Here is the caller graph for this function:

◆ ssaForm() [1/3]

std::string ssaForm ( const ComputationGraph g,
const std::vector< std::string > &  opCodeLabels,
const std::vector< T > &  values,
const std::vector< T > &  values2 
)

Definition at line 43 of file ssaform.cpp.

44 {
45
46 std::ostringstream os;
47
48 for (std::size_t i = 0; i < g.size(); ++i) {
49
50 os << i << "," << getLabel(g, i);
51
52 os << ",";
53 if (!g.predecessors(i).empty()) {
54 os << (opCodeLabels.size() > g.opId(i) ? opCodeLabels[g.opId(i)] : "???") << "(";
55 for (std::size_t j = 0; j < g.predecessors(i).size(); ++j) {
56 auto p = g.predecessors(i)[j];
57 os << getLabel(g, p, false) << (j < g.predecessors(i).size() - 1 ? ";" : "");
58 }
59 os << ")";
60 }
61
62 if (values.size() > i) {
63 os << "," << values[i];
64 }
65
66 if (values2.size() > i) {
67 os << "," << values2[i];
68 }
69
70 os << "\n";
71 }
72
73 return os.str();
74}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ ssaForm() [2/3]

template std::string ssaForm ( const ComputationGraph g,
const std::vector< std::string > &  opCodeLabels,
const std::vector< double > &  values,
const std::vector< double > &  values2 
)

◆ ssaForm() [3/3]

template std::string ssaForm ( const ComputationGraph g,
const std::vector< std::string > &  opCodeLabels,
const std::vector< RandomVariable > &  values,
const std::vector< RandomVariable > &  values2 
)

◆ pricingDates() [1/2]

set< Date > pricingDates ( const Date &  s,
const Date &  e,
const Calendar &  pricingCalendar,
bool  excludeStart,
bool  includeEnd,
bool  useBusinessDays 
)

Definition at line 48 of file commoditycashflow.cpp.

49 {
50
51 // If start date is after end date, return no dates.
52 if (s > e)
53 return set<Date>();
54
55 Date start = s;
56 Date end = e;
57
58 // Cover the possible exclusion of the start date
59 if ((useBusinessDays && pricingCalendar.isBusinessDay(start)) && excludeStart) {
60 start = pricingCalendar.advance(start, 1, Days);
61 }
62
63 if ((!useBusinessDays && pricingCalendar.isHoliday(start)) && excludeStart) {
64 while (pricingCalendar.isHoliday(start) && start <= end)
65 start++;
66 }
67
68 // Cover the possible exclusion of the end date
69 if ((useBusinessDays && pricingCalendar.isBusinessDay(end)) && !includeEnd) {
70 end = pricingCalendar.advance(end, -1, Days);
71 }
72
73 if ((!useBusinessDays && pricingCalendar.isHoliday(end)) && !includeEnd) {
74 while (pricingCalendar.isHoliday(end) && start <= end)
75 end--;
76 }
77
78 // Create the set of dates, which may be empty.
79 set<Date> res;
80 for (; start <= end; start++) {
81 if (isPricingDate(start, pricingCalendar, useBusinessDays))
82 res.insert(start);
83 }
84
85 return res;
86}
bool isPricingDate(const Date &d, const Calendar &pricingCalendar, bool useBusinessDays)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isPricingDate() [1/2]

bool isPricingDate ( const Date &  d,
const Calendar &  pricingCalendar,
bool  useBusinessDays 
)

Definition at line 88 of file commoditycashflow.cpp.

88 {
89 return ((useBusinessDays && pricingCalendar.isBusinessDay(d)) ||
90 (!useBusinessDays && pricingCalendar.isHoliday(d)));
91}
+ Here is the caller graph for this function:

◆ pricingDates() [2/2]

std::set< QuantLib::Date > pricingDates ( const QuantLib::Date &  start,
const QuantLib::Date &  end,
const QuantLib::Calendar &  pricingCalendar,
bool  excludeStart,
bool  includeEnd,
bool  useBusinessDays = true 
)

Get the set of valid pricing dates in a period.

Parameters
startThe start date of the period.
endThe end date of the period.
pricingCalendarThe pricing calendar used to determine valid dates
excludeStartSet to true if the start date should be excluded from the set of pricing dates and to false if the start date should be included.
includeEndset to true if the end date should be included in the set of pricing dates and to false if the end date should be excluded.
useBusinessDaysSet to true if pricingCalendar business dates are to be considered valid pricing dates and false if pricingCalendar holidays are to be considered valid pricing dates. The latter case is unusual but is useful for some electricity futures e.g. ICE PW2 contract which averages over weekends and non-NERC business days.
Returns
The set of valid pricing dates in the period.

◆ isPricingDate() [2/2]

bool isPricingDate ( const QuantLib::Date &  d,
const QuantLib::Calendar &  pricingCalendar,
bool  useBusinessDays = true 
)

Check if a date is a pricing date.

Parameters
dThe date that we wish to check.
pricingCalendarThe pricing calendar used to determine valid dates
useBusinessDaysSet to true if pricingCalendar business dates are to be considered valid pricing dates and false if pricingCalendar holidays are to be considered valid pricing dates. The latter case is unusual but is useful for some electricity futures e.g. ICE PW2 contract which averages over weekends and non-NERC business days.
Returns
Returns true if d is a pricing date and false otherwise.

◆ operator<<() [1/16]

std::ostream & operator<< ( std::ostream &  out,
EquityReturnType  t 
)

Definition at line 30 of file equitycoupon.cpp.

30 {
31 switch (t) {
32 case EquityReturnType::Price:
33 return out << "Price";
34 case EquityReturnType::Total:
35 return out << "Total";
36 case EquityReturnType::Absolute:
37 return out << "Absolute";
38 case EquityReturnType::Dividend:
39 return out << "Dividend";
40 default:
41 QL_FAIL("unknown EquityReturnType(" << int(t) << ")");
42 }
43}
+ Here is the caller graph for this function:

◆ parseEquityReturnType()

EquityReturnType parseEquityReturnType ( const std::string &  str)

Definition at line 45 of file equitycoupon.cpp.

45 {
46 if (boost::algorithm::to_upper_copy(str) == "PRICE")
47 return EquityReturnType::Price;
48 else if (boost::algorithm::to_upper_copy(str) == "TOTAL")
49 return EquityReturnType::Total;
50 else if (boost::algorithm::to_upper_copy(str) == "ABSOLUTE")
51 return EquityReturnType::Absolute;
52 else if (boost::algorithm::to_upper_copy(str) == "DIVIDEND")
53 return EquityReturnType::Dividend;
54 QL_FAIL("Invalid EquityReturnType " << str);
55}

◆ makeFloatingAnnuityNominalLeg()

Leg makeFloatingAnnuityNominalLeg ( const Leg &  floatingAnnuityLeg)

Definition at line 23 of file floatingannuitynominal.cpp.

23 {
24 Leg leg;
25 for (Size i = 0; i < floatingAnnuityLeg.size(); i++) {
26 QuantLib::ext::shared_ptr<FloatingAnnuityCoupon> coupon =
27 QuantLib::ext::dynamic_pointer_cast<FloatingAnnuityCoupon>(floatingAnnuityLeg[i]);
28 if (coupon)
29 leg.push_back(QuantLib::ext::shared_ptr<CashFlow>(new FloatingAnnuityNominal(coupon)));
30 }
31 return leg;
32}

◆ unpackIndexedCouponOrCashFlow()

QuantLib::ext::shared_ptr< CashFlow > unpackIndexedCouponOrCashFlow ( const QuantLib::ext::shared_ptr< CashFlow > &  c)

Definition at line 224 of file indexedcoupon.cpp.

224 {
225 if (auto cpn = QuantLib::ext::dynamic_pointer_cast<Coupon>(c))
226 return unpackIndexedCoupon(cpn);
227 else
229}
QuantLib::ext::shared_ptr< Coupon > unpackIndexedCoupon(const QuantLib::ext::shared_ptr< Coupon > &c)
QuantLib::ext::shared_ptr< CashFlow > unpackIndexWrappedCashFlow(const QuantLib::ext::shared_ptr< CashFlow > &c)
+ Here is the call graph for this function:

◆ unpackIndexedCoupon()

QuantLib::ext::shared_ptr< Coupon > unpackIndexedCoupon ( const QuantLib::ext::shared_ptr< Coupon > &  c)

Definition at line 231 of file indexedcoupon.cpp.

231 {
232 if (auto cpn = QuantLib::ext::dynamic_pointer_cast<IndexedCoupon>(c)) {
233 QuantLib::ext::shared_ptr<Coupon> unpacked_cpn = cpn->underlying();
234 return unpackIndexedCoupon(unpacked_cpn);
235 } else
236 return c;
237}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ unpackIndexWrappedCashFlow()

QuantLib::ext::shared_ptr< CashFlow > unpackIndexWrappedCashFlow ( const QuantLib::ext::shared_ptr< CashFlow > &  c)

Definition at line 239 of file indexedcoupon.cpp.

239 {
240 if (auto cf = QuantLib::ext::dynamic_pointer_cast<IndexWrappedCashFlow>(c)) {
241 QuantLib::ext::shared_ptr<CashFlow> unpacked_cf = cf->underlying();
242 return unpackIndexWrappedCashFlow(unpacked_cf);
243 } else
244 return c;
245}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getIndexedCouponOrCashFlowMultiplier()

Real getIndexedCouponOrCashFlowMultiplier ( const QuantLib::ext::shared_ptr< CashFlow > &  c)

Definition at line 247 of file indexedcoupon.cpp.

247 {
248 if (auto cpn = QuantLib::ext::dynamic_pointer_cast<IndexedCoupon>(c)) {
249 return cpn->multiplier() * getIndexedCouponOrCashFlowMultiplier(cpn->underlying());
250 } else if (auto cf = QuantLib::ext::dynamic_pointer_cast<IndexWrappedCashFlow>(c)) {
251 return cf->multiplier() * getIndexedCouponOrCashFlowMultiplier(cf->underlying());
252 } else {
253 return 1.0;
254 }
255}
Real getIndexedCouponOrCashFlowMultiplier(const QuantLib::ext::shared_ptr< CashFlow > &c)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getIndexedCouponOrCashFlowFixingDetails()

std::vector< std::tuple< Date, QuantLib::ext::shared_ptr< Index >, Real > > getIndexedCouponOrCashFlowFixingDetails ( const QuantLib::ext::shared_ptr< CashFlow > &  c)

Definition at line 258 of file indexedcoupon.cpp.

258 {
259 if (auto cpn = QuantLib::ext::dynamic_pointer_cast<IndexedCoupon>(c)) {
260 auto v = getIndexedCouponOrCashFlowFixingDetails(cpn->underlying());
261 v.push_back(std::make_tuple(cpn->fixingDate(), cpn->index(), cpn->multiplier()));
262 return v;
263 } else if (auto cf = QuantLib::ext::dynamic_pointer_cast<IndexWrappedCashFlow>(c)) {
264 auto v = getIndexedCouponOrCashFlowFixingDetails(cf->underlying());
265 v.push_back(std::make_tuple(cf->fixingDate(), cf->index(), cf->multiplier()));
266 return v;
267 } else {
268 return {};
269 }
270}
std::vector< std::tuple< Date, QuantLib::ext::shared_ptr< Index >, Real > > getIndexedCouponOrCashFlowFixingDetails(const QuantLib::ext::shared_ptr< CashFlow > &c)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ jyExpectedIndexRatio() [1/2]

Real jyExpectedIndexRatio ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
Size  index,
Time  S,
Time  T,
bool  indexIsInterpolated 
)

Definition at line 77 of file jyyoyinflationcouponpricer.cpp.

78 {
79
80 using namespace CrossAssetAnalytics;
81 auto irIdx = model->ccyIndex(model->infjy(index)->currency());
82 auto irTs = model->irlgm1f(irIdx)->termStructure();
83 auto zts = model->infjy(index)->realRate()->termStructure();
84
85 // Calculate growthRatio: \frac{P_r(0,T)}{P_n(0,T)} / \frac{P_r(0,S)}{P_n(0,S)}
86 auto growthRatio = inflationGrowth(zts, T, indexIsInterpolated) / inflationGrowth(zts, S, indexIsInterpolated);
87
88 // Calculate exponent of the convexity adjustment i.e. c.
89 auto rrParam = model->infjy(index)->realRate();
90 auto H_r_S = rrParam->H(S);
91 auto H_r_T = rrParam->H(T);
92 auto H_n_S = model->irlgm1f(irIdx)->H(S);
93
94 auto c = H_r_S * rrParam->zeta(S);
95 c -= H_n_S * integral(*model, P(rzy(irIdx, index, 0), az(irIdx), ay(index)), 0.0, S);
96 c += integral(*model,
97 LC(0.0, -1.0, P(ay(index), ay(index), Hy(index)), 1.0,
98 P(rzy(irIdx, index, 0), az(irIdx), ay(index), Hz(irIdx)), -1.0,
99 P(ryy(index, index, 0, 1), ay(index), sy(index))),
100 0.0, S);
101 c *= (H_r_S - H_r_T);
102
103 return growthRatio * exp(c);
104}
const LC1_< E1 > LC(QuantLib::Real c, QuantLib::Real c1, const E1 &e1)
Real integral(const CrossAssetModel &model, const E &e, const Real a, const Real b)
const P2_< E1, E2 > P(const E1 &e1, const E2 &e2)
CompiledFormula exp(CompiledFormula x)
Real inflationGrowth(const QuantLib::ext::shared_ptr< CrossAssetModel > &model, Size index, Time S, Time T, Real irState, Real rrState, bool indexIsInterpolated)
INF H component. May relate to real rate portion of JY model or z component of DK model.
INF alpha component. May relate to real rate portion of JY model or z component of DK model.
JY INF index sigma component.
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ jyExpectedIndexRatio() [2/2]

QuantLib::Real jyExpectedIndexRatio ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
QuantLib::Size  index,
QuantLib::Time  S,
QuantLib::Time  T,
bool  indexIsInterpolated 
)

Return the expected value of the inflation index ratio \(I(T)/I(S)\) under Jarrow Yildrim where \( 0 < S < T \). The value is given in Section 13 of Modern Derivatives Pricing and Credit Exposure Analysis, 2015 by the following:

\[ \frac{P_r(0,T)}{P_n(0,T)} \frac{P_n(0,S)}{P_r(0,S)} e^{C(S,T)} \]

◆ operator<<() [2/16]

std::ostream & operator<< ( std::ostream &  os,
ConfigurableCurrency::Type  ccytype 
)

Definition at line 38 of file configurablecurrency.cpp.

38 {
39 switch (ccytype) {
40 case ConfigurableCurrency::Type::Major:
41 return os << "Major";
42 case ConfigurableCurrency::Type::Metal:
43 return os <<"Metal";
44 case ConfigurableCurrency::Type::Crypto:
45 return os << "Crypto";
46 default:
47 QL_FAIL("Unknown AssetClass");
48 }
49}

◆ isMetal() [1/2]

bool isMetal ( const Currency &  currency)

Definition at line 55 of file metals.cpp.

55 {
56
57 static auto cmpCcy = [](const Currency& c1, const Currency& c2) { return c1.name() < c2.name(); };
58 static set<Currency, decltype(cmpCcy)> metals(cmpCcy);
59
60 if (metals.empty()) {
61 metals.insert(XAUCurrency());
62 metals.insert(XAGCurrency());
63 metals.insert(XPTCurrency());
64 metals.insert(XPDCurrency());
65 }
66
67 return metals.count(currency) == 1;
68}

◆ isMetal() [2/2]

bool isMetal ( const QuantLib::Currency &  currency)

Check if a given currency is a metal.

◆ applyDividends()

void applyDividends ( const set< Dividend > &  dividends)

Utility to write a set of dividends in the dividend manager's history.

Definition at line 30 of file dividendmanager.cpp.

30 {
31 map<string, QuantLib::ext::shared_ptr<EquityIndex2>> cache;
32 QuantLib::ext::shared_ptr<EquityIndex2> index;
33 std::string lastIndexName;
34 for (auto& d: dividends) {
35 try {
36 if (lastIndexName != d.name) {
37 index = QuantLib::ext::make_shared<EquityIndex2>(d.name, NullCalendar(), Currency());
38 lastIndexName = d.name;
39 }
40 index->addDividend(d, true);
41 } catch (...) {}
42 }
43}

◆ operator<() [1/4]

bool operator< ( const Dividend d1,
const Dividend d2 
)

Definition at line 45 of file dividendmanager.cpp.

45 {
46 if (d1.name != d2.name)
47 return d1.name < d2.name;
48 return d1.exDate < d2.exDate;
49}
std::string name
Index name.
QuantLib::Date exDate
Ex dividend date.

◆ operator==() [1/3]

bool operator== ( const Dividend d1,
const Dividend d2 
)

Compare dividends.

Definition at line 51 of file dividendmanager.cpp.

51 {
52 return d1.exDate == d2.exDate && d1.name == d2.name;
53}

◆ operator<<() [3/16]

std::ostream & operator<< ( std::ostream &  out,
Dividend  dividend 
)

Definition at line 55 of file dividendmanager.cpp.

55 {
56 return out << dividend.name << "," << dividend.exDate;
57}

◆ sum()

Real sum ( const Cash c,
const Cash d 
)

Definition at line 107 of file bondbasket.cpp.

107 {
108 return c.flow_ + d.flow_;
109 }
+ Here is the caller graph for this function:

◆ sumDiscounted()

Real sumDiscounted ( const Cash c,
const Cash d 
)

Definition at line 111 of file bondbasket.cpp.

111 {
112 return c.discountedFlow_ + d.discountedFlow_;
113 }
Real discountedFlow_
Definition: bondbasket.hpp:48

◆ operator<<() [4/16]

std::ostream & operator<< ( std::ostream &  out,
const CashFlowResults t 
)

Definition at line 31 of file cashflowresults.cpp.

31 {
32 if (t.amount != Null<Real>())
33 out << t.amount;
34 else
35 out << "?";
36 out << " " << t.currency;
37 if (t.payDate != Null<Date>())
38 out << " @ " << QuantLib::io::iso_date(t.payDate);
39 return out;
40}

◆ standardCashFlowResults() [1/2]

CashFlowResults standardCashFlowResults ( const QuantLib::ext::shared_ptr< CashFlow > &  c,
const Real  multiplier,
const std::string &  type,
const Size  legNo,
const Currency &  currency,
const Handle< YieldTermStructure > &  discountCurve 
)

Definition at line 42 of file cashflowresults.cpp.

44 {
45
46 CashFlowResults cfResults = populateCashFlowResultsFromCashflow(c, multiplier, legNo, currency);
47
48 if (!type.empty()) {
49 cfResults.type = type;
50 }
51
52 if (!discountCurve.empty()) {
53 cfResults.discountFactor = discountCurve->discount(cfResults.payDate);
54 cfResults.presentValue = cfResults.amount * cfResults.discountFactor;
55 }
56 return cfResults;
57}
CashFlowResults populateCashFlowResultsFromCashflow(const QuantLib::ext::shared_ptr< QuantLib::CashFlow > &c, const QuantLib::Real multiplier, const QuantLib::Size legNo, const QuantLib::Currency &currency)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ populateCashFlowResultsFromCashflow()

CashFlowResults populateCashFlowResultsFromCashflow ( const QuantLib::ext::shared_ptr< QuantLib::CashFlow > &  c,
const QuantLib::Real  multiplier,
const QuantLib::Size  legNo,
const QuantLib::Currency &  currency 
)

Definition at line 59 of file cashflowresults.cpp.

61 {
62
63 Date today = Settings::instance().evaluationDate();
64
65 CashFlowResults cfResults;
66
67 cfResults.amount = c->amount() * multiplier;
68 cfResults.payDate = c->date();
69
70 if (!currency.empty())
71 cfResults.currency = currency.code();
72
73 cfResults.legNumber = legNo;
74
75 if (auto cpn = QuantLib::ext::dynamic_pointer_cast<Coupon>(c)) {
76 cfResults.rate = cpn->rate();
77 cfResults.accrualStartDate = cpn->accrualStartDate();
78 cfResults.accrualEndDate = cpn->accrualEndDate();
79 cfResults.accrualPeriod = cpn->accrualPeriod();
80 cfResults.accruedAmount = cpn->accruedAmount(today);
81 cfResults.notional = cpn->nominal();
82 cfResults.type = "Interest";
83 if (auto ptrFloat = QuantLib::ext::dynamic_pointer_cast<QuantLib::FloatingRateCoupon>(cpn)) {
84 cfResults.fixingDate = ptrFloat->fixingDate();
85 cfResults.fixingValue = ptrFloat->index()->fixing(cfResults.fixingDate);
86 if (cfResults.fixingDate > today)
87 cfResults.type = "InterestProjected";
88 } else if (auto ptrInfl = QuantLib::ext::dynamic_pointer_cast<QuantLib::InflationCoupon>(cpn)) {
89 // We return the last fixing inside the coupon period
90 cfResults.fixingDate = ptrInfl->fixingDate();
91 cfResults.fixingValue = ptrInfl->indexFixing();
92 cfResults.type = "Inflation";
93 } else if (auto ptrBMA = QuantLib::ext::dynamic_pointer_cast<QuantLib::AverageBMACoupon>(cpn)) {
94 // We return the last fixing inside the coupon period
95 cfResults.fixingDate = ptrBMA->fixingDates().end()[-2];
96 cfResults.fixingValue = ptrBMA->pricer()->swapletRate();
97 if (cfResults.fixingDate > today)
98 cfResults.type = "BMAaverage";
99 }
100 } else {
101 cfResults.type = "Notional";
102 if (auto ptrIndCf = QuantLib::ext::dynamic_pointer_cast<QuantLib::IndexedCashFlow>(c)) {
103 cfResults.fixingDate = ptrIndCf->fixingDate();
104 cfResults.fixingValue = ptrIndCf->index()->fixing(cfResults.fixingDate);
105 cfResults.type = "Index";
106 } else if (auto ptrFxlCf = QuantLib::ext::dynamic_pointer_cast<QuantExt::FXLinkedCashFlow>(c)) {
107 // We return the last fixing inside the coupon period
108 cfResults.fixingDate = ptrFxlCf->fxFixingDate();
109 cfResults.fixingValue = ptrFxlCf->fxRate();
110 }
111 }
112 return cfResults;
113}
+ Here is the caller graph for this function:

◆ standardCashFlowResults() [2/2]

CashFlowResults standardCashFlowResults ( const QuantLib::ext::shared_ptr< QuantLib::CashFlow > &  c,
const QuantLib::Real  multiplier = 1.0,
const std::string &  type = "Unspecified",
const QuantLib::Size  legNo = 0,
const QuantLib::Currency &  currency = QuantLib::Currency(),
const QuantLib::Handle< QuantLib::YieldTermStructure > &  discountCurve = QuantLib::Handle< QuantLib::YieldTermStructure >() 
)

◆ MakeCreditDefaultSwap::operator QuantLib::ext::shared_ptr< QuantExt::CreditDefaultSwap >()

MakeCreditDefaultSwap::operator QuantLib::ext::shared_ptr< QuantExt::CreditDefaultSwap > ( ) const

Definition at line 64 of file makecds.cpp.

64 {
65
66 Date tradeDate = Settings::instance().evaluationDate();
67 Date upfrontDate = WeekendsOnly().advance(tradeDate, cashSettlementDays_, Days);
68
69 Date protectionStart;
70 if (rule_ == DateGeneration::CDS2015 || rule_ == DateGeneration::CDS) {
71 protectionStart = tradeDate;
72 } else {
73 protectionStart = tradeDate + 1;
74 }
75
76 Date end;
77 if (tenor_) {
78 if (rule_ == DateGeneration::CDS2015 || rule_ == DateGeneration::CDS || rule_ == DateGeneration::OldCDS) {
79 end = cdsMaturity(tradeDate, *tenor_, rule_);
80 } else {
81 end = tradeDate + *tenor_;
82 }
83 } else {
84 end = *termDate_;
85 }
86
87 Schedule schedule(protectionStart, end, couponTenor_, WeekendsOnly(), Following, Unadjusted, rule_, false);
88
89 CreditDefaultSwap::ProtectionPaymentTime timing = paysAtDefaultTime_ ?
90 CreditDefaultSwap::ProtectionPaymentTime::atDefault :
91 CreditDefaultSwap::ProtectionPaymentTime::atPeriodEnd;
92 QuantLib::ext::shared_ptr<CreditDefaultSwap> cds = QuantLib::ext::make_shared<CreditDefaultSwap>(
93 side_, nominal_, upfrontRate_, couponRate_, schedule, Following, dayCounter_, settlesAccrual_,
94 timing, protectionStart, upfrontDate, QuantLib::ext::shared_ptr<Claim>(),
95 lastPeriodDayCounter_, rebatesAccrual_, tradeDate, cashSettlementDays_);
96
97 cds->setPricingEngine(engine_);
98 return cds;
99}
QuantLib::ext::shared_ptr< PricingEngine > engine_
Definition: cdsoption.cpp:78

◆ getOisCapFloorUnderlying()

Leg getOisCapFloorUnderlying ( const Leg &  oisCapFloor)

get the underlying ON coupons from an OIS cf

Definition at line 138 of file makeoiscapfloor.cpp.

138 {
139 Leg underlying;
140 for (auto const& c : oisCapFloor) {
141 auto cfon = QuantLib::ext::dynamic_pointer_cast<CappedFlooredOvernightIndexedCoupon>(c);
142 QL_REQUIRE(cfon, "getOisCapFloorUnderlying(): expected CappedFlooredOvernightIndexedCoupon");
143 underlying.push_back(cfon->underlying());
144 }
145 return underlying;
146}
+ Here is the caller graph for this function:

◆ getOisCapFloorStrikes()

std::vector< std::pair< Real, Real > > getOisCapFloorStrikes ( const Leg &  oisCapFloor)

get the (cap, floor) - strikes from an OIS cf

Definition at line 148 of file makeoiscapfloor.cpp.

148 {
149 std::vector<std::pair<Real, Real>> result;
150 for (auto const& c : oisCapFloor) {
151 auto cfon = QuantLib::ext::dynamic_pointer_cast<CappedFlooredOvernightIndexedCoupon>(c);
152 QL_REQUIRE(cfon, "getOisCapFloorUnderlying(): expected CappedFlooredOvernightIndexedCoupon");
153 result.push_back(std::make_pair(cfon->cap(), cfon->floor()));
154 }
155 return result;
156}
+ Here is the caller graph for this function:

◆ inverse()

QuantLib::SparseMatrix inverse ( QuantLib::SparseMatrix  m)

Definition at line 49 of file blockmatrixinverse.cpp.

49 {
50 QL_REQUIRE(m.size1() == m.size2(), "matrix is not square");
51 boost::numeric::ublas::permutation_matrix<Size> pert(m.size1());
52 // lu decomposition
53 const Size singular = lu_factorize(m, pert);
54 QL_REQUIRE(singular == 0, "singular matrix given");
55 QuantLib::SparseMatrix inverse = boost::numeric::ublas::identity_matrix<Real>(m.size1());
56 // backsubstitution
57 boost::numeric::ublas::lu_substitute(m, pert, inverse);
58 return inverse;
59}
QuantLib::SparseMatrix inverse(QuantLib::SparseMatrix m)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ blockMatrixInverse() [1/4]

Matrix blockMatrixInverse ( const Matrix &  A,
const std::vector< Size > &  blockIndices 
)

Definition at line 61 of file blockmatrixinverse.cpp.

61 {
62
63 QL_REQUIRE(blockIndices.size() > 0, "blockMatrixInverse: at least one entry in blockIndices required");
64 Size n = blockIndices.back();
65 QL_REQUIRE(n > 0 && A.rows() == A.columns() && A.rows() == n,
66 "blockMatrixInverse: matrix (" << A.rows() << "x" << A.columns() << ") must be square of size " << n
67 << "x" << n << ", n>0");
68
69 if (blockIndices.size() == 1) {
70 Matrix res = inverse(A);
71 return res;
72 }
73
74 Size mid = (blockIndices.size() - 1) / 2;
75 Size m = blockIndices[mid];
76 QL_REQUIRE(m > 0 && m < n,
77 "blockMatrixInverse: expected m (" << m << ") to be positive and less than n (" << n << ")");
78 std::vector<Size> leftIndices(blockIndices.begin(), blockIndices.begin() + (mid + 1));
79 std::vector<Size> rightIndices(blockIndices.begin() + (mid + 1), blockIndices.end());
80 for (auto& i : rightIndices) {
81 i -= m;
82 }
83 QL_REQUIRE(leftIndices.size() > 0, "blockMatrixInverse: expected left indices to be non-empty");
84 QL_REQUIRE(rightIndices.size() > 0, "blockMatrixInverse: expected right indices to be non-empty");
85
86 // FIXME it would be nice if we could avoid building these submatrices, instead use a view
87 // on parts of the original matrix
88 Matrix a(m, m), b(m, n - m), c(n - m, m), d(n - m, n - m);
89
90 for (Size i = 0; i < n; ++i) {
91 for (Size j = 0; j < n; ++j) {
92 if (i < m) {
93 if (j < m)
94 a[i][j] = A[i][j];
95 else
96 b[i][j - m] = A[i][j];
97 } else {
98 if (j < m)
99 c[i - m][j] = A[i][j];
100 else
101 d[i - m][j - m] = A[i][j];
102 }
103 }
104 }
105
106 Matrix aInv = blockMatrixInverse(a, leftIndices);
107 Matrix tmp = c * aInv;
108 Matrix schurCompInv;
109 if (isNull(c) || isNull(b))
110 schurCompInv = blockMatrixInverse(d, rightIndices);
111 else
112 schurCompInv = blockMatrixInverse(d - tmp * b, rightIndices);
113 Matrix b2 = (-1) * (aInv * b * schurCompInv);
114 Matrix a2 = aInv - b2 * tmp;
115 Matrix c2 = (-1) * schurCompInv * tmp;
116
117 Matrix res(n, n);
118 for (Size i = 0; i < n; ++i) {
119 for (Size j = 0; j < n; ++j) {
120 if (i < m) {
121 if (j < m)
122 res[i][j] = a2[i][j];
123 else
124 res[i][j] = b2[i][j - m];
125 } else {
126 if (j < m)
127 res[i][j] = c2[i - m][j];
128 else
129 res[i][j] = schurCompInv[i - m][j - m];
130 }
131 }
132 }
133
134 return res;
135} // blockMatrixInverse(Matrix)
Matrix blockMatrixInverse(const Matrix &A, const std::vector< Size > &blockIndices)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ blockMatrixInverse() [2/4]

QuantLib::SparseMatrix blockMatrixInverse ( const QuantLib::SparseMatrix &  A,
const std::vector< Size > &  blockIndices 
)

Definition at line 137 of file blockmatrixinverse.cpp.

137 {
138
139 QL_REQUIRE(blockIndices.size() > 0, "blockMatrixInverse: at least one entry in blockIndices required");
140 Size n = blockIndices.back();
141 QL_REQUIRE(n > 0 && A.size1() == A.size2() && A.size1() == n,
142 "blockMatrixInverse: matrix (" << A.size1() << "x" << A.size2() << ") must be square of size " << n
143 << "x" << n << ", n>0");
144
145 if (blockIndices.size() == 1) {
146 QuantLib::SparseMatrix res = inverse(A);
147 return res;
148 }
149
150 Size mid = (blockIndices.size() - 1) / 2;
151 Size m = blockIndices[mid];
152 QL_REQUIRE(m > 0 && m < n,
153 "blockMatrixInverse: expected m (" << m << ") to be positive and less than n (" << n << ")");
154 std::vector<Size> leftIndices(blockIndices.begin(), blockIndices.begin() + (mid + 1));
155 std::vector<Size> rightIndices(blockIndices.begin() + (mid + 1), blockIndices.end());
156 for (auto& i : rightIndices) {
157 i -= m;
158 }
159 QL_REQUIRE(leftIndices.size() > 0, "blockMatrixInverse: expected left indices to be non-empty");
160 QL_REQUIRE(rightIndices.size() > 0, "blockMatrixInverse: expected right indices to be non-empty");
161
162 QuantLib::SparseMatrix a = project(A, range(0, m), range(0, m));
163 QuantLib::SparseMatrix b = project(A, range(0, m), range(m, n));
164 QuantLib::SparseMatrix c = project(A, range(m, n), range(0, m));
165 QuantLib::SparseMatrix d = project(A, range(m, n), range(m, n));
166
167 QuantLib::SparseMatrix aInv = blockMatrixInverse(a, leftIndices);
168 QuantLib::SparseMatrix tmp(n - m, m), schurCompInv, p(m, n - m), p1(n - m, n - m), p2(m, m), b2(m, n - m), c2(n - m, m);
169 axpy_prod(c, aInv, tmp, true);
170 if (isNull(c) || isNull(b))
171 schurCompInv = blockMatrixInverse(d, rightIndices);
172 else {
173 axpy_prod(tmp, b, p1, true);
174 schurCompInv = blockMatrixInverse(d - p1, rightIndices);
175 }
176 axpy_prod(aInv, b, p, true);
177 axpy_prod(-p, schurCompInv, b2);
178 axpy_prod(b2, tmp, p2);
179 QuantLib::SparseMatrix a2 = aInv - p2;
180 axpy_prod(-schurCompInv, tmp, c2);
181
182 QuantLib::SparseMatrix res(n, n);
183
184 for (auto i1 = a2.begin1(); i1 != a2.end1(); ++i1) {
185 for (auto i2 = i1.begin(); i2 != i1.end(); ++i2) {
186 res(i2.index1(), i2.index2()) = *i2;
187 }
188 }
189 for (auto i1 = b2.begin1(); i1 != b2.end1(); ++i1) {
190 for (auto i2 = i1.begin(); i2 != i1.end(); ++i2) {
191 res(i2.index1(), i2.index2() + m) = *i2;
192 }
193 }
194 for (auto i1 = c2.begin1(); i1 != c2.end1(); ++i1) {
195 for (auto i2 = i1.begin(); i2 != i1.end(); ++i2) {
196 res(i2.index1() + m, i2.index2()) = *i2;
197 }
198 }
199 for (auto i1 = schurCompInv.begin1(); i1 != schurCompInv.end1(); ++i1) {
200 for (auto i2 = i1.begin(); i2 != i1.end(); ++i2) {
201 res(i2.index1() + m, i2.index2() + m) = *i2;
202 }
203 }
204
205 return res;
206} // blockMatrixInverse(SparseMatrix)
+ Here is the call graph for this function:

◆ modifiedMaxNorm()

QuantLib::Real modifiedMaxNorm ( const QuantLib::SparseMatrix &  A)

modified max norm of a sparse matrix, i.e. std::sqrt(row * columns) * max_i,j abs(a_i,j)

Definition at line 208 of file blockmatrixinverse.cpp.

208 {
209 Real r = 0.0;
210 for (auto i1 = A.begin1(); i1 != A.end1(); ++i1) {
211 for (auto i2 = i1.begin(); i2 != i1.end(); ++i2) {
212 r = std::max(r, std::abs(*i2));
213 }
214 }
215 return std::sqrt(static_cast<Real>(A.size1()) * static_cast<Real>(A.size2())) * r;
216}

◆ blockMatrixInverse() [3/4]

QuantLib::Matrix blockMatrixInverse ( const QuantLib::Matrix &  A,
const std::vector< QuantLib::Size > &  blockIndices 
)

◆ blockMatrixInverse() [4/4]

QuantLib::SparseMatrix blockMatrixInverse ( const QuantLib::SparseMatrix &  A,
const std::vector< QuantLib::Size > &  blockIndices 
)

◆ operator+() [1/3]

BucketedDistribution operator+ ( const BucketedDistribution lhs,
const BucketedDistribution rhs 
)

Sum probabilities in two bucketed distributions with equal buckets.

Definition at line 278 of file bucketeddistribution.cpp.

278 {
279
280 BucketedDistribution result = lhs;
281 result += rhs;
282 return result;
283}
Represents a bucketed probability distibution.

◆ operator*() [1/5]

BucketedDistribution operator* ( Real  factor,
const BucketedDistribution rhs 
)

Definition at line 285 of file bucketeddistribution.cpp.

285 {
286 vector<Real> probabilities(rhs.numberBuckets(), 0.0);
287 // transform(rhs.probabilities().begin(), rhs.probabilities().end(), probabilities.begin(),
288 // std::bind1st(multiplies<Real>(), factor));
289 transform(rhs.probabilities().begin(), rhs.probabilities().end(), probabilities.begin(),
290 [factor](const Real x) { return x * factor; });
291 return BucketedDistribution(rhs.buckets(), probabilities, rhs.points());
292}
const std::vector< QuantLib::Real > & probabilities() const
Get the probabilities.
Size numberBuckets() const
Return the number of buckets in the distribution.
const std::vector< QuantLib::Real > & buckets() const
Return the buckets of the distribution.
const std::vector< QuantLib::Real > & points() const
Return the points of the distribution.
+ Here is the call graph for this function:

◆ operator*() [2/5]

BucketedDistribution operator* ( const BucketedDistribution lhs,
QuantLib::Real  factor 
)

Definition at line 294 of file bucketeddistribution.cpp.

294{ return factor * lhs; }

◆ operator*() [3/5]

BucketedDistribution operator* ( QuantLib::Real  factor,
const BucketedDistribution rhs 
)

Multiply probabilities in bucketed distribution by factor.

◆ operator+() [2/3]

CompiledFormula operator+ ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 98 of file compiledformula.cpp.

98 {
99 x += y;
100 return x;
101}

◆ operator-() [1/3]

CompiledFormula operator- ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 103 of file compiledformula.cpp.

103 {
104 x -= y;
105 return x;
106}

◆ operator*() [4/5]

CompiledFormula operator* ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 108 of file compiledformula.cpp.

108 {
109 x *= y;
110 return x;
111}

◆ operator/() [1/2]

CompiledFormula operator/ ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 113 of file compiledformula.cpp.

113 {
114 x /= y;
115 return x;
116}

◆ unaryOp()

Definition at line 118 of file compiledformula.cpp.

118 {
119 std::vector<CompiledFormula> newArgs;
120 newArgs.push_back(x);
121 x.op_ = op;
122 x.x_ = Null<Real>();
123 x.v_ = Null<Size>();
124 x.args_.swap(newArgs);
125 return x;
126}
std::vector< CompiledFormula > args_

◆ binaryOp()

Definition at line 128 of file compiledformula.cpp.

128 {
129 std::vector<CompiledFormula> newArgs;
130 newArgs.push_back(x);
131 newArgs.push_back(y);
132 x.op_ = op;
133 x.x_ = Null<Real>();
134 x.v_ = Null<Size>();
135 x.args_.swap(newArgs);
136 return x;
137}

◆ gtZero()

Definition at line 142 of file compiledformula.cpp.

142{ return unaryOp(x, CompiledFormula::gtZero); }
CompiledFormula unaryOp(CompiledFormula x, CompiledFormula::Operator op)

◆ geqZero()

Definition at line 145 of file compiledformula.cpp.

145{ return unaryOp(x, CompiledFormula::geqZero); }

◆ abs() [1/2]

Definition at line 148 of file compiledformula.cpp.

148{ return unaryOp(x, CompiledFormula::abs); }
+ Here is the caller graph for this function:

◆ exp() [1/2]

Definition at line 151 of file compiledformula.cpp.

151{ return unaryOp(x, CompiledFormula::exp); }
+ Here is the caller graph for this function:

◆ log() [1/2]

Definition at line 154 of file compiledformula.cpp.

154{ return unaryOp(x, CompiledFormula::log); }
+ Here is the caller graph for this function:

◆ max() [1/2]

CompiledFormula max ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 159 of file compiledformula.cpp.

159{ return binaryOp(x, y, CompiledFormula::max); }
CompiledFormula binaryOp(CompiledFormula x, const CompiledFormula &y, CompiledFormula::Operator op)
+ Here is the caller graph for this function:

◆ min() [1/2]

CompiledFormula min ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 162 of file compiledformula.cpp.

162{ return binaryOp(x, y, CompiledFormula::min); }
+ Here is the caller graph for this function:

◆ pow() [1/2]

CompiledFormula pow ( CompiledFormula  x,
const CompiledFormula y 
)

Definition at line 165 of file compiledformula.cpp.

165{ return binaryOp(x, y, CompiledFormula::pow); }
+ Here is the caller graph for this function:

◆ createComputeFrameworkCreator()

T * createComputeFrameworkCreator ( )

Definition at line 118 of file computeenvironment.hpp.

118{ return new T; }

◆ deltaVar()

Real deltaVar ( const Matrix &  omega,
const Array &  delta,
const Real  p,
const CovarianceSalvage sal = NoCovarianceSalvage() 
)

function that computes a delta VaR

For a given covariance matrix and a delta vector this function computes a parametric var w.r.t. a given confidence level for multivariate normal risk factors.

Definition at line 305 of file deltagammavar.cpp.

305 {
306 detail::check(p);
307 detail::check(omega, delta);
308 Real num = detail::absMax(delta);
309 if (close_enough(num, 0.0))
310 return 0.0;
311 Array tmpDelta = delta / num;
312 return std::sqrt(DotProduct(tmpDelta, sal.salvage(omega).first * tmpDelta)) *
313 QuantLib::InverseCumulativeNormal()(p) * num;
314} // deltaVar
Filter close_enough(const RandomVariable &x, const RandomVariable &y)
virtual std::pair< Matrix, Matrix > salvage(const Matrix &m) const =0
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ deltaGammaVarNormal()

Real deltaGammaVarNormal ( const Matrix &  omega,
const Array &  delta,
const Matrix &  gamma,
const Real  p,
const CovarianceSalvage sal = NoCovarianceSalvage() 
)

function that computes a delta-gamma normal VaR

For a given a covariance matrix, a delta vector and a gamma matrix this function computes a parametric var w.r.t. a given confidence level. The gamma matrix is taken into account when computing the variance of the PL distribution, but the PL distribution is still assumed to be normal.

Definition at line 316 of file deltagammavar.cpp.

317 {
318 detail::check(p);
319 Real s = QuantLib::InverseCumulativeNormal()(p);
320 Real num = 0.0, mu = 0.0, variance = 0.0;
321 moments(sal.salvage(omega).first, delta, gamma, num, mu, variance);
322 if (close_enough(num, 0.0) || close_enough(variance, 0.0))
323 return 0.0;
324 return (std::sqrt(variance) * s + mu) * num;
325
326} // deltaGammaVarNormal
RandomVariable variance(const RandomVariable &r)
+ Here is the call graph for this function:

◆ deltaGammaVarCornishFisher()

Real deltaGammaVarCornishFisher ( const Matrix &  omega,
const Array &  delta,
const Matrix &  gamma,
const Real  p,
const CovarianceSalvage sal 
)

Definition at line 328 of file deltagammavar.cpp.

329 {
330 detail::check(p);
331 Real s = QuantLib::InverseCumulativeNormal()(p);
332 Real num = 0.0, mu = 0.0, variance = 0.0, tau = 0.0, kappa = 0.0;
333 moments(sal.salvage(omega).first, delta, gamma, num, mu, variance, tau, kappa);
334 if (close_enough(num, 0.0) || close_enough(variance, 0.0))
335 return 0.0;
336
337 Real xTilde =
338 s + tau / 6.0 * (s * s - 1.0) + kappa / 24.0 * s * (s * s - 3.0) - tau * tau / 36.0 * s * (2.0 * s * s - 5.0);
339 return (xTilde * std::sqrt(variance) + mu) * num;
340} // deltaGammaVarCornishFisher
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ deltaGammaVarSaddlepoint()

Real deltaGammaVarSaddlepoint ( const Matrix &  omega,
const Array &  delta,
const Matrix &  gamma,
const Real  p,
const CovarianceSalvage sal 
)

Definition at line 342 of file deltagammavar.cpp.

343 {
344
345 /* References:
346
347 Lugannani, R.and S.Rice (1980),
348 Saddlepoint Approximations for the Distribution of the Sum of Independent Random Variables,
349 Advances in Applied Probability, 12,475-490.
350
351 Daniels, H. E. (1987), Tail Probability Approximations, International Statistical Review, 55, 37-48.
352 */
353
354 detail::check(p);
355 detail::check(omega, delta, gamma);
356
357 auto S = sal.salvage(omega);
358 Matrix L = S.second;
359 if (L.rows() == 0) {
360 L = CholeskyDecomposition(omega, true);
361 }
362
363 Matrix hLGL = 0.5 * transpose(L) * gamma * L;
364 SymmetricSchurDecomposition schur(hLGL);
365 Array lambda = schur.eigenvalues();
366
367 // we scale the problem to ensure numerical stability; for this we divide delta and gamma by a
368 // factor such that the largest eigenvalue has absolute value 1.0
369
370 // find the largest absolute eigenvalue
371 Real scaling = 0.0;
372 for (const auto l : lambda) {
373 Real a = std::abs(l);
374 if (!close_enough(a, 0.0))
375 scaling = std::max(scaling, a);
376 }
377
378 // if all eigenvalues are zero we do not scale anything
379 if (close_enough(scaling, 0.0))
380 scaling = 1.0;
381
382 // scaled delta and gamma
383 Array tmpDelta = delta / scaling;
384 Matrix tmpGamma = gamma / scaling;
385
386 // adjusted eigenvalues
387 for (auto& l : lambda) {
388 l /= scaling;
389 }
390
391 // compute quantile
392 Array deltaBar = transpose(schur.eigenvectors()) * transpose(L) * tmpDelta;
393
394 // At this point, the delta-gamma PL can be written as scaling * ( deltaBar^T z + z^T GammaBar z ), where GammaBar
395 // is a diagonal matrix with the lambdas on the diagonal and z a vector of independent standard normal variates.
396 // We now compare the 2-norms of deltaBar and gammaBar and fall back on a simple delta VaR calculation, if the
397 // norm of gammaBar is negligible compared to the norm of deltaBar; this prevents numerical instabilities in the
398 // saddlepoint search, where the function k'(x)-x can become very steep around the saddlepoint in this situation.
399 Real normDeltaBar = 0.0, normGammaBar = 0.0;
400 for (Size i = 0; i < deltaBar.size(); ++i) {
401 normDeltaBar += deltaBar[i] * deltaBar[i];
402 normGammaBar += lambda[i] * lambda[i];
403 }
404 if (normGammaBar / normDeltaBar < 1E-10)
405 return QuantExt::deltaVar(S.first, delta, p);
406
407 // continue with the saddlepoint approach
408 auto FMinusP = [&lambda, &deltaBar, &p](const Real x) { return F(lambda, deltaBar, x) - p; };
409 Real quantile;
410 try {
411 // TODO check hardcoded tolerance, guess and step
412 Brent b;
413 quantile = b.solve(FMinusP, 1E-6, 0.0, 1.0);
414 } catch (const std::exception& e) {
415 QL_FAIL("deltaGammaVarSaddlepoint: could no solve for quantile p = " << p << ": " << e.what());
416 }
417
418 // undo scaling and return result
419 return quantile * scaling;
420
421} // deltaGammaVarSaddlepoint
Real deltaVar(const Matrix &omega, const Array &delta, const Real p, const CovarianceSalvage &sal)
function that computes a delta VaR
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ deltaGammaVarMc() [1/2]

Real deltaGammaVarMc ( const Matrix &  omega,
const Array &  delta,
const Matrix &  gamma,
const Real  p,
const Size  paths,
const Size  seed,
const CovarianceSalvage sal = NoCovarianceSalvage() 
)

function that computes a delta-gamma VaR using Monte Carlo (single quantile)

For a given a covariance matrix, a delta vector and a gamma matrix this function computes a parametric var w.r.t. a given confidence level. The var quantile is estimated from Monte-Carlo realisations of a second order sensitivity based PL.

Definition at line 138 of file deltagammavar.hpp.

139 {
140
141 std::vector<Real> pv(1, p);
142 return deltaGammaVarMc<RNG>(omega, delta, gamma, pv, paths, seed, sal).front();
143}

◆ deltaGammaVarMc() [2/2]

std::vector< Real > deltaGammaVarMc ( const Matrix &  omega,
const Array &  delta,
const Matrix &  gamma,
const std::vector< Real > &  p,
const Size  paths,
const Size  seed,
const CovarianceSalvage sal = NoCovarianceSalvage() 
)

function that computes a delta-gamma VaR using Monte Carlo (multiple quantiles)

For a given a covariance matrix, a delta vector and a gamma matrix this function computes a parametric var w.r.t. a vector of given confidence levels. The var quantile is estimated from Monte-Carlo realisations of a second order sensitivity based PL.

Definition at line 95 of file deltagammavar.hpp.

97 {
98 BOOST_FOREACH (Real q, p) { detail::check(q); }
99 detail::check(omega, delta, gamma);
100
101 Real num = std::max(detail::absMax(delta), detail::absMax(gamma));
102 if (QuantLib::close_enough(num, 0.0)) {
103 std::vector<Real> res(p.size(), 0.0);
104 return res;
105 }
106
107 Matrix L = sal.salvage(omega).second;
108 if (L.rows() == 0) {
109 L = CholeskyDecomposition(omega, true);
110 }
111
112 Real pmin = QL_MAX_REAL;
113 BOOST_FOREACH (Real q, p) { pmin = std::min(pmin, q); }
114
115 Size cache = Size(std::floor(static_cast<double>(paths) * (1.0 - pmin) + 0.5)) + 2;
116 boost::accumulators::accumulator_set<
117 double, boost::accumulators::stats<boost::accumulators::tag::tail_quantile<boost::accumulators::right> > >
118 acc(boost::accumulators::tag::tail<boost::accumulators::right>::cache_size = cache);
119
120 typename RNG::rsg_type rng = RNG::make_sequence_generator(delta.size(), seed);
121
122 for (Size i = 0; i < paths; ++i) {
123 std::vector<Real> seq = rng.nextSequence().value;
124 Array z(seq.begin(), seq.end());
125 Array u = L * z;
126 acc(DotProduct(u, delta) + 0.5 * DotProduct(u, gamma * u));
127 }
128
129 std::vector<Real> res;
130 BOOST_FOREACH (Real q, p) {
131 res.push_back(boost::accumulators::quantile(acc, boost::accumulators::quantile_probability = q));
132 }
133
134 return res;
135}
+ Here is the call graph for this function:

◆ operator<() [2/4]

bool operator< ( const Distributionpair p1,
const Distributionpair p2 
)

Definition at line 49 of file discretedistribution.hpp.

49{ return p1.x_ < p2.x_; }

◆ operator>() [1/2]

bool operator> ( const Distributionpair p1,
const Distributionpair p2 
)

Definition at line 51 of file discretedistribution.hpp.

51{ return p1.x_ > p2.x_; }

◆ fillIncompleteMatrix()

void fillIncompleteMatrix ( Matrix &  mat,
bool  interpRows,
Real  blank 
)

function that fills a matrix

This function fills a matrix that is not completely populated by linear interpolation across the desired axis.

Definition at line 87 of file fillemptymatrix.cpp.

87 {
88 QL_REQUIRE(mat.columns() > 0 && mat.rows() > 0, "Matrix has no elements.");
89
90 // check if already complete
91 bool isFull = true;
92 for (Size i = 0; i < mat.rows(); i++) {
93 for (Size j = 0; j < mat.columns(); j++) {
94 if (mat[i][j] == blank) {
95 isFull = false;
96 }
97 if (!isFull) {
98 break;
99 }
100 }
101 if (!isFull) {
102 break;
103 }
104 }
105
106 if (!isFull) {
107 if (mat.columns() == 1 && mat.rows() == 1) {
108 QL_FAIL("1 X 1 empty matrix given to fill."); // !is_full and 1 X 1 matrix.
109 }
110 if (interpRows) {
111 QL_REQUIRE(mat.columns() > 1, "Too few columns in matrix to interpolate within rows.");
112 fillMatrixImpl(mat, blank);
113 } else {
114 QL_REQUIRE(mat.rows() > 1, "Too few rows in matrix to interpolate within columns.");
115 Matrix m2 = transpose(mat);
116 fillMatrixImpl(m2, blank);
117 Matrix m3 = transpose(m2);
118 mat.swap(m3);
119 }
120 }
121}
+ Here is the caller graph for this function:

◆ kendallRankCorrelation()

Real kendallRankCorrelation ( I1  begin1,
I1  end1,
I2  begin2 
)

Definition at line 30 of file kendallrankcorrelation.hpp.

30 {
31 double sum = 0.0, n = static_cast<Real>(end1 - begin1);
32 auto w = begin2;
33 for (auto v = begin1; v != end1; ++v, ++w) {
34 auto w2 = begin2;
35 for (auto v2 = begin1; v2 != v; ++v2, ++w2) {
36 Real t = (*v2 - *v) * (*w2 - *w);
37 if (!QuantLib::close_enough(t, 0.0)) {
38 sum += t > 0.0 ? 1.0 : -1.0;
39 }
40 }
41 }
42 return 2.0 * sum / (n * (n - 1));
43}
Real sum(const Cash &c, const Cash &d)
Definition: bondbasket.cpp:107
+ Here is the call graph for this function:

◆ supports_Logm()

bool supports_Logm ( )

Definition at line 78 of file matrixfunctions.cpp.

78{ return false; }
+ Here is the caller graph for this function:

◆ supports_Expm()

bool supports_Expm ( )

Definition at line 79 of file matrixfunctions.cpp.

79{ return true; }
+ Here is the caller graph for this function:

◆ Logm()

QuantLib::Matrix Logm ( const QuantLib::Matrix &  m)

Definition at line 81 of file matrixfunctions.cpp.

81 {
82 QL_FAIL("Logm(): no implementation provided, you can e.g. install Eigen and rebuild ORE to enable this function.");
83}
+ Here is the caller graph for this function:

◆ Expm()

QuantLib::Matrix Expm ( const QuantLib::Matrix &  m)

Definition at line 85 of file matrixfunctions.cpp.

85{ return QuantLib::Expm(m); }
+ Here is the caller graph for this function:

◆ operator==() [2/3]

bool operator== ( const Filter a,
const Filter b 
)

Definition at line 213 of file randomvariable.cpp.

213 {
214 if (a.size() != b.size())
215 return false;
216 if (a.deterministic_ && b.deterministic_) {
217 return a.constantData_ == b.constantData_;
218 } else {
219 resumeCalcStats();
220 for (Size j = 0; j < a.size(); ++j)
221 if (a[j] != b[j]) {
222 stopCalcStats(j);
223 return false;
224 }
225 stopCalcStats(a.size());
226 }
227 return true;
228}
Size size() const

◆ operator!=() [1/3]

bool operator!= ( const Filter a,
const Filter b 
)

Definition at line 230 of file randomvariable.cpp.

230{ return !(a == b); }

◆ operator&&()

Filter operator&& ( Filter  x,
const Filter y 
)

Definition at line 232 of file randomvariable.cpp.

232 {
233 QL_REQUIRE(!x.initialised() || !y.initialised() || x.size() == y.size(),
234 "RandomVariable: x && y: x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
235 if (x.deterministic() && !x.constantData_)
236 return Filter(x.size(), false);
237 if (y.deterministic() && !y.constantData_)
238 return Filter(y.size(), false);
239 if (!x.initialised() || !y.initialised())
240 return Filter();
241 if (!y.deterministic_)
242 x.expand();
243 if (x.deterministic_) {
245 } else {
246 resumeCalcStats();
247 for (Size i = 0; i < x.size(); ++i) {
248 x.data_[i] = x.data_[i] && y[i];
249 }
250 stopCalcStats(x.size());
251 }
252 return x;
253}
bool deterministic() const
bool initialised() const

◆ operator||()

Filter operator|| ( Filter  x,
const Filter y 
)

Definition at line 255 of file randomvariable.cpp.

255 {
256 QL_REQUIRE(!x.initialised() || !y.initialised() || x.size() == y.size(),
257 "RandomVariable: x || y: x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
258 if (x.deterministic() && x.constantData_)
259 return Filter(x.size(), true);
260 if (y.deterministic() && y.constantData_)
261 return Filter(y.size(), true);
262 if (!x.initialised() || !y.initialised())
263 return Filter();
264 if (!y.deterministic_)
265 x.expand();
266 if (x.deterministic_) {
268 } else {
269 resumeCalcStats();
270 for (Size i = 0; i < x.size(); ++i) {
271 x.data_[i] = x.data_[i] || y[i];
272 }
273 stopCalcStats(x.size());
274 }
275 return x;
276}

◆ equal()

Filter equal ( Filter  x,
const Filter y 
)

Definition at line 278 of file randomvariable.cpp.

278 {
279 if (!x.initialised() || !y.initialised())
280 return Filter();
281 QL_REQUIRE(x.size() == y.size(),
282 "RandomVariable: equal(x,y): x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
283 if (!y.deterministic_)
284 x.expand();
285 if (x.deterministic_) {
287 } else {
288 resumeCalcStats();
289 for (Size i = 0; i < x.size(); ++i) {
290 x.data_[i] = x.data_[i] == y[i];
291 }
292 stopCalcStats(x.size());
293 }
294 return x;
295}
+ Here is the caller graph for this function:

◆ operator!()

Filter operator! ( Filter  x)

Definition at line 297 of file randomvariable.cpp.

297 {
298 if (x.deterministic_)
300 else {
301 resumeCalcStats();
302 for (Size i = 0; i < x.size(); ++i) {
303 x.data_[i] = !x.data_[i];
304 }
305 stopCalcStats(x.size());
306 }
307 return x;
308}

◆ checkTimeConsistency()

void checkTimeConsistency ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 510 of file randomvariable.cpp.

510 {
511 QL_REQUIRE((x.time() == Null<Real>() || y.time() == Null<Real>()) || QuantLib::close_enough(x.time(), y.time()),
512 "got inconsistent random variable times (" << x.time() << ", " << y.time() << ")");
513}
+ Here is the call graph for this function:

◆ operator==() [3/3]

bool operator== ( const RandomVariable a,
const RandomVariable b 
)

Definition at line 515 of file randomvariable.cpp.

515 {
516 if (a.size() != b.size())
517 return false;
518 if (a.deterministic_ && b.deterministic_) {
519 return a.constantData_ == b.constantData_;
520 } else {
521 resumeCalcStats();
522 for (Size j = 0; j < a.size(); ++j)
523 if (a[j] != b[j]) {
524 stopCalcStats(j);
525 return false;
526 }
527 }
528 return QuantLib::close_enough(a.time(), b.time());
529}

◆ operator!=() [2/3]

bool operator!= ( const RandomVariable a,
const RandomVariable  b 
)

Definition at line 531 of file randomvariable.cpp.

531{ return !(a == b); }

◆ operator+() [3/3]

RandomVariable operator+ ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 629 of file randomvariable.cpp.

629 {
630 if (!x.initialised() || !y.initialised())
631 return RandomVariable();
632 x += y;
633 return x;
634}

◆ operator-() [2/3]

RandomVariable operator- ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 636 of file randomvariable.cpp.

636 {
637 if (!x.initialised() || !y.initialised())
638 return RandomVariable();
639 x -= y;
640 return x;
641}

◆ operator*() [5/5]

RandomVariable operator* ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 643 of file randomvariable.cpp.

643 {
644 if (!x.initialised() || !y.initialised())
645 return RandomVariable();
646 x *= y;
647 return x;
648}

◆ operator/() [2/2]

RandomVariable operator/ ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 650 of file randomvariable.cpp.

650 {
651 if (!x.initialised() || !y.initialised())
652 return RandomVariable();
653 x /= y;
654 return x;
655}

◆ max() [2/2]

RandomVariable max ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 657 of file randomvariable.cpp.

657 {
658 if (!x.initialised() || !y.initialised())
659 return RandomVariable();
660 QL_REQUIRE(x.size() == y.size(),
661 "RandomVariable: max(x,y): x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
663 if (!y.deterministic_)
664 x.expand();
665 if (x.deterministic())
666 x.constantData_ = std::max(x.constantData_, y.constantData_);
667 else {
668 resumeCalcStats();
669 for (Size i = 0; i < x.size(); ++i) {
670 x.data_[i] = std::max(x.data_[i], y[i]);
671 }
672 stopCalcStats(x.size());
673 }
674 return x;
675}
void checkTimeConsistencyAndUpdate(const Real t)

◆ min() [2/2]

RandomVariable min ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 677 of file randomvariable.cpp.

677 {
678 if (!x.initialised() || !y.initialised())
679 return RandomVariable();
680 QL_REQUIRE(x.size() == y.size(),
681 "RandomVariable: min(x,y): x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
683 if (!y.deterministic_)
684 x.expand();
685 if (x.deterministic())
686 x.constantData_ = std::min(x.constantData_, y.constantData_);
687 else {
688 resumeCalcStats();
689 for (Size i = 0; i < x.size(); ++i) {
690 x.data_[i] = std::min(x.data_[i], y[i]);
691 }
692 stopCalcStats(x.size());
693 }
694 return x;
695}

◆ pow() [2/2]

RandomVariable pow ( RandomVariable  x,
const RandomVariable y 
)

Definition at line 697 of file randomvariable.cpp.

697 {
698 if (!x.initialised() || !y.initialised())
699 return RandomVariable();
700 QL_REQUIRE(x.size() == y.size(),
701 "RandomVariable: pow(x,y): x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
703 if (!y.deterministic_)
704 x.expand();
705 else if (QuantLib::close_enough(y.constantData_, 1.0))
706 return x;
707 if (x.deterministic())
708 x.constantData_ = std::pow(x.constantData_, y.constantData_);
709 else {
710 resumeCalcStats();
711 for (Size i = 0; i < x.size(); ++i) {
712 x.data_[i] = std::pow(x.data_[i], y[i]);
713 }
714 stopCalcStats(x.size());
715 }
716 return x;
717}

◆ operator-() [3/3]

RandomVariable operator- ( RandomVariable  x)

Definition at line 719 of file randomvariable.cpp.

719 {
720 if (x.deterministic_)
722 else {
723 resumeCalcStats();
724 for (Size i = 0; i < x.n_; ++i) {
725 x.data_[i] = -x.data_[i];
726 }
727 stopCalcStats(x.n_);
728 }
729 return x;
730}

◆ abs() [2/2]

Definition at line 732 of file randomvariable.cpp.

732 {
733 if (x.deterministic_)
734 x.constantData_ = std::abs(x.constantData_);
735 else {
736 resumeCalcStats();
737 for (Size i = 0; i < x.n_; ++i) {
738 x.data_[i] = std::abs(x.data_[i]);
739 }
740 stopCalcStats(x.n_);
741 }
742 return x;
743}

◆ exp() [2/2]

Definition at line 745 of file randomvariable.cpp.

745 {
746 if (x.deterministic_)
747 x.constantData_ = std::exp(x.constantData_);
748 else {
749 resumeCalcStats();
750 for (Size i = 0; i < x.n_; ++i) {
751 x.data_[i] = std::exp(x.data_[i]);
752 }
753 stopCalcStats(x.n_);
754 }
755 return x;
756}

◆ log() [2/2]

Definition at line 758 of file randomvariable.cpp.

758 {
759 if (x.deterministic_)
760 x.constantData_ = std::log(x.constantData_);
761 else {
762 resumeCalcStats();
763 for (Size i = 0; i < x.n_; ++i) {
764 x.data_[i] = std::log(x.data_[i]);
765 }
766 stopCalcStats(x.n_);
767 }
768 return x;
769}

◆ sqrt()

Definition at line 771 of file randomvariable.cpp.

771 {
772 if (x.deterministic_)
773 x.constantData_ = std::sqrt(x.constantData_);
774 else {
775 resumeCalcStats();
776 for (Size i = 0; i < x.n_; ++i) {
777 x.data_[i] = std::sqrt(x.data_[i]);
778 }
779 stopCalcStats(x.n_);
780 }
781 return x;
782}
+ Here is the caller graph for this function:

◆ sin()

Definition at line 784 of file randomvariable.cpp.

784 {
785 if (x.deterministic_)
786 x.constantData_ = std::sin(x.constantData_);
787 else {
788 resumeCalcStats();
789 for (Size i = 0; i < x.n_; ++i) {
790 x.data_[i] = std::sin(x.data_[i]);
791 }
792 stopCalcStats(x.n_);
793 }
794 return x;
795}
+ Here is the caller graph for this function:

◆ cos()

Definition at line 797 of file randomvariable.cpp.

797 {
798 if (x.deterministic_)
799 x.constantData_ = std::cos(x.constantData_);
800 else {
801 resumeCalcStats();
802 for (Size i = 0; i < x.n_; ++i) {
803 x.data_[i] = std::cos(x.data_[i]);
804 }
805 stopCalcStats(x.n_);
806 }
807 return x;
808}

◆ normalCdf()

RandomVariable normalCdf ( RandomVariable  x)

Definition at line 810 of file randomvariable.cpp.

810 {
811 static const boost::math::normal_distribution<double> n;
812 if (x.deterministic_)
813 x.constantData_ = boost::math::cdf(n, x.constantData_);
814 else {
815 resumeCalcStats();
816 for (Size i = 0; i < x.n_; ++i) {
817 x.data_[i] = boost::math::cdf(n, x.data_[i]);
818 }
819 stopCalcStats(x.n_);
820 }
821 return x;
822}
+ Here is the caller graph for this function:

◆ normalPdf()

RandomVariable normalPdf ( RandomVariable  x)

Definition at line 824 of file randomvariable.cpp.

824 {
825 static const boost::math::normal_distribution<double> n;
826 if (x.deterministic_)
827 x.constantData_ = boost::math::pdf(n, x.constantData_);
828 else {
829 resumeCalcStats();
830 for (Size i = 0; i < x.n_; ++i) {
831 x.data_[i] = boost::math::pdf(n, x.data_[i]);
832 }
833 stopCalcStats(x.n_);
834 }
835 return x;
836}
+ Here is the caller graph for this function:

◆ close_enough()

Filter close_enough ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 838 of file randomvariable.cpp.

838 {
839 if (!x.initialised() || !y.initialised())
840 return Filter();
841 QL_REQUIRE(x.size() == y.size(), "RandomVariable: close_enough(x,y): x size ("
842 << x.size() << ") must be equal to y size (" << y.size() << ")");
844 if (x.deterministic_ && y.deterministic_) {
845 return Filter(x.size(), QuantLib::close_enough(x.constantData_, y.constantData_));
846 }
847 resumeCalcStats();
848 Filter result(x.size(), false);
849 for (Size i = 0; i < x.size(); ++i) {
850 result.set(i, QuantLib::close_enough(x[i], y[i]));
851 }
852 stopCalcStats(x.size());
853 return result;
854}
void checkTimeConsistency(const RandomVariable &x, const RandomVariable &y)
+ Here is the caller graph for this function:

◆ close_enough_all()

bool close_enough_all ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 856 of file randomvariable.cpp.

856 {
857 QL_REQUIRE(x.size() == y.size(), "RandomVariable: close_enough_all(x,y): x size ("
858 << x.size() << ") must be equal to y size (" << y.size() << ")");
860 if (x.deterministic_ && y.deterministic_) {
861 return QuantLib::close_enough(x.constantData_, y.constantData_);
862 }
863 resumeCalcStats();
864 for (Size i = 0; i < x.size(); ++i) {
865 if (!QuantLib::close_enough(x[i], y[i]))
866 return false;
867 }
868 stopCalcStats(x.size());
869 return true;
870}
+ Here is the caller graph for this function:

◆ conditionalResult()

RandomVariable conditionalResult ( const Filter f,
RandomVariable  x,
const RandomVariable y 
)

Definition at line 872 of file randomvariable.cpp.

872 {
873 if (!f.initialised() || !x.initialised() || !y.initialised())
874 return RandomVariable();
875 QL_REQUIRE(f.size() == x.size(),
876 "conditionalResult(f,x,y): f size (" << f.size() << ") must match x size (" << x.size() << ")");
877 QL_REQUIRE(f.size() == y.size(),
878 "conditionalResult(f,x,y): f size (" << f.size() << ") must match y size (" << y.size() << ")");
880 if (f.deterministic())
881 return f.at(0) ? x : y;
882 resumeCalcStats();
883 x.expand();
884 for (Size i = 0; i < f.size(); ++i) {
885 if (!f[i])
886 x.set(i, y[i]);
887 }
888 stopCalcStats(f.size());
889 return x;
890}
bool at(const Size i) const
void set(const Size i, const Real v)
+ Here is the caller graph for this function:

◆ indicatorEq()

RandomVariable indicatorEq ( RandomVariable  x,
const RandomVariable y,
const Real  trueVal,
const Real  falseVal 
)

Definition at line 892 of file randomvariable.cpp.

892 {
893 if (!x.initialised() || !y.initialised())
894 return RandomVariable();
895 QL_REQUIRE(x.size() == y.size(), "RandomVariable: indicatorEq(x,y): x size ("
896 << x.size() << ") must be equal to y size (" << y.size() << ")");
898 if (!y.deterministic_)
899 x.expand();
900 if (x.deterministic()) {
901 x.constantData_ = QuantLib::close_enough(x.constantData_, y.constantData_) ? trueVal : falseVal;
902 } else {
903 resumeCalcStats();
904 for (Size i = 0; i < x.n_; ++i) {
905 x.data_[i] = QuantLib::close_enough(x.data_[i], y[i]) ? trueVal : falseVal;
906 }
907 stopCalcStats(x.n_);
908 }
909 return x;
910}
+ Here is the caller graph for this function:

◆ indicatorGt()

RandomVariable indicatorGt ( RandomVariable  x,
const RandomVariable y,
const Real  trueVal,
const Real  falseVal,
const Real  eps 
)

Definition at line 912 of file randomvariable.cpp.

913 {
914 if (!x.initialised() || !y.initialised())
915 return RandomVariable();
916 QL_REQUIRE(x.size() == y.size(), "RandomVariable: indicatorEq(x,y): x size ("
917 << x.size() << ") must be equal to y size (" << y.size() << ")");
919 if (!y.deterministic_)
920 x.expand();
921 if (eps != 0.0) {
922 Real delta = getDelta(x - y, eps);
923 if (!QuantLib::close_enough(delta, 0.0)) {
924 // logistic function
925 x.expand();
926 Real delta = getDelta(x - y, eps);
927 resumeCalcStats();
928 for (Size i = 0; i < x.n_; ++i) {
929 x.data_[i] = falseVal + (trueVal - falseVal) * 1.0 / (1.0 + std::exp(-x.data_[i] / delta));
930 }
931 stopCalcStats(x.n_);
932 return x;
933 }
934 }
935 // eps == 0.0 or delta == 0.0
936 if (x.deterministic()) {
937 x.constantData_ =
938 (x.constantData_ > y.constantData_ && !QuantLib::close_enough(x.constantData_, y.constantData_)) ? trueVal
939 : falseVal;
940 } else {
941 resumeCalcStats();
942 for (Size i = 0; i < x.n_; ++i) {
943 x.data_[i] = (x.data_[i] > y[i] && !QuantLib::close_enough(x.data_[i], y[i])) ? trueVal : falseVal;
944 }
945 stopCalcStats(x.n_);
946 }
947 return x;
948}
+ Here is the caller graph for this function:

◆ indicatorGeq()

RandomVariable indicatorGeq ( RandomVariable  x,
const RandomVariable y,
const Real  trueVal,
const Real  falseVal,
const Real  eps 
)

Definition at line 950 of file randomvariable.cpp.

951 {
952 if (!x.initialised() || !y.initialised())
953 return RandomVariable();
954 QL_REQUIRE(x.size() == y.size(), "RandomVariable: indicatorEq(x,y): x size ("
955 << x.size() << ") must be equal to y size (" << y.size() << ")");
957 if (!y.deterministic_)
958 x.expand();
959 if (eps != 0.0) {
960 Real delta = getDelta(x - y, eps);
961 if (!QuantLib::close_enough(delta, 0.0)) {
962 // logistic function
963 x.expand();
964 Real delta = getDelta(x - y, eps);
965 resumeCalcStats();
966 for (Size i = 0; i < x.n_; ++i) {
967 x.data_[i] = falseVal + (trueVal - falseVal) * 1.0 / (1.0 + std::exp(-x.data_[i] / delta));
968 }
969 stopCalcStats(x.n_);
970 return x;
971 }
972 }
973 // eps == 0.0 or delta == 0.0
974 if (x.deterministic()) {
975 x.constantData_ =
976 (x.constantData_ > y.constantData_ || QuantLib::close_enough(x.constantData_, y.constantData_)) ? trueVal
977 : falseVal;
978 } else {
979 resumeCalcStats();
980 for (Size i = 0; i < x.n_; ++i) {
981 x.data_[i] = (x.data_[i] > y[i] || QuantLib::close_enough(x.data_[i], y[i])) ? trueVal : falseVal;
982 }
983 stopCalcStats(x.n_);
984 }
985 return x;
986}
+ Here is the caller graph for this function:

◆ operator<() [3/4]

Filter operator< ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 988 of file randomvariable.cpp.

988 {
989 if (!x.initialised() || !y.initialised())
990 return Filter();
991 QL_REQUIRE(x.size() == y.size(),
992 "RandomVariable: x < y: x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
994 if (x.deterministic_ && y.deterministic_) {
995 return Filter(x.size(),
996 x.constantData_ < y.constantData_ && !QuantLib::close_enough(x.constantData_, y.constantData_));
997 }
998 resumeCalcStats();
999 Filter result(x.size(), false);
1000 for (Size i = 0; i < x.size(); ++i) {
1001 result.set(i, x[i] < y[i] && !QuantLib::close_enough(x[i], y[i]));
1002 }
1003 stopCalcStats(x.size());
1004 return result;
1005}

◆ operator<=()

Filter operator<= ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 1007 of file randomvariable.cpp.

1007 {
1008 if (!x.initialised() || !y.initialised())
1009 return Filter();
1010 QL_REQUIRE(x.size() == y.size(),
1011 "RandomVariable: x <= y: x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
1013 if (x.deterministic_ && y.deterministic_) {
1014 return Filter(x.size(),
1015 x.constantData_ < y.constantData_ || QuantLib::close_enough(x.constantData_, y.constantData_));
1016 }
1017 resumeCalcStats();
1018 Filter result(x.size(), false);
1019 for (Size i = 0; i < x.size(); ++i) {
1020 result.set(i, x[i] < y[i] || QuantLib::close_enough(x[i], y[i]));
1021 }
1022 stopCalcStats(x.size());
1023 return result;
1024}

◆ operator>() [2/2]

Filter operator> ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 1026 of file randomvariable.cpp.

1026 {
1027 if (!x.initialised() || !y.initialised())
1028 return Filter();
1029 QL_REQUIRE(x.size() == y.size(),
1030 "RandomVariable: x > y: x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
1032 if (x.deterministic_ && y.deterministic_) {
1033 return Filter(x.size(),
1034 x.constantData_ > y.constantData_ && !QuantLib::close_enough(x.constantData_, y.constantData_));
1035 }
1036 Filter result(x.size(), false);
1037 for (Size i = 0; i < x.size(); ++i) {
1038 result.set(i, x[i] > y[i] && !QuantLib::close_enough(x[i], y[i]));
1039 }
1040 return result;
1041}

◆ operator>=()

Filter operator>= ( const RandomVariable x,
const RandomVariable y 
)

Definition at line 1043 of file randomvariable.cpp.

1043 {
1044 if (!x.initialised() || !y.initialised())
1045 return Filter();
1046 QL_REQUIRE(x.size() == y.size(),
1047 "RandomVariable: x >= y: x size (" << x.size() << ") must be equal to y size (" << y.size() << ")");
1049 if (x.deterministic_ && y.deterministic_) {
1050 return Filter(x.size(),
1051 x.constantData_ > y.constantData_ || QuantLib::close_enough(x.constantData_, y.constantData_));
1052 }
1053 resumeCalcStats();
1054 Filter result(x.size(), false);
1055 for (Size i = 0; i < x.size(); ++i) {
1056 result.set(i, x[i] > y[i] || QuantLib::close_enough(x[i], y[i]));
1057 }
1058 stopCalcStats(x.size());
1059 return result;
1060}

◆ applyFilter()

RandomVariable applyFilter ( RandomVariable  x,
const Filter f 
)

Definition at line 1062 of file randomvariable.cpp.

1062 {
1063 if (!x.initialised())
1064 return x;
1065 QL_REQUIRE(!f.initialised() || f.size() == x.size(), "RandomVariable: applyFitler(x,f): filter size ("
1066 << f.size() << ") must be equal to x size (" << x.size()
1067 << ")");
1068 if (!f.initialised())
1069 return x;
1070 if (f.deterministic()) {
1071 if (!f[0])
1072 return RandomVariable(x.size(), 0.0, x.time());
1073 else
1074 return x;
1075 }
1076 if (x.deterministic_ && QuantLib::close_enough(x.constantData_, 0.0))
1077 return x;
1078 resumeCalcStats();
1079 for (Size i = 0; i < x.size(); ++i) {
1080 if (!f[i])
1081 x.set(i, 0.0);
1082 }
1083 stopCalcStats(x.size());
1084 return x;
1085}
+ Here is the caller graph for this function:

◆ applyInverseFilter()

RandomVariable applyInverseFilter ( RandomVariable  x,
const Filter f 
)

Definition at line 1087 of file randomvariable.cpp.

1087 {
1088 if (!x.initialised())
1089 return x;
1090 QL_REQUIRE(!f.initialised() || f.size() == x.size(), "RandomVariable: applyFitler(x,f): filter size ("
1091 << f.size() << ") must be equal to x size (" << x.size()
1092 << ")");
1093 if (!f.initialised())
1094 return x;
1095 if (f.deterministic()) {
1096 if (f[0])
1097 return RandomVariable(x.size(), 0.0, x.time());
1098 else
1099 return x;
1100 }
1101 if (x.deterministic_ && QuantLib::close_enough(x.constantData_, 0.0))
1102 return x;
1103 resumeCalcStats();
1104 for (Size i = 0; i < x.size(); ++i) {
1105 if (f[i])
1106 x.set(i, 0.0);
1107 }
1108 stopCalcStats(x.size());
1109 return x;
1110}
+ Here is the caller graph for this function:

◆ pcaCoordinateTransform()

Matrix pcaCoordinateTransform ( const std::vector< const RandomVariable * > &  regressor,
const Real  varianceCutoff 
)

Definition at line 1112 of file randomvariable.cpp.

1112 {
1113 if (regressor.empty())
1114 return {};
1115
1116 Matrix cov(regressor.size(), regressor.size());
1117 for (Size i = 0; i < regressor.size(); ++i) {
1118 cov(i, i) = variance(*regressor[i]).at(0);
1119 for (Size j = 0; j < i; ++j) {
1120 cov(i, j) = cov(j, i) = covariance(*regressor[i], *regressor[j]).at(0);
1121 }
1122 }
1123
1124 QuantLib::SymmetricSchurDecomposition schur(cov);
1125 Real totalVariance = std::accumulate(schur.eigenvalues().begin(), schur.eigenvalues().end(), 0.0);
1126
1127 Size keep = 0;
1128 Real explainedVariance = 0.0;
1129 while (keep < schur.eigenvalues().size() && explainedVariance < totalVariance * (1.0 - varianceCutoff)) {
1130 explainedVariance += schur.eigenvalues()[keep++];
1131 }
1132
1133 Matrix result(keep, regressor.size());
1134 for (Size i = 0; i < keep; ++i) {
1135 std::copy(schur.eigenvectors().column_begin(i), schur.eigenvectors().column_end(i), result.row_begin(i));
1136 }
1137 return result;
1138}
Real at(const Size i) const
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ applyCoordinateTransform()

std::vector< RandomVariable > applyCoordinateTransform ( const std::vector< const RandomVariable * > &  regressor,
const Matrix &  transform 
)

Definition at line 1140 of file randomvariable.cpp.

1141 {
1142 QL_REQUIRE(transform.columns() == regressor.size(),
1143 "applyCoordinateTransform(): number of random variables ("
1144 << regressor.size() << ") does not match number of columns in transform (" << transform.columns());
1145 if (regressor.empty())
1146 return {};
1147 Size n = regressor.front()->size();
1148 std::vector<RandomVariable> result(transform.rows(), RandomVariable(n, 0.0));
1149 for (Size i = 0; i < transform.rows(); ++i) {
1150 for (Size j = 0; j < transform.columns(); ++j) {
1151 result[i] += RandomVariable(n, transform(i, j)) * (*regressor[j]);
1152 }
1153 }
1154 return result;
1155}
+ Here is the caller graph for this function:

◆ vec2vecptr()

std::vector< const RandomVariable * > vec2vecptr ( const std::vector< RandomVariable > &  values)

Definition at line 1157 of file randomvariable.cpp.

1157 {
1158 std::vector<const RandomVariable*> result(values.size());
1159 std::transform(values.begin(), values.end(), result.begin(), [](const RandomVariable& v) { return &v; });
1160 return result;
1161}
+ Here is the caller graph for this function:

◆ regressionCoefficients()

Array regressionCoefficients ( RandomVariable  r,
std::vector< const RandomVariable * >  regressor,
const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)>  ,
basisFn,
const Filter filter,
const RandomVariableRegressionMethod  regressionMethod,
const std::string &  debugLabel 
)

Definition at line 1163 of file randomvariable.cpp.

1166 {
1167
1168 for (auto const reg : regressor) {
1169 QL_REQUIRE(reg->size() == r.size(),
1170 "regressor size (" << reg->size() << ") must match regressand size (" << r.size() << ")");
1171 }
1172
1173 QL_REQUIRE(filter.size() == 0 || filter.size() == r.size(),
1174 "filter size (" << filter.size() << ") must match regressand size (" << r.size() << ")");
1175
1176 QL_REQUIRE(r.size() >= basisFn.size(), "regressionCoefficients(): sample size ("
1177 << r.size() << ") must be geq basis fns size (" << basisFn.size()
1178 << ")");
1179
1180 resumeCalcStats();
1181
1182 Matrix A(r.size(), basisFn.size());
1183 for (Size j = 0; j < basisFn.size(); ++j) {
1184 RandomVariable a = basisFn[j](regressor);
1185 if (filter.initialised()) {
1186 a = applyFilter(a, filter);
1187 }
1188 if (a.deterministic())
1189 std::fill(A.column_begin(j), A.column_end(j), a[0]);
1190 else
1191 a.copyToMatrixCol(A, j);
1192 }
1193
1194 if (!debugLabel.empty()) {
1195 for (Size i = 0; i < r.size(); ++i) {
1196 std::cout << debugLabel << "," << r[i] << ",";
1197 for (Size j = 0; j < regressor.size(); ++j) {
1198 std::cout << regressor[j]->operator[](i) << (j == regressor.size() - 1 ? "\n" : ",");
1199 }
1200 }
1201 std::cout << std::flush;
1202 }
1203
1204 if (filter.size() > 0) {
1205 r = applyFilter(r, filter);
1206 }
1207
1208 Array b(r.size());
1209 if (r.deterministic())
1210 std::fill(b.begin(), b.end(), r[0]);
1211 else
1212 r.copyToArray(b);
1213
1214 Array res;
1215 if (regressionMethod == RandomVariableRegressionMethod::SVD) {
1216 SVD svd(A);
1217 const Matrix& V = svd.V();
1218 const Matrix& U = svd.U();
1219 const Array& w = svd.singularValues();
1220 Real threshold = r.size() * QL_EPSILON * svd.singularValues()[0];
1221 res = Array(basisFn.size(), 0.0);
1222 for (Size i = 0; i < basisFn.size(); ++i) {
1223 if (w[i] > threshold) {
1224 Real u = std::inner_product(U.column_begin(i), U.column_end(i), b.begin(), Real(0.0)) / w[i];
1225 for (Size j = 0; j < basisFn.size(); ++j) {
1226 res[j] += u * V[j][i];
1227 }
1228 }
1229 }
1230 } else if (regressionMethod == RandomVariableRegressionMethod::QR) {
1231 res = qrSolve(A, b);
1232 } else {
1233 QL_FAIL("regressionCoefficients(): unknown regression method, expected SVD or QR");
1234 }
1235
1236 // rough estimate, SVD is O(mn min(m,n))
1237 stopCalcStats(r.size() * basisFn.size() * std::min(r.size(), basisFn.size()));
1238 return res;
1239}
RandomVariable applyFilter(RandomVariable x, const Filter &f)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ conditionalExpectation() [1/2]

RandomVariable conditionalExpectation ( const std::vector< const RandomVariable * > &  regressor,
const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)>  ,
basisFn,
const Array &  coefficients 
)

Definition at line 1241 of file randomvariable.cpp.

1244 {
1245 QL_REQUIRE(!regressor.empty(), "regressor vector is empty");
1246 Size n = regressor.front()->size();
1247 for (Size i = 1; i < regressor.size(); ++i) {
1248 QL_REQUIRE(regressor[i] != nullptr, "regressor #" << i << " is null.");
1249 QL_REQUIRE(n == regressor[i]->size(), "regressor #" << i << " size (" << regressor[i]->size()
1250 << ") must match regressor #0 size (" << n << ")");
1251 }
1252 QL_REQUIRE(basisFn.size() == coefficients.size(),
1253 "basisFn size (" << basisFn.size() << ") must match coefficients size (" << coefficients.size() << ")");
1254 RandomVariable r(n, 0.0);
1255 for (Size i = 0; i < coefficients.size(); ++i) {
1256 r = r + RandomVariable(n, coefficients[i]) * basisFn[i](regressor);
1257 }
1258 return r;
1259}
+ Here is the caller graph for this function:

◆ conditionalExpectation() [2/2]

RandomVariable conditionalExpectation ( const RandomVariable r,
const std::vector< const RandomVariable * > &  regressor,
const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)>  ,
basisFn,
const Filter filter,
const RandomVariableRegressionMethod  regressionMethod 
)

Definition at line 1261 of file randomvariable.cpp.

1264 {
1265 if (r.deterministic())
1266 return r;
1267 auto coeff = regressionCoefficients(r, regressor, basisFn, filter, regressionMethod);
1268 return conditionalExpectation(regressor, basisFn, coeff);
1269}
Array regressionCoefficients(RandomVariable r, std::vector< const RandomVariable * > regressor, const std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > &basisFn, const Filter &filter, const RandomVariableRegressionMethod regressionMethod, const std::string &debugLabel)
+ Here is the call graph for this function:

◆ expectation()

RandomVariable expectation ( const RandomVariable r)

Definition at line 1271 of file randomvariable.cpp.

1271 {
1272 if (r.deterministic())
1273 return r;
1274 resumeCalcStats();
1275 boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::mean>> acc;
1276 for (Size i = 0; i < r.size(); ++i)
1277 acc(r[i]);
1278 return RandomVariable(r.size(), boost::accumulators::mean(acc));
1279}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ variance()

RandomVariable variance ( const RandomVariable r)

Definition at line 1281 of file randomvariable.cpp.

1281 {
1282 if (r.deterministic())
1283 return RandomVariable(r.size(), 0.0);
1284 resumeCalcStats();
1285 boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::variance>> acc;
1286 for (Size i = 0; i < r.size(); ++i) {
1287 acc(r[i]);
1288 }
1289 stopCalcStats(r.size());
1290 return RandomVariable(r.size(), boost::accumulators::variance(acc));
1291}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ covariance()

RandomVariable covariance ( const RandomVariable r,
const RandomVariable s 
)

Definition at line 1293 of file randomvariable.cpp.

1293 {
1294 QL_REQUIRE(r.size() == s.size(), "covariance(RandomVariable r, RandomVariable s): inconsistent sizes r ("
1295 << r.size() << "), s(" << s.size() << ")");
1296 if (r.deterministic() || s.deterministic())
1297 return RandomVariable(r.size(), 0.0);
1298 resumeCalcStats();
1299 boost::accumulators::accumulator_set<
1300 double,
1301 boost::accumulators::stats<boost::accumulators::tag::covariance<double, boost::accumulators::tag::covariate1>>>
1302 acc;
1303 for (Size i = 0; i < r.size(); ++i) {
1304 acc(r[i], boost::accumulators::covariate1 = s[i]);
1305 }
1306 stopCalcStats(r.size());
1307 return RandomVariable(r.size(), boost::accumulators::covariance(acc));
1308}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ black()

RandomVariable black ( const RandomVariable omega,
const RandomVariable t,
const RandomVariable strike,
const RandomVariable forward,
const RandomVariable impliedVol 
)

Definition at line 1310 of file randomvariable.cpp.

1311 {
1312 Filter zeroStrike = close_enough(strike, RandomVariable(omega.size(), 0.0));
1313 Filter call = omega > RandomVariable(omega.size(), 0.0);
1314 RandomVariable stdDev = impliedVol * sqrt(t);
1315 RandomVariable d1 = log(forward / strike) / stdDev + RandomVariable(omega.size(), 0.5) * stdDev;
1316 RandomVariable d2 = d1 - stdDev;
1317 return applyFilter(forward, zeroStrike && call) +
1318 applyInverseFilter(omega * (forward * normalCdf(omega * d1) - strike * normalCdf(omega * d2)), zeroStrike);
1319}
RandomVariable sqrt(RandomVariable x)
RandomVariable normalCdf(RandomVariable x)
RandomVariable applyInverseFilter(RandomVariable x, const Filter &f)
CompiledFormula log(CompiledFormula x)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ indicatorDerivative()

RandomVariable indicatorDerivative ( const RandomVariable x,
const double  eps 
)

Definition at line 1321 of file randomvariable.cpp.

1321 {
1322 RandomVariable tmp(x.size(), 0.0);
1323
1324 // We follow section 4, eq 10 in
1325 // Fries, 2017: Automatic Backward Differentiation for American Monte-Carlo Algorithms -
1326 // ADD for Conditional Expectations and Indicator Functions
1327
1328 resumeCalcStats();
1329
1330 Real delta = getDelta(x, eps);
1331
1332 if (QuantLib::close_enough(delta, 0.0))
1333 return tmp;
1334
1335 // compute derivative
1336
1337 for (Size i = 0; i < tmp.size(); ++i) {
1338
1339 // linear approximation of step
1340 // Real ax = std::abs(x[i]);
1341 // if (ax < delta) {
1342 // tmp.set(i, 1.0 / (2.0 * delta));
1343 // }
1344
1345 // logistic function
1346 // f(x) = 1 / (1 + exp(-x / delta))
1347 // f'(x) = exp(-x/delta) / (delta * (1 + exp(-x / delta))^2), this is an even function
1348 tmp.set(i, std::exp(-1.0 / delta * x[i]) / (delta * std::pow(1.0 + std::exp(-1.0 / delta * x[i]), 2.0)));
1349 }
1350
1351 stopCalcStats(x.size() * 8);
1352
1353 return tmp;
1354}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ multiPathBasisSystem()

std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > multiPathBasisSystem ( Size  dim,
Size  order,
QuantLib::LsmBasisSystem::PolynomialType  type,
Size  basisSystemSizeBound = Null< Size >() 
)

helper function that returns a LSM basis system with size restriction: the order is reduced until the size of the basis system is not greater than the given bound (if this is not null) or the order is 1

Definition at line 1360 of file randomvariable.cpp.

1360 {
1361 thread_local static std::map<std::pair<Size, Size>,
1362 std::vector<std::function<RandomVariable(const std::vector<const RandomVariable*>&)>>>
1363 cache;
1364 QL_REQUIRE(order > 0, "multiPathBasisSystem: order must be > 0");
1365 if (basisSystemSizeBound != Null<Size>()) {
1366 while (RandomVariableLsmBasisSystem::size(dim, order) > static_cast<Real>(basisSystemSizeBound) && order > 1) {
1367 --order;
1368 }
1369 }
1370 if (auto c = cache.find(std::make_pair(dim, order)); c != cache.end())
1371 return c->second;
1372 auto tmp = RandomVariableLsmBasisSystem::multiPathBasisSystem(dim, order, type);
1373 cache[std::make_pair(dim, order)] = tmp;
1374 return tmp;
1375}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ operator!=() [3/3]

bool operator!= ( const RandomVariable a,
const RandomVariable b 
)
+ Here is the call graph for this function:

◆ isDeterministicAndZero() [2/2]

bool isDeterministicAndZero ( const RandomVariable x)

Definition at line 340 of file randomvariable.hpp.

340 {
341 return x.deterministic() && QuantLib::close_enough(x[0], 0.0);
342}
+ Here is the call graph for this function:

◆ operator<<() [5/16]

std::ostream & operator<< ( std::ostream &  out,
const randomvariable_output_size r 
)

Definition at line 38 of file randomvariable_io.cpp.

38 {
39 out.iword(get_index_randomvariable_output_size()) = static_cast<long>(r.n());
40 return out;
41}
+ Here is the call graph for this function:

◆ operator<<() [6/16]

std::ostream & operator<< ( std::ostream &  out,
const randomvariable_output_pattern p 
)

Definition at line 43 of file randomvariable_io.cpp.

43 {
44 out.iword(get_index_randomvariable_output_pattern()) = static_cast<long>(p.getPattern());
45 return out;
46}
+ Here is the call graph for this function:

◆ operator<<() [7/16]

std::ostream & operator<< ( std::ostream &  out,
const Filter f 
)

Definition at line 108 of file randomvariable_io.cpp.

108{ return output(out, f); }

◆ operator<<() [8/16]

std::ostream & operator<< ( std::ostream &  out,
const RandomVariable r 
)

Definition at line 110 of file randomvariable_io.cpp.

110 {
111 output(out, r);
112 if (r.time() != Null<Real>())
113 out << " t=" << r.time();
114 return out;
115}
+ Here is the call graph for this function:

◆ getRandomVariableOpLabels()

std::vector< std::string > getRandomVariableOpLabels ( )

Definition at line 50 of file randomvariable_opcodes.hpp.

50 {
51 static std::vector<std::string> tmp = {
52 "None", "Add", "Subtract", "Negative", "Mult", "Div", "ConditionalExpectation",
53 "IndicatorEq", "IndicatorGt", "IndicatorGeq", "Min", "Max", "Abs", "Exp",
54 "Sqrt", "Log", "Pow", "NormalCdf", "NormalPdf"};
55
56 return tmp;
57}
+ Here is the caller graph for this function:

◆ getRandomVariableOps()

std::vector< RandomVariableOp > getRandomVariableOps ( const Size  size,
const Size  regressionOrder,
QuantLib::LsmBasisSystem::PolynomialType  polynomType,
const double  eps,
QuantLib::Real  regressionVarianceCutoff 
)

Definition at line 27 of file randomvariable_ops.cpp.

29 {
30 std::vector<RandomVariableOp> ops;
31
32 // None = 0
33 ops.push_back([](const std::vector<const RandomVariable*>& args) { return RandomVariable(); });
34
35 // Add = 1
36 ops.push_back([](const std::vector<const RandomVariable*>& args) { return *args[0] + (*args[1]); });
37
38 // Subtract = 2
39 ops.push_back([](const std::vector<const RandomVariable*>& args) { return *args[0] - (*args[1]); });
40
41 // Negative = 3
42 ops.push_back([](const std::vector<const RandomVariable*>& args) { return -(*args[0]); });
43
44 // Mult = 4
45 ops.push_back([](const std::vector<const RandomVariable*>& args) { return *args[0] * (*args[1]); });
46
47 // Div = 5
48 ops.push_back([](const std::vector<const RandomVariable*>& args) { return *args[0] / (*args[1]); });
49
50 // ConditionalExpectation = 6
51 ops.push_back([size, regressionOrder, polynomType,
52 regressionVarianceCutoff](const std::vector<const RandomVariable*>& args) {
53 std::vector<const RandomVariable*> regressor;
54 for (auto r = std::next(args.begin(), 2); r != args.end(); ++r) {
55 if ((*r)->initialised() && !(*r)->deterministic())
56 regressor.push_back(*r);
57 }
58 std::vector<RandomVariable> transformedRegressor;
59 Matrix coordinateTransform;
60 if (regressionVarianceCutoff != Null<Real>()) {
61 coordinateTransform = pcaCoordinateTransform(regressor, regressionVarianceCutoff);
62 transformedRegressor = applyCoordinateTransform(regressor, coordinateTransform);
63 regressor = vec2vecptr(transformedRegressor);
64 }
65 if (regressor.empty())
66 return expectation(*args[0]);
67 else {
68 auto tmp = multiPathBasisSystem(regressor.size(), regressionOrder, polynomType, size);
69 return conditionalExpectation(*args[0], regressor, tmp, !close_enough(*args[1], RandomVariable(size, 0.0)));
70 }
71 });
72
73 // IndicatorEq = 7
74 ops.push_back([](const std::vector<const RandomVariable*>& args) { return indicatorEq(*args[0], *args[1]); });
75
76 // IndicatorGt = 8
77 ops.push_back([eps](const std::vector<const RandomVariable*>& args) {
78 return indicatorGt(*args[0], *args[1], 1.0, 0.0, eps);
79 });
80
81 // IndicatorGeq = 9
82 ops.push_back([eps](const std::vector<const RandomVariable*>& args) {
83 return indicatorGeq(*args[0], *args[1], 1.0, 0.0, eps);
84 });
85
86 // Min = 10
87 if (eps == 0.0) {
88 ops.push_back(
89 [](const std::vector<const RandomVariable*>& args) { return QuantExt::min(*args[0], *args[1]); });
90 } else {
91 ops.push_back([eps](const std::vector<const RandomVariable*>& args) {
92 return indicatorGt(*args[0], *args[1], 1.0, 0.0, eps) * (*args[1] - *args[0]) + *args[0];
93 });
94 }
95
96 // Max = 11
97 if (eps == 0.0) {
98 ops.push_back(
99 [](const std::vector<const RandomVariable*>& args) { return QuantExt::max(*args[0], *args[1]); });
100 } else {
101 ops.push_back([eps](const std::vector<const RandomVariable*>& args) {
102 return indicatorGt(*args[0], *args[1], 1.0, 0.0, eps) * (*args[0] - *args[1]) + *args[1];
103 });
104 }
105
106 // Abs = 12
107 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::abs(*args[0]); });
108
109 // Exp = 13
110 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::exp(*args[0]); });
111
112 // Sqrt = 14
113 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::sqrt(*args[0]); });
114
115 // Log = 15
116 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::log(*args[0]); });
117
118 // Pow = 16
119 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::pow(*args[0], *args[1]); });
120
121 // NormalCdf = 17
122 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::normalCdf(*args[0]); });
123
124 // NormalPdf = 18
125 ops.push_back([](const std::vector<const RandomVariable*>& args) { return QuantExt::normalPdf(*args[0]); });
126
127 return ops;
128}
std::vector< std::function< RandomVariable(const std::vector< const RandomVariable * > &)> > multiPathBasisSystem(Size dim, Size order, QuantLib::LsmBasisSystem::PolynomialType type, Size basisSystemSizeBound)
CompiledFormula min(CompiledFormula x, const CompiledFormula &y)
CompiledFormula pow(CompiledFormula x, const CompiledFormula &y)
std::vector< const RandomVariable * > vec2vecptr(const std::vector< RandomVariable > &values)
RandomVariable expectation(const RandomVariable &r)
RandomVariable indicatorGeq(RandomVariable x, const RandomVariable &y, const Real trueVal, const Real falseVal, const Real eps)
CompiledFormula max(CompiledFormula x, const CompiledFormula &y)
CompiledFormula abs(CompiledFormula x)
RandomVariable indicatorEq(RandomVariable x, const RandomVariable &y, const Real trueVal, const Real falseVal)
RandomVariable normalPdf(RandomVariable x)
Matrix pcaCoordinateTransform(const std::vector< const RandomVariable * > &regressor, const Real varianceCutoff)
RandomVariable indicatorGt(RandomVariable x, const RandomVariable &y, const Real trueVal, const Real falseVal, const Real eps)
std::vector< RandomVariable > applyCoordinateTransform(const std::vector< const RandomVariable * > &regressor, const Matrix &transform)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getRandomVariableGradients() [1/2]

std::vector< RandomVariableGrad > getRandomVariableGradients ( const Size  size,
const Size  regressionOrder,
const QuantLib::LsmBasisSystem::PolynomialType  polynomType,
const double  eps,
const Real  regressionVarianceCutoff 
)

Definition at line 130 of file randomvariable_ops.cpp.

132 {
133
134 std::vector<RandomVariableGrad> grads;
135
136 // None = 0
137 grads.push_back([](const std::vector<const RandomVariable*>& args,
138 const RandomVariable* v) -> std::vector<RandomVariable> { return {RandomVariable()}; });
139
140 // Add = 1
141 grads.push_back(
142 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
143 return {RandomVariable(size, 1.0), RandomVariable(size, 1.0)};
144 });
145
146 // Subtract = 2
147 grads.push_back(
148 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
149 return {RandomVariable(size, 1.0), RandomVariable(size, -1.0)};
150 });
151
152 // Negative = 3
153 grads.push_back(
154 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
155 return {RandomVariable(size, -1.0)};
156 });
157
158 // Mult = 4
159 grads.push_back(
160 [](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
161 return {*args[1], *args[0]};
162 });
163
164 // Div = 5
165 grads.push_back(
166 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
167 return {RandomVariable(size, 1.0) / *args[1], -*args[0] / (*args[1] * *args[1])};
168 });
169
170 // ConditionalExpectation = 6
171 grads.push_back(
172 [](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
173 QL_FAIL("gradient of conditional expectation not implemented");
174 });
175
176 // IndicatorEq = 7
177 grads.push_back(
178 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
179 return {RandomVariable(size, 0.0), RandomVariable(size, 0.0)};
180 });
181
182 // IndicatorGt = 8
183 grads.push_back(
184 [eps](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
185 RandomVariable tmp = indicatorDerivative(*args[0] - *args[1], eps);
186 return {tmp, -tmp};
187 });
188
189 // IndicatorGeq = 9
190 grads.push_back(grads.back());
191
192 // Min = 10
193 grads.push_back([eps](const std::vector<const RandomVariable*>& args,
194 const RandomVariable* v) -> std::vector<RandomVariable> {
195 return {
196 indicatorDerivative(*args[1] - *args[0], eps) * (*args[1] - *args[0]) + indicatorGeq(*args[1], *args[0]),
197 indicatorDerivative(*args[0] - *args[1], eps) * (*args[0] - *args[1]) + indicatorGeq(*args[0], *args[1])};
198 });
199
200 // Max = 11
201 grads.push_back([eps](const std::vector<const RandomVariable*>& args,
202 const RandomVariable* v) -> std::vector<RandomVariable> {
203 return {
204 indicatorDerivative(*args[0] - *args[1], eps) * (*args[0] - *args[1]) + indicatorGeq(*args[0], *args[1]),
205 indicatorDerivative(*args[1] - *args[0], eps) * (*args[1] - *args[0]) + indicatorGeq(*args[1], *args[0])};
206 });
207
208 // Abs = 12
209 grads.push_back(
210 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
211 return {indicatorGeq(*args[0], RandomVariable(size, 0.0), 1.0, -1.0)};
212 });
213
214 // Exp = 13
215 grads.push_back([](const std::vector<const RandomVariable*>& args,
216 const RandomVariable* v) -> std::vector<RandomVariable> { return {*v}; });
217
218 // Sqrt = 14
219 grads.push_back(
220 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
221 return {RandomVariable(size, 0.5) / *v};
222 });
223
224 // Log = 15
225 grads.push_back(
226 [size](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
227 return {RandomVariable(size, 1.0) / *args[0]};
228 });
229
230 // Pow = 16
231 grads.push_back(
232 [](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
233 return {*args[1] / *args[0] * (*v), QuantExt::log(*args[0]) * (*v)};
234 });
235
236 // NormalCdf = 17
237 grads.push_back(
238 [](const std::vector<const RandomVariable*>& args, const RandomVariable* v) -> std::vector<RandomVariable> {
239 return {QuantExt::normalPdf(*args[0])};
240 });
241
242 // NormalPdf = 18
243 grads.push_back([](const std::vector<const RandomVariable*>& args,
244 const RandomVariable* v) -> std::vector<RandomVariable> { return {-(*args[0]) * *v}; });
245
246 return grads;
247}
RandomVariable indicatorDerivative(const RandomVariable &x, const double eps)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getRandomVariableOpNodeRequirements()

std::vector< RandomVariableOpNodeRequirements > getRandomVariableOpNodeRequirements ( )

Definition at line 249 of file randomvariable_ops.cpp.

249 {
250 std::vector<RandomVariableOpNodeRequirements> res;
251
252 // None = 0
253 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), false); });
254
255 // Add = 1
256 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), false); });
257
258 // Subtract = 1
259 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), false); });
260
261 // Negative = 3
262 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), false); });
263
264 // Mult = 4
265 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
266
267 // Div = 5
268 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
269
270 // ConditionalExpectation = 6
271 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), true); });
272
273 // IndicatorEq = 7
274 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), false); });
275
276 // IndicatorGt = 8
277 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
278
279 // IndicatorGeq = 9
280 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
281
282 // Min = 10
283 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
284
285 // Max = 11
286 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
287
288 // Abs = 12
289 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
290
291 // Exp = 13
292 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), true); });
293
294 // Sqrt = 14
295 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, false), true); });
296
297 // Log = 15
298 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
299
300 // Pow = 16
301 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), true); });
302
303 // NormalCdf = 17
304 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), false); });
305
306 // NormalCdf = 18
307 res.push_back([](const std::size_t nArgs) { return std::make_pair(std::vector<bool>(nArgs, true), true); });
308
309 return res;
310}
+ Here is the caller graph for this function:

◆ getRandomVariableGradients() [2/2]

std::vector< RandomVariableGrad > getRandomVariableGradients ( const Size  size,
const Size  regressionOrder = 2,
const QuantLib::LsmBasisSystem::PolynomialType  polynomType = QuantLib::LsmBasisSystem::Monomial,
const double  eps = 0.2,
QuantLib::Real  regressionVarianceCutoff = Null< Real >() 
)

◆ stopLightBoundsTabulated()

std::vector< Size > stopLightBoundsTabulated ( const std::vector< Real > &  stopLightP,
const Size  observations,
const Size  numberOfDays,
const Real  p 
)

Definition at line 153 of file stoplightbounds.cpp.

154 {
155
156 if (stopLightP.size() == 2 && QuantLib::close_enough(stopLightP[0], 0.95) &&
157 QuantLib::close_enough(stopLightP[1], 0.9999) && numberOfDays == 10 && observations >= 1 &&
158 observations <= (tab1_obs.back() + 9) && QuantLib::close_enough(p, 0.99)) {
159 Size idx = std::upper_bound(tab1_obs.begin(), tab1_obs.end(), observations) - tab1_obs.begin();
160 QL_REQUIRE(idx > 0 && idx <= tab1_green.size() && idx <= tab1_amber.size(),
161 "stopLightBoundsTabulated: unexpected index 0");
162 return {tab1_green[idx - 1], tab1_amber[idx - 1]};
163 } else {
164 QL_FAIL(
165 "stopLightBoundsTabulated: no tabulated values found for sl-p = "
166 << boost::join(stopLightP | boost::adaptors::transformed([](double x) { return std::to_string(x); }), ",")
167 << ", obs = " << observations << ", numberOfDays = " << numberOfDays << ", p = " << p);
168 }
169}
+ Here is the caller graph for this function:

◆ stopLightBounds() [1/2]

std::vector< Size > stopLightBounds ( const std::vector< Real > &  stopLightP,
const Size  observations,
const Size  numberOfDays = 10,
const Real  p = 0.99,
const Size  numberOfPortfolios = 1,
const Matrix &  correlation = Matrix(1, 1, 1.0),
const Size  samples = 1500000,
const Size  seed = 42,
const SalvagingAlgorithm::Type  salvaging = SalvagingAlgorithm::Spectral,
const Size  exceptions = Null< Size >(),
Real *  cumProb = nullptr 
)

Computes the maximum number of exceptions n such that the probability of having less or equal to n exceptions is less than p for a given vector of stop light levels (0.95 = green, 0.9999 = red in the Basel approach). An overlapping PL over a given period is considered, possibly also several portfolios with correlated PL. If the parameter exceptions m is not null, cumProb is set to the probability of having less of equal to m exceptions (this is not affecting the return value).

Definition at line 171 of file stoplightbounds.cpp.

174 {
175 checkMatrix(correlation);
176 Size r = correlation.rows();
177
178 QL_REQUIRE(stopLightP.size() > 0, "stopLightBounds: stopLightP is empty");
179 QL_REQUIRE(numberOfDays > 0, "stopLightBounds: numberOfDays must be greater than zero");
180 QL_REQUIRE(numberOfPortfolios > 0, "stopLightBounds: numberOfPortfolios must be greater than zero");
181 QL_REQUIRE(numberOfPortfolios == r, "stopLightBounds: numberOfPortfolios ("
182 << numberOfPortfolios << ") must match correlation matrix dimension (" << r
183 << "x" << r);
184 QL_REQUIRE(samples > 0, "stopLightBounds: samples must be greater than zero");
185 QL_REQUIRE(p > 0.0, "stopLightBounds: p must be greater than zero");
186 if (exceptions != Null<Size>()) {
187 QL_REQUIRE(cumProb != nullptr, "stopLightBounds: cumProb is a null pointer");
188 *cumProb = 0.0;
189 }
190
191 Matrix pseudoRoot = pseudoSqrt(correlation, salvaging);
192 Size len = observations + (numberOfDays - 1);
193 auto sgen = PseudoRandom::make_sequence_generator(len * r, seed);
194 // auto sgen = LowDiscrepancy::make_sequence_generator(len * r, seed);
195 Real h = InverseCumulativeNormal()(p) * std::sqrt(static_cast<Real>(numberOfDays));
196 Real minP = *std::min_element(stopLightP.begin(), stopLightP.end());
197 Size cache = Size(std::floor(static_cast<Real>(samples) * (1.0 - minP) + 0.5)) + 2;
198 accumulator_set<Real, stats<tag::tail_quantile<right>>> acc(tag::tail<right>::cache_size = cache);
199 for (Size i = 0; i < samples; ++i) {
200 auto seq = sgen.nextSequence().value;
201 Size exCount = 0;
202 for (Size rr = 0; rr < r; ++rr) {
203 Array oneDayPls(len, 0.0);
204 for (Size l = 0; l < len; ++l) {
205 for (Size kk = 0; kk < r; ++kk) {
206 oneDayPls[l] += pseudoRoot[rr][kk] * seq[len * kk + l];
207 }
208 }
209 // compute the 10d PL only once ...
210 Real pl = 0.0;
211 for (Size dd = 0; dd < numberOfDays; ++dd) {
212 pl += oneDayPls[dd];
213 }
214 if (pl > h)
215 ++exCount;
216 for (Size l = 0; l < observations - 1; ++l) {
217 // and only correct for the tail and head
218 pl += oneDayPls[l + numberOfDays] - oneDayPls[l];
219 if (pl > h)
220 ++exCount;
221 }
222 } // for rr
223 acc(static_cast<Real>(exCount));
224 if (exceptions != Null<Size>() && exCount <= exceptions) {
225 *cumProb += 1.0 / static_cast<Real>(samples);
226 }
227 } // for samples
228 std::vector<Size> res;
229 for (auto const p : stopLightP) {
230 Size tmp = static_cast<Size>(quantile(acc, quantile_probability = p));
231 res.push_back(tmp > 0 ? tmp - 1 : 0);
232 }
233 return res;
234} // stopLightBounds (overlapping, correlated)
+ Here is the caller graph for this function:

◆ stopLightBounds() [2/2]

std::vector< Size > stopLightBounds ( const std::vector< Real > &  stopLightP,
const Size  observations,
const Real  p,
const Size  exceptions,
Real *  cumProb 
)

Definition at line 236 of file stoplightbounds.cpp.

237 {
238
239 QL_REQUIRE(stopLightP.size() > 0, "stopLightBounds: stopLightP is empty");
240 QL_REQUIRE(p > 0.0, "stopLightBounds: p must be greater than zero");
241 if (exceptions != Null<Size>()) {
242 QL_REQUIRE(cumProb != nullptr, "stopLightBounds: cumProb is a null pointer");
243 *cumProb = 0.0;
244 }
245 boost::math::binomial_distribution<Real> b((Real)observations, (Real)(1.0) - p);
246 std::vector<Size> res;
247 for (auto const p : stopLightP) {
248 res.push_back(std::max(static_cast<Size>(boost::math::quantile(b, p)), (Size)(1)) - 1);
249 }
250 if (exceptions != Null<Size>()) {
251 *cumProb = boost::math::cdf(b, exceptions);
252 }
253 return res;
254} // stopLightBounds (iid)

◆ generateStopLightBoundTable()

std::vector< std::pair< Size, std::vector< Size > > > generateStopLightBoundTable ( const std::vector< Size > &  observations,
const std::vector< Real > &  stopLightP,
const Size  samples,
const Size  seed,
const Size  numberOfDays,
const Real  p 
)

Definition at line 256 of file stoplightbounds.cpp.

259 {
260
261 QL_REQUIRE(!observations.empty(), "generateStopLightBoundTable(): no observations given");
262 QL_REQUIRE(!stopLightP.empty(), "generateStopLightBoundTable(): stopLightP is empty");
263 QL_REQUIRE(numberOfDays > 0, "generateStopLightBoundTable(): numberOfDays must be greater than zero");
264 QL_REQUIRE(samples > 0, "generateStopLightBoundTable(): samples must be greater than zero");
265 QL_REQUIRE(p > 0.0, "generateStopLightBoundTable():: p must be greater than zero");
266
267 for (Size i = 0; i < observations.size() - 1; ++i) {
268 QL_REQUIRE(observations[i] > 0, "generateStopLightBoundTable(): observations must be positive, got 0 at " << i);
269 QL_REQUIRE(observations[i] < observations[i + 1],
270 "generateStopLightBoundTable(): observations must be increasing, got "
271 << observations[i] << " at " << i << " and " << observations[i + 1] << " at " << i + 1);
272 }
273
274 Size len = observations.back() + (numberOfDays - 1);
275 auto sgen = PseudoRandom::make_sequence_generator(len, seed);
276 Real h = InverseCumulativeNormal()(p) * std::sqrt(static_cast<Real>(numberOfDays));
277
278 /*! populate matrix where the rows correspond to the observations and column j
279 contain P(exceptions == j) */
280 // heuristic... is this ok, too low (will throw an excetpion below), too high (wastes memory)?
281 Size cols;
282 if (observations.back() <= 100)
283 cols = observations.back() + 1;
284 else if (observations.back() <= 500)
285 cols = observations.back() / 5;
286 else
287 cols = observations.back() / 10;
288
289 Matrix cumProb(observations.size(), cols, 0.0);
290
291 for (Size i = 0; i < samples; ++i) {
292 auto seq = sgen.nextSequence().value;
293 Size exCount = 0, obsIdx = 0;
294 Real pl = 0.0;
295 for (Size l = 0; l < observations.back(); ++l) {
296 if (l == 0) {
297 // compute the 10d PL only once ...
298 for (Size dd = 0; dd < numberOfDays; ++dd) {
299 pl += seq[dd];
300 }
301 } else {
302 // and only correct for the tail and head
303 pl += seq[l - 1 + numberOfDays] - seq[l - 1];
304 }
305 if (pl > h)
306 ++exCount;
307 if (l == observations[obsIdx] - 1) {
308 if (exCount < cols)
309 cumProb(obsIdx, exCount) += 1.0 / static_cast<Real>(samples);
310 obsIdx++;
311 }
312 }
313 }
314
315 // compute result table
316 std::vector<std::pair<Size, std::vector<Size>>> result;
317 for (Size i = 0; i < observations.size(); ++i) {
318 Real P = 0.0;
319 Size idx = 0;
320 std::vector<Size> b;
321 for (Size j = 0; j < cols && idx < stopLightP.size(); ++j) {
322 P += cumProb(i, j);
323 while (idx < stopLightP.size() && (P >= stopLightP[idx] || QuantLib::close_enough(P, stopLightP[idx]))) {
324 b.push_back(std::max<Size>(j, 1) - 1);
325 idx++;
326 }
327 }
328 QL_REQUIRE(b.size() == stopLightP.size(),
329 "generateStopLightBoundTable(): could not determine bound for observations = "
330 << observations[i] << " and stopLightP = " << stopLightP[b.size()]
331 << " - try to increase number of cols in matrix cumProb");
332 result.push_back(std::make_pair(observations[i], b));
333 }
334
335 return result;
336}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ Trace()

Real Trace ( const Matrix &  m)

Definition at line 34 of file trace.hpp.

34 {
35 QL_REQUIRE(m.rows() == m.columns(), "Trace: input matrix must be quadratic");
36 Real t = 0.0;
37 for (Size i = 0; i < m.rows(); ++i)
38 t += m[i][i];
39 return t;
40}

◆ interpolateVariatesWithBrownianBridge()

void interpolateVariatesWithBrownianBridge ( const std::vector< QuantLib::Real > &  times,
std::vector< std::vector< QuantExt::RandomVariable > > &  variates,
const Size  seed 
)

Input is

  • a vector of ascending times 0 < t1 < t2 < ... < tn
  • for a subset of these times a d-vector of N(0,1) variates that can be used to evolve a stochastic process of dimension d on this subset of the given times, this subset is required to be non-empty

Here, the outer vector of the input variable variates refers to the times and the inner vector contains d random variables. The components of the random variables correspond to the monte carlo pathts. For times where initially no variates are given, the inner vector should be empty.

After the function call, the variates vector contains N(0,1) variates for all times. These variates can be used to evolve the same stochastic process, but on the full time grid. The missing variates are interpolated using a brownian bridge.

Definition at line 40 of file brownianbridgepathinterpolator.cpp.

42 {
43
44 // check inputs
45
46 for (Size i = 1; i < times.size(); ++i) {
47 QL_REQUIRE(times[i] > times[i - 1] && !QuantLib::close_enough(times[i], times[i - 1]),
48 "interpolateVariatesWithBrownianBridge():: times must be ascending, got "
49 << times[i - 1] << " at " << i - 1 << " and " << times[i] << " at " << i);
50 }
51
52 QL_REQUIRE(variates.size() == times.size(), "interpolateVariatesWithBrownianBridge(): variates vector size ("
53 << variates.size() << ") must match times vector size ("
54 << times.size() << ")");
55
56 Size d = Null<Size>(), p = Null<Size>();
57 for (Size i = 0; i < times.size(); ++i) {
58 if (variates[i].empty())
59 continue;
60 if (d == Null<Size>()) {
61 d = variates[i].size();
62 p = variates[i].front().size();
63 QL_REQUIRE(p > 0,
64 "interpolatedVariatesWithBrownianBridge(): found RandomVariable of size 0 at time step " << i);
65 } else {
66 QL_REQUIRE(variates[i].size() == d,
67 "interpolateVariatesWithBrownianBridge(): variates dimension at time step "
68 << i << " (" << variates[i].size() << ") is expected to be " << d);
69 for (Size j = 0; j < d; ++j) {
70 QL_REQUIRE(variates[i][j].size() == p, "interpolateVariatesWithBrownianBridge(): variate at time step "
71 << i << " dimension " << j << " has "
72 << variates[i][j].size() << " paths, expected " << p);
73 }
74 }
75 }
76
77 QL_REQUIRE(d != Null<Size>(),
78 "interpolateVariatesWithBrownianBridge(): expected at least one time step with non-empty variate");
79
80 // we construct a Wiener process W(t) from the initially given variates by adding the given variates up
81 // on a unit distance time grid 1, 2, 3, 4, ... which we call the "standardised time grid".
82
83 std::vector<std::vector<QuantExt::RandomVariable>> paths(times.size(), std::vector<QuantExt::RandomVariable>(d));
84 std::vector<Real> standardisedTimes(times.size(), Null<Real>());
85
86 Size counter = 0;
87 Size lastTimeStep = Null<Size>();
88
89 std::vector<bool> initialised(times.size(), false);
90 for (Size i = 0; i < times.size(); ++i) {
91 if (variates[i].empty())
92 continue;
93 standardisedTimes[i] = static_cast<Real>(++counter);
94 for (Size j = 0; j < d; ++j) {
95 paths[i][j] = lastTimeStep == Null<Size>() ? variates[i][j] : paths[lastTimeStep][j] + variates[i][j];
96 }
97 lastTimeStep = i;
98 initialised[i] = true;
99 }
100
101 // next we fill in the missing times and create interpolated variates using a Brownian bridge, this will generate
102 // intermediate times on the unit distance grid from above as a scaled version of the original times
103
104 MersenneTwisterUniformRng mt(seed);
105
106 for (Size i = 0; i < times.size(); ++i) {
107 if (initialised[i])
108 continue;
109 // we interpolate between time indices l and r
110 Size l = i + 1, r = i;
111 while (l > 0 && variates[--l].empty())
112 ;
113 while (r < variates.size() - 1 && variates[++r].empty())
114 ;
115 if (variates[r].empty()) {
116 // if there is no right point to interpolate we just continue the path with new variates ...
117 QL_REQUIRE(!variates[l].empty(),
118 "interpolateVariatesWithBrownianBridge(): internal error, expected variates["
119 << l << "] to be non-empty");
120 for (Size k = l + 1; k <= r; ++k) {
121 for (Size j = 0; j < d; ++j) {
122 paths[k][j] = paths[k - 1][j] + createNewVariate(p, mt);
123 }
124 standardisedTimes[k] = standardisedTimes[k - 1] + 1.0;
125 initialised[k] = true;
126 }
127 } else {
128 // ... otherwise we interpolate using a Brownian bridge, this relies on Theorem 14.2 in
129 // Mark Joshi, "More Mathematical Finance", Pilot Whale Press
130 RandomVariable t, T;
131 // compute the standardised times first
132 if (variates[l].empty()) {
133 QL_REQUIRE(l == 0, "interpolateVariatesWithBrownianBridge(): internal error, expected l==0, got " << l);
134 for (Size k = l; k < r; ++k) {
135 standardisedTimes[k] = times[k] / times[r];
136 }
137 } else {
138 for (Size k = l; k < r; ++k) {
139 standardisedTimes[k] = standardisedTimes[l] + (times[k] - times[l]) / (times[r] - times[l]);
140 }
141 }
142 // now interpolate the path
143 for (Size k = l; k < r; ++k) {
144 if (variates[l].empty() && k == l) {
145 // interpolate between 0 and the first non-empty point
146 t = RandomVariable(p, standardisedTimes[k]);
147 T = RandomVariable(p, standardisedTimes[r]);
148 } else if (k > l) {
149 // interpolate between two non-empty points
150 t = RandomVariable(p, standardisedTimes[k] - standardisedTimes[k - 1]);
151 T = RandomVariable(p, standardisedTimes[r] - standardisedTimes[k - 1]);
152 } else {
153 // k=l and variates[l] non empty => nothing to do
154 continue;
155 }
156 RandomVariable stdDev = sqrt(t * (T - t) / T);
157 for (Size j = 0; j < d; ++j) {
158 RandomVariable expectedValue =
159 ((T - t) * (k == l ? RandomVariable(p, 0.0) : paths[k - 1][j]) + t * paths[r][j]) / T;
160 paths[k][j] = expectedValue + stdDev * createNewVariate(p, mt);
161 }
162 initialised[k] = true;
163 }
164 }
165 }
166
167 // finally we calcuate the sequenctial differences on the paths and rescale them to a unit distance grid
168 // in order to get the desired N(0,1) variates on the refined time grid
169
170 for (Size i = 0; i < times.size(); ++i) {
171 RandomVariable scaling(p, std::sqrt(1.0 / (standardisedTimes[i] - (i == 0 ? 0.0 : standardisedTimes[i - 1]))));
172 if (variates[i].empty())
173 variates[i] = std::vector<RandomVariable>(d, RandomVariable(p));
174 for (Size j = 0; j < d; ++j) {
175 variates[i][j] = (i == 0 ? paths[i][j] : paths[i][j] - paths[i - 1][j]) * scaling;
176 }
177 }
178
179 // results are set in variates, exit without returning anything
180
181 return;
182}
+ Here is the call graph for this function:

◆ makeMultiPathGenerator()

QuantLib::ext::shared_ptr< MultiPathGeneratorBase > makeMultiPathGenerator ( const SequenceType  s,
const QuantLib::ext::shared_ptr< StochasticProcess > &  process,
const TimeGrid &  timeGrid,
const BigNatural  seed,
const SobolBrownianGenerator::Ordering  ordering,
const SobolRsg::DirectionIntegers  directionIntegers 
)

Make function for path generators.

Definition at line 190 of file multipathgeneratorbase.cpp.

192 {
193 switch (s) {
194 case MersenneTwister:
195 return QuantLib::ext::make_shared<QuantExt::MultiPathGeneratorMersenneTwister>(process, timeGrid, seed, false);
197 return QuantLib::ext::make_shared<QuantExt::MultiPathGeneratorMersenneTwister>(process, timeGrid, seed, true);
198 case Sobol:
199 return QuantLib::ext::make_shared<QuantExt::MultiPathGeneratorSobol>(process, timeGrid, seed, directionIntegers);
200 case Burley2020Sobol:
201 return QuantLib::ext::make_shared<QuantExt::MultiPathGeneratorBurley2020Sobol>(
202 process, timeGrid, seed, directionIntegers, seed == 0 ? 0 : seed + 1);
204 return QuantLib::ext::make_shared<QuantExt::MultiPathGeneratorSobolBrownianBridge>(process, timeGrid, ordering, seed,
205 directionIntegers);
207 return QuantLib::ext::make_shared<QuantExt::MultiPathGeneratorBurley2020SobolBrownianBridge>(
208 process, timeGrid, ordering, seed, directionIntegers, seed == 0 ? 0 : seed + 1);
209 default:
210 QL_FAIL("Unknown sequence type");
211 }
212}
+ Here is the caller graph for this function:

◆ operator<<() [9/16]

std::ostream & operator<< ( std::ostream &  out,
const SequenceType  s 
)

Output function.

Definition at line 214 of file multipathgeneratorbase.cpp.

214 {
215 switch (s) {
216 case MersenneTwister:
217 return out << "MersenneTwister";
219 return out << "MersenneTwisterAntithetic";
220 case Sobol:
221 return out << "Sobol";
222 case Burley2020Sobol:
223 return out << "Burley2020Sobol";
225 return out << "SobolBrownianBridge";
227 return out << "Burley2020SobolBrownianBridge";
228 default:
229 return out << "Unknown sequence type";
230 }
231}

◆ makeMultiPathVariateGenerator()

QuantLib::ext::shared_ptr< MultiPathVariateGeneratorBase > makeMultiPathVariateGenerator ( const SequenceType  s,
const Size  dimension,
const Size  timeSteps,
const BigNatural  seed,
const SobolBrownianGenerator::Ordering  ordering,
const SobolRsg::DirectionIntegers  directionIntegers 
)

Definition at line 153 of file multipathvariategenerator.cpp.

155 {
156 switch (s) {
157 case MersenneTwister:
158 return QuantLib::ext::make_shared<QuantExt::MultiPathVariateGeneratorMersenneTwister>(dimension, timeSteps, seed,
159 false);
161 return QuantLib::ext::make_shared<QuantExt::MultiPathVariateGeneratorMersenneTwister>(dimension, timeSteps, seed, true);
162 case Sobol:
163 return QuantLib::ext::make_shared<QuantExt::MultiPathVariateGeneratorSobol>(dimension, timeSteps, seed,
164 directionIntegers);
165 case Burley2020Sobol:
166 return QuantLib::ext::make_shared<QuantExt::MultiPathVariateGeneratorBurley2020Sobol>(dimension, timeSteps, seed,
167 directionIntegers, seed + 1);
169 return QuantLib::ext::make_shared<QuantExt::MultiPathVariateGeneratorSobolBrownianBridge>(
170 dimension, timeSteps, ordering, seed, directionIntegers);
172 return QuantLib::ext::make_shared<QuantExt::MultiPathVariateGeneratorBurley2020SobolBrownianBridge>(
173 dimension, timeSteps, ordering, seed, directionIntegers, seed + 1);
174 default:
175 QL_FAIL("Unknown sequence type");
176 }
177}

◆ arbitrageAsString() [1/4]

std::string arbitrageAsString ( const CarrMadanMarginalProbabilityClass &  cm)

Definition at line 164 of file carrmadanarbitragecheck.cpp.

164 {
165 std::ostringstream out;
166 for (Size i = 0; i < cm.strikes().size(); ++i) {
167 Size code = 0;
168 if (cm.callSpreadArbitrage()[i])
169 code += 1;
170 if (cm.butterflyArbitrage()[i])
171 code += 2;
172 out << (code > 0 ? std::to_string(code) : ".");
173 }
174 return out.str();
175}

◆ arbitrageAsString() [2/4]

template std::string arbitrageAsString ( const CarrMadanMarginalProbability cm)

◆ arbitrageAsString() [3/4]

template std::string arbitrageAsString ( const CarrMadanMarginalProbabilitySafeStrikes cm)

◆ arbitrageAsString() [4/4]

std::string arbitrageAsString ( const CarrMadanSurface cm)

Definition at line 256 of file carrmadanarbitragecheck.cpp.

256 {
257 std::ostringstream out;
258 for (Size j = 0; j < cm.times().size(); ++j) {
259 for (Size i = 0; i < cm.moneyness().size(); ++i) {
260 Size code = 0;
261 if (cm.timeSlices()[j].callSpreadArbitrage()[i])
262 code += 1;
263 if (cm.timeSlices()[j].butterflyArbitrage()[i])
264 code += 2;
265 if (cm.calendarArbitrage()[j][i])
266 code += 4;
267 out << (code > 0 ? std::to_string(code) : ".");
268 }
269 out << "\n";
270 }
271 return out.str();
272}
const std::vector< Real > & times() const
const std::vector< std::vector< bool > > & calendarArbitrage() const
const std::vector< CarrMadanMarginalProbability > & timeSlices() const
const std::vector< Real > & moneyness() const
+ Here is the call graph for this function:

◆ operator<<() [10/16]

std::ostream & operator<< ( std::ostream &  out,
const CrossAssetModel::AssetType type 
)

Definition at line 36 of file crossassetmodel.cpp.

36 {
37 switch (type) {
38 case CrossAssetModel::AssetType::IR:
39 return out << "IR";
40 case CrossAssetModel::AssetType::FX:
41 return out << "FX";
42 case CrossAssetModel::AssetType::INF:
43 return out << "INF";
44 case CrossAssetModel::AssetType::CR:
45 return out << "CR";
46 case CrossAssetModel::AssetType::EQ:
47 return out << "EQ";
48 case CrossAssetModel::AssetType::COM:
49 return out << "COM";
50 case CrossAssetModel::AssetType::CrState:
51 return out << "CrState";
52 default:
53 QL_FAIL("Did not recognise cross asset model type " << static_cast<int>(type) << ".");
54 }
55}

◆ inflationTermStructure() [1/2]

Handle< ZeroInflationTermStructure > inflationTermStructure ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
Size  index 
)

Definition at line 1034 of file crossassetmodel.cpp.

1034 {
1035
1036 if (model->modelType(CrossAssetModel::AssetType::INF, index) == CrossAssetModel::ModelType::DK) {
1037 return model->infdk(index)->termStructure();
1038 } else if (model->modelType(CrossAssetModel::AssetType::INF, index) == CrossAssetModel::ModelType::JY) {
1039 return model->infjy(index)->realRate()->termStructure();
1040 } else {
1041 QL_FAIL("Expected inflation model to be either DK or JY.");
1042 }
1043}

◆ inflationTermStructure() [2/2]

QuantLib::Handle< QuantLib::ZeroInflationTermStructure > inflationTermStructure ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
QuantLib::Size  index 
)

Utility function to return a handle to the inflation term structure given the inflation index.

◆ exactBachelierImpliedVolatility()

Real exactBachelierImpliedVolatility ( Option::Type  optionType,
Real  strike,
Real  forward,
Real  tte,
Real  bachelierPrice,
Real  discount 
)

Definition at line 59 of file exactbachelierimpliedvolatility.cpp.

60 {
61
62 Real theta = optionType == Option::Call ? 1.0 : -1.0;
63
64 // compound bechelierPrice, so that effectively discount = 1
65
66 bachelierPrice /= discount;
67
68 // handle case strike = forward
69
70 if (std::abs(strike - forward) < 1E-15) {
71 return bachelierPrice / (std::sqrt(tte) * phi(0.0));
72 }
73
74 // handle case strike != forward
75
76 Real timeValue = bachelierPrice - std::max(theta * (forward - strike), 0.0);
77
78 if (std::abs(timeValue) < 1E-15)
79 return 0.0;
80
81 QL_REQUIRE(timeValue > 0.0, "exactBachelierImpliedVolatility(theta="
82 << theta << ",strike=" << strike << ",forward=" << forward << ",tte=" << tte
83 << ",price=" << bachelierPrice << "): option price implies negative time value ("
84 << timeValue << ")");
85
86 Real PhiTildeStar = -std::abs(timeValue / (strike - forward));
87 Real xstar = inversePhiTilde(PhiTildeStar);
88 Real impliedVol = std::abs((strike - forward) / (xstar * std::sqrt(tte)));
89
90 return impliedVol;
91}
+ Here is the caller graph for this function:

◆ inflationGrowth() [1/6]

Real inflationGrowth ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
Size  index,
Time  S,
Time  T,
Real  irState,
Real  rrState,
bool  indexIsInterpolated 
)

Definition at line 61 of file jyimpliedzeroinflationtermstructure.cpp.

62 {
63
64 QL_REQUIRE(T >= S, "inflationGrowth: end time (" << T << ") must be >= start time (" << S << ")");
65
66 // After this step, p_n holds P_n(S, T) * P_n(0, S) / P_n(0, T)
67 // = \exp \left( - \left[ H_n(T) - H_n(S) \right] z_n(S) -
68 // \frac{1}{2} \left[ H^2_n(T) - H^2_n(S) \right] \zeta_n(S) \right)
69 auto irIdx = model->ccyIndex(model->infjy(index)->currency());
70 auto irTs = model->irlgm1f(irIdx)->termStructure();
71 auto p_n = model->discountBond(irIdx, S, T, irState) * irTs->discount(S) / irTs->discount(T);
72
73 // After this step, p_r holds P_r(S, T) * P_r(0, S) / P_r(0, T)
74 // = \exp \left( - \left[ H_r(T) - H_r(S) \right] z_r(S) -
75 // \frac{1}{2} \left[ H^2_r(T) - H^2_r(S) \right] \zeta_r(S) \right)
76 auto rrParam = model->infjy(index)->realRate();
77 auto H_r_S = rrParam->H(S);
78 auto H_r_T = rrParam->H(T);
79 auto zeta_r_S = rrParam->zeta(S);
80 auto p_r = std::exp(-(H_r_T - H_r_S) * rrState - 0.5 * (H_r_T * H_r_T - H_r_S * H_r_S) * zeta_r_S);
81
82 // Now, use the original zero inflation term structure to get P_r(0, S) / P_n(0, S) and P_r(0, T) / P_n(0, T) and
83 // return \frac{P_r(S, T)}{P_n(S, T)}
84 const auto& zts = model->infjy(index)->realRate()->termStructure();
85 return inflationGrowth(zts, T, indexIsInterpolated) / inflationGrowth(zts, S, indexIsInterpolated) * p_r / p_n;
86
87}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ inflationGrowth() [2/6]

QuantLib::Real inflationGrowth ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
QuantLib::Size  index,
QuantLib::Time  S,
QuantLib::Time  T,
QuantLib::Real  irState,
QuantLib::Real  rrState,
bool  indexIsInterpolated 
)

Calculation of inflation growth between two times given the Jarrow Yildrim (JY) real rate state, rrState, and the nominal interest rate state, irState.

◆ getAdditionalResultsMap()

std::map< std::string, boost::any > getAdditionalResultsMap ( const LgmCalibrationInfo info)

Definition at line 23 of file lgmcalibrationinfo.cpp.

23 {
24 std::map<std::string, boost::any> result;
25 if (info.valid) {
26 result["lgmCalibrationError"] = info.rmse;
27 std::vector<Real> timeToExpiry, swapLength, strike, atmForward, annuity, vega, vols;
28 std::vector<Real> modelTime, modelVol, marketVol, modelValue, marketValue, modelAlpha, modelKappa, modelHwSigma;
29 std::vector<Real> volDiff, valueDiff;
30 for (auto const& d : info.swaptionData) {
31 timeToExpiry.push_back(d.timeToExpiry);
32 swapLength.push_back(d.swapLength);
33 strike.push_back(d.strike);
34 atmForward.push_back(d.atmForward);
35 annuity.push_back(d.annuity);
36 vega.push_back(d.vega);
37 vols.push_back(d.stdDev / std::sqrt(d.timeToExpiry));
38 }
39 for (auto const& d : info.lgmCalibrationData) {
40 modelTime.push_back(d.modelTime);
41 modelVol.push_back(d.modelVol);
42 marketVol.push_back(d.marketVol);
43 modelValue.push_back(d.modelValue);
44 marketValue.push_back(d.marketValue);
45 modelAlpha.push_back(d.modelAlpha);
46 modelKappa.push_back(d.modelKappa);
47 modelHwSigma.push_back(d.modelHwSigma);
48 volDiff.push_back(d.modelVol - d.marketVol);
49 valueDiff.push_back(d.modelValue - d.marketValue);
50 }
51 result["lgmCalibrationBasketExpiryTimes"] = timeToExpiry;
52 result["lgmCalibrationBasketSwapLengths"] = swapLength;
53 result["lgmCalibrationBasketStrikes"] = strike;
54 result["lgmCalibrationBasketAtmForwards"] = atmForward;
55 result["lgmCalibrationBasketAnnuities"] = annuity;
56 result["lgmCalibrationBasketVegas"] = vega;
57 result["lgmCalibrationBasketVols"] = vols;
58 result["lgmCalibrationTimes"] = modelTime;
59 result["lgmCalibrationModelVols"] = modelVol;
60 result["lgmCalibrationMarketVols"] = marketVol;
61 result["lgmCalibrationModelValues"] = modelValue;
62 result["lgmCalibrationMarketValues"] = marketValue;
63 result["lgmCalibrationModelAlphas"] = modelAlpha;
64 result["lgmCalibrationModelKappas"] = modelKappa;
65 result["lgmCalibrationModelHwSigmas"] = modelHwSigma;
66 result["lgmCalibrationModelMarketVolDiffs"] = volDiff;
67 result["lgmCalibrationModelMarketValueDiffs"] = valueDiff;
68 }
69 return result;
70}
std::vector< LgmCalibrationData > lgmCalibrationData
std::vector< SwaptionData > swaptionData
+ Here is the caller graph for this function:

◆ normalSabrVolatility()

Real normalSabrVolatility ( Rate  strike,
Rate  forward,
Time  expiryTime,
Real  alpha,
Real  nu,
Real  rho 
)

Definition at line 28 of file normalsabr.cpp.

28 {
29
30 // update extreme parameters
31
32 alpha = std::max(alpha, 1E-5);
33 if (rho < -1 + 1E-5)
34 rho = -1 + 1E-5;
35 else if (rho > 1 - 1E-5)
36 rho = 1 - 1E-5;
37
38 // calculate result
39
40 Real zeta = nu / alpha * (forward - strike);
41 Real x = std::log((std::sqrt(1.0 - 2.0 * rho * zeta + zeta * zeta) - rho + zeta) / (1.0 - rho));
42 Real f = close_enough(x, 0.0) ? 1.0 : zeta / x;
43 Real vol = alpha * f * (1.0 + expiryTime * (2.0 - 3.0 * rho * rho) * nu * nu / 24.0);
44 QL_REQUIRE(std::isfinite(vol), "normalSabrVolatility: computed invalid vol for strike="
45 << strike << ", forward=" << forward << ", expiryTime=" << expiryTime
46 << ", alpha=" << alpha << ", nu=" << nu << ", rho=" << rho);
47 return std::max(vol, 0.00001);
48}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ normalSabrAlphaFromAtmVol()

Real normalSabrAlphaFromAtmVol ( Rate  forward,
Time  expiryTime,
Real  atmVol,
Real  nu,
Real  rho 
)

Definition at line 50 of file normalsabr.cpp.

50 {
51 return std::max(atmVol / (1.0 + expiryTime * (2.0 - 3.0 * rho * rho) * nu * nu / 24.0), 0.00001);
52}
+ Here is the caller graph for this function:

◆ normalFreeBoundarySabrPrice()

Real normalFreeBoundarySabrPrice ( Rate  strike,
Rate  forward,
Time  expiryTime,
Real  alpha,
Real  nu,
Real  rho 
)

Definition at line 81 of file normalsabr.cpp.

81 {
82 // update extreme parameters
83
84 nu = std::max(nu, 1E-6);
85 if (rho < -1 + 1E-5)
86 rho = -1 + 1E-5;
87 else if (rho > 1 - 1E-5)
88 rho = 1 - 1E-5;
89
90 // compute option price
91
92 Real V0 = alpha / nu;
93 Real k = (strike - forward) / V0 + rho;
94 Real rhobar = std::sqrt(1.0 - rho * rho);
95 Real arg = (-rho * k + std::sqrt(k * k + rhobar * rhobar)) / (rhobar * rhobar);
96 QL_REQUIRE(arg > 1.0 - 1E-12, "invalid arg (" << arg << "), must be >= 1");
97 Real s0 = std::acosh(std::max(1.0, arg));
98
99 auto integrand = [k, rho, nu, expiryTime](const Real s) {
100 Real tmp = (k - rho * std::cosh(s));
101 Real arg = std::sinh(s) * std::sinh(s) - tmp * tmp;
102 QL_REQUIRE(arg > -1E-12, "invalid arg (" << arg << "), must be >= 0 (tmp=" << tmp << ")");
103 return G(nu * nu * expiryTime, s) / std::sinh(s) * std::sqrt(std::max(0.0, arg));
104 };
105
106 Real lowerBound = std::max(s0, 1E-12);
107 Real upperBound = std::max(1.5 * s0, 1.0);
108 while (integrand(upperBound) > 1E-12)
109 upperBound *= 1.5;
110
111 GaussLobattoIntegral gl(10000, 1E-8);
112 Real price = V0 / M_PI * gl(integrand, lowerBound, upperBound);
113 price += std::max(forward - strike, 0.0);
114
115 return price;
116}
+ Here is the caller graph for this function:

◆ normalFreeBoundarySabrVolatility()

Real normalFreeBoundarySabrVolatility ( Rate  strike,
Rate  forward,
Time  expiryTime,
Real  alpha,
Real  nu,
Real  rho 
)

Definition at line 118 of file normalsabr.cpp.

118 {
119 return exactBachelierImpliedVolatility(Option::Call, strike, forward, expiryTime,
120 normalFreeBoundarySabrPrice(strike, forward, expiryTime, alpha, nu, rho));
121}
Real exactBachelierImpliedVolatility(Option::Type optionType, Real strike, Real forward, Real tte, Real bachelierPrice, Real discount)
Real normalFreeBoundarySabrPrice(Rate strike, Rate forward, Time expiryTime, Real alpha, Real nu, Real rho)
Definition: normalsabr.cpp:81
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getProjectedCrossAssetModel()

QuantLib::ext::shared_ptr< CrossAssetModel > getProjectedCrossAssetModel ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
const std::vector< std::pair< CrossAssetModel::AssetType, Size > > &  selectedComponents,
std::vector< Size > &  projectedStateProcessIndices 
)

Definition at line 24 of file projectedcrossassetmodel.cpp.

26 {
27
28 projectedStateProcessIndices.clear();
29
30 // vectors holding the selected parametrizations and associated indices in the correlation matrix
31
32 std::vector<QuantLib::ext::shared_ptr<Parametrization>> parametrizations;
33 std::vector<Size> correlationIndices;
34
35 // loop over selected components and fill
36 // - parametrizations
37 // - correlation indices
38 // - state process indices
39
40 for (auto const& c : selectedComponents) {
41 parametrizations.push_back(model->parametrizations().at(model->idx(c.first, c.second)));
42 for (Size b = 0; b < model->brownians(c.first, c.second); ++b)
43 correlationIndices.push_back(model->cIdx(c.first, c.second, b));
44 for (Size p = 0; p < model->stateVariables(c.first, c.second); ++p)
45 projectedStateProcessIndices.push_back(model->pIdx(c.first, c.second, p));
46 }
47
48 // build correlation matrix
49
50 Matrix correlation(correlationIndices.size(), correlationIndices.size());
51 for (Size j = 0; j < correlationIndices.size(); ++j) {
52 correlation(j, j) = 1.0;
53 for (Size k = 0; k < j; ++k) {
54 correlation(k, j) = correlation(j, k) =
55 model->correlation()(correlationIndices.at(j), correlationIndices.at(k));
56 }
57 }
58
59 // build projected cam and return it
60
61 return QuantLib::ext::make_shared<CrossAssetModel>(parametrizations, correlation, model->salvagingAlgorithm(),
62 model->measure(), model->discretization());
63}

◆ getStateProcessProjection()

std::vector< Size > getStateProcessProjection ( const QuantLib::ext::shared_ptr< CrossAssetModel > &  model,
const QuantLib::ext::shared_ptr< CrossAssetModel > &  projectedModel 
)

Definition at line 65 of file projectedcrossassetmodel.cpp.

66 {
67
68 std::vector<Size> stateProcessProjection(projectedModel->stateProcess()->size(), Null<Size>());
69
70 for (Size i = 0; i < model->components(CrossAssetModel::AssetType::IR); ++i) {
71 for (Size j = 0; j < projectedModel->components(CrossAssetModel::AssetType::IR); ++j) {
72 if (projectedModel->ir(j)->currency() == model->ir(i)->currency()) {
73 for (Size k = 0; k < projectedModel->stateVariables(CrossAssetModel::AssetType::IR, j); ++k) {
74 stateProcessProjection[projectedModel->pIdx(CrossAssetModel::AssetType::IR, j, k)] =
75 model->pIdx(CrossAssetModel::AssetType::IR, i, k);
76 }
77 }
78 }
79 }
80
81 for (Size i = 0; i < model->components(CrossAssetModel::AssetType::FX); ++i) {
82 for (Size j = 0; j < projectedModel->components(CrossAssetModel::AssetType::FX); ++j) {
83 if (projectedModel->fx(j)->currency() == model->fx(i)->currency()) {
84 for (Size k = 0; k < projectedModel->stateVariables(CrossAssetModel::AssetType::FX, j); ++k) {
85 stateProcessProjection[projectedModel->pIdx(CrossAssetModel::AssetType::FX, j, k)] =
86 model->pIdx(CrossAssetModel::AssetType::FX, i, k);
87 }
88 }
89 }
90 }
91
92 for (Size i = 0; i < model->components(CrossAssetModel::AssetType::INF); ++i) {
93 for (Size j = 0; j < projectedModel->components(CrossAssetModel::AssetType::INF); ++j) {
94 if (projectedModel->inf(j)->name() == model->inf(i)->name()) {
95 for (Size k = 0; k < projectedModel->stateVariables(CrossAssetModel::AssetType::INF, j); ++k) {
96 stateProcessProjection[projectedModel->pIdx(CrossAssetModel::AssetType::INF, j, k)] =
97 model->pIdx(CrossAssetModel::AssetType::INF, i, k);
98 }
99 }
100 }
101 }
102
103 for (Size i = 0; i < model->components(CrossAssetModel::AssetType::CR); ++i) {
104 for (Size j = 0; j < projectedModel->components(CrossAssetModel::AssetType::CR); ++j) {
105 if (projectedModel->cr(j)->name() == model->cr(i)->name()) {
106 for (Size k = 0; k < projectedModel->stateVariables(CrossAssetModel::AssetType::CR, j); ++k) {
107 stateProcessProjection[projectedModel->pIdx(CrossAssetModel::AssetType::CR, j, k)] =
108 model->pIdx(CrossAssetModel::AssetType::CR, i, k);
109 }
110 }
111 }
112 }
113
114 for (Size i = 0; i < model->components(CrossAssetModel::AssetType::EQ); ++i) {
115 for (Size j = 0; j < projectedModel->components(CrossAssetModel::AssetType::EQ); ++j) {
116 if (projectedModel->eq(j)->name() == model->eq(i)->name()) {
117 for (Size k = 0; k < projectedModel->stateVariables(CrossAssetModel::AssetType::EQ, j); ++k) {
118 stateProcessProjection[projectedModel->pIdx(CrossAssetModel::AssetType::EQ, j, k)] =
119 model->pIdx(CrossAssetModel::AssetType::EQ, i, k);
120 }
121 }
122 }
123 }
124
125 return stateProcessProjection;
126}

◆ sanitiseTransitionMatrix()

void sanitiseTransitionMatrix ( Matrix &  m)

cap / floor elements at 1 / 0, adjust diagonal elements so that row sums are 1, or if that is not possible, divide the row elements by the row sum

Definition at line 32 of file transitionmatrix.cpp.

32 {
33 for (Size i = 0; i < m.rows(); ++i) {
34 Real sum = 0.0;
35 for (Size j = 0; j < m.columns(); ++j) {
36 m[i][j] = std::max(std::min(m[i][j], 1.0), 0.0);
37 if (i != j)
38 sum += m[i][j];
39 }
40 if (sum <= 1.0) {
41 m(i, i) = 1.0 - sum;
42 } else {
43 sum += m[i][i];
44 for (Size j = 0; j < m.columns(); ++j) {
45 m[i][j] = m[i][j] / sum;
46 }
47 }
48 }
49}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ checkTransitionMatrix()

void checkTransitionMatrix ( const Matrix &  t)

check if the matrix is a transition matrix, i.e. row sums are 1 and entries are non-negative

Definition at line 51 of file transitionmatrix.cpp.

51 {
52 QL_REQUIRE(t.rows() == t.columns(), "transition matrix must be quadratic");
53 for (Size i = 0; i < t.rows(); ++i) {
54 Real sum = 0.0;
55 for (Size j = 0; j < t.columns(); ++j) {
56 sum += t[i][j];
57 QL_REQUIRE(t[i][j] > 0.0 || close_enough(t[i][j], 0.0),
58 "transition matrix entry (" << i << "," << j << ") is negative: " << t[i][j]);
59 }
60 QL_REQUIRE(close_enough(sum, 1.0), "row " << i << " sum (" << sum << ") not equal to 1");
61 }
62 return;
63}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ checkGeneratorMatrix()

void checkGeneratorMatrix ( const Matrix &  g)

check if the matrix is a generator matirx, i.e. row sums are 0 and non-diagonal elements are non-negative

Definition at line 65 of file transitionmatrix.cpp.

65 {
66 QL_REQUIRE(g.rows() == g.columns(), "generator matrix must be quadratic");
67 for (Size i = 0; i < g.rows(); ++i) {
68 Real sum = 0.0;
69 for (Size j = 0; j < g.columns(); ++j) {
70 sum += g[i][j];
71 if (i != j) {
72 QL_REQUIRE(g[i][j] > 0.0 || close_enough(g[i][j], 0.0),
73 "generator matrix entry (" << i << "," << j << ") is negative: " << g[i][j]);
74 }
75 }
76 QL_REQUIRE(std::fabs(sum) < QL_EPSILON, "row " << i << " sum (" << sum << ") not equal to 0");
77 }
78 return;
79}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ generator()

Matrix generator ( const Matrix &  t,
const Real  horizon = 1.0 
)

build generator from transition matrix cf. Alexander Kreinin and Marina Sidelnikova, "Regularization Algorithms for Transition Matrices", Algorithm QOG

Definition at line 89 of file transitionmatrix.cpp.

89 {
90 // naked log
91 Matrix A = QuantExt::Logm(t) / horizon;
92 // regularisation
93 Size n = A.columns();
94 for (Size row = 0; row < A.rows(); ++row) {
95 // Step 1
96 Real lambda = 0.0;
97 for (Size i = 0; i < n; ++i) {
98 lambda += A(row, i);
99 }
100 lambda /= static_cast<Real>(n);
101 std::vector<Real> b(n);
102 for (Size i = 0; i < n; ++i) {
103 b[i] = A(row, i) - lambda;
104 }
105 // Step 2
106 std::vector<Size> pi(n);
107 for (Size i = 0; i < n; ++i)
108 pi[i] = i;
109 // ascending order, in the paper it says descending order...
110 std::sort(pi.begin(), pi.end(), PiCompare(b));
111 std::vector<Real> ahat(n);
112 for (Size i = 0; i < n; ++i)
113 ahat[i] = b[pi[i]];
114 // Step 3
115 // start with l=1, the paper says l=2....
116 Size l = 1;
117 for (; l <= n - 1; ++l) {
118 Real sum = 0.0;
119 for (Size i = 0; i <= n - (l + 1); ++i)
120 sum += ahat[n - i - 1];
121 if (static_cast<Real>(n - l + 1) * ahat[l + 1 - 1] >= ahat[0] + sum)
122 break;
123 }
124 QL_REQUIRE(l <= n - 1, "regularisedGenerator: expected 2 <= l <= n-1");
125 // Step 4
126 std::vector<Real> ghat(n, 0.0);
127 Real sum = 0.0;
128 for (Size j = 0; j < n; ++j) {
129 if (!(j + 1 >= 2 && j + 1 <= l))
130 sum += ahat[j];
131 }
132 sum /= static_cast<Real>(n - l + 1);
133 for (Size i = 0; i < n; ++i) {
134 if (!(i + 1 >= 2 && i + 1 <= l))
135 ghat[i] = ahat[i] - sum;
136 }
137 // Step 5
138 for (Size i = 0; i < n; ++i) {
139 A(row, pi[i]) = ghat[i];
140 }
141 } // for row
142 return A;
143}
QuantLib::Matrix Logm(const QuantLib::Matrix &m)
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ creditStateBoundaries()

std::vector< Real > creditStateBoundaries ( const I &  begin,
const I &  end 
)

compute N(0,1) credit state boundaries

Definition at line 145 of file transitionmatrix.cpp.

145 {
146 InverseCumulativeNormal icn;
147 std::vector<Real> bounds(end - begin);
148 Real sum = 0.0;
149 for (Size i = 0; i < bounds.size(); ++i) {
150 Real p = *(begin + i);
151 QL_REQUIRE(p >= 0.0, "transistion probability " << i << " is negative: " << p);
152 sum += p;
153 QL_REQUIRE(sum < 1.0 || close_enough(sum, 1.0), "sum of transition probabilities is greater than 1: " << sum);
154 bounds[i] = icn(sum);
155 }
156 QL_REQUIRE(close_enough(sum, 1.0), "sum of transition probabilities is not 1: " << sum);
157 return bounds;
158}
+ Here is the call graph for this function:

◆ print()

void print ( Distribution &  dist,
std::string  fileName 
)

Definition at line 56 of file cboengine.cpp.

56 {
57 std::ofstream file;
58 file.open(fileName.c_str());
59 if (!file.is_open())
60 QL_FAIL("error opening file " << fileName);
61 file.setf(std::ios::scientific, std::ios::floatfield);
62 file.setf(std::ios::showpoint);
63 file.precision(4);
64 for (Size i = 0; i < dist.size(); i++)
65 file << i << " " << dist.x(i) << " " << dist.density(i) << std::endl;
66 file.close();
67}

◆ getCallPriceAmount()

Real getCallPriceAmount ( const FdConvertibleBondEvents::CallData cd,
Real  notional,
Real  accruals 
)

Definition at line 36 of file fddefaultableequityjumpdiffusionconvertiblebondengine.cpp.

36 {
37 Real price = cd.price * notional;
38 if (cd.priceType == ConvertibleBond2::CallabilityData::PriceType::Clean)
39 price += accruals;
40 if (!cd.includeAccrual)
41 price -= accruals;
42 return price;
43}
ConvertibleBond2::CallabilityData::PriceType priceType
+ Here is the caller graph for this function:

◆ interpolateValueFromPlanes()

Real interpolateValueFromPlanes ( const Real  conversionRatio,
const std::vector< Array > &  value,
const std::vector< Real > &  stochasticConversionRatios,
const Size  j 
)

Definition at line 46 of file fddefaultableequityjumpdiffusionconvertiblebondengine.cpp.

47 {
48 if (value.size() == 1)
49 return value.front()[j];
50 // linear interpolation and flat extrapolation
51 Size idx = std::distance(
52 stochasticConversionRatios.begin(),
53 std::upper_bound(stochasticConversionRatios.begin(), stochasticConversionRatios.end(), conversionRatio));
54 if (idx == 0)
55 return value.front()[j];
56 else if (idx == stochasticConversionRatios.size())
57 return value.back()[j];
58 else {
59 Real x0 = stochasticConversionRatios[idx - 1];
60 Real x1 = stochasticConversionRatios[idx];
61 Real y0 = value[idx - 1][j];
62 Real y1 = value[idx][j];
63 Real alpha = (x1 - conversionRatio) / (x1 - x0);
64 return alpha * y0 + (1.0 - alpha) * y1;
65 }
66}
+ Here is the caller graph for this function:

◆ getRebatePv()

RandomVariable getRebatePv ( const LgmVectorised lgm,
const Real  t,
const RandomVariable x,
const Handle< YieldTermStructure > &  discountCurve,
const QuantLib::ext::shared_ptr< RebatedExercise > &  exercise,
const Date &  d 
)

Definition at line 248 of file numericlgmmultilegoptionengine.cpp.

250 {
251 if (exercise == nullptr)
252 return RandomVariable(x.size(), 0.0);
253 if (exercise->type() == Exercise::American) {
254 return RandomVariable(x.size(), exercise->rebate(0)) *
256 t, lgm.parametrization()->termStructure()->timeFromReference(exercise->rebatePaymentDate(d)), x);
257 } else {
258 auto f = std::find(exercise->dates().begin(), exercise->dates().end(), d);
259 QL_REQUIRE(f != exercise->dates().end(), "NumericLgmMultiLegOptionEngine: internal error: exercise date "
260 << d << " from rebate payment not found amount exercise dates.");
261 Size index = std::distance(exercise->dates().begin(), f);
262 return RandomVariable(x.size(), exercise->rebate(index)) *
264 t, lgm.parametrization()->termStructure()->timeFromReference(exercise->rebatePaymentDate(index)), x);
265 }
266}
QuantLib::ext::shared_ptr< IrLgm1fParametrization > parametrization() const
RandomVariable reducedDiscountBond(const Time t, const Time T, const RandomVariable &x, const Handle< YieldTermStructure > &discountCurve=Handle< YieldTermStructure >()) const
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getStrikeFromDelta()

Real getStrikeFromDelta ( Option::Type  optionType,
Real  delta,
DeltaVolQuote::DeltaType  dt,
Real  spot,
Real  domDiscount,
Real  forDiscount,
QuantLib::ext::shared_ptr< BlackVolTermStructure vol,
Real  t,
Real  accuracy,
Size  maxIterations 
)

Definition at line 25 of file blackdeltautilities.cpp.

27 {
28 Real forward = spot / domDiscount * forDiscount;
29 Real result = forward, lastResult;
30 Size iterations = 0;
31 do {
32 Real stddev = std::sqrt(vol->blackVariance(t, result));
33 try {
34 BlackDeltaCalculator bdc(optionType, dt, spot, domDiscount, forDiscount, stddev);
35 lastResult = result;
36 result = bdc.strikeFromDelta(delta);
37 } catch (const std::exception& e) {
38 QL_FAIL("getStrikeFromDelta("
39 << (optionType == Option::Call ? 1.0 : -1.0) * delta << ") could not be computed for spot=" << spot
40 << ", forward=" << spot / domDiscount * forDiscount << " (domRate=" << -std::log(domDiscount) / t
41 << ", forRate=" << -std::log(forDiscount) / t << "), vol=" << stddev / std::sqrt(t)
42 << ", expiry=" << t << ": " << e.what());
43 }
44 } while (std::abs((result - lastResult) / lastResult) > accuracy && ++iterations < maxIterations);
45 QL_REQUIRE(iterations < maxIterations, "getStrikeFromDelta: max iterations ("
46 << maxIterations << "), no solution found for accuracy " << accuracy
47 << ", last iterations: " << lastResult << "/" << result
48 << ", spot=" << spot << ", forward=" << spot / domDiscount * forDiscount
49 << " (domRate=" << -std::log(domDiscount) / t
50 << ", forRate=" << -std::log(forDiscount) / t << "), expiry=" << t);
51
52 return result;
53}
+ Here is the caller graph for this function:

◆ getAtmStrike()

Real getAtmStrike ( DeltaVolQuote::DeltaType  dt,
DeltaVolQuote::AtmType  at,
Real  spot,
Real  domDiscount,
Real  forDiscount,
QuantLib::ext::shared_ptr< BlackVolTermStructure vol,
Real  t,
Real  accuracy,
Size  maxIterations 
)

Definition at line 55 of file blackdeltautilities.cpp.

56 {
57 Real forward = spot / domDiscount * forDiscount;
58 Real result = forward, lastResult;
59 Size iterations = 0;
60 do {
61 Real stddev = std::sqrt(vol->blackVariance(t, result));
62 try {
63 BlackDeltaCalculator bdc(Option::Call, dt, spot, domDiscount, forDiscount, stddev);
64 lastResult = result;
65 result = bdc.atmStrike(at);
66 } catch (const std::exception& e) {
67 QL_FAIL("getAtmStrike() could not be computed for spot="
68 << spot << ", forward=" << spot / domDiscount * forDiscount
69 << " (domRate=" << -std::log(domDiscount) / t << ", forRate=" << -std::log(forDiscount) / t
70 << "), vol=" << stddev / std::sqrt(t) << ", expiry=" << t << ": " << e.what());
71 }
72 } while (std::abs((result - lastResult) / lastResult) > accuracy && ++iterations < maxIterations);
73 QL_REQUIRE(iterations < maxIterations, "getAtmStrike: max iterations ("
74 << maxIterations << "), no solution found for accuracy " << accuracy
75 << ", last iterations: " << lastResult << "/" << result
76 << ", spot=" << spot << ", forward=" << spot / domDiscount * forDiscount
77 << " (domRate=" << -std::log(domDiscount) / t
78 << ", forRate=" << -std::log(forDiscount) / t << "), expiry=" << t);
79 return result;
80}
+ Here is the caller graph for this function:

◆ operator<<() [11/16]

std::ostream & operator<< ( ostream &  out,
CapFloorHelper::Type  type 
)

In order to convert CapFloorHelper::Type to string.

Definition at line 180 of file capfloorhelper.cpp.

180 {
181 switch (type) {
182 case CapFloorHelper::Cap:
183 return out << "Cap";
184 case CapFloorHelper::Floor:
185 return out << "Floor";
186 case CapFloorHelper::Automatic:
187 return out << "Automatic";
188 default:
189 QL_FAIL("Unknown CapFloorHelper::Type (" << Integer(type) << ")");
190 }
191}

◆ operator<<() [12/16]

std::ostream & operator<< ( ostream &  out,
CapFloorHelper::QuoteType  type 
)

In order to convert CapFloorHelper::QuoteType to string.

Definition at line 193 of file capfloorhelper.cpp.

193 {
194 switch (type) {
195 case CapFloorHelper::Volatility:
196 return out << "Volatility";
197 case CapFloorHelper::Premium:
198 return out << "Premium";
199 default:
200 QL_FAIL("Unknown CapFloorHelper::QuoteType (" << Integer(type) << ")");
201 }
202}

◆ operator<<() [13/16]

std::ostream & operator<< ( ostream &  out,
CapFloorTermVolSurfaceExact::InterpolationMethod  method 
)

In order to convert CapFloorTermVolSurface::InterpolationMethod to string.

Definition at line 180 of file capfloortermvolsurface.cpp.

180 {
181 switch (method) {
182 case CapFloorTermVolSurfaceExact::BicubicSpline:
183 return out << "BicubicSpline";
184 case CapFloorTermVolSurfaceExact::Bilinear:
185 return out << "Bilinear";
186 default:
187 QL_FAIL("Unknown CapFloorTermVolSurface::InterpolationMethod (" << Integer(method) << ")");
188 }
189}
+ Here is the call graph for this function:

◆ operator<<() [14/16]

std::ostream & operator<< ( std::ostream &  out,
const Stickyness t 
)

Definition at line 46 of file dynamicstype.hpp.

46 {
47 switch (t) {
48 case StickyStrike:
49 return out << "StickyStrike";
51 return out << "StickyLogMoneyness";
53 return out << "StickyAbsoluteMoneyness";
54 default:
55 return out << "Unknown stickiness type (" << t << ")";
56 }
57}
@ StickyLogMoneyness
@ StickyAbsoluteMoneyness

◆ operator<<() [15/16]

std::ostream & operator<< ( std::ostream &  out,
const ReactionToTimeDecay t 
)

Definition at line 59 of file dynamicstype.hpp.

59 {
60 switch (t) {
62 return out << "ConstantVariance";
64 return out << "ForwardForwardVariance";
65 default:
66 return out << "Unknown reaction to time decay type (" << t << ")";
67 }
68}
@ ConstantVariance
@ ForwardForwardVariance

◆ operator<<() [16/16]

std::ostream & operator<< ( std::ostream &  out,
const YieldCurveRollDown t 
)

Definition at line 70 of file dynamicstype.hpp.

70 {
71 switch (t) {
73 return out << "ConstantDiscounts";
74 case ForwardForward:
75 return out << "ForwardForward";
76 default:
77 return out << "Unknown yield curve roll down type (" << t << ")";
78 }
79}
@ ConstantDiscounts

◆ getImmDate()

Date getImmDate ( Date  asof,
Size  i 
)

Definition at line 26 of file immfraratehelper.cpp.

26 {
27 Date imm = asof;
28 for (Size j = 0; j < i; j++) {
29 imm = IMM::nextDate(imm, true);
30 }
31 return imm;
32}
+ Here is the caller graph for this function:

◆ operator<() [4/4]

Definition at line 108 of file parametricvolatility.cpp.

108 {
109 if (s.timeToExpiry < t.timeToExpiry)
110 return true;
111 if (s.timeToExpiry > t.timeToExpiry)
112 return false;
114 return true;
116 return false;
117 return false;
118}

◆ getOisAtmLevel()

Real getOisAtmLevel ( const QuantLib::ext::shared_ptr< OvernightIndex > &  on,
const Date &  fixingDate,
const Period &  rateComputationPeriod 
)

Utility function for calculating the atm strike level to a given fixingDate based on a given ois index, on, and a given irate computation period, rateComputationPeriod.

Definition at line 29 of file cashflows.cpp.

30 {
31 Date today = Settings::instance().evaluationDate();
32 Date start = on->valueDate(fixingDate);
33 Date end = on->fixingCalendar().advance(start, rateComputationPeriod);
34 Date adjStart = std::max(start, today);
35 Date adjEnd = std::max(adjStart + 1, end);
36 OvernightIndexedCoupon cpn(end, 1.0, adjStart, adjEnd, on);
37 cpn.setPricer(QuantLib::ext::make_shared<OvernightIndexedCouponPricer>());
38 return cpn.rate();
39}

◆ getBMAAtmLevel()

Real getBMAAtmLevel ( const QuantLib::ext::shared_ptr< BMAIndex > &  bma,
const Date &  fixingDate,
const Period &  rateComputationPeriod 
)

Utility function for calculating the atm strike level to a given fixingDate based on a given BMA index, on, and a given irate computation period, rateComputationPeriod.

Definition at line 41 of file cashflows.cpp.

42 {
43 Date today = Settings::instance().evaluationDate();
44 Date start = bma->fixingCalendar().advance(fixingDate, 1 * Days);
45 Date end = bma->fixingCalendar().advance(start, rateComputationPeriod);
46 Date adjStart = std::max(start, today);
47 Date adjEnd = std::max(adjStart + 1, end);
48 AverageBMACoupon cpn(end, 1.0, adjStart, adjEnd, bma);
49 return cpn.rate();
50}

◆ makeCommodityCashflowForBasisFuture()

QuantLib::ext::shared_ptr< CashFlow > makeCommodityCashflowForBasisFuture ( const QuantLib::Date &  start,
const QuantLib::Date &  end,
const QuantLib::ext::shared_ptr< CommodityIndex > &  baseIndex,
const QuantLib::ext::shared_ptr< FutureExpiryCalculator > &  baseFec,
bool  baseIsAveraging,
const QuantLib::Date &  paymentDate 
)

Make a commodity indexed cashflow.

Definition at line 7 of file commodity.cpp.

10 {
11 if (baseIsAveraging == true) {
12 return QuantLib::ext::make_shared<CommodityIndexedAverageCashFlow>(
13 1.0, start, end, paymentDate, baseIndex, QuantLib::Calendar(), 0.0, 1.0, true, 0, 0, baseFec);
14 } else {
15 return QuantLib::ext::make_shared<CommodityIndexedCashFlow>(
16 1.0, start, end, baseIndex, 0, QuantLib::NullCalendar(), QuantLib::Unadjusted, 0,
17 QuantLib::NullCalendar(), 0.0, 1.0, CommodityIndexedCashFlow::PaymentTiming::InArrears, true, true, true, 0,
18 baseFec, paymentDate);
19 }
20}
+ Here is the caller graph for this function:

◆ inflationTime() [1/2]

Time inflationTime ( const Date &  date,
const QuantLib::ext::shared_ptr< InflationTermStructure > &  inflationTs,
bool  indexIsInterpolated,
const DayCounter &  dayCounter 
)

Definition at line 61 of file inflation.cpp.

64 {
65
66 DayCounter dc = inflationTs->dayCounter();
67 if (dayCounter != DayCounter())
68 dc = dayCounter;
69
70 return inflationYearFraction(inflationTs->frequency(), indexIsInterpolated,
71 dc, inflationTs->baseDate(), date);
72}
+ Here is the caller graph for this function:

◆ inflationGrowth() [3/6]

Real inflationGrowth ( const Handle< ZeroInflationTermStructure > &  ts,
Time  t,
const DayCounter &  dc,
bool  indexIsInterpolated 
)

Definition at line 74 of file inflation.cpp.

74 {
75 auto lag = inflationTime(ts->referenceDate(), *ts, indexIsInterpolated, dc);
76 return pow(1.0 + ts->zeroRate(t - lag), t);
77}
Time inflationTime(const Date &date, const QuantLib::ext::shared_ptr< InflationTermStructure > &inflationTs, bool indexIsInterpolated, const DayCounter &dayCounter)
Definition: inflation.cpp:61
+ Here is the call graph for this function:

◆ inflationGrowth() [4/6]

Real inflationGrowth ( const Handle< ZeroInflationTermStructure > &  ts,
Time  t,
bool  indexIsInterpolated 
)

Definition at line 79 of file inflation.cpp.

79 {
80 return inflationGrowth(ts, t, ts->dayCounter(), indexIsInterpolated);
81}
+ Here is the call graph for this function:

◆ inflationLinkedBondQuoteFactor()

QuantLib::Real inflationLinkedBondQuoteFactor ( const QuantLib::ext::shared_ptr< QuantLib::Bond > &  bond)

Calculate the Compound Factor to compute the nominal price from the real price I(t_s)/I(t_0) with I(t_s) the CPI at settlement date and I(t_0) the bond's base CPI

Definition at line 83 of file inflation.cpp.

83 {
84 QuantLib::Real inflFactor = 1;
85 for (auto& cf : bond->cashflows()) {
86 if (auto inflCpn = QuantLib::ext::dynamic_pointer_cast<QuantLib::CPICoupon>(cf)) {
87 const auto& inflationIndex = QuantLib::ext::dynamic_pointer_cast<QuantLib::ZeroInflationIndex>(inflCpn->index());
88 Date settlementDate = bond->settlementDate();
89 std::pair<Date, Date> currentInflationPeriod = inflationPeriod(settlementDate, inflationIndex->frequency());
90 std::pair<Date, Date> settlementFixingPeriod = inflationPeriod(settlementDate - inflCpn->observationLag(), inflationIndex->frequency());
91 Date curveBaseDate = settlementFixingPeriod.first;
92 //Date curveBaseDate = inflationIndex->zeroInflationTermStructure()->baseDate();
93 Real todaysCPI = inflationIndex->fixing(curveBaseDate);
94 if (inflCpn->observationInterpolation() == QuantLib::CPI::Linear) {
95
96 std::pair<Date, Date> observationPeriod = inflationPeriod(curveBaseDate, inflationIndex->frequency());
97
98 Real indexStart = inflationIndex->fixing(observationPeriod.first);
99 Real indexEnd = inflationIndex->fixing(observationPeriod.second + 1 * QuantLib::Days);
100
101 todaysCPI = indexStart + (settlementDate - currentInflationPeriod.first) *
102 (indexEnd - indexStart) /
103 (Real)(currentInflationPeriod.second - currentInflationPeriod.first);
104 }
105 QuantLib::Rate baseCPI = inflCpn->baseCPI();
106 if (baseCPI == QuantLib::Null<QuantLib::Rate>()) {
107 baseCPI =
108 QuantLib::CPI::laggedFixing(inflCpn->cpiIndex(), inflCpn->baseDate() + inflCpn->observationLag(),
109 inflCpn->observationLag(),
110 inflCpn->observationInterpolation());
111 }
112 inflFactor = todaysCPI / baseCPI;
113 break;
114 }
115 }
116 return inflFactor;
117}
+ Here is the caller graph for this function:

◆ addInflationIndexToMap()

void addInflationIndexToMap ( std::map< std::tuple< std::string, QuantLib::CPI::InterpolationType, QuantLib::Frequency, QuantLib::Period >, QuantLib::ext::shared_ptr< QuantLib::ZeroInflationIndex > > &  inflationIndices,
const QuantLib::ext::shared_ptr< QuantLib::Index > &  index,
QuantLib::CPI::InterpolationType  interpolation,
Frequency  couponFrequency,
Period  observationLag 
)

Definition at line 119 of file inflation.cpp.

123 {
124 if (index != nullptr) {
125 const auto zInfIndex = QuantLib::ext::dynamic_pointer_cast<QuantLib::ZeroInflationIndex>(index);
126 std::string name = index->name();
127 const auto key = std::make_tuple(name, interpolation, couponFrequency, observationLag);
128 if (zInfIndex != nullptr && inflationIndices.count(key) == 0) {
129 inflationIndices[key] = zInfIndex;
130 }
131 }
132};
+ Here is the caller graph for this function:

◆ extractAllInflationUnderlyingFromBond()

std::map< std::tuple< std::string, QuantLib::CPI::InterpolationType, QuantLib::Frequency, QuantLib::Period >, QuantLib::ext::shared_ptr< QuantLib::ZeroInflationIndex > > extractAllInflationUnderlyingFromBond ( const QuantLib::ext::shared_ptr< QuantLib::Bond > &  bond)

Iterates over all bond cashflows, and extract all inflation underlyings

Definition at line 136 of file inflation.cpp.

136 {
137
138 std::map<std::tuple<std::string, QuantLib::CPI::InterpolationType, Frequency, Period>,
139 QuantLib::ext::shared_ptr<QuantLib::ZeroInflationIndex>>
140 inflationIndices;
141 if (bond != nullptr) {
142 for (const auto& cf : bond->cashflows()) {
143 if (auto cp = QuantLib::ext::dynamic_pointer_cast<QuantLib::CPICoupon>(cf)) {
144 addInflationIndexToMap(inflationIndices, cp->index(), cp->observationInterpolation(),
145 cp->index()->frequency(), cp->observationLag());
146 } else if (auto cp = QuantLib::ext::dynamic_pointer_cast<QuantLib::CPICashFlow>(cf)) {
147 addInflationIndexToMap(inflationIndices, cp->index(), cp->interpolation(), cp->frequency(),
148 cp->observationLag());
149 }
150 }
151 }
152 return inflationIndices;
153}
void addInflationIndexToMap(std::map< std::tuple< std::string, QuantLib::CPI::InterpolationType, QuantLib::Frequency, QuantLib::Period >, QuantLib::ext::shared_ptr< QuantLib::ZeroInflationIndex > > &inflationIndices, const QuantLib::ext::shared_ptr< QuantLib::Index > &index, QuantLib::CPI::InterpolationType interpolation, Frequency couponFrequency, Period observationLag)
Definition: inflation.cpp:119
+ Here is the call graph for this function:

◆ inflationTime() [2/2]

QuantLib::Time inflationTime ( const QuantLib::Date &  date,
const QuantLib::ext::shared_ptr< QuantLib::InflationTermStructure > &  inflationTs,
bool  indexIsInterpolated,
const QuantLib::DayCounter &  dayCounter = QuantLib::DayCounter() 
)

Utility function for calculating the time to a given date based on a given inflation index, inflationIndex, and a given inflation term structure, inflationTs. An optional dayCounter can be provided to use instead of the inflation term structure day counter.

◆ inflationGrowth() [5/6]

QuantLib::Real inflationGrowth ( const QuantLib::Handle< QuantLib::ZeroInflationTermStructure > &  ts,
QuantLib::Time  t,
const QuantLib::DayCounter &  dc,
bool  indexIsInterpolated 
)

Utility for calculating the ratio \( \frac{P_r(0, t)}{P_n(0, t)} \) where \( P_r(0, t) \) is the real zero coupon bond price at time zero for maturity \( t \) and \( P_n(0, t) \) is the nominal zero coupon bond price.

◆ inflationGrowth() [6/6]

QuantLib::Real inflationGrowth ( const QuantLib::Handle< QuantLib::ZeroInflationTermStructure > &  ts,
QuantLib::Time  t,
bool  indexIsInterpolated 
)

Utility for calculating the ratio \( \frac{P_r(0, t)}{P_n(0, t)} \) where \( P_r(0, t) \) is the real zero coupon bond price at time zero for maturity \( t \) and \( P_n(0, t) \) is the nominal zero coupon bond price.

◆ interpolationIndices()

std::tuple< Size, Size, Real > interpolationIndices ( const T &  x,
const Real  v 
)

Given a non-empty container x of distinct and sorted values and a value v return a tuple (m,p,w) s.t. w * y[m] + (1-w) * y[p] linearly interpolates between points (x[0], y[0]), ..., (x[n], y[n]) and extrapolates flat at x = v. It is m = p if and only if v <= x[0] or v >= x[n]. In this case we have w = 1 and either m = p = 0 (if v <= [0]) or m = p = n (if v >= x[n]).

Definition at line 34 of file interpolation.hpp.

34 {
35 QL_REQUIRE(!x.empty(), "interpolationIndices(x," << v << "): empty x");
36 if (x.size() == 1)
37 return std::make_tuple(0, 0, 1.0);
38 if (v < x.front() || QuantLib::close_enough(v, x.front()))
39 return std::make_tuple(0, 0, 1.0);
40 if (v > x.back() || QuantLib::close_enough(v, x.back()))
41 return std::make_tuple(x.size() - 1, x.size() - 1, 1.0);
42 Size index = std::distance(x.begin(), std::upper_bound(x.begin(), x.end(), v, [](Real x1, Real x2) {
43 return x1 < x2 && !QuantLib::close_enough(x1, x2);
44 }));
45 return std::make_tuple(index - 1, index, (x[index] - v) / (x[index] - x[index - 1]));
46}
+ Here is the caller graph for this function:

◆ periodToTime() [1/2]

Real periodToTime ( const Period &  p)

Definition at line 37 of file time.cpp.

37 {
38 switch (p.units()) {
39 case Days:
40 return static_cast<Real>(p.length()) / 365.25;
41 case Weeks:
42 return static_cast<Real>(p.length()) * 7.0 / 365.25;
43 case Months:
44 return static_cast<Real>(p.length()) / 12.0;
45 case Years:
46 return static_cast<Real>(p.length());
47 default:
48 QL_FAIL("periodToTime(): time unit (" << p.units() << ") not handled");
49 }
50}
+ Here is the caller graph for this function:

◆ implyIndexTerm() [1/2]

QuantLib::Period implyIndexTerm ( const Date &  startDate,
const Date &  endDate 
)

Definition at line 52 of file time.cpp.

52 {
53 static const std::vector<Period> eligibleTerms = {5 * Years, 7 * Years, 10 * Years, 3 * Years, 1 * Years,
54 2 * Years, 4 * Years, 6 * Years, 8 * Years, 9 * Years};
55 static const int gracePeriod = 15;
56
57 for (auto const& p : eligibleTerms) {
58 if (std::abs(cdsMaturity(startDate, p, DateGeneration::CDS2015) - endDate) < gracePeriod) {
59 return p;
60 }
61 }
62
63 return 0 * Days;
64}

◆ lowerDate() [1/2]

QuantLib::Date lowerDate ( const Real  t,
const QuantLib::Date &  refDate,
const QuantLib::DayCounter &  dc 
)

Definition at line 66 of file time.cpp.

66 {
67 if (close_enough(t, 0.0))
68 return refDate;
69 QL_REQUIRE(t > 0.0, "lowerDate(" << t << "," << refDate << "," << dc.name()
70 << ") was called with negative time, this is not allowed.");
71 bool done = false;
72 Date d = refDate + static_cast<int>(t * 365.25);
73 Real tmp = dc.yearFraction(refDate, d);
74 Size attempts = 0;
75 while ((tmp < t || close_enough(tmp, t)) && (++attempts < 10000)) {
76 ++d;
77 tmp = dc.yearFraction(refDate, d);
78 done = true;
79 }
80 QL_REQUIRE(attempts < 10000, "lowerDate(" << t << "," << refDate << "," << dc.name() << ") could not be computed.");
81 if (done)
82 return --d;
83 while ((tmp > t && !close_enough(tmp, t)) && (++attempts < 10000)) {
84 --d;
85 tmp = dc.yearFraction(refDate, d);
86 done = true;
87 }
88 QL_REQUIRE(attempts < 10000, "lowerDate(" << t << "," << refDate << "," << dc.name() << ") could not be computed.");
89 if (done)
90 return d;
91 QL_FAIL("lowerDate(" << t << "," << refDate << "," << dc.name() << ") could not be computed.");
92}
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ tenorFromLength()

QuantLib::Period tenorFromLength ( const QuantLib::Real  length)

Definition at line 94 of file time.cpp.

94 {
95 if (std::abs(length - std::round(length)) < 1.0 / 365.25)
96 return std::lround(length) * Years;
97 if (std::abs(length * 12.0 - std::round(length * 12.0)) < 12.0 / 365.25)
98 return std::lround(length * 12.0) * Months;
99 return std::lround(length * 365.25) * Days;
100}

◆ daylightSavingCorrection()

QuantLib::Integer daylightSavingCorrection ( const std::string &  location,
const QuantLib::Date &  start,
const QuantLib::Date &  end 
)

Definition at line 102 of file time.cpp.

103 {
104 Integer result = 0;
105 if (location == "Null") {
106 result = 0;
107 } else if (location == "US") {
108 for (Integer y = start.year(); y <= end.year(); ++y) {
109 Date d1 = Date::nthWeekday(2, Sunday, March, y);
110 Date d2 = Date::nthWeekday(1, Sunday, November, y);
111 if (start <= d1 && end > d1)
112 --result;
113 if (start <= d2 && end > d2)
114 ++result;
115 }
116 } else {
117 QL_FAIL("daylightSavings(" << location << ") not supported. Contact dev to add support for this location.");
118 }
119 return result;
120}

◆ periodToTime() [2/2]

QuantLib::Real periodToTime ( const QuantLib::Period &  p)

◆ implyIndexTerm() [2/2]

QuantLib::Period implyIndexTerm ( const QuantLib::Date &  startDate,
const QuantLib::Date &  endDate 
)

Imply cds index term from start and end date. If no reasonable term can be implied, 0 * Days is returned

◆ lowerDate() [2/2]

QuantLib::Date lowerDate ( const QuantLib::Real  t,
const QuantLib::Date &  refDate,
const QuantLib::DayCounter &  dc 
)