idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
146,500
public static double blackScholesOptionRho ( double initialStockValue , double riskFreeRate , double volatility , double optionMaturity , double optionStrike ) { if ( optionStrike <= 0.0 || optionMaturity <= 0.0 ) { // The Black-Scholes model does not consider it being an option return 0.0 ; } else { // Calculate rho double dMinus = ( Math . log ( initialStockValue / optionStrike ) + ( riskFreeRate - 0.5 * volatility * volatility ) * optionMaturity ) / ( volatility * Math . sqrt ( optionMaturity ) ) ; double rho = optionStrike * optionMaturity * Math . exp ( - riskFreeRate * optionMaturity ) * NormalDistribution . cumulativeDistribution ( dMinus ) ; return rho ; } }
This static method calculated the rho of a call option under a Black - Scholes model
173
18
146,501
public static double blackScholesDigitalOptionValue ( double initialStockValue , double riskFreeRate , double volatility , double optionMaturity , double optionStrike ) { if ( optionStrike <= 0.0 ) { // The Black-Scholes model does not consider it being an option return 1.0 ; } else { // Calculate analytic value double dPlus = ( Math . log ( initialStockValue / optionStrike ) + ( riskFreeRate + 0.5 * volatility * volatility ) * optionMaturity ) / ( volatility * Math . sqrt ( optionMaturity ) ) ; double dMinus = dPlus - volatility * Math . sqrt ( optionMaturity ) ; double valueAnalytic = Math . exp ( - riskFreeRate * optionMaturity ) * NormalDistribution . cumulativeDistribution ( dMinus ) ; return valueAnalytic ; } }
Calculates the Black - Scholes option value of a digital call option .
179
16
146,502
public static double blackScholesDigitalOptionDelta ( double initialStockValue , double riskFreeRate , double volatility , double optionMaturity , double optionStrike ) { if ( optionStrike <= 0.0 || optionMaturity <= 0.0 ) { // The Black-Scholes model does not consider it being an option return 0.0 ; } else { // Calculate delta double dPlus = ( Math . log ( initialStockValue / optionStrike ) + ( riskFreeRate + 0.5 * volatility * volatility ) * optionMaturity ) / ( volatility * Math . sqrt ( optionMaturity ) ) ; double dMinus = dPlus - volatility * Math . sqrt ( optionMaturity ) ; double delta = Math . exp ( - 0.5 * dMinus * dMinus ) / ( Math . sqrt ( 2.0 * Math . PI * optionMaturity ) * initialStockValue * volatility ) ; return delta ; } }
Calculates the delta of a digital option under a Black - Scholes model
199
16
146,503
public static double blackScholesDigitalOptionVega ( double initialStockValue , double riskFreeRate , double volatility , double optionMaturity , double optionStrike ) { if ( optionStrike <= 0.0 || optionMaturity <= 0.0 ) { // The Black-Scholes model does not consider it being an option return 0.0 ; } else { // Calculate vega double dPlus = ( Math . log ( initialStockValue / optionStrike ) + ( riskFreeRate + 0.5 * volatility * volatility ) * optionMaturity ) / ( volatility * Math . sqrt ( optionMaturity ) ) ; double dMinus = dPlus - volatility * Math . sqrt ( optionMaturity ) ; double vega = - Math . exp ( - riskFreeRate * optionMaturity ) * Math . exp ( - 0.5 * dMinus * dMinus ) / Math . sqrt ( 2.0 * Math . PI ) * dPlus / volatility ; return vega ; } }
Calculates the vega of a digital option under a Black - Scholes model
211
17
146,504
public static double blackScholesDigitalOptionRho ( double initialStockValue , double riskFreeRate , double volatility , double optionMaturity , double optionStrike ) { if ( optionMaturity <= 0.0 ) { // The Black-Scholes model does not consider it being an option return 0.0 ; } else if ( optionStrike <= 0.0 ) { double rho = - optionMaturity * Math . exp ( - riskFreeRate * optionMaturity ) ; return rho ; } else { // Calculate rho double dMinus = ( Math . log ( initialStockValue / optionStrike ) + ( riskFreeRate - 0.5 * volatility * volatility ) * optionMaturity ) / ( volatility * Math . sqrt ( optionMaturity ) ) ; double rho = - optionMaturity * Math . exp ( - riskFreeRate * optionMaturity ) * NormalDistribution . cumulativeDistribution ( dMinus ) + Math . sqrt ( optionMaturity ) / volatility * Math . exp ( - riskFreeRate * optionMaturity ) * Math . exp ( - 0.5 * dMinus * dMinus ) / Math . sqrt ( 2.0 * Math . PI ) ; return rho ; } }
Calculates the rho of a digital option under a Black - Scholes model
262
17
146,505
public static double blackModelCapletValue ( double forward , double volatility , double optionMaturity , double optionStrike , double periodLength , double discountFactor ) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas . blackScholesGeneralizedOptionValue ( forward , volatility , optionMaturity , optionStrike , periodLength * discountFactor ) ; }
Calculate the value of a caplet assuming the Black 76 model .
81
15
146,506
public static double blackModelDgitialCapletValue ( double forward , double volatility , double periodLength , double discountFactor , double optionMaturity , double optionStrike ) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas . blackScholesDigitalOptionValue ( forward , 0.0 , volatility , optionMaturity , optionStrike ) * periodLength * discountFactor ; }
Calculate the value of a digital caplet assuming the Black 76 model .
87
16
146,507
public static double blackModelSwaptionValue ( double forwardSwaprate , double volatility , double optionMaturity , double optionStrike , double swapAnnuity ) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas . blackScholesGeneralizedOptionValue ( forwardSwaprate , volatility , optionMaturity , optionStrike , swapAnnuity ) ; }
Calculate the value of a swaption assuming the Black 76 model .
83
16
146,508
public static double huntKennedyCMSOptionValue ( double forwardSwaprate , double volatility , double swapAnnuity , double optionMaturity , double swapMaturity , double payoffUnit , double optionStrike ) { double a = 1.0 / swapMaturity ; double b = ( payoffUnit / swapAnnuity - a ) / forwardSwaprate ; double convexityAdjustment = Math . exp ( volatility * volatility * optionMaturity ) ; double valueUnadjusted = blackModelSwaptionValue ( forwardSwaprate , volatility , optionMaturity , optionStrike , swapAnnuity ) ; double valueAdjusted = blackModelSwaptionValue ( forwardSwaprate * convexityAdjustment , volatility , optionMaturity , optionStrike , swapAnnuity ) ; return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted ; }
Calculate the value of a CMS option using the Black - Scholes model for the swap rate together with the Hunt - Kennedy convexity adjustment .
181
31
146,509
public static double huntKennedyCMSFloorValue ( double forwardSwaprate , double volatility , double swapAnnuity , double optionMaturity , double swapMaturity , double payoffUnit , double optionStrike ) { double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue ( forwardSwaprate , volatility , swapAnnuity , optionMaturity , swapMaturity , payoffUnit , optionStrike ) ; // A floor is an option plus the strike (max(X,K) = max(X-K,0) + K) return huntKennedyCMSOptionValue + optionStrike * payoffUnit ; }
Calculate the value of a CMS strike using the Black - Scholes model for the swap rate together with the Hunt - Kennedy convexity adjustment .
132
31
146,510
public static double huntKennedyCMSAdjustedRate ( double forwardSwaprate , double volatility , double swapAnnuity , double optionMaturity , double swapMaturity , double payoffUnit ) { double a = 1.0 / swapMaturity ; double b = ( payoffUnit / swapAnnuity - a ) / forwardSwaprate ; double convexityAdjustment = Math . exp ( volatility * volatility * optionMaturity ) ; double rateUnadjusted = forwardSwaprate ; double rateAdjusted = forwardSwaprate * convexityAdjustment ; return ( a * rateUnadjusted + b * forwardSwaprate * rateAdjusted ) * swapAnnuity / payoffUnit ; }
Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit using the Black - Scholes model for the swap rate together with the Hunt - Kennedy convexity adjustment .
145
48
146,511
public static double volatilityConversionLognormalATMtoNormalATM ( double forward , double displacement , double maturity , double lognormalVolatiltiy ) { double x = lognormalVolatiltiy * Math . sqrt ( maturity / 8 ) ; double y = org . apache . commons . math3 . special . Erf . erf ( x ) ; double normalVol = Math . sqrt ( 2 * Math . PI / maturity ) * ( forward + displacement ) * y ; return normalVol ; }
Exact conversion of displaced lognormal ATM volatiltiy to normal ATM volatility .
111
18
146,512
private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor ( Element leg , String forwardCurveName , String discountCurveName , DayCountConvention daycountConvention ) { boolean isFixed = leg . getElementsByTagName ( "interestType" ) . item ( 0 ) . getTextContent ( ) . equalsIgnoreCase ( "FIX" ) ; ArrayList < Period > periods = new ArrayList <> ( ) ; ArrayList < Double > notionalsList = new ArrayList <> ( ) ; ArrayList < Double > rates = new ArrayList <> ( ) ; //extracting data for each period NodeList periodsXML = leg . getElementsByTagName ( "incomePayment" ) ; for ( int periodIndex = 0 ; periodIndex < periodsXML . getLength ( ) ; periodIndex ++ ) { Element periodXML = ( Element ) periodsXML . item ( periodIndex ) ; LocalDate startDate = LocalDate . parse ( periodXML . getElementsByTagName ( "startDate" ) . item ( 0 ) . getTextContent ( ) ) ; LocalDate endDate = LocalDate . parse ( periodXML . getElementsByTagName ( "endDate" ) . item ( 0 ) . getTextContent ( ) ) ; LocalDate fixingDate = startDate ; LocalDate paymentDate = LocalDate . parse ( periodXML . getElementsByTagName ( "payDate" ) . item ( 0 ) . getTextContent ( ) ) ; if ( ! isFixed ) { fixingDate = LocalDate . parse ( periodXML . getElementsByTagName ( "fixingDate" ) . item ( 0 ) . getTextContent ( ) ) ; } periods . add ( new Period ( fixingDate , paymentDate , startDate , endDate ) ) ; double notional = Double . parseDouble ( periodXML . getElementsByTagName ( "nominal" ) . item ( 0 ) . getTextContent ( ) ) ; notionalsList . add ( new Double ( notional ) ) ; if ( isFixed ) { double fixedRate = Double . parseDouble ( periodXML . getElementsByTagName ( "fixedRate" ) . item ( 0 ) . getTextContent ( ) ) ; rates . add ( new Double ( fixedRate ) ) ; } else { rates . add ( new Double ( 0 ) ) ; } } ScheduleDescriptor schedule = new ScheduleDescriptor ( periods , daycountConvention ) ; double [ ] notionals = notionalsList . stream ( ) . mapToDouble ( Double :: doubleValue ) . toArray ( ) ; double [ ] spreads = rates . stream ( ) . mapToDouble ( Double :: doubleValue ) . toArray ( ) ; return new InterestRateSwapLegProductDescriptor ( forwardCurveName , discountCurveName , schedule , notionals , spreads , false ) ; }
Construct an InterestRateSwapLegProductDescriptor from a node in a FIPXML file .
629
22
146,513
private static AbstractIndex constructLiborIndex ( String forwardCurveName , Schedule schedule ) { if ( forwardCurveName != null ) { //determine average fixing offset and period length double fixingOffset = 0 ; double periodLength = 0 ; for ( int i = 0 ; i < schedule . getNumberOfPeriods ( ) ; i ++ ) { fixingOffset *= ( ( double ) i ) / ( i + 1 ) ; fixingOffset += ( schedule . getPeriodStart ( i ) - schedule . getFixing ( i ) ) / ( i + 1 ) ; periodLength *= ( ( double ) i ) / ( i + 1 ) ; periodLength += schedule . getPeriodLength ( i ) / ( i + 1 ) ; } return new LIBORIndex ( forwardCurveName , fixingOffset , periodLength ) ; } else { return null ; } }
Construct a Libor index for a given curve and schedule .
185
12
146,514
public RandomVariable getImpliedBachelierATMOptionVolatility ( RandomVariable optionValue , double optionMaturity , double swapAnnuity ) { return optionValue . average ( ) . mult ( Math . sqrt ( 2.0 * Math . PI / optionMaturity ) / swapAnnuity ) ; }
Calculates ATM Bachelier implied volatilities .
65
12
146,515
public RandomVariable [ ] getBasisFunctions ( double fixingDate , LIBORModelMonteCarloSimulationModel model ) throws CalculationException { ArrayList < RandomVariable > basisFunctions = new ArrayList <> ( ) ; // Constant RandomVariable basisFunction = new RandomVariableFromDoubleArray ( 1.0 ) ; //.getRandomVariableForConstant(1.0); basisFunctions . add ( basisFunction ) ; int fixingDateIndex = Arrays . binarySearch ( fixingDates , fixingDate ) ; if ( fixingDateIndex < 0 ) { fixingDateIndex = - fixingDateIndex ; } if ( fixingDateIndex >= fixingDates . length ) { fixingDateIndex = fixingDates . length - 1 ; } // forward rate to the next period RandomVariable rateShort = model . getLIBOR ( fixingDate , fixingDate , paymentDates [ fixingDateIndex ] ) ; RandomVariable discountShort = rateShort . mult ( paymentDates [ fixingDateIndex ] - fixingDate ) . add ( 1.0 ) . invert ( ) ; basisFunctions . add ( discountShort ) ; basisFunctions . add ( discountShort . pow ( 2.0 ) ) ; // basisFunctions.add(rateShort.pow(3.0)); // forward rate to the end of the product RandomVariable rateLong = model . getLIBOR ( fixingDate , fixingDates [ fixingDateIndex ] , paymentDates [ paymentDates . length - 1 ] ) ; RandomVariable discountLong = rateLong . mult ( paymentDates [ paymentDates . length - 1 ] - fixingDates [ fixingDateIndex ] ) . add ( 1.0 ) . invert ( ) ; basisFunctions . add ( discountLong ) ; basisFunctions . add ( discountLong . pow ( 2.0 ) ) ; // basisFunctions.add(rateLong.pow(3.0)); // Numeraire RandomVariable numeraire = model . getNumeraire ( fixingDate ) . invert ( ) ; basisFunctions . add ( numeraire ) ; // basisFunctions.add(numeraire.pow(2.0)); // basisFunctions.add(numeraire.pow(3.0)); return basisFunctions . toArray ( new RandomVariable [ basisFunctions . size ( ) ] ) ; }
Return the basis functions for the regression suitable for this product .
498
12
146,516
private RandomVariableInterface getDrift ( int timeIndex , int componentIndex , RandomVariableInterface [ ] realizationAtTimeIndex , RandomVariableInterface [ ] realizationPredictor ) { // Check if this LIBOR is already fixed if ( getTime ( timeIndex ) >= this . getLiborPeriod ( componentIndex ) ) { return null ; } /* * We implemented several different methods to calculate the drift */ if ( driftApproximationMethod == Driftapproximation . PREDICTOR_CORRECTOR && realizationPredictor != null ) { RandomVariableInterface drift = getDriftEuler ( timeIndex , componentIndex , realizationAtTimeIndex ) ; RandomVariableInterface driftEulerWithPredictor = getDriftEuler ( timeIndex , componentIndex , realizationPredictor ) ; drift = drift . add ( driftEulerWithPredictor ) . div ( 2.0 ) ; return drift ; } else if ( driftApproximationMethod == Driftapproximation . LINE_INTEGRAL && realizationPredictor != null ) { return getDriftLineIntegral ( timeIndex , componentIndex , realizationAtTimeIndex , realizationPredictor ) ; } else { return getDriftEuler ( timeIndex , componentIndex , realizationAtTimeIndex ) ; } }
Alternative implementation for the drift . For experimental purposes .
269
10
146,517
public static double getHaltonNumberForGivenBase ( long index , int base ) { index += 1 ; double x = 0.0 ; double factor = 1.0 / base ; while ( index > 0 ) { x += ( index % base ) * factor ; factor /= base ; index /= base ; } return x ; }
Return a Halton number sequence starting at index = 0 base &gt ; 1 .
70
17
146,518
public Map < Integer , RandomVariable > getGradient ( ) { int numberOfCalculationSteps = getFunctionList ( ) . size ( ) ; RandomVariable [ ] omegaHat = new RandomVariable [ numberOfCalculationSteps ] ; omegaHat [ numberOfCalculationSteps - 1 ] = new RandomVariableFromDoubleArray ( 1.0 ) ; for ( int variableIndex = numberOfCalculationSteps - 2 ; variableIndex >= 0 ; variableIndex -- ) { omegaHat [ variableIndex ] = new RandomVariableFromDoubleArray ( 0.0 ) ; ArrayList < Integer > childrenList = getAADRandomVariableFromList ( variableIndex ) . getChildrenIndices ( ) ; for ( int functionIndex : childrenList ) { RandomVariable D_i_j = getPartialDerivative ( functionIndex , variableIndex ) ; omegaHat [ variableIndex ] = omegaHat [ variableIndex ] . addProduct ( D_i_j , omegaHat [ functionIndex ] ) ; } } ArrayList < Integer > arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables ( ) ; Map < Integer , RandomVariable > gradient = new HashMap < Integer , RandomVariable > ( ) ; for ( Integer indexOfDependentRandomVariable : arrayListOfAllIndicesOfDependentRandomVariables ) { gradient . put ( indexOfDependentRandomVariable , omegaHat [ arrayListOfAllIndicesOfDependentRandomVariables . get ( indexOfDependentRandomVariable ) ] ) ; } return gradient ; }
Implements the AAD Algorithm
335
8
146,519
public double [ ] getZeroRates ( double [ ] maturities ) { double [ ] values = new double [ maturities . length ] ; for ( int i = 0 ; i < maturities . length ; i ++ ) { values [ i ] = getZeroRate ( maturities [ i ] ) ; } return values ; }
Returns the zero rates for a given vector maturities .
73
12
146,520
public static double [ ] [ ] invert ( double [ ] [ ] matrix ) { if ( isSolverUseApacheCommonsMath ) { // Use LU from common math LUDecomposition lu = new LUDecomposition ( new Array2DRowRealMatrix ( matrix ) ) ; double [ ] [ ] matrixInverse = lu . getSolver ( ) . getInverse ( ) . getData ( ) ; return matrixInverse ; } else { return org . jblas . Solve . pinv ( new org . jblas . DoubleMatrix ( matrix ) ) . toArray2 ( ) ; } }
Returns the inverse of a given matrix .
136
8
146,521
public static double [ ] [ ] factorReductionUsingCommonsMath ( double [ ] [ ] correlationMatrix , int numberOfFactors ) { // Extract factors corresponding to the largest eigenvalues double [ ] [ ] factorMatrix = getFactorMatrix ( correlationMatrix , numberOfFactors ) ; // Renormalize rows for ( int row = 0 ; row < correlationMatrix . length ; row ++ ) { double sumSquared = 0 ; for ( int factor = 0 ; factor < numberOfFactors ; factor ++ ) { sumSquared += factorMatrix [ row ] [ factor ] * factorMatrix [ row ] [ factor ] ; } if ( sumSquared != 0 ) { for ( int factor = 0 ; factor < numberOfFactors ; factor ++ ) { factorMatrix [ row ] [ factor ] = factorMatrix [ row ] [ factor ] / Math . sqrt ( sumSquared ) ; } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for ( int factor = 0 ; factor < numberOfFactors ; factor ++ ) { factorMatrix [ row ] [ factor ] = 1.0 ; } } } // Orthogonalized again double [ ] [ ] reducedCorrelationMatrix = ( new Array2DRowRealMatrix ( factorMatrix ) . multiply ( new Array2DRowRealMatrix ( factorMatrix ) . transpose ( ) ) ) . getData ( ) ; return getFactorMatrix ( reducedCorrelationMatrix , numberOfFactors ) ; }
Returns a correlation matrix which has rank &lt ; n and for which the first n factors agree with the factors of correlationMatrix .
316
26
146,522
public static double [ ] [ ] pseudoInverse ( double [ ] [ ] matrix ) { if ( isSolverUseApacheCommonsMath ) { // Use LU from common math SingularValueDecomposition svd = new SingularValueDecomposition ( new Array2DRowRealMatrix ( matrix ) ) ; double [ ] [ ] matrixInverse = svd . getSolver ( ) . getInverse ( ) . getData ( ) ; return matrixInverse ; } else { return org . jblas . Solve . pinv ( new org . jblas . DoubleMatrix ( matrix ) ) . toArray2 ( ) ; } }
Pseudo - Inverse of a matrix calculated in the least square sense .
139
16
146,523
public static double [ ] [ ] diag ( double [ ] vector ) { // Note: According to the Java Language spec, an array is initialized with the default value, here 0. double [ ] [ ] diagonalMatrix = new double [ vector . length ] [ vector . length ] ; for ( int index = 0 ; index < vector . length ; index ++ ) { diagonalMatrix [ index ] [ index ] = vector [ index ] ; } return diagonalMatrix ; }
Generates a diagonal matrix with the input vector on its diagonal
96
12
146,524
private double [ ] formatTargetValuesForOptimizer ( ) { //Put all values in an array for the optimizer. int numberOfMaturities = surface . getMaturities ( ) . length ; double mats [ ] = surface . getMaturities ( ) ; ArrayList < Double > vals = new ArrayList < Double > ( ) ; for ( int t = 0 ; t < numberOfMaturities ; t ++ ) { double mat = mats [ t ] ; double [ ] myStrikes = surface . getSurface ( ) . get ( mat ) . getStrikes ( ) ; OptionSmileData smileOfInterest = surface . getSurface ( ) . get ( mat ) ; for ( int k = 0 ; k < myStrikes . length ; k ++ ) { vals . add ( smileOfInterest . getSmile ( ) . get ( myStrikes [ k ] ) . getValue ( ) ) ; } } Double [ ] targetVals = new Double [ vals . size ( ) ] ; return ArrayUtils . toPrimitive ( vals . toArray ( targetVals ) ) ; }
This is a service method that takes care of putting al the target values in a single array .
241
19
146,525
public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors ( String name , double [ ] times , RandomVariable [ ] givenDiscountFactors , double paymentOffset ) { ForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation ( name , paymentOffset , InterpolationEntityForward . FORWARD , null ) ; if ( times . length == 0 ) { throw new IllegalArgumentException ( "Vector of times must not be empty." ) ; } if ( times [ 0 ] > 0 ) { // Add first forward RandomVariable forward = givenDiscountFactors [ 0 ] . sub ( 1.0 ) . pow ( - 1.0 ) . div ( times [ 0 ] ) ; forwardCurveInterpolation . addForward ( null , 0.0 , forward , true ) ; } for ( int timeIndex = 0 ; timeIndex < times . length - 1 ; timeIndex ++ ) { RandomVariable forward = givenDiscountFactors [ timeIndex ] . div ( givenDiscountFactors [ timeIndex + 1 ] . sub ( 1.0 ) ) . div ( times [ timeIndex + 1 ] - times [ timeIndex ] ) ; double fixingTime = times [ timeIndex ] ; boolean isParameter = ( fixingTime > 0 ) ; forwardCurveInterpolation . addForward ( null , fixingTime , forward , isParameter ) ; } return forwardCurveInterpolation ; }
Create a forward curve from given times and discount factors .
306
11
146,526
public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel ( String name , LIBORModelMonteCarloSimulationModel model , double startTime ) throws CalculationException { int timeIndex = model . getTimeIndex ( startTime ) ; // Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves ArrayList < RandomVariable > liborsAtTimeIndex = new ArrayList <> ( ) ; int firstLiborIndex = model . getLiborPeriodDiscretization ( ) . getTimeIndexNearestGreaterOrEqual ( startTime ) ; double firstLiborTime = model . getLiborPeriodDiscretization ( ) . getTime ( firstLiborIndex ) ; if ( firstLiborTime > startTime ) { liborsAtTimeIndex . add ( model . getLIBOR ( startTime , startTime , firstLiborTime ) ) ; } // Vector of times for the forward curve double [ ] times = new double [ firstLiborTime == startTime ? ( model . getNumberOfLibors ( ) - firstLiborIndex ) : ( model . getNumberOfLibors ( ) - firstLiborIndex + 1 ) ] ; times [ 0 ] = 0 ; int indexOffset = firstLiborTime == startTime ? 0 : 1 ; for ( int i = firstLiborIndex ; i < model . getNumberOfLibors ( ) ; i ++ ) { liborsAtTimeIndex . add ( model . getLIBOR ( timeIndex , i ) ) ; times [ i - firstLiborIndex + indexOffset ] = model . getLiborPeriodDiscretization ( ) . getTime ( i ) - startTime ; } RandomVariable [ ] libors = liborsAtTimeIndex . toArray ( new RandomVariable [ liborsAtTimeIndex . size ( ) ] ) ; return ForwardCurveInterpolation . createForwardCurveFromForwards ( name , times , libors , model . getLiborPeriodDiscretization ( ) . getTimeStep ( firstLiborIndex ) ) ; }
Create a forward curve from forwards given by a LIBORMonteCarloModel .
458
17
146,527
private void addForward ( AnalyticModel model , double fixingTime , RandomVariable forward , boolean isParameter ) { double interpolationEntitiyTime ; RandomVariable interpolationEntityForwardValue ; switch ( interpolationEntityForward ) { case FORWARD : default : interpolationEntitiyTime = fixingTime ; interpolationEntityForwardValue = forward ; break ; case FORWARD_TIMES_DISCOUNTFACTOR : interpolationEntitiyTime = fixingTime ; interpolationEntityForwardValue = forward . mult ( model . getDiscountCurve ( getDiscountCurveName ( ) ) . getValue ( model , fixingTime + getPaymentOffset ( fixingTime ) ) ) ; break ; case ZERO : { double paymentOffset = getPaymentOffset ( fixingTime ) ; interpolationEntitiyTime = fixingTime + paymentOffset ; interpolationEntityForwardValue = forward . mult ( paymentOffset ) . add ( 1.0 ) . log ( ) . div ( paymentOffset ) ; break ; } case DISCOUNTFACTOR : { double paymentOffset = getPaymentOffset ( fixingTime ) ; interpolationEntitiyTime = fixingTime + paymentOffset ; interpolationEntityForwardValue = getValue ( fixingTime ) . div ( forward . mult ( paymentOffset ) . add ( 1.0 ) ) ; break ; } } super . addPoint ( interpolationEntitiyTime , interpolationEntityForwardValue , isParameter ) ; }
Add a forward to this curve .
305
7
146,528
public LinearInterpolatedTimeDiscreteProcess add ( LinearInterpolatedTimeDiscreteProcess process ) throws CalculationException { Map < Double , RandomVariable > sum = new HashMap <> ( ) ; for ( double time : timeDiscretization ) { sum . put ( time , realizations . get ( time ) . add ( process . getProcessValue ( time , 0 ) ) ) ; } return new LinearInterpolatedTimeDiscreteProcess ( timeDiscretization , sum ) ; }
Create a new linear interpolated time discrete process by using the time discretization of this process and the sum of this process and the given one as its values .
104
33
146,529
public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues ( List < RandomVariable > newTargetVaues , List < RandomVariable > newWeights , boolean isUseBestParametersAsInitialParameters ) throws CloneNotSupportedException { StochasticPathwiseLevenbergMarquardt clonedOptimizer = clone ( ) ; clonedOptimizer . targetValues = numberListToDoubleArray ( newTargetVaues ) ; clonedOptimizer . weights = numberListToDoubleArray ( newWeights ) ; if ( isUseBestParametersAsInitialParameters && this . done ( ) ) { clonedOptimizer . initialParameters = this . getBestFitParameters ( ) ; } return clonedOptimizer ; }
Create a clone of this LevenbergMarquardt optimizer with a new vector for the target values and weights .
164
25
146,530
private DiscountCurve createDiscountCurve ( String discountCurveName ) { DiscountCurve discountCurve = model . getDiscountCurve ( discountCurveName ) ; if ( discountCurve == null ) { discountCurve = DiscountCurveInterpolation . createDiscountCurveFromDiscountFactors ( discountCurveName , new double [ ] { 0.0 } , new double [ ] { 1.0 } ) ; model = model . addCurves ( discountCurve ) ; } return discountCurve ; }
Get a discount curve from the model if not existing create a discount curve .
115
15
146,531
public double d ( double x ) { int intervalNumber = getIntervalNumber ( x ) ; if ( intervalNumber == 0 || intervalNumber == points . length ) { return x ; } return getIntervalReferencePoint ( intervalNumber - 1 ) ; }
If a given x is into an interval of the partition this method returns the reference point of the corresponding interval . If the given x is not contained in any interval of the partition this method returns x .
53
40
146,532
public double getValue ( ForwardCurveInterface forwardCurve , double swaprateVolatility ) { double swaprate = swaprates [ 0 ] ; for ( double swaprate1 : swaprates ) { if ( swaprate1 != swaprate ) { throw new RuntimeException ( "Uneven swaprates not allows for analytical pricing." ) ; } } double [ ] swapTenor = new double [ fixingDates . length + 1 ] ; System . arraycopy ( fixingDates , 0 , swapTenor , 0 , fixingDates . length ) ; swapTenor [ swapTenor . length - 1 ] = paymentDates [ paymentDates . length - 1 ] ; double forwardSwapRate = Swap . getForwardSwapRate ( new TimeDiscretization ( swapTenor ) , new TimeDiscretization ( swapTenor ) , forwardCurve ) ; double swapAnnuity = SwapAnnuity . getSwapAnnuity ( new TimeDiscretization ( swapTenor ) , forwardCurve ) ; return AnalyticFormulas . blackModelSwaptionValue ( forwardSwapRate , swaprateVolatility , exerciseDate , swaprate , swapAnnuity ) ; }
This method returns the value of the product using a Black - Scholes model for the swap rate The model is determined by a discount factor curve and a swap rate volatility .
248
34
146,533
public double getRate ( AnalyticModel model ) { if ( model == null ) { throw new IllegalArgumentException ( "model==null" ) ; } ForwardCurve forwardCurve = model . getForwardCurve ( forwardCurveName ) ; if ( forwardCurve == null ) { throw new IllegalArgumentException ( "No forward curve of name '" + forwardCurveName + "' found in given model:\n" + model . toString ( ) ) ; } double fixingDate = schedule . getFixing ( 0 ) ; return forwardCurve . getForward ( model , fixingDate ) ; }
Return the par FRA rate for a given curve .
129
11
146,534
public RandomVariable [ ] getParameter ( ) { double [ ] parameterAsDouble = this . getParameterAsDouble ( ) ; RandomVariable [ ] parameter = new RandomVariable [ parameterAsDouble . length ] ; for ( int i = 0 ; i < parameter . length ; i ++ ) { parameter [ i ] = new Scalar ( parameterAsDouble [ i ] ) ; } return parameter ; }
Get the parameters of determining this parametric covariance model . The parameters are usually free parameters which may be used in calibration .
82
25
146,535
public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel ( String forwardCurveName , LIBORModelMonteCarloSimulationModel model , double startTime ) throws CalculationException { // Check if the LMM uses a discount curve which is created from a forward curve if ( model . getModel ( ) . getDiscountCurve ( ) == null || model . getModel ( ) . getDiscountCurve ( ) . getName ( ) . toLowerCase ( ) . contains ( "DiscountCurveFromForwardCurve" . toLowerCase ( ) ) ) { return new DiscountCurveFromForwardCurve ( ForwardCurveInterpolation . createForwardCurveFromMonteCarloLiborModel ( forwardCurveName , model , startTime ) ) ; } else { // i.e. forward curve of Libor Model not OIS. In this case return the OIS curve. // Only at startTime 0! return ( DiscountCurveInterface ) model . getModel ( ) . getDiscountCurve ( ) ; } }
Create a discount curve from forwards given by a LIBORMonteCarloModel . If the model uses multiple curves return its discount curve .
230
28
146,536
public static boolean isEasterSunday ( LocalDate date ) { int y = date . getYear ( ) ; int a = y % 19 ; int b = y / 100 ; int c = y % 100 ; int d = b / 4 ; int e = b % 4 ; int f = ( b + 8 ) / 25 ; int g = ( b - f + 1 ) / 3 ; int h = ( 19 * a + b - d - g + 15 ) % 30 ; int i = c / 4 ; int k = c % 4 ; int l = ( 32 + 2 * e + 2 * i - h - k ) % 7 ; int m = ( a + 11 * h + 22 * l ) / 451 ; int easterSundayMonth = ( h + l - 7 * m + 114 ) / 31 ; int easterSundayDay = ( ( h + l - 7 * m + 114 ) % 31 ) + 1 ; int month = date . getMonthValue ( ) ; int day = date . getDayOfMonth ( ) ; return ( easterSundayMonth == month ) && ( easterSundayDay == day ) ; }
Test a given date for being easter sunday .
240
11
146,537
public static LocalDateTime getDateFromFloatingPointDate ( LocalDateTime referenceDate , double floatingPointDate ) { if ( referenceDate == null ) { return null ; } Duration duration = Duration . ofSeconds ( Math . round ( floatingPointDate * SECONDS_PER_DAY ) ) ; return referenceDate . plus ( duration ) ; }
Convert a floating point date to a LocalDateTime .
74
12
146,538
public static double getFloatingPointDateFromDate ( LocalDateTime referenceDate , LocalDateTime date ) { Duration duration = Duration . between ( referenceDate , date ) ; return ( ( double ) duration . getSeconds ( ) ) / SECONDS_PER_DAY ; }
Convert a given date to a floating point date using a given reference date .
59
16
146,539
public static LocalDate getDateFromFloatingPointDate ( LocalDate referenceDate , double floatingPointDate ) { if ( referenceDate == null ) { return null ; } return referenceDate . plusDays ( ( int ) Math . round ( floatingPointDate * 365.0 ) ) ; }
Convert a floating point date to a LocalDate .
60
11
146,540
public double inverseCumulativeDistribution ( double x ) { double p = Math . exp ( - lambda ) ; double dp = p ; int k = 0 ; while ( x > p ) { k ++ ; dp *= lambda / k ; p += dp ; } return k ; }
Return the inverse cumulative distribution function at x .
63
9
146,541
protected void addPoint ( double time , RandomVariable value , boolean isParameter ) { synchronized ( rationalFunctionInterpolationLazyInitLock ) { if ( interpolationEntity == InterpolationEntity . LOG_OF_VALUE_PER_TIME && time == 0 ) { boolean containsOne = false ; int index = 0 ; for ( int i = 0 ; i < value . size ( ) ; i ++ ) { if ( value . get ( i ) == 1.0 ) { containsOne = true ; index = i ; break ; } } if ( containsOne && isParameter == false ) { return ; } else { throw new IllegalArgumentException ( "The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index" + index + ")." ) ; } } RandomVariable interpolationEntityValue = interpolationEntityFromValue ( value , time ) ; int index = getTimeIndex ( time ) ; if ( index >= 0 ) { if ( points . get ( index ) . value == interpolationEntityValue ) { return ; // Already in list } else if ( isParameter ) { return ; } else { throw new RuntimeException ( "Trying to add a value for a time for which another value already exists." ) ; } } else { // Insert the new point, retain ordering. Point point = new Point ( time , interpolationEntityValue , isParameter ) ; points . add ( - index - 1 , point ) ; if ( isParameter ) { // Add this point also to the list of parameters int parameterIndex = getParameterIndex ( time ) ; if ( parameterIndex >= 0 ) { new RuntimeException ( "CurveFromInterpolationPoints inconsistent." ) ; } pointsBeingParameters . add ( - parameterIndex - 1 , point ) ; } } rationalFunctionInterpolation = null ; curveCacheReference = null ; } }
Add a point to this curveFromInterpolationPoints . The method will throw an exception if the point is already part of the curveFromInterpolationPoints .
403
33
146,542
public static String getOffsetCodeFromSchedule ( Schedule schedule ) { double doubleLength = 0 ; for ( int i = 0 ; i < schedule . getNumberOfPeriods ( ) ; i ++ ) { doubleLength += schedule . getPeriodLength ( i ) ; } doubleLength /= schedule . getNumberOfPeriods ( ) ; doubleLength *= 12 ; int periodLength = ( int ) Math . round ( doubleLength ) ; String offsetCode = periodLength + "M" ; return offsetCode ; }
Determines the offset code of a forward contract from a schedule . Rounds the average period length to full months .
110
23
146,543
public static String getOffsetCodeFromCurveName ( String curveName ) { if ( curveName == null || curveName . length ( ) == 0 ) { return null ; } String [ ] splits = curveName . split ( "(?<=\\D)(?=\\d)" ) ; String offsetCode = splits [ splits . length - 1 ] ; if ( ! Character . isDigit ( offsetCode . charAt ( 0 ) ) ) { return null ; } offsetCode = offsetCode . split ( "(?<=[A-Za-z])(?=.)" , 2 ) [ 0 ] ; offsetCode = offsetCode . replaceAll ( "[\\W_]" , "" ) ; return offsetCode ; }
Determines the offset code of a forward contract from the name of a forward curve . This method will extract a group of one or more digits together with the first letter behind them if any . If there are multiple groups of digits in the name this method will extract the last . If there is no number in the string this method will return null .
152
70
146,544
public ScheduleDescriptor generateScheduleDescriptor ( LocalDate startDate , LocalDate endDate ) { return new ScheduleDescriptor ( startDate , endDate , getFrequency ( ) , getDaycountConvention ( ) , getShortPeriodConvention ( ) , getDateRollConvention ( ) , getBusinessdayCalendar ( ) , getFixingOffsetDays ( ) , getPaymentOffsetDays ( ) , isUseEndOfMonth ( ) ) ; }
Generate a schedule descriptor for the given start and end date .
101
13
146,545
public Schedule generateSchedule ( LocalDate referenceDate , LocalDate startDate , LocalDate endDate ) { return ScheduleGenerator . createScheduleFromConventions ( referenceDate , startDate , endDate , getFrequency ( ) , getDaycountConvention ( ) , getShortPeriodConvention ( ) , getDateRollConvention ( ) , getBusinessdayCalendar ( ) , getFixingOffsetDays ( ) , getPaymentOffsetDays ( ) , isUseEndOfMonth ( ) ) ; }
Generate a schedule for the given start and end date .
108
12
146,546
@ Deprecated public static ScheduleInterface createScheduleFromConventions ( LocalDate referenceDate , LocalDate startDate , String frequency , double maturity , String daycountConvention , String shortPeriodConvention ) { return createScheduleFromConventions ( referenceDate , startDate , frequency , maturity , daycountConvention , shortPeriodConvention , "UNADJUSTED" , new BusinessdayCalendarAny ( ) , 0 , 0 ) ; }
Generates a schedule based on some meta data . The schedule generation considers short periods . Date rolling is ignored .
95
22
146,547
public AnalyticProductInterface getCalibrationProductForSymbol ( String symbol ) { /* * The internal data structure is not optimal here (a map would make more sense here), * if the user does not require access to the products, we would allow non-unique symbols. * Hence we store both in two side by side vectors. */ for ( int i = 0 ; i < calibrationProductsSymbols . size ( ) ; i ++ ) { String calibrationProductSymbol = calibrationProductsSymbols . get ( i ) ; if ( calibrationProductSymbol . equals ( symbol ) ) { return calibrationProducts . get ( i ) ; } } return null ; }
Returns the first product found in the vector of calibration products which matches the given symbol where symbol is the String set in the calibrationSpecs .
138
28
146,548
@ Override public RandomVariable getValue ( double evaluationTime , AssetModelMonteCarloSimulationModel model ) throws CalculationException { if ( exerciseMethod == ExerciseMethod . UPPER_BOUND_METHOD ) { // Find optimal lambda GoldenSectionSearch optimizer = new GoldenSectionSearch ( - 1.0 , 1.0 ) ; while ( ! optimizer . isDone ( ) ) { double lambda = optimizer . getNextPoint ( ) ; double value = this . getValues ( evaluationTime , model , lambda ) . getAverage ( ) ; optimizer . setValue ( value ) ; } return getValues ( evaluationTime , model , optimizer . getBestPoint ( ) ) ; } else { return getValues ( evaluationTime , model , 0.0 ) ; } }
This method returns the value random variable of the product within the specified model evaluated at a given evalutationTime . Cash - flows prior evaluationTime are not considered .
165
32
146,549
public static HazardCurve createHazardCurveFromSurvivalProbabilities ( String name , double [ ] times , double [ ] givenSurvivalProbabilities ) { HazardCurve survivalProbabilities = new HazardCurve ( name ) ; for ( int timeIndex = 0 ; timeIndex < times . length ; timeIndex ++ ) { survivalProbabilities . addSurvivalProbability ( times [ timeIndex ] , givenSurvivalProbabilities [ timeIndex ] , times [ timeIndex ] > 0 ) ; } return survivalProbabilities ; }
Create a hazard curve from given times and given discount factors using default interpolation and extrapolation methods .
118
20
146,550
public SwaptionDataLattice convertLattice ( QuotingConvention targetConvention , double displacement , AnalyticModel model ) { if ( displacement != 0 && targetConvention != QuotingConvention . PAYERVOLATILITYLOGNORMAL ) { throw new IllegalArgumentException ( "SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL." ) ; } //Reverse sign of moneyness, if switching between payer and receiver convention. int reverse = ( ( targetConvention == QuotingConvention . RECEIVERPRICE ) ^ ( quotingConvention == QuotingConvention . RECEIVERPRICE ) ) ? - 1 : 1 ; List < Integer > maturities = new ArrayList <> ( ) ; List < Integer > tenors = new ArrayList <> ( ) ; List < Integer > moneynesss = new ArrayList <> ( ) ; List < Double > values = new ArrayList <> ( ) ; for ( DataKey key : entryMap . keySet ( ) ) { maturities . add ( key . maturity ) ; tenors . add ( key . tenor ) ; moneynesss . add ( key . moneyness * reverse ) ; values . add ( getValue ( key . maturity , key . tenor , key . moneyness , targetConvention , displacement , model ) ) ; } return new SwaptionDataLattice ( referenceDate , targetConvention , displacement , forwardCurveName , discountCurveName , floatMetaSchedule , fixMetaSchedule , maturities . stream ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) , tenors . stream ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) , moneynesss . stream ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) , values . stream ( ) . mapToDouble ( Double :: doubleValue ) . toArray ( ) ) ; }
Convert this lattice to store data in the given convention . Conversion involving receiver premium assumes zero wide collar .
433
22
146,551
public SwaptionDataLattice append ( SwaptionDataLattice other , AnalyticModel model ) { SwaptionDataLattice combined = new SwaptionDataLattice ( referenceDate , quotingConvention , displacement , forwardCurveName , discountCurveName , floatMetaSchedule , fixMetaSchedule ) ; combined . entryMap . putAll ( entryMap ) ; if ( quotingConvention == other . quotingConvention && displacement == other . displacement ) { combined . entryMap . putAll ( other . entryMap ) ; } else { SwaptionDataLattice converted = other . convertLattice ( quotingConvention , displacement , model ) ; combined . entryMap . putAll ( converted . entryMap ) ; } return combined ; }
Append the data of another lattice to this lattice . If the other lattice follows a different quoting convention it is automatically converted . However this method does not check whether the two lattices are aligned in terms of reference date curve names and meta schedules . If the two lattices have shared data points the data from this lattice will be overwritten .
165
72
146,552
public double [ ] getMoneynessAsOffsets ( ) { DoubleStream moneyness = getGridNodesPerMoneyness ( ) . keySet ( ) . stream ( ) . mapToDouble ( Integer :: doubleValue ) ; if ( quotingConvention == QuotingConvention . PAYERVOLATILITYLOGNORMAL ) { moneyness = moneyness . map ( new DoubleUnaryOperator ( ) { @ Override public double applyAsDouble ( double x ) { return x * 0.01 ; } } ) ; } else if ( quotingConvention == QuotingConvention . RECEIVERPRICE ) { moneyness = moneyness . map ( new DoubleUnaryOperator ( ) { @ Override public double applyAsDouble ( double x ) { return - x * 0.0001 ; } } ) ; } else { moneyness = moneyness . map ( new DoubleUnaryOperator ( ) { @ Override public double applyAsDouble ( double x ) { return x * 0.0001 ; } } ) ; } return moneyness . toArray ( ) ; }
Return all levels of moneyness for which data exists . Moneyness is returned as actual difference strike - par swap rate .
227
24
146,553
public double [ ] getMaturities ( double moneyness ) { int [ ] maturitiesInMonths = getMaturities ( convertMoneyness ( moneyness ) ) ; double [ ] maturities = new double [ maturitiesInMonths . length ] ; for ( int index = 0 ; index < maturities . length ; index ++ ) { maturities [ index ] = convertMaturity ( maturitiesInMonths [ index ] ) ; } return maturities ; }
Return all valid maturities for a given moneyness . Uses the fixing times of the fix schedule to determine fractions .
106
24
146,554
public int [ ] getTenors ( ) { Set < Integer > setTenors = new HashSet <> ( ) ; for ( int moneyness : getGridNodesPerMoneyness ( ) . keySet ( ) ) { setTenors . addAll ( Arrays . asList ( ( IntStream . of ( keyMap . get ( moneyness ) [ 1 ] ) . boxed ( ) . toArray ( Integer [ ] :: new ) ) ) ) ; } return setTenors . stream ( ) . sorted ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) ; }
Return all tenors for which data exists .
127
9
146,555
public int [ ] getTenors ( int moneynessBP , int maturityInMonths ) { try { List < Integer > ret = new ArrayList <> ( ) ; for ( int tenor : getGridNodesPerMoneyness ( ) . get ( moneynessBP ) [ 1 ] ) { if ( containsEntryFor ( maturityInMonths , tenor , moneynessBP ) ) { ret . add ( tenor ) ; } } return ret . stream ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) ; } catch ( NullPointerException e ) { return new int [ 0 ] ; } }
Return all valid tenors for a given moneyness and maturity .
134
13
146,556
public double [ ] getTenors ( double moneyness , double maturity ) { int maturityInMonths = ( int ) Math . round ( maturity * 12 ) ; int [ ] tenorsInMonths = getTenors ( convertMoneyness ( moneyness ) , maturityInMonths ) ; double [ ] tenors = new double [ tenorsInMonths . length ] ; for ( int index = 0 ; index < tenors . length ; index ++ ) { tenors [ index ] = convertTenor ( maturityInMonths , tenorsInMonths [ index ] ) ; } return tenors ; }
Return all valid tenors for a given moneyness and maturity . Uses the payment times of the fix schedule to determine fractions .
128
25
146,557
private int convertMoneyness ( double moneyness ) { if ( quotingConvention == QuotingConvention . PAYERVOLATILITYLOGNORMAL ) { return ( int ) Math . round ( moneyness * 100 ) ; } else if ( quotingConvention == QuotingConvention . RECEIVERPRICE ) { return - ( int ) Math . round ( moneyness * 10000 ) ; } else { return ( int ) Math . round ( moneyness * 10000 ) ; } }
Convert moneyness given as difference to par swap rate to moneyness in bp . Uses the fixing times of the fix schedule to determine fractions .
101
30
146,558
private double convertMaturity ( int maturityInMonths ) { Schedule schedule = fixMetaSchedule . generateSchedule ( referenceDate , maturityInMonths , 12 ) ; return schedule . getFixing ( 0 ) ; }
Convert maturity given as offset in months to year fraction .
47
12
146,559
private double convertTenor ( int maturityInMonths , int tenorInMonths ) { Schedule schedule = fixMetaSchedule . generateSchedule ( referenceDate , maturityInMonths , tenorInMonths ) ; return schedule . getPayment ( schedule . getNumberOfPeriods ( ) - 1 ) ; }
Convert tenor given as offset in months to year fraction .
69
13
146,560
public boolean containsEntryFor ( int maturityInMonths , int tenorInMonths , int moneynessBP ) { return entryMap . containsKey ( new DataKey ( maturityInMonths , tenorInMonths , moneynessBP ) ) ; }
Returns true if the lattice contains an entry at the specified location .
54
14
146,561
private double convertToConvention ( double value , DataKey key , QuotingConvention toConvention , double toDisplacement , QuotingConvention fromConvention , double fromDisplacement , AnalyticModel model ) { if ( toConvention == fromConvention ) { if ( toConvention != QuotingConvention . PAYERVOLATILITYLOGNORMAL ) { return value ; } else { if ( toDisplacement == fromDisplacement ) { return value ; } else { return convertToConvention ( convertToConvention ( value , key , QuotingConvention . PAYERPRICE , 0 , fromConvention , fromDisplacement , model ) , key , toConvention , toDisplacement , QuotingConvention . PAYERPRICE , 0 , model ) ; } } } Schedule floatSchedule = floatMetaSchedule . generateSchedule ( getReferenceDate ( ) , key . maturity , key . tenor ) ; Schedule fixSchedule = fixMetaSchedule . generateSchedule ( getReferenceDate ( ) , key . maturity , key . tenor ) ; double forward = Swap . getForwardSwapRate ( fixSchedule , floatSchedule , model . getForwardCurve ( forwardCurveName ) , model ) ; double optionMaturity = floatSchedule . getFixing ( 0 ) ; double offset = key . moneyness / 10000.0 ; double optionStrike = forward + ( quotingConvention == QuotingConvention . RECEIVERPRICE ? - offset : offset ) ; double payoffUnit = SwapAnnuity . getSwapAnnuity ( fixSchedule . getFixing ( 0 ) , fixSchedule , model . getDiscountCurve ( discountCurveName ) , model ) ; if ( toConvention . equals ( QuotingConvention . PAYERPRICE ) && fromConvention . equals ( QuotingConvention . PAYERVOLATILITYLOGNORMAL ) ) { return AnalyticFormulas . blackScholesGeneralizedOptionValue ( forward + fromDisplacement , value , optionMaturity , optionStrike + fromDisplacement , payoffUnit ) ; } else if ( toConvention . equals ( QuotingConvention . PAYERPRICE ) && fromConvention . equals ( QuotingConvention . PAYERVOLATILITYNORMAL ) ) { return AnalyticFormulas . bachelierOptionValue ( forward , value , optionMaturity , optionStrike , payoffUnit ) ; } else if ( toConvention . equals ( QuotingConvention . PAYERPRICE ) && fromConvention . equals ( QuotingConvention . RECEIVERPRICE ) ) { return value + ( forward - optionStrike ) * payoffUnit ; } else if ( toConvention . equals ( QuotingConvention . PAYERVOLATILITYLOGNORMAL ) && fromConvention . equals ( QuotingConvention . PAYERPRICE ) ) { return AnalyticFormulas . blackScholesOptionImpliedVolatility ( forward + toDisplacement , optionMaturity , optionStrike + toDisplacement , payoffUnit , value ) ; } else if ( toConvention . equals ( QuotingConvention . PAYERVOLATILITYNORMAL ) && fromConvention . equals ( QuotingConvention . PAYERPRICE ) ) { return AnalyticFormulas . bachelierOptionImpliedVolatility ( forward , optionMaturity , optionStrike , payoffUnit , value ) ; } else if ( toConvention . equals ( QuotingConvention . RECEIVERPRICE ) && fromConvention . equals ( QuotingConvention . PAYERPRICE ) ) { return value - ( forward - optionStrike ) * payoffUnit ; } else { return convertToConvention ( convertToConvention ( value , key , QuotingConvention . PAYERPRICE , 0 , fromConvention , fromDisplacement , model ) , key , toConvention , toDisplacement , QuotingConvention . PAYERPRICE , 0 , model ) ; } }
Convert the value to requested quoting convention . Conversion involving receiver premium assumes zero wide collar .
855
18
146,562
public double getCouponPayment ( int periodIndex , AnalyticModel model ) { ForwardCurve forwardCurve = model . getForwardCurve ( forwardCurveName ) ; if ( forwardCurve == null && forwardCurveName != null && forwardCurveName . length ( ) > 0 ) { throw new IllegalArgumentException ( "No forward curve with name '" + forwardCurveName + "' was found in the model:\n" + model . toString ( ) ) ; } double periodLength = schedule . getPeriodLength ( periodIndex ) ; double couponPayment = fixedCoupon ; if ( forwardCurve != null ) { couponPayment = floatingSpread + forwardCurve . getForward ( model , schedule . getFixing ( periodIndex ) ) ; } return couponPayment * periodLength ; }
Returns the coupon payment of the period with the given index . The analytic model is needed in case of floating bonds .
177
23
146,563
public double getValueWithGivenSpreadOverCurve ( double evaluationTime , Curve referenceCurve , double spread , AnalyticModel model ) { double value = 0 ; for ( int periodIndex = 0 ; periodIndex < schedule . getNumberOfPeriods ( ) ; periodIndex ++ ) { double paymentDate = schedule . getPayment ( periodIndex ) ; value += paymentDate > evaluationTime ? getCouponPayment ( periodIndex , model ) * Math . exp ( - spread * paymentDate ) * referenceCurve . getValue ( paymentDate ) : 0.0 ; } double paymentDate = schedule . getPayment ( schedule . getNumberOfPeriods ( ) - 1 ) ; return paymentDate > evaluationTime ? value + Math . exp ( - spread * paymentDate ) * referenceCurve . getValue ( paymentDate ) : 0.0 ; }
Returns the value of the sum of discounted cash flows of the bond where the discounting is done with the given reference curve and an additional spread . This method can be used for optimizer .
183
38
146,564
public double getValueWithGivenYield ( double evaluationTime , double rate , AnalyticModel model ) { DiscountCurve referenceCurve = DiscountCurveInterpolation . createDiscountCurveFromDiscountFactors ( "referenceCurve" , new double [ ] { 0.0 , 1.0 } , new double [ ] { 1.0 , 1.0 } ) ; return getValueWithGivenSpreadOverCurve ( evaluationTime , referenceCurve , rate , model ) ; }
Returns the value of the sum of discounted cash flows of the bond where the discounting is done with the given yield curve . This method can be used for optimizer .
105
34
146,565
public double getSpread ( double bondPrice , Curve referenceCurve , AnalyticModel model ) { GoldenSectionSearch search = new GoldenSectionSearch ( - 2.0 , 2.0 ) ; while ( search . getAccuracy ( ) > 1E-11 && ! search . isDone ( ) ) { double x = search . getNextPoint ( ) ; double fx = getValueWithGivenSpreadOverCurve ( 0.0 , referenceCurve , x , model ) ; double y = ( bondPrice - fx ) * ( bondPrice - fx ) ; search . setValue ( y ) ; } return search . getBestPoint ( ) ; }
Returns the spread value such that the sum of cash flows of the bond discounted with a given reference curve with the additional spread coincides with a given price .
139
30
146,566
public double getYield ( double bondPrice , AnalyticModel model ) { GoldenSectionSearch search = new GoldenSectionSearch ( - 2.0 , 2.0 ) ; while ( search . getAccuracy ( ) > 1E-11 && ! search . isDone ( ) ) { double x = search . getNextPoint ( ) ; double fx = getValueWithGivenYield ( 0.0 , x , model ) ; double y = ( bondPrice - fx ) * ( bondPrice - fx ) ; search . setValue ( y ) ; } return search . getBestPoint ( ) ; }
Returns the yield value such that the sum of cash flows of the bond discounted with the yield curve coincides with a given price .
129
25
146,567
public double getAccruedInterest ( LocalDate date , AnalyticModel model ) { int periodIndex = schedule . getPeriodIndex ( date ) ; Period period = schedule . getPeriod ( periodIndex ) ; DayCountConvention dcc = schedule . getDaycountconvention ( ) ; double accruedInterest = getCouponPayment ( periodIndex , model ) * ( dcc . getDaycountFraction ( period . getPeriodStart ( ) , date ) ) / schedule . getPeriodLength ( periodIndex ) ; return accruedInterest ; }
Returns the accrued interest of the bond for a given date .
117
12
146,568
public double getAccruedInterest ( double time , AnalyticModel model ) { LocalDate date = FloatingpointDate . getDateFromFloatingPointDate ( schedule . getReferenceDate ( ) , time ) ; return getAccruedInterest ( date , model ) ; }
Returns the accrued interest of the bond for a given time .
55
12
146,569
public static double blackScholesOptionTheta ( double initialStockValue , double riskFreeRate , double volatility , double optionMaturity , double optionStrike ) { if ( optionStrike <= 0.0 || optionMaturity <= 0.0 ) { // The Black-Scholes model does not consider it being an option return 0.0 ; } else { // Calculate theta double dPlus = ( Math . log ( initialStockValue / optionStrike ) + ( riskFreeRate + 0.5 * volatility * volatility ) * optionMaturity ) / ( volatility * Math . sqrt ( optionMaturity ) ) ; double dMinus = dPlus - volatility * Math . sqrt ( optionMaturity ) ; double theta = volatility * Math . exp ( - 0.5 * dPlus * dPlus ) / Math . sqrt ( 2.0 * Math . PI ) / Math . sqrt ( optionMaturity ) / 2 * initialStockValue + riskFreeRate * optionStrike * Math . exp ( - riskFreeRate * optionMaturity ) * NormalDistribution . cumulativeDistribution ( dMinus ) ; return theta ; } }
This static method calculated the vega of a call option under a Black - Scholes model
240
18
146,570
public Map < String , Object > getValues ( double evaluationTime , MonteCarloSimulationInterface model ) throws CalculationException { RandomVariableInterface values = getValue ( evaluationTime , model ) ; if ( values == null ) { return null ; } // Sum up values on path double value = values . getAverage ( ) ; double error = values . getStandardError ( ) ; Map < String , Object > results = new HashMap < String , Object > ( ) ; results . put ( "value" , value ) ; results . put ( "error" , error ) ; return results ; }
This method returns the value of the product under the specified model and other information in a key - value map .
124
22
146,571
public double getValue ( double x ) { synchronized ( interpolatingRationalFunctionsLazyInitLock ) { if ( interpolatingRationalFunctions == null ) { doCreateRationalFunctions ( ) ; } } // Get interpolating rational function for the given point x int pointIndex = java . util . Arrays . binarySearch ( points , x ) ; if ( pointIndex >= 0 ) { return values [ pointIndex ] ; } int intervallIndex = - pointIndex - 2 ; // Check for extrapolation if ( intervallIndex < 0 ) { // Extrapolation if ( this . extrapolationMethod == ExtrapolationMethod . CONSTANT ) { return values [ 0 ] ; } else if ( this . extrapolationMethod == ExtrapolationMethod . LINEAR ) { return values [ 0 ] + ( values [ 1 ] - values [ 0 ] ) / ( points [ 1 ] - points [ 0 ] ) * ( x - points [ 0 ] ) ; } else { intervallIndex = 0 ; } } else if ( intervallIndex > points . length - 2 ) { // Extrapolation if ( this . extrapolationMethod == ExtrapolationMethod . CONSTANT ) { return values [ points . length - 1 ] ; } else if ( this . extrapolationMethod == ExtrapolationMethod . LINEAR ) { return values [ points . length - 1 ] + ( values [ points . length - 2 ] - values [ points . length - 1 ] ) / ( points [ points . length - 2 ] - points [ points . length - 1 ] ) * ( x - points [ points . length - 1 ] ) ; } else { intervallIndex = points . length - 2 ; } } RationalFunction rationalFunction = interpolatingRationalFunctions [ intervallIndex ] ; // Calculate interpolating value return rationalFunction . getValue ( x - points [ intervallIndex ] ) ; }
Get an interpolated value for a given argument x .
405
11
146,572
public RandomVariable [ ] getGradient ( ) { // for now let us take the case for output-dimension equal to one! int numberOfVariables = getNumberOfVariablesInList ( ) ; int numberOfCalculationSteps = factory . getNumberOfEntriesInList ( ) ; RandomVariable [ ] omega_hat = new RandomVariable [ numberOfCalculationSteps ] ; // first entry gets initialized omega_hat [ numberOfCalculationSteps - 1 ] = new RandomVariableFromDoubleArray ( 1.0 ) ; /* * TODO: Find way that calculations form here on are not 'recorded' by the factory * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down! * */ for ( int functionIndex = numberOfCalculationSteps - 2 ; functionIndex > 0 ; functionIndex -- ) { // apply chain rule omega_hat [ functionIndex ] = new RandomVariableFromDoubleArray ( 0.0 ) ; /*TODO: save all D_{i,j}*\omega_j in vector and sum up later */ for ( RandomVariableUniqueVariable parent : parentsVariables ) { int variableIndex = parent . getVariableID ( ) ; omega_hat [ functionIndex ] = omega_hat [ functionIndex ] . add ( getPartialDerivative ( functionIndex , variableIndex ) . mult ( omega_hat [ variableIndex ] ) ) ; } } /* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices! * Thus save the indices of the true variables and recover them after finalizing all the calculations * IDEA: quit calculation after minimal true variable index is reached */ RandomVariable [ ] gradient = new RandomVariable [ numberOfVariables ] ; /* TODO: sort array in correct manner! */ int [ ] indicesOfVariables = getIDsOfVariablesInList ( ) ; for ( int i = 0 ; i < numberOfVariables ; i ++ ) { gradient [ i ] = omega_hat [ numberOfCalculationSteps - numberOfVariables + indicesOfVariables [ i ] ] ; } return gradient ; }
Apply the AAD algorithm to this very variable
463
9
146,573
public AbstractVolatilitySurfaceParametric getCloneCalibrated ( final AnalyticModel calibrationModel , final Vector < AnalyticProduct > calibrationProducts , final List < Double > calibrationTargetValues , Map < String , Object > calibrationParameters , final ParameterTransformation parameterTransformation , OptimizerFactory optimizerFactory ) throws SolverException { if ( calibrationParameters == null ) { calibrationParameters = new HashMap <> ( ) ; } Integer maxIterationsParameter = ( Integer ) calibrationParameters . get ( "maxIterations" ) ; Double accuracyParameter = ( Double ) calibrationParameters . get ( "accuracy" ) ; Double evaluationTimeParameter = ( Double ) calibrationParameters . get ( "evaluationTime" ) ; // @TODO currently ignored, we use the setting form the OptimizerFactory int maxIterations = maxIterationsParameter != null ? maxIterationsParameter . intValue ( ) : 600 ; double accuracy = accuracyParameter != null ? accuracyParameter . doubleValue ( ) : 1E-8 ; double evaluationTime = evaluationTimeParameter != null ? evaluationTimeParameter . doubleValue ( ) : 0.0 ; AnalyticModel model = calibrationModel . addVolatilitySurfaces ( this ) ; Solver solver = new Solver ( model , calibrationProducts , calibrationTargetValues , parameterTransformation , evaluationTime , optimizerFactory ) ; Set < ParameterObject > objectsToCalibrate = new HashSet <> ( ) ; objectsToCalibrate . add ( this ) ; AnalyticModel modelCalibrated = solver . getCalibratedModel ( objectsToCalibrate ) ; // Diagnostic output if ( logger . isLoggable ( Level . FINE ) ) { double lastAccuracy = solver . getAccuracy ( ) ; int lastIterations = solver . getIterations ( ) ; logger . fine ( "The solver achieved an accuracy of " + lastAccuracy + " in " + lastIterations + "." ) ; } return ( AbstractVolatilitySurfaceParametric ) modelCalibrated . getVolatilitySurface ( this . getName ( ) ) ; }
Create a clone of this volatility surface using a generic calibration of its parameters to given market data .
446
19
146,574
public static double [ ] computeSeasonalAdjustments ( double [ ] realizedCPIValues , int lastMonth , int numberOfYearsToAverage ) { /* * Cacluate average log returns */ double [ ] averageLogReturn = new double [ 12 ] ; Arrays . fill ( averageLogReturn , 0.0 ) ; for ( int arrayIndex = 0 ; arrayIndex < 12 * numberOfYearsToAverage ; arrayIndex ++ ) { int month = ( ( ( ( ( lastMonth - 1 - arrayIndex ) % 12 ) + 12 ) % 12 ) ) ; double logReturn = Math . log ( realizedCPIValues [ realizedCPIValues . length - 1 - arrayIndex ] / realizedCPIValues [ realizedCPIValues . length - 2 - arrayIndex ] ) ; averageLogReturn [ month ] += logReturn / numberOfYearsToAverage ; } /* * Normalize */ double sum = 0.0 ; for ( int index = 0 ; index < averageLogReturn . length ; index ++ ) { sum += averageLogReturn [ index ] ; } double averageSeasonal = sum / averageLogReturn . length ; double [ ] seasonalAdjustments = new double [ averageLogReturn . length ] ; for ( int index = 0 ; index < seasonalAdjustments . length ; index ++ ) { seasonalAdjustments [ index ] = averageLogReturn [ index ] - averageSeasonal ; } // Annualize seasonal adjustments for ( int index = 0 ; index < seasonalAdjustments . length ; index ++ ) { seasonalAdjustments [ index ] = seasonalAdjustments [ index ] * 12 ; } return seasonalAdjustments ; }
Computes annualized seasonal adjustments from given monthly realized CPI values .
342
13
146,575
public ProductFactoryCascade < T > addFactoryBefore ( ProductFactory < ? extends T > factory ) { ArrayList < ProductFactory < ? extends T > > factories = new ArrayList < ProductFactory < ? extends T > > ( this . factories . size ( ) + 1 ) ; factories . addAll ( this . factories ) ; factories . add ( 0 , factory ) ; return new ProductFactoryCascade <> ( factories ) ; }
Add a given factory to the list of factories at the BEGINNING .
91
15
146,576
public RandomVariable getValues ( double evaluationTime , LIBORMarketModel model ) { if ( evaluationTime > 0 ) { throw new RuntimeException ( "Forward start evaluation currently not supported." ) ; } // Fetch the covariance model of the model LIBORCovarianceModel covarianceModel = model . getCovarianceModel ( ) ; // We sum over all forward rates int numberOfComponents = covarianceModel . getLiborPeriodDiscretization ( ) . getNumberOfTimeSteps ( ) ; // Accumulator RandomVariable integratedLIBORCurvature = new RandomVariableFromDoubleArray ( 0.0 ) ; for ( int componentIndex = 0 ; componentIndex < numberOfComponents ; componentIndex ++ ) { // Integrate from 0 up to the fixing of the rate double timeEnd = covarianceModel . getLiborPeriodDiscretization ( ) . getTime ( componentIndex ) ; int timeEndIndex = covarianceModel . getTimeDiscretization ( ) . getTimeIndex ( timeEnd ) ; // If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint if ( timeEndIndex < 0 ) { timeEndIndex = - timeEndIndex - 2 ; } // Sum squared second derivative of the variance for all components at this time step RandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray ( 0.0 ) ; for ( int timeIndex = 0 ; timeIndex < timeEndIndex - 2 ; timeIndex ++ ) { double timeStep1 = covarianceModel . getTimeDiscretization ( ) . getTimeStep ( timeIndex ) ; double timeStep2 = covarianceModel . getTimeDiscretization ( ) . getTimeStep ( timeIndex + 1 ) ; RandomVariable covarianceLeft = covarianceModel . getCovariance ( timeIndex + 0 , componentIndex , componentIndex , null ) ; RandomVariable covarianceCenter = covarianceModel . getCovariance ( timeIndex + 1 , componentIndex , componentIndex , null ) ; RandomVariable covarianceRight = covarianceModel . getCovariance ( timeIndex + 2 , componentIndex , componentIndex , null ) ; // Calculate second derivative RandomVariable curvatureSquared = covarianceRight . sub ( covarianceCenter . mult ( 2.0 ) ) . add ( covarianceLeft ) ; curvatureSquared = curvatureSquared . div ( timeStep1 * timeStep2 ) ; // Take square curvatureSquared = curvatureSquared . squared ( ) ; // Integrate over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate . add ( curvatureSquared . mult ( timeStep1 ) ) ; } // Empty intervall - skip if ( timeEnd == 0 ) { continue ; } // Average over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate . div ( timeEnd ) ; // Take square root integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate . sqrt ( ) ; // Take max over all forward rates integratedLIBORCurvature = integratedLIBORCurvature . add ( integratedLIBORCurvatureCurrentRate ) ; } integratedLIBORCurvature = integratedLIBORCurvature . div ( numberOfComponents ) ; return integratedLIBORCurvature . sub ( tolerance ) . floor ( 0.0 ) ; }
Calculates the squared curvature of the LIBOR instantaneous variance .
744
14
146,577
public RandomVariableInterface [ ] getFactorLoading ( double time , double component , RandomVariableInterface [ ] realizationAtTimeIndex ) { int componentIndex = liborPeriodDiscretization . getTimeIndex ( component ) ; if ( componentIndex < 0 ) { componentIndex = - componentIndex - 2 ; } return getFactorLoading ( time , componentIndex , realizationAtTimeIndex ) ; }
Return the factor loading for a given time and a given component .
81
13
146,578
private RandomVariable getValueUnderlyingNumeraireRelative ( LIBORModelMonteCarloSimulationModel model , Schedule legSchedule , boolean paysFloat , double swaprate , double notional ) throws CalculationException { RandomVariable value = model . getRandomVariableForConstant ( 0.0 ) ; for ( int periodIndex = legSchedule . getNumberOfPeriods ( ) - 1 ; periodIndex >= 0 ; periodIndex -- ) { double fixingTime = FloatingpointDate . getFloatingPointDateFromDate ( model . getReferenceDate ( ) . toLocalDate ( ) , legSchedule . getPeriod ( periodIndex ) . getFixing ( ) ) ; double paymentTime = FloatingpointDate . getFloatingPointDateFromDate ( model . getReferenceDate ( ) . toLocalDate ( ) , legSchedule . getPeriod ( periodIndex ) . getPayment ( ) ) ; double periodLength = legSchedule . getPeriodLength ( periodIndex ) ; RandomVariable numeraireAtPayment = model . getNumeraire ( paymentTime ) ; RandomVariable monteCarloProbabilitiesAtPayment = model . getMonteCarloWeights ( paymentTime ) ; if ( swaprate != 0.0 ) { RandomVariable periodCashFlowFix = model . getRandomVariableForConstant ( swaprate * periodLength * notional ) . div ( numeraireAtPayment ) . mult ( monteCarloProbabilitiesAtPayment ) ; value = value . add ( periodCashFlowFix ) ; } if ( paysFloat ) { RandomVariable libor = model . getLIBOR ( fixingTime , fixingTime , paymentTime ) ; RandomVariable periodCashFlowFloat = libor . mult ( periodLength ) . mult ( notional ) . div ( numeraireAtPayment ) . mult ( monteCarloProbabilitiesAtPayment ) ; value = value . add ( periodCashFlowFloat ) ; } } return value ; }
Calculated the numeraire relative value of an underlying swap leg .
419
13
146,579
public ConditionalExpectationEstimator getConditionalExpectationEstimator ( double exerciseTime , LIBORModelMonteCarloSimulationModel model ) throws CalculationException { RandomVariable [ ] regressionBasisFunctions = regressionBasisFunctionProvider . getBasisFunctions ( exerciseTime , model ) ; return conditionalExpectationRegressionFactory . getConditionalExpectationEstimator ( regressionBasisFunctions , regressionBasisFunctions ) ; }
The conditional expectation is calculated using a Monte - Carlo regression technique .
101
13
146,580
@ Override public RandomVariable getNumeraire ( double time ) throws CalculationException { int timeIndex = getLiborPeriodIndex ( time ) ; if ( timeIndex < 0 ) { // Interpolation of Numeraire: linear interpolation of the reciprocal. int lowerIndex = - timeIndex - 1 ; int upperIndex = - timeIndex ; double alpha = ( time - getLiborPeriod ( lowerIndex ) ) / ( getLiborPeriod ( upperIndex ) - getLiborPeriod ( lowerIndex ) ) ; return getNumeraire ( getLiborPeriod ( upperIndex ) ) . invert ( ) . mult ( alpha ) . add ( getNumeraire ( getLiborPeriod ( lowerIndex ) ) . invert ( ) . mult ( 1.0 - alpha ) ) . invert ( ) ; } // Calculate the numeraire, when time is part of liborPeriodDiscretization // Get the start of the product int firstLiborIndex = getLiborPeriodIndex ( time ) ; if ( firstLiborIndex < 0 ) { throw new CalculationException ( "Simulation time discretization not part of forward rate tenor discretization." ) ; } // Get the end of the product int lastLiborIndex = liborPeriodDiscretization . getNumberOfTimeSteps ( ) - 1 ; if ( measure == Measure . SPOT ) { // Spot measure firstLiborIndex = 0 ; lastLiborIndex = getLiborPeriodIndex ( time ) - 1 ; } /* * Calculation of the numeraire */ // Initialize to 1.0 RandomVariable numeraire = new RandomVariableFromDoubleArray ( time , 1.0 ) ; // The product for ( int liborIndex = firstLiborIndex ; liborIndex <= lastLiborIndex ; liborIndex ++ ) { RandomVariable libor = getLIBOR ( getTimeIndex ( Math . min ( time , liborPeriodDiscretization . getTime ( liborIndex ) ) ) , liborIndex ) ; double periodLength = liborPeriodDiscretization . getTimeStep ( liborIndex ) ; if ( measure == Measure . SPOT ) { numeraire = numeraire . accrue ( libor , periodLength ) ; } else { numeraire = numeraire . discount ( libor , periodLength ) ; } } /* * Adjust for discounting */ if ( discountCurve != null ) { DiscountCurve discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve ( forwardRateCurve ) ; double deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance . getDiscountFactor ( time ) / discountCurve . getDiscountFactor ( time ) ; numeraire = numeraire . mult ( deterministicNumeraireAdjustment ) ; } return numeraire ; }
Return the numeraire at a given time . The numeraire is provided for interpolated points . If requested on points which are not part of the tenor discretization the numeraire uses a linear interpolation of the reciprocal value . See ISBN 0470047224 for details .
605
57
146,581
private double u_neg_inf ( double x , double tau ) { return f ( boundaryCondition . getValueAtLowerBoundary ( model , f_t ( tau ) , f_s ( x ) ) , x , tau ) ; }
Heat Equation Boundary Conditions
54
6
146,582
public double [ ] getRegressionCoefficients ( RandomVariable value ) { if ( basisFunctions . length == 0 ) { return new double [ ] { } ; } else if ( basisFunctions . length == 1 ) { /* * Regression with one basis function is just a projection on that vector. <b,x>/<b,b> */ return new double [ ] { value . mult ( basisFunctions [ 0 ] ) . getAverage ( ) / basisFunctions [ 0 ] . squared ( ) . getAverage ( ) } ; } else if ( basisFunctions . length == 2 ) { /* * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD) */ double a = basisFunctions [ 0 ] . squared ( ) . getAverage ( ) ; double b = basisFunctions [ 0 ] . mult ( basisFunctions [ 1 ] ) . average ( ) . squared ( ) . doubleValue ( ) ; double c = b ; double d = basisFunctions [ 1 ] . squared ( ) . getAverage ( ) ; double determinant = ( a * d - b * c ) ; if ( determinant != 0 ) { double x = value . mult ( basisFunctions [ 0 ] ) . getAverage ( ) ; double y = value . mult ( basisFunctions [ 1 ] ) . getAverage ( ) ; double alpha0 = ( d * x - b * y ) / determinant ; double alpha1 = ( a * y - c * x ) / determinant ; return new double [ ] { alpha0 , alpha1 } ; } } /* * General case */ // Build regression matrix double [ ] [ ] BTB = new double [ basisFunctions . length ] [ basisFunctions . length ] ; for ( int i = 0 ; i < basisFunctions . length ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { double covariance = basisFunctions [ i ] . mult ( basisFunctions [ j ] ) . getAverage ( ) ; BTB [ i ] [ j ] = covariance ; BTB [ j ] [ i ] = covariance ; } } double [ ] BTX = new double [ basisFunctions . length ] ; for ( int i = 0 ; i < basisFunctions . length ; i ++ ) { double covariance = basisFunctions [ i ] . mult ( value ) . getAverage ( ) ; BTX [ i ] = covariance ; } return LinearAlgebra . solveLinearEquationLeastSquare ( BTB , BTX ) ; }
Get the vector of regression coefficients .
554
7
146,583
private ProductDescriptor getSwapProductDescriptor ( Element trade ) { InterestRateSwapLegProductDescriptor legReceiver = null ; InterestRateSwapLegProductDescriptor legPayer = null ; NodeList legs = trade . getElementsByTagName ( "swapStream" ) ; for ( int legIndex = 0 ; legIndex < legs . getLength ( ) ; legIndex ++ ) { Element leg = ( Element ) legs . item ( legIndex ) ; boolean isPayer = leg . getElementsByTagName ( "payerPartyReference" ) . item ( 0 ) . getAttributes ( ) . getNamedItem ( "href" ) . getNodeValue ( ) . equals ( homePartyId ) ; if ( isPayer ) { legPayer = getSwapLegProductDescriptor ( leg ) ; } else { legReceiver = getSwapLegProductDescriptor ( leg ) ; } } return new InterestRateSwapProductDescriptor ( legReceiver , legPayer ) ; }
Construct an InterestRateSwapProductDescriptor from a node in a FpML file .
223
20
146,584
public static String getVersionString ( ) { String versionString = "UNKNOWN" ; Properties propeties = getProperites ( ) ; if ( propeties != null ) { versionString = propeties . getProperty ( "finmath-lib.version" ) ; } return versionString ; }
Return the version string of this instance of finmath - lib .
62
13
146,585
public static String getBuildString ( ) { String versionString = "UNKNOWN" ; Properties propeties = getProperites ( ) ; if ( propeties != null ) { versionString = propeties . getProperty ( "finmath-lib.build" ) ; } return versionString ; }
Return the build string of this instance of finmath - lib . Currently this is the Git commit hash .
62
21
146,586
public static DiscountCurve createDiscountCurveFromDiscountFactors ( String name , double [ ] times , double [ ] givenDiscountFactors ) { DiscountCurve discountFactors = new DiscountCurve ( name ) ; for ( int timeIndex = 0 ; timeIndex < times . length ; timeIndex ++ ) { discountFactors . addDiscountFactor ( times [ timeIndex ] , givenDiscountFactors [ timeIndex ] , times [ timeIndex ] > 0 ) ; } return discountFactors ; }
Create a discount curve from given times and given discount factors using default interpolation and extrapolation methods .
110
20
146,587
public Map < Double , SingleAssetEuropeanOptionProductDescriptor > getDescriptors ( LocalDate referenceDate ) { int numberOfStrikes = strikes . length ; HashMap < Double , SingleAssetEuropeanOptionProductDescriptor > descriptors = new HashMap < Double , SingleAssetEuropeanOptionProductDescriptor > ( ) ; LocalDate maturityDate = FloatingpointDate . getDateFromFloatingPointDate ( referenceDate , maturity ) ; for ( int i = 0 ; i < numberOfStrikes ; i ++ ) { descriptors . put ( strikes [ i ] , new SingleAssetEuropeanOptionProductDescriptor ( underlyingName , maturityDate , strikes [ i ] ) ) ; } return descriptors ; }
Return a collection of product descriptors for each option in the smile .
150
14
146,588
public SingleAssetEuropeanOptionProductDescriptor getDescriptor ( LocalDate referenceDate , int index ) throws ArrayIndexOutOfBoundsException { LocalDate maturityDate = FloatingpointDate . getDateFromFloatingPointDate ( referenceDate , maturity ) ; if ( index >= strikes . length ) { throw new ArrayIndexOutOfBoundsException ( "Strike index out of bounds" ) ; } else { return new SingleAssetEuropeanOptionProductDescriptor ( underlyingName , maturityDate , strikes [ index ] ) ; } }
Return a product descriptor for a specific strike .
110
9
146,589
public RandomVariable [ ] getValues ( double [ ] times ) { RandomVariable [ ] values = new RandomVariable [ times . length ] ; for ( int i = 0 ; i < times . length ; i ++ ) { values [ i ] = getValue ( null , times [ i ] ) ; } return values ; }
Return a vector of values corresponding to a given vector of times .
67
13
146,590
public static double getDaycount ( LocalDate startDate , LocalDate endDate , String convention ) { DayCountConventionInterface daycountConvention = getDayCountConvention ( convention ) ; return daycountConvention . getDaycount ( startDate , endDate ) ; }
Return the number of days between startDate and endDate given the specific daycount convention .
58
18
146,591
public double getValue ( ForwardCurve forwardCurve , double swaprateVolatility ) { double [ ] swapTenor = new double [ fixingDates . length + 1 ] ; System . arraycopy ( fixingDates , 0 , swapTenor , 0 , fixingDates . length ) ; swapTenor [ swapTenor . length - 1 ] = paymentDates [ paymentDates . length - 1 ] ; TimeDiscretization fixTenor = new TimeDiscretizationFromArray ( swapTenor ) ; TimeDiscretization floatTenor = new TimeDiscretizationFromArray ( swapTenor ) ; double forwardSwapRate = Swap . getForwardSwapRate ( fixTenor , floatTenor , forwardCurve ) ; double swapAnnuity = SwapAnnuity . getSwapAnnuity ( fixTenor , forwardCurve ) ; double payoffUnit = SwapAnnuity . getSwapAnnuity ( new TimeDiscretizationFromArray ( swapTenor [ 0 ] , swapTenor [ 1 ] ) , forwardCurve ) / ( swapTenor [ 1 ] - swapTenor [ 0 ] ) ; return AnalyticFormulas . huntKennedyCMSOptionValue ( forwardSwapRate , swaprateVolatility , swapAnnuity , exerciseDate , swapTenor [ swapTenor . length - 1 ] - swapTenor [ 0 ] , payoffUnit , strike ) * ( swapTenor [ 1 ] - swapTenor [ 0 ] ) ; }
This method returns the value of the product using a Black - Scholes model for the swap rate with the Hunt - Kennedy convexity adjustment . The model is determined by a discount factor curve and a swap rate volatility .
313
44
146,592
@ Override public double getDiscountFactor ( AnalyticModelInterface model , double maturity ) { // Change time scale maturity *= timeScaling ; double beta1 = parameter [ 0 ] ; double beta2 = parameter [ 1 ] ; double beta3 = parameter [ 2 ] ; double beta4 = parameter [ 3 ] ; double tau1 = parameter [ 4 ] ; double tau2 = parameter [ 5 ] ; double x1 = tau1 > 0 ? FastMath . exp ( - maturity / tau1 ) : 0.0 ; double x2 = tau2 > 0 ? FastMath . exp ( - maturity / tau2 ) : 0.0 ; double y1 = tau1 > 0 ? ( maturity > 0.0 ? ( 1.0 - x1 ) / maturity * tau1 : 1.0 ) : 0.0 ; double y2 = tau2 > 0 ? ( maturity > 0.0 ? ( 1.0 - x2 ) / maturity * tau2 : 1.0 ) : 0.0 ; double zeroRate = beta1 + beta2 * y1 + beta3 * ( y1 - x1 ) + beta4 * ( y2 - x2 ) ; return Math . exp ( - zeroRate * maturity ) ; }
Return the discount factor within a given model context for a given maturity .
271
14
146,593
@ Deprecated public static Schedule createScheduleFromConventions ( LocalDate referenceDate , LocalDate startDate , String frequency , double maturity , String daycountConvention , String shortPeriodConvention , String dateRollConvention , BusinessdayCalendar businessdayCalendar , int fixingOffsetDays , int paymentOffsetDays ) { LocalDate maturityDate = createDateFromDateAndOffset ( startDate , maturity ) ; return createScheduleFromConventions ( referenceDate , startDate , maturityDate , Frequency . valueOf ( frequency . toUpperCase ( ) ) , DaycountConvention . getEnum ( daycountConvention ) , ShortPeriodConvention . valueOf ( shortPeriodConvention . toUpperCase ( ) ) , DateRollConvention . getEnum ( dateRollConvention ) , businessdayCalendar , fixingOffsetDays , paymentOffsetDays ) ; }
Generates a schedule based on some meta data . The schedule generation considers short periods .
186
17
146,594
public Curve getRegressionCurve ( ) { // @TODO Add threadsafe lazy init. if ( regressionCurve != null ) { return regressionCurve ; } DoubleMatrix a = solveEquationSystem ( ) ; double [ ] curvePoints = new double [ partition . getLength ( ) ] ; curvePoints [ 0 ] = a . get ( 0 ) ; for ( int i = 1 ; i < curvePoints . length ; i ++ ) { curvePoints [ i ] = curvePoints [ i - 1 ] + a . get ( i ) * ( partition . getIntervalLength ( i - 1 ) ) ; } return new CurveInterpolation ( "RegressionCurve" , referenceDate , CurveInterpolation . InterpolationMethod . LINEAR , CurveInterpolation . ExtrapolationMethod . CONSTANT , CurveInterpolation . InterpolationEntity . VALUE , partition . getPoints ( ) , curvePoints ) ; }
Returns the curve resulting from the local linear regression with discrete kernel .
200
13
146,595
public double getValueAsPrice ( double evaluationTime , AnalyticModel model ) { ForwardCurve forwardCurve = model . getForwardCurve ( forwardCurveName ) ; DiscountCurve discountCurve = model . getDiscountCurve ( discountCurveName ) ; DiscountCurve discountCurveForForward = null ; if ( forwardCurve == null && forwardCurveName != null && forwardCurveName . length ( ) > 0 ) { // User might like to get forward from discount curve. discountCurveForForward = model . getDiscountCurve ( forwardCurveName ) ; if ( discountCurveForForward == null ) { // User specified a name for the forward curve, but no curve was found. throw new IllegalArgumentException ( "No curve of the name " + forwardCurveName + " was found in the model." ) ; } } double value = 0.0 ; for ( int periodIndex = 0 ; periodIndex < schedule . getNumberOfPeriods ( ) ; periodIndex ++ ) { double fixingDate = schedule . getFixing ( periodIndex ) ; double paymentDate = schedule . getPayment ( periodIndex ) ; double periodLength = schedule . getPeriodLength ( periodIndex ) ; /* * We do not count empty periods. * Since empty periods are an indication for a ill-specified product, * it might be reasonable to throw an illegal argument exception instead. */ if ( periodLength == 0 ) { continue ; } double forward = 0.0 ; if ( forwardCurve != null ) { forward += forwardCurve . getForward ( model , fixingDate , paymentDate - fixingDate ) ; } else if ( discountCurveForForward != null ) { /* * Classical single curve case: using a discount curve as a forward curve. * This is only implemented for demonstration purposes (an exception would also be appropriate :-) */ if ( fixingDate != paymentDate ) { forward += ( discountCurveForForward . getDiscountFactor ( fixingDate ) / discountCurveForForward . getDiscountFactor ( paymentDate ) - 1.0 ) / ( paymentDate - fixingDate ) ; } } double discountFactor = paymentDate > evaluationTime ? discountCurve . getDiscountFactor ( model , paymentDate ) : 0.0 ; double payoffUnit = discountFactor * periodLength ; double effektiveStrike = strike ; if ( isStrikeMoneyness ) { effektiveStrike += getATMForward ( model , true ) ; } VolatilitySurface volatilitySurface = model . getVolatilitySurface ( volatiltiySufaceName ) ; if ( volatilitySurface == null ) { throw new IllegalArgumentException ( "Volatility surface not found in model: " + volatiltiySufaceName ) ; } if ( volatilitySurface . getQuotingConvention ( ) == QuotingConvention . VOLATILITYLOGNORMAL ) { double volatility = volatilitySurface . getValue ( model , fixingDate , effektiveStrike , VolatilitySurface . QuotingConvention . VOLATILITYLOGNORMAL ) ; value += AnalyticFormulas . blackScholesGeneralizedOptionValue ( forward , volatility , fixingDate , effektiveStrike , payoffUnit ) ; } else { // Default to normal volatility as quoting convention double volatility = volatilitySurface . getValue ( model , fixingDate , effektiveStrike , VolatilitySurface . QuotingConvention . VOLATILITYNORMAL ) ; value += AnalyticFormulas . bachelierOptionValue ( forward , volatility , fixingDate , effektiveStrike , payoffUnit ) ; } } return value / discountCurve . getDiscountFactor ( model , evaluationTime ) ; }
Returns the value of this product under the given model .
786
11
146,596
public void setDerivatives ( double [ ] parameters , double [ ] [ ] derivatives ) throws SolverException { // Calculate new derivatives. Note that this method is called only with // parameters = parameterCurrent, so we may use valueCurrent. Vector < Future < double [ ] > > valueFutures = new Vector < Future < double [ ] > > ( parameterCurrent . length ) ; for ( int parameterIndex = 0 ; parameterIndex < parameterCurrent . length ; parameterIndex ++ ) { final double [ ] parametersNew = parameters . clone ( ) ; final double [ ] derivative = derivatives [ parameterIndex ] ; final int workerParameterIndex = parameterIndex ; Callable < double [ ] > worker = new Callable < double [ ] > ( ) { public double [ ] call ( ) { double parameterFiniteDifference ; if ( parameterSteps != null ) { parameterFiniteDifference = parameterSteps [ workerParameterIndex ] ; } else { /* * Try to adaptively set a parameter shift. Note that in some * applications it may be important to set parameterSteps. * appropriately. */ parameterFiniteDifference = ( Math . abs ( parametersNew [ workerParameterIndex ] ) + 1 ) * 1E-8 ; } // Shift parameter value parametersNew [ workerParameterIndex ] += parameterFiniteDifference ; // Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference try { setValues ( parametersNew , derivative ) ; } catch ( Exception e ) { // We signal an exception to calculate the derivative as NaN Arrays . fill ( derivative , Double . NaN ) ; } for ( int valueIndex = 0 ; valueIndex < valueCurrent . length ; valueIndex ++ ) { derivative [ valueIndex ] -= valueCurrent [ valueIndex ] ; derivative [ valueIndex ] /= parameterFiniteDifference ; if ( Double . isNaN ( derivative [ valueIndex ] ) ) { derivative [ valueIndex ] = 0.0 ; } } return derivative ; } } ; if ( executor != null ) { Future < double [ ] > valueFuture = executor . submit ( worker ) ; valueFutures . add ( parameterIndex , valueFuture ) ; } else { FutureTask < double [ ] > valueFutureTask = new FutureTask < double [ ] > ( worker ) ; valueFutureTask . run ( ) ; valueFutures . add ( parameterIndex , valueFutureTask ) ; } } for ( int parameterIndex = 0 ; parameterIndex < parameterCurrent . length ; parameterIndex ++ ) { try { derivatives [ parameterIndex ] = valueFutures . get ( parameterIndex ) . get ( ) ; } catch ( InterruptedException e ) { throw new SolverException ( e ) ; } catch ( ExecutionException e ) { throw new SolverException ( e ) ; } } }
The derivative of the objective function . You may override this method if you like to implement your own derivative .
593
21
146,597
private List < String > parseParams ( String param ) { Assert . hasText ( param , "param must not be empty nor null" ) ; List < String > paramsToUse = new ArrayList <> ( ) ; Matcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN . matcher ( param ) ; int start = 0 ; while ( regexMatcher . find ( ) ) { String p = removeQuoting ( param . substring ( start , regexMatcher . start ( ) ) . trim ( ) ) ; if ( StringUtils . hasText ( p ) ) { paramsToUse . add ( p ) ; } start = regexMatcher . start ( ) ; } if ( param != null && param . length ( ) > 0 ) { String p = removeQuoting ( param . substring ( start , param . length ( ) ) . trim ( ) ) ; if ( StringUtils . hasText ( p ) ) { paramsToUse . add ( p ) ; } } return paramsToUse ; }
Parses a string of space delimited command line parameters and returns a list of parameters which doesn t contain any special quoting either for values or whole parameter .
221
32
146,598
public static String load ( LoadConfiguration config , String prefix ) { if ( config . getMode ( ) == Mode . INSERT ) { return loadInsert ( config , prefix ) ; } else if ( config . getMode ( ) == Mode . UPDATE ) { return loadUpdate ( config , prefix ) ; } throw new IllegalArgumentException ( "Unsupported mode " + config . getMode ( ) ) ; }
Builds sql clause to load data into a database .
85
11
146,599
public static Map < String , String > parseProperties ( String s ) { Map < String , String > properties = new HashMap < String , String > ( ) ; if ( ! StringUtils . isEmpty ( s ) ) { Matcher matcher = PROPERTIES_PATTERN . matcher ( s ) ; int start = 0 ; while ( matcher . find ( ) ) { addKeyValuePairAsProperty ( s . substring ( start , matcher . start ( ) ) , properties ) ; start = matcher . start ( ) + 1 ; } addKeyValuePairAsProperty ( s . substring ( start ) , properties ) ; } return properties ; }
Parses a String comprised of 0 or more comma - delimited key = value pairs .
146
19