WebCab Options and Futures Demo v2.5 (J2SE Edition)

## webcab.lib.finance.options.pricing
Class EquityDerivatives

    java.lang.Object
      |
      +--webcab.lib.finance.options.pricing.EquityDerivatives

All Implemented Interfaces:
  Serializable

public class EquityDerivatives
extends Object
implements Serializable

The Equity Derivatives (BETA) Module is only included here for demonstration purposes. To get the latest version of this module please download the latest version of WebCab Bonds from our Web site.

### Overview

Using this class you are able to price a wide range of financial contracts on equity and interest instruments using a wide variety of price, interest rate and volatility models.

### Apply the functionality

In order to price a contract in accordance with a given combination of models you will need to:

1. Set contract - Use one of the contract set methods within this interface.
2. Set Barrier - Use `setPriceBarrier` is you want the option to be triggered by a barrier.
3. Set interest rate model - Use one of the set methods for interest rate models. This will determine a model use for interest rates and allow you to calibrate the model.
4. Set price model - Use a set method for a pricing model to determine the model used for the underlying assets price evolution.
5. Set volatility model - Set the model to be used for the volatility.

Once you have set the contract and the price, barrier (if applicable), interest and volatility models you will be able to run the Monte Carlo simulation by calling `runSimulation`. Once the simulation is complete you will be able to read off the price of the given contract in accordance with the models specified by the above set methods. You will also be able read off the standard deviation of the price estimate and the minimum and maximum price expected to a given level of confidence, using:

1. `getPrice()` - Reads the price.
2. `getStddev()` - Reads the expected deviation of the price estimate.
3. `getMinPrice()` - The minimum price to a given level of confidence.
4. `getMaxPrice()` - The maximum price to a given level of confidence.

### The Set Methods

The Set Methods fall into the following categories:

1. Contract Set Methods
2. Interest Rate Model Set Methods
3. Price Models Set Methods
4. Volatility Model Set Methods
5. Simulation Run Methods

To price a financial contract you will need to call one of the set methods from each of the categories listed above in exactly the same fashion as is demonstrated within the QA Clients and is described above. Once you have called one of the "Simulation Run" methods you will be able to read off the values using the Get Methods.

For your convenience we have listed below these set methods contained within each of these categories with a brief description (or naming) following by a link to the methods documentation.

#### Contract Set Methods

1. Asian option - `setAsianOptionContract`
2. Binary option - `setBinaryOptionContract`
3. Cap (use with forward rate models only) - `setCapForwardContract`
4. Cap (can use with any interest rate model) - `setCapSpotContract`
5. Coupon Bond (i.e. cash instrument) - `setCouponBondContract`
6. Floor (use with forward rate models only) - `setFloorForwardContract`
7. Floor (use with any interest rate model) - `setFloorSpotContract`
8. Forward start stock option - `setForwardStartAtTheMoneyOptionContract`
9. Lookback option - `setLookbackOption`
10. Ladder Option - `setLadderOption`
11. Vanilla Swap (use with forward rate model only) - `setVanillaInterestRateSwapForward`
12. Vanilla Swap (use with any stop rate model) - `setVanillaInterestRateSwapSpot`
13. Vanilla Stock option - `setVanillaOptionContract`
14. Zero Coupon Bond (i.e. cash instrument) - `setZeroCouponBondContract`
15. Barrier contract - `setPriceBarrier`
16. Parisian contract - `setPriceBarrier`
17. Parasian contract - `setPriceBarrier`
18. Forward Contract - `setForwardContract`
19. Future Contract - `setFutureContract`

Remark: Within the documentation (given below) of a number of contracts we used the `max` operator. The `max` operator applied to two real numbers, say `A` and `B`, denoted by `max(A,B)`, is equal to the maximum of `A` and `B`.

#### Interest Rate Model Set Methods

1. Constant Spot Rate Model - `setConstantRateModel`
2. Constant (in time) yield curve interest rate model - `setConstantYieldCurveModel`
3. Vasicek one factor stochastic model of the spot rate - `setVasicekRateModel`
4. Black, Derman & Toy (BDT) one factor factor stochastic model of the spot rate - `setBlackDermanToyRateModel`
5. Brennan & Schwartz is a two factor stochastic model - `setBrennanSchwartzRateModel`
6. Cox, Ingersoll & Ross is an equilibrium model - `setCoxIngersollRossRateModel`
7. Ho & Lee model of the spot rate with automatic yield curve fitting using forward rates - `setFittedHoLeeRateModel`
8. Hull & White model of the spot rate with automatic yield curve fitting using forward rates - `setFittedHullWhiteRateModel`
9. Fong & Vasicek is a two factor model providing both the spot rate and the volatility of the spot rate - `setFongVasicekRateModel`
10. Heath, Jarrow and Morton is a model of the forward rate curve - `setHJMRateModel`
11. Ho & Lee is a one factor stochastic spot rate model - `setHoLeeRateModel`
12. Hull & White is a one factor stochastic spot rate model - `setHoLeeRateModel`
13. Longstaff & Schwartz is a two factor stochastic interest rate model - `setLongstaffSchwartzRateModel`
14. Brace, Gatarek and Musiela (BGM) model (also known as the LIBOR market model which is a model of the forward rate curve - `setSimplifiedBGMRateModel`

#### Price Models Set Methods

1. Constant price model - `setConstantPriceModel(double price)`
2. General Deterministic Price Model - `setDeterministPriceModel(KOrderDiff priceFunction, double currentTime)`
3. Lognormal Price model (used in Black-Scholes) - `setLognormalPriceModel`
4. Poisson Price Model - `setPoissonPriceModel`

#### Volatility Model Set Methods

1. Constant volatility model - `setConstantVolatilityModel(double)`
2. General deterministic Volatility model - `setDeterministVolatilityModel`
3. Hull & White Stochastic model of the Variance - `setHullWhiteVolatilityModel`
4. Hoston Stochastic Volatility model - `setHostonVolatilityModel`

#### Simulation Run Methods

1. Run Monte Carlo Simulation with the number of simulations as the sole exit criteria - `runSimulation(int, int, double)`
2. Run Monte Carlo Simulation with the number of simulations or the maximum error for a given confidence level being the dual exit criteria - `runSimulation(int, double, double, int, double)`

#### Get Methods

1. Get Price estimation - `getPrice()`
2. Get Standard Deviation of the price estimate - `getStddev()`
3. Get minimal expected price for a given confidence level - `getMinPrice(double)`
4. Get maximal expected price for a given confidence level - `getMaxPrice(double)`

### QA Client Examples

Probably the easiest way the see the application of this pricing module and the ease with which custom pricing models can be formulated for a range of interest rate derivatives is to view and run the QA Clients provided with this component. These clients can be found within the `Client / QAClients /` folder of this installation package.

The logic of the code of each of these client examples take the following form:

1. Set the contract and price, volatility and interest rate models.
   1. setConstract("contract parameters");
   2. setPriceModel("price model parameters");
   3. setVolatilityModel("volatility model parameters");
   4. setRateModel("rate model parameters");
2. Run the Monte Carlo simulation.
   1. runSimulation("simulation parameters (i.e. no of walk etc)");
3. Read off the results.
   1. getPrice();
   2. getStddev();
   3. getMinPrice("confidence level");
   4. getMaxPrice("confidence level");

See Also:
  Serialized Form

Constructor Summary
`EquityDerivatives()`

Method Summary
`double` `getMaxPrice(double confidence)` Returns the maximum value of the estimated price expected for a given confidence level for the last Monte Carlo simulation performed of the set contract (i.e. asset) in accordance with the price, volatility and interest rate models used.
`double` `getMinPrice(double confidence)` Returns the minimum value of the estimated price expected for a given confidence level for the last Monte Carlo simulation performed of the set contract (i.e. asset) in accordance with the price, volatility and interest rate models used.
`double` `getPrice()` Returns the price of the contract set (i.e. asset) priced in accordance with the price, volatility and interest rate models set using the Monte Carlo simulation performed.
`double` `getStddev()` Returns the standard deviation of the price estimate given by the last Monte Carlo simulation performed of the set contract (i.e. asset) in accordance with the price, volatility and interest rate models used.
`void` `runSimulation(int timeSteps, double confidence, double maxRelativeError, int maxRandomWalks, double timeToEvaluation)` Performs the Monte Carlo simulation for the set (cash or derivative) contract, in accordance to the set price model, interest rate model and volatility model; and returns the result found when it satisfies a given level in confidence and maximum relative error.
`void` `runSimulation(int monteCarloTimesteps, int monteCarloRandomWalks, double currentTime)` Performs the Monte Carlo simulation for a fixed number of random walks for the set (cash or derivative) contract, in accordance to the set price model, interest rate model and volatility model.
`void` `setAsianOptionContract(BlackScholesConstants callPut, BlackScholesConstants strikeRate, BlackScholesConstants arithmGeom, double maturity, double strike, double updatingInterval)` Implements an Asian option contract.
`void` `setBinaryOptionContract(BlackScholesConstants type, double maturity, double strike, double amount)` Implements a stock Binary option contract.
`void` `setBlackDermanToyRateModel(Function phi, KOrderDiff sigma, double initialRate)` Implements the Black, Derman & Toy (BDT) one factor stochastic spot rate model.
`void` `setBlackKarasinskiRateModel(Function phi, Function modelFunction, Function sigma, double initialRate)` Implements the Black & Karasinski is a one factor stochastic spot rate model.
`void` `setBrennanSchwartzRateModel(double a1, double b1, double sigma1, double a2, double b2, double c2, double sigma2, double initialShortRate, double initialLongRate)` Implements the Brennan & Schwartz two factor stochastic interest rate model.
`void` `setCapForwardContract(double principal, double firstResetDate, double capRate, double tenor, double expiry)` Implements a Cap contract which can only be priced in conjunction with a forward rate model.
`void` `setCapSpotContract(double principal, double firstResetDate, double capRate, double tenor, double expiry)` Implements a Cap contract which can be priced in conjunction with any interest rate model.
`void` `setConstantPriceModel(double price)` Implements the constant price model which assumes that the price is constant.
`void` `setConstantRateModel(double rate)` Implements the Constant Spot Rate model which assumes that the spot rate is a constant.
`void` `setConstantVolatilityModel(double volatility)` Implements the constant volatility model which is deterministic in nature.
`void` `setConstantYieldCurveModel(double[] forwardRates, double[] maturities, int numberMaturities, BlackScholesConstants interpolationType, double currentTime)` Implements the Constant (in time) yield curve interest rate model.
`void` `setCouponBondContract(double principal, double firstCouponDate, double couponInterest, double couponPeriod, double expiry)` Implements the fixed income security (i.e. contract) known as a Coupon Bond.
`void` `setCoxIngersollRossRateModel(double equilibriumRate, double adjustmentSpeed, double sigma, double initialRate)` Implements the Cox, Ingersoll and Ross interest rate model.
`void` `setDeterministPriceModel(KOrderDiff priceFunction, double currentTime)` Implements a General Deterministic Price Model.
`void` `setDeterministVolatilityModel(KOrderDiff volatilityFunction, double value, double currentTime)` Implements a General deterministic Volatility model.
`void` `setFittedHoLeeRateModel(double[] forwardRates, double[] maturities, int numberMaturities, BlackScholesConstants interpolationType, double currentTime, double sigma)` Implements the Ho & Lee model of the spot rate with automatic yield curve fitting using forward rates.
`void` `setFittedHullWhiteRateModel(double[] forwardRates, double[] maturities, int numberMaturities, BlackScholesConstants interpolationType, double currentTime, double adjustmentSpeed, double sigma)` Implements the Hull & White model of the spot rate with automatic yield curve fitting using forward rates.
`void` `setFloorForwardContract(double principal, double settlement, double floorRate, double tenor, double expiry)` Implements a Floor contract which can only be priced in conjunction with forward curve models.
`void` `setFloorSpotContract(double principal, double firstResetDate, double floorRate, double tenor, double expiry)` Implements a Floor contract which can be pricing in conjunction within any interest rate model.
`void` `setFongVasicekRateModel(double spotRateMean, double sqrVolMean, double meanReversionRateSpot, double meanReversionRateVariance, double volatilityVariance, double initialSpotRate, double initialSqrtVolatility)` Implements the Fong & Vasicek model which is a two factor model providing both the spot rate and the volatility of the spot rate.
`void` `setForwardContract(double settledPrice, double maturity, double amount)` Implements a forward contract.
`void` `setForwardStartAtTheMoneyOptionContract(BlackScholesConstants type, double maturity, double startTime, double amount)` Implements a Forward Start stock option contract.
`void` `setFutureContract(double settledPrice, double settlementTime, double maturity, double amount, double marginingPeriod)` Implements a futures contract.
`void` `setHJMRateModel(double[][] historicZcbPrices, double[] forwardRates, double[] maturities, int numberMaturities, double tolerance, int numberObservations, int numberPCAVectors, double dt, double currentTime, int internalMemorySteps)` Implements the Heath, Jarrow and Morton model of the forward rate curve.
`void` `setHoLeeRateModel(Function drift, double sigma, double initialRate)` Implements the Ho & Lee one factor stochastic spot rate model which provide a spot rate process which is a semi martingale.
`void` `setHostonVolatilityModel(double gamma, double delta, double initialVolatility)` Implements the Hoston Stochastic Volatility model.
`void` `setHullWhiteRateModel(Function averageLongTermRate, double adjustmentSpeed, double sigma, double initialRate)` Implements the Hull & White one factor stochastic spot rate model.
`void` `setHullWhiteVolatilityModel(double adjustmentSpeed, double averageLongTermVariance, double varianceVolatility, double initialVariance)` Implements the Hull & White Stochastic model of the Variance (recall that, `volatility = sqrt(variance)`).
`void` `setLadderOption(BlackScholesConstants callPut, BlackScholesConstants strikeRate, BlackScholesConstants minMax, double maturity, double strike, double[] ladderPrices, double updatingInterval)` Implements a Ladder option contract.
`void` `setLognormalPriceModel(double initialPrice)` Implements the Lognormal model of the dynamics of the asset prices.
`void` `setLongstaffSchwartzRateModel(double xMean, double yMean, double reversionX, double reversionY, double c, double d, double initialX, double initialY)` Implements the Longstaff & Schwartz two factor stochastic interest rate model.
`void` `setLookbackOption(BlackScholesConstants callPut, BlackScholesConstants strikeRate, BlackScholesConstants minMax, double maturity, double strike, double updatingInterval)` Implements a Lookback option contract.
`void` `setPoissonPriceModel(double initialPrice, double intensity, double jumpStddev)` Implements the jump-diffusion price model for the dynamics of asset prices.
`void` `setPriceBarrier(BlackScholesConstants triggeredBy, BlackScholesConstants type, BlackScholesConstants upDown, BlackScholesConstants inOut, double barrierLevel, double rebate, double monitoringInterval, double timeToTrigger)` Implements a Barrier, Parisian or Parasian contract triggered by a price with a simple constant barrier.
`void` `setSimplifiedBGMRateModel(double[] discreteCurrentForwardRate, double[] capletVolatilities, double[] resetDates, int forwardCurveSteps, double currentTime)` Implements the Brace, Gatarek and Musiela (BGM) model (also known as the LIBOR market model) of the forward rate curve.
`void` `setVanillaInterestRateSwapForward(double principal, double fixedRate, double firstResetDate, double tenor, double expiry)` Implements a standard plain Vanilla Swap contract which must be priced in conjunction with a forward curve rate model.
`void` `setVanillaInterestRateSwapSpot(double principal, double fixedRate, double firstResetDate, double tenor, double expiry)` Implements an approximation of a plain vanilla swap contract which can be priced in conjunction with any spot rate model.
`void` `setVanillaOptionContract(BlackScholesConstants callPut, double maturity, double strike, double amount)` Implements a Vanilla stock option contract.
`void` `setVanillaSwaptionSpotContract(BlackScholesConstants callPut, double maturity, double strike, double amount, double principal, double fixedRate, int monteCarloTimesteps, int monteCarloRandomWalks, double firstResetDate, double tenor, double expiry)` Implements an Option on a Vanilla Swap approximation which can be priced in accordance with any rate model.
`void` `setVasicekRateModel(double averageLongTermRate, double adjustmentSpeed, double sigma, double initialRate)` Implements the Vasicek one factor stochastic model of the spot rate.
`void` `setZeroCouponBondContract(double principal, double maturity)` Implements a fixed income security known as a Zero Coupon bond.

Methods inherited from class java.lang.Object
`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

Constructor Detail

### EquityDerivatives

    public EquityDerivatives()

Method Detail

### setAsianOptionContract

    public void setAsianOptionContract(BlackScholesConstants callPut,
                                       BlackScholesConstants strikeRate,
                                       BlackScholesConstants arithmGeom,
                                       double maturity,
                                       double strike,
                                       double updatingInterval)
                                throws EvaluationException,
                                       EquityDerivativesDemoException

  Implements an Asian option contract.

  #### Types of Asian Options

  There are four types of Asian option:

  - average rate call (or average price call): payoff = max(average - strike price, 0)
  - average rate put (or average rate put): payoff = max(strike price - average, 0)
  - average strike call: payoff = max(final price - average price)
  - average strike put: payoff = max(average price - final price)

  Where the average use can be either arithmetic or geometric.

  Parameters:
    `callPut` - either `BlackScholesConstants.CALL` or `BlackScholesConstants.PUT`, to indicate whether the option is a call option or a put option.
    `strikeRate` - either STRIKE or RATE
    `arithmGeom` - specifies the type of averaging used. Either ARITHMETIC or GEOMETRIC
    `maturity` - the expiry time (in years, absolute time)
    `strike` - the strike price - used only for rate (price) Asian options
    `updatingInterval` - the interval of updating the value of the average in years (i.e. `0.1` means updating with take place 10 times a year.
    `EvaluationException`
    `EquityDerivativesDemoException`

### setBinaryOptionContract

    public void setBinaryOptionContract(BlackScholesConstants type,
                                        double maturity,
                                        double strike,
                                        double amount)
                                 throws EquityDerivativesDemoException

  Implements a stock Binary option contract.

  Parameters:
    `type` - either BinaryOption.CALL (for call options) or BinaryOption.PUT (for put options)
    `maturity` - the expiry time (in years, absolute time)
    `strike` - the strike price
    `amount` - the sum which will be payed if the option is exercised
    `EquityDerivativesDemoException`

### setCapForwardContract

    public void setCapForwardContract(double principal,
                                      double firstResetDate,
                                      double capRate,
                                      double tenor,
                                      double expiry)
                               throws EquityDerivativesDemoException

  Implements a Cap contract which can only be priced in conjunction with a forward rate model.

  #### Description of Contract

  A cap guarantees to the holder that floating interest rates will not exceed a predefined maximum level. If the rates go beyond this level, the holder will be compensated by receiving the fraction that capped from a fixed premium.

  #### Payoff Function of the Cap Contract

  The payoff function for this contract is:

  1. `principal * max(floatingRate - capRate, 0)`.
  where the `principle` is the sum which is insured against interest rate fluctuations, `floatingRate` is the floating rate modeling in accordance with the set interest rate model, `capRate` is the

  #### Compatible Rate Models

  The Cap contract can only be priced using a forward curve model for the interest rates. Two such models provide within this pricing framework our: `setHJMRateModel(double[][], double[], double[], int, double, int, int, double, double, int)` and `setSimplifiedBGMRateModel(double[], double[], double[], int, double)`.

  Parameters:
    `principal` - the sum which is insured against interest rate fluctuations
    `firstResetDate` - the moment when the first payment takes place
    `capRate` - the maximum admissible interest rate without compensation
    `tenor` - the period between two consecutive regular payments
    `expiry` - the maturity time of the contract
    `EquityDerivativesDemoException`

### setCapSpotContract

    public void setCapSpotContract(double principal,
                                   double firstResetDate,
                                   double capRate,
                                   double tenor,
                                   double expiry)
                            throws EvaluationException,
                                   EquityDerivativesDemoException

  Implements a Cap contract which can be priced in conjunction with any interest rate model.

  #### Description of Contract

  A cap guarantees to the holder that floating interest rates will not exceed a predefined maximum level. If the rates go beyond this level, the holder will be compensated by receiving the fraction that capped from a fixed premium.

  #### Payoff Function

  The payoff function for this contract is:

  - `principal * max(floatingRate - capRate, 0)`.
  where the `principle` is the sum which is insured against interest rate fluctuations, `floatingRate` the present floating rate against which the swap is considered and `capRate` is the maximum admissible interest rate before compensation is due.

  Parameters:
    `principal` - the sum which is insured against interest rate fluctuations
    `firstResetDate` - the moment when the first payment takes place
    `capRate` - the maximum admissible interest rate without compensation
    `tenor` - the period between two consecutive regular payments
    `expiry` - the maturity time of the contract
    `EvaluationException`
    `EquityDerivativesDemoException`

### setCouponBondContract

    public void setCouponBondContract(double principal,
                                      double firstCouponDate,
                                      double couponInterest,
                                      double couponPeriod,
                                      double expiry)
                               throws EvaluationException,
                                      EquityDerivativesDemoException

  Implements the fixed income security (i.e. contract) known as a Coupon Bond.

  #### Description of Coupon Bond

  A coupon bond pays a principal at expiry (in exactly the same way as `setZeroCouponBondContract(double, double)`). Additionally it pays an interest on the principal at fixed and equal intervals of time (know as the coupon period) beginning with a specified moment first coupon date until expiry.

  Parameters:
    `principal` - the amount paid at expiry
    `firstCouponDate` - the time when the first coupon is paid
    `couponInterest` - the fraction of the principal paid at each coupon date
    `couponPeriod` - the interval between two coupon payments
    `expiry` - the moment when the principal is paid
    `EvaluationException`
    `EquityDerivativesDemoException`

### setFloorForwardContract

    public void setFloorForwardContract(double principal,
                                        double settlement,
                                        double floorRate,
                                        double tenor,
                                        double expiry)
                                 throws EvaluationException,
                                        EquityDerivativesDemoException

  Implements a Floor contract which can only be priced in conjunction with forward curve models.

  #### Description of Contract

  A floor guarantees to the holder that floating interest rates will not exceed a predefined maximum level. If the rates go beyond this level, the holder will be compensated by receiving the fraction that is beneath the minimum from a fixed premium.

  #### Payoff Function

  The payoff function for this contract is:

  - `principal * max(floorRate - floatingRate, 0)`.
  where the `principle` is the sum which is insured against interest rate fluctuations, `floatingRate` the present floating rate against which the floor is considered and `floorRate` is the minimum admissible interest rate before compensation is due.

  #### Compatible (Forward) Rate Models

  The Cap contract can only be priced using a forward curve model for the interest rates. Two such models are presently provided: `setHJMRateModel(double[][], double[], double[], int, double, int, int, double, double, int)` and `setSimplifiedBGMRateModel(double[], double[], double[], int, double)`.

  Parameters:
    `principal` - the sum which is insured against interest rate fluctuations
    `settlement` - the settlement date for this contract (first cash flow will be exchanged at moment `settlement + tenor`
    `floorRate` - the minimum admissible interest rate without compensation
    `tenor` - the period between two consecutive regular payments
    `expiry` - the maturity time of the contract
    `EvaluationException`
    `EquityDerivativesDemoException`

### setFloorSpotContract

    public void setFloorSpotContract(double principal,
                                     double firstResetDate,
                                     double floorRate,
                                     double tenor,
                                     double expiry)
                              throws EvaluationException,
                                     EquityDerivativesDemoException

  Implements a Floor contract which can be pricing in conjunction within any interest rate model.

  #### Description of Contract

  A floor guarantees to the holder that floating interest rates will not go beneath a predefined minimum level. If this happens, the holder will be compensated by receiving the fraction beneath the level from a fixed premium.

  #### Payoff Function

  The payoff function for this contract is:

  - `principal * max(floorRate - floatingRate, 0)`.
  where the `principle` is the sum which is insured against interest rate fluctuations, `floatingRate` the present floating rate against which the floor is considered and `floorRate` is the minimum admissible interest rate before compensation is due.

  Parameters:
    `principal` - the sum which is insured against interest rate fluctuations
    `firstResetDate` - the moment when the first payment takes place
    `floorRate` - the minimum admissible interest rate without compensation
    `tenor` - the period between two consecutive regular payments
    `expiry` - the maturity time of the contract
    `EvaluationException`
    `EquityDerivativesDemoException`

### setForwardContract

    public void setForwardContract(double settledPrice,
                                   double maturity,
                                   double amount)
                            throws EvaluationException,
                                   EquityDerivativesDemoException

  Implements a forward contract.

  #### Payoff Function

  The payoff of a forward contract is:

  - `payoff = (finalPrice - settledPrice) * amount`
  where `finalPrice` is the market price of the futures contract at expiry, `settledPrice` is the settlement price and `amount` is the amount which is paid at settlement.

  #### Comparison Between Future and Forward Contracts

  Though payoff function of the future and forward contract are the same these two contracts do fundamentally differ. The difference lies in the fact that the a future contract has a Mark-To-Market characteristic and hence provides a continuous cash flow, positive or negative, based on the current value of the underlying variable. This process is also often referred to as remargining and has the additional property that it reduces the credit exposure of the contract for both counter parties.

  #### Application of this Contract

  The principle reason for the inclusion of a forward contract with are general framework is to allow the implementation of the pricing of compound (non-linear) contracts involving Forwards. For example, an options contract which has a payoff of a forward contract, i.e. an option on a future contract.

  Parameters:
    `settledPrice` - the price fixed at settlement (strike price)
    `maturity` - the expiry time (in years, absolute time)
    `amount` - the number of shares which will be bought or sold
    `EvaluationException`
    `EquityDerivativesDemoException`

### setForwardStartAtTheMoneyOptionContract

    public void setForwardStartAtTheMoneyOptionContract(BlackScholesConstants type,
                                                        double maturity,
                                                        double startTime,
                                                        double amount)
                                                 throws EvaluationException,
                                                        EquityDerivativesDemoException

  Implements a Forward Start stock option contract. This option contract is at the money at the moment it starts (that is, its strike price is set to be equal to the price at the point when the contract is entered).

  Parameters:
    `type` - either VanillaOption.CALL (for call options) or VanillaOption.PUT (for put options)
    `maturity` - the expiry time (in years, absolute time)
    `startTime` - the starting moment. The strike price is considered to be the price recorded at this moment
    `amount` - the number of shares which will be bought or sold
    `EvaluationException`
    `EquityDerivativesDemoException`

### setFutureContract

    public void setFutureContract(double settledPrice,
                                  double settlementTime,
                                  double maturity,
                                  double amount,
                                  double marginingPeriod)
                           throws EvaluationException,
                                  EquityDerivativesDemoException

  Implements a futures contract.

  #### Payoff Function

  The payoff of the implemented futures contract is:

  - payoff = (finalPrice - settledPrice) * amount
  where `finalPrice` is the market price of the futures contract at expiry, `settledPrice` is the settlement price and `amount` is the amount which is paid at settlement.

  #### Comparison Between Future and Forward Contracts

  Though payoff function of the future and forward contract are the same these two contracts do fundamentally differ. The difference lies in the fact that the a future contract has a Mark-To-Market characteristic and hence provides a continuous cash flow, positive or negative, based on the current value of the underlying variable. This process is also often refereed to as remargining and has the additional property that it reduces the credit exposure of the contract for both counter parties.

  #### Application of this Contract

  The principle reason for the inclusion of a future contract with are general framework is to allow the implementation of the pricing of compound (non-linear) contracts involving futures. For example, an options contract which has a payoff of a futures contract, i.e. an option on a future contract.

  Parameters:
    `settledPrice` - the price fixed at settlement (strike price)
    `settlementTime` - the moment when the futures contract becomes effective
    `maturity` - the expiry time (in years, absolute time)
    `amount` - the number of shares which will be bought or sold
    `marginingPeriod` - the time interval between two successive Mark To Market cash exchanges (usually 1 day - it depends on the calendar you use how this translates into years - e.g. `1.0 / 260`, where `260` is the number of business days in a year)
    `EvaluationException`
    `EquityDerivativesDemoException`

### setLookbackOption

    public void setLookbackOption(BlackScholesConstants callPut,
                                  BlackScholesConstants strikeRate,
                                  BlackScholesConstants minMax,
                                  double maturity,
                                  double strike,
                                  double updatingInterval)
                           throws EvaluationException,
                                  EquityDerivativesDemoException

  Implements a Lookback option contract.

  #### Types of Lookback Options

  There are four types of lookback options:

  - rate call (or average price call): payoff = max(extremum - strike price, 0)
  - rate put (or average rate put): payoff = max(strike price - extremum, 0)
  - strike call: payoff = max(final price - extremum)
  - strike put: payoff = max(extremum - final price)
  where the extremum can be a minimum or a maximum.

  Parameters:
    `callPut` - either CALL or PUT
    `strikeRate` - either STRIKE or RATE
    `minMax` - specifies the type of extremum used. Either MIN or MAX.
    `maturity` - the expiry time (in years, absolute time)
    `strike` - the strike price - used only for rate (price) Asian options
    `updatingInterval` - the interval of updating the value of the extremum in years (i.e. `0.1` means updating with take place 10 times a year.
    `EvaluationException`
    `EquityDerivativesDemoException`

### setLadderOption

    public void setLadderOption(BlackScholesConstants callPut,
                                BlackScholesConstants strikeRate,
                                BlackScholesConstants minMax,
                                double maturity,
                                double strike,
                                double[] ladderPrices,
                                double updatingInterval)
                         throws EvaluationException,
                                EquityDerivativesDemoException

  Implements a Ladder option contract.

  #### Types of Ladder Options

  There are four types of ladder options:

  - rate call (or average price call): payoff = max(extremum - strike price, 0)
  - rate put (or average rate put): payoff = max(strike price - ladder(extremum), 0)
  - strike call: payoff = max(final price - ladder(extremum))
  - strike put: payoff = max(ladder(extremum) - final price)
  where the extremum can be either a minimum or a maximum.

  Parameters:
    `callPut` - either CALL or PUT
    `strikeRate` - either STRIKE or RATE
    `minMax` - specifies the type of extremum used. Either MIN or MAX.
    `maturity` - the expiry time (in years, absolute time)
    `strike` - the strike price - used only for rate (price) Asian options
    `ladderPrices` - a vector containing the discrete ladder prices.
    `updatingInterval` - the interval of updating the value of the average in years (i.e. `0.1` means updating with take place 10 times a year.
    `EvaluationException`
    `EquityDerivativesDemoException`

### setVanillaInterestRateSwapForward

    public void setVanillaInterestRateSwapForward(double principal,
                                                  double fixedRate,
                                                  double firstResetDate,
                                                  double tenor,
                                                  double expiry)
                                           throws EvaluationException,
                                                  EquityDerivativesDemoException

  Implements a standard plain Vanilla Swap contract which must be priced in conjunction with a forward curve rate model.

  #### Description of Vanilla Swap Contract

  The holder of this contract pays the other party a fixed percentage of the principal whilst receiving a variable amount. That is the contract exchanges a fixed interest rate for a floating one. Note that the rate model used will refer to a rate model for the floating rate must be provided which must in this case be a forward curve model (such as `HJM` or `BGM`).

  #### Compatible (Forward) Rate Models

  This Swap contract can only be priced using a forward curve model for the interest rates. Two such models are presently provided: `setHJMRateModel` and `setSimplifiedBGMRateModel`.

  Parameters:
    `principal` - the notional principal. This it's actually not exchanged at maturity, only used to compute the cash flow.
    `fixedRate` - the fixed interest rate paid
    `firstResetDate` - the date of the first payment
    `tenor` - the interval between payments
    `expiry` - the maturity date
    `EvaluationException`
    `EquityDerivativesDemoException`

### setVanillaInterestRateSwapSpot

    public void setVanillaInterestRateSwapSpot(double principal,
                                               double fixedRate,
                                               double firstResetDate,
                                               double tenor,
                                               double expiry)
                                        throws EvaluationException,
                                               EquityDerivativesDemoException

  Implements an approximation of a plain vanilla swap contract which can be priced in conjunction with any spot rate model.

  #### Description of Vanilla Swap Contract

  The holder of this contract pays the other party a fixed percentage of the principal whilst receiving a variable amount. That's exchanging a fixed interest rate for a floating one. A model for the floating rate must be provided. This can be any interest rate model provided with our product.

  Parameters:
    `principal` - the notional principal. This it's actually not exchanged at maturity, only used to compute the cash flow.
    `fixedRate` - the fixed interest rate paid
    `firstResetDate` - the date of the first payment
    `tenor` - the interval between payments
    `expiry` - the maturity date
    `EvaluationException`
    `EquityDerivativesDemoException`

### setVanillaOptionContract

    public void setVanillaOptionContract(BlackScholesConstants callPut,
                                         double maturity,
                                         double strike,
                                         double amount)
                                  throws EvaluationException,
                                         EquityDerivativesDemoException

  Implements a Vanilla stock option contract.

  #### Description of Vanilla Option

  The holder of a vanilla call or put option contact has the right to either buy or sell (respectively) the underlying asset at the strike price at the maturity of the contract.

  Parameters:
    `callPut` - either BlackScholesConstants.CALL (for call options) or BlackScholesConstants.PUT (for put options)
    `maturity` - the expiry time (in years, absolute time)
    `strike` - the strike price
    `amount` - the number of shares which will be bought or sold
    `EvaluationException`
    `EquityDerivativesDemoException`

### setVanillaSwaptionSpotContract

    public void setVanillaSwaptionSpotContract(BlackScholesConstants callPut,
                                               double maturity,
                                               double strike,
                                               double amount,
                                               double principal,
                                               double fixedRate,
                                               int monteCarloTimesteps,
                                               int monteCarloRandomWalks,
                                               double firstResetDate,
                                               double tenor,
                                               double expiry)
                                        throws EvaluationException,
                                               EquityDerivativesDemoException

  Implements an Option on a Vanilla Swap approximation which can be priced in accordance with any rate model.

  Parameters:
    `callPut` - either BlackScholesConstants.CALL (for call options) or BlackScholesConstants.PUT (for put options)
    `maturity` - the expiry time (in years, absolute time)
    `strike` - the strike price
    `amount` - the number of shares which will be bought or sold
    `principal` - the notional principal. This it's actually not exchanged at maturity, only used to compute the cash flow.
    `fixedRate` - the fixed interest rate paid
    `monteCarloTimesteps` - the number of time axis divisions for one random walk
    `monteCarloRandomWalks` - the number of random walks executed
    `firstResetDate` - the date of the first payment
    `tenor` - the interval between payments
    `expiry` - the maturity date
    `EvaluationException`
    `EquityDerivativesDemoException`

### setZeroCouponBondContract

    public void setZeroCouponBondContract(double principal,
                                          double maturity)
                                   throws EvaluationException,
                                          EquityDerivativesDemoException

  Implements a fixed income security known as a Zero Coupon bond.

  #### Description of Contract

  The bond pays a specified amount of money known as the principal to the contract holder at the maturity of the bond.

  Parameters:
    `principal` - the amount received at maturity
    `maturity` - the maturity date (absolute time - not time relative to start time).
    `EvaluationException`
    `EquityDerivativesDemoException`

### setPriceBarrier

    public void setPriceBarrier(BlackScholesConstants triggeredBy,
                                BlackScholesConstants type,
                                BlackScholesConstants upDown,
                                BlackScholesConstants inOut,
                                double barrierLevel,
                                double rebate,
                                double monitoringInterval,
                                double timeToTrigger)
                         throws EvaluationException,
                                EquityDerivativesDemoException

  Implements a Barrier, Parisian or Parasian contract triggered by a price with a simple constant barrier.

  Parameters:
    `triggeredBy` - can be either PRICE, RISK_FREE_RATE, PRICE_VOLATILITY
    `type` - can be either BARRIER, PARISIAN or PARASIAN.
    `upDown` - can be either UP or DOWN.
    `inOut` - can be either IN or OUT.
    `barrierLevel` - the price level for which the barrier is triggered
    `rebate` - the compensation paid instead of the normal payoff
    `monitoringInterval` - the variable which may trigger the contract is not continuously monitored. Only at this time interval the value is recorded and the trigger state is updated.
    `timeToTrigger` - this parameter is used only for Parisian or Parasian contracts. It is the minimum amount of time which must be spent with the barrier condition active, before the contract is triggered. For Parisians this time must be not interrupted. The Parisians use the total time spent (even with interruptions).
  Throws:
    `EvaluationException`
    `EquityDerivativesDemoException`

### setConstantRateModel

    public void setConstantRateModel(double rate)
                              throws EquityDerivativesDemoException

  Implements the Constant Spot Rate model which assumes that the spot rate is a constant.

  #### Description of Rate Model

  This interest rate model is deterministic in nature and should be very familiar to the reader since it is the interest rate model used within the classical Black-Scholes model.

  Parameters:
    `rate` - the constant value of the spot interest rate
    `EquityDerivativesDemoException`

### setConstantYieldCurveModel

    public void setConstantYieldCurveModel(double[] forwardRates,
                                           double[] maturities,
                                           int numberMaturities,
                                           BlackScholesConstants interpolationType,
                                           double currentTime)
                                    throws EquityDerivativesDemoException

  Implements the Constant (in time) yield curve interest rate model.

  #### Description of Model

  This model assumes that the forward rate, as a function of absolute time, does not change over time. This means that, advancing in time, the spot rate follows a deterministic path, which is given by the forward rate curve set at the initial moment.

  #### Representing the Rate Curve

  A forward rate curve is a function of one real variable namely time, and the shape of the forward curve in accordance with this model does not change with time. Here we apply interpolation and other approximation methods in order to construct the curve from a number of tabulation points. In particular, the forward rate curve is specified at different discrete maturities of the forward rate (e.g. 1 month, 2 months, 3 months, etc.). These values of the forward rate can either be directly read from the market prices of zero coupon bonds or implied from the market prices of other interest rate securities such as swap prices. For further details concerning the evaluating points on the forward curve we refer the reader to the Basic Bonds module of this product and/or the section of the accompanying documentation entitled `Fundamental Theory of Bonds'.

  Once the discrete values of the forward curve are known we are able to use an interpolation and other approximation procedure over these discrete tabulation values in order to construct the full forward rate curve between the maximum and minimum maturities which are considered.

  #### Selecting an Forward Rate Construction

  The particular procedure of interpolation or other approximation procedure to use will depend on your view of forward rates. In particular, there is no `right way' to interpolate a set of forward rates of differing maturities to construct the forward rate curve and the broader literature takes a number of points of view with regard to this matter. However, within this method we allow you to select from the three most popular approaches of the construction of the forward rate:

  1. Constant interpolation algorithm - the forward rate is considered to be constant on the intervals between the discrete points. At each point the forward rate makes a sudden jump to the next interpolation point, thus making the forward curve non-differentiable which is a disadvantage of this approach. It is also the case that this method is not usable for fitting.
  2. Linear approximation algorithm - this approach in recommended in most cases and is the only method which can be fitted in a consistent manner using market data. Though this approach is not an interpolation procedure it is based on interpolation since the basic idea to is interpolate the integral of the forward rate, rather than the forward rates themselves. The fitted forward curve produced by this procedure will be continuous and differentiable and hence is amenable to further analysis. The two main disadvantages with this approach our:
     1. The forward curve constructed may not necessarily pass through all the points given.
     2. The derivative of the forward curve may not be continuous.
  3. Cubic spline interpolation algorithm - This interpolation procedure produces a smooth function and is compatible with fitting, however the curve found may not be consistent with market prices.

  #### Providing the Parameters

  A forward rate is specified using pairs of the following type `(forwardRate, maturity)`. These values are given in two separate vectors: `forwardRates` and `maturities`, where the values contained with these vectors correspond in the following sense:

  - `forwardRate[0]` contains the spot rate - that is the forward rate with zero time until maturity, that is, here the maturity is zero.
  - `forwardRate[1]` contains the rate with maturity = `maturities[0]`
  - `forwardRate[2]` contains the rate with maturity = `maturities[1]`
  - ..............................................................
  - `forwardRate[nMaturities - 1]` contains the rate with maturity = `maturities[numberMaturities - 2]`
  As you can see, the length of the `forwardRate` and `maturities` vectors are equal. The last value `maturities[numberMaturities - 1]` has no corresponding forward rate and is used to give a point in time such that the forward rates beyond this point can be considered unknown - or undefined.

  Parameters:
    `forwardRates` - the vector of forward rates as described above.
    `maturities` - the vector of maturities given in absolute time. That is, to represent the maturity of say 1st March 2004, we would write `2004 + (2.0/12)`, and so on.
    `numberMaturities` - the number of maturities (or forward rates) given
    `interpolationType` - can be either `CONSTANT`, `LINEAR` or `SPLINE`, depending on whether the constant interpolation, linear approximation or cubic spline interpolation procedures respectively are used in order to construct the forward curve from the set of discrete known points.
    `currentTime` - the current time in absolute terms. That is, if the current date is 1st April 2006 - then in absolute terms we would represent it as `2006.25`, since `(2006 years + 3 months)/ 12 months = 2006.25`.
    `EquityDerivativesDemoException`

### setVasicekRateModel

    public void setVasicekRateModel(double averageLongTermRate,
                                    double adjustmentSpeed,
                                    double sigma,
                                    double initialRate)
                             throws EquityDerivativesDemoException

  Implements the Vasicek one factor stochastic model of the spot rate.

  #### Description of Vasicek one factor Rate model

  This model of the spot rate process is a semi martingale and is in fact a particular case of the Hull-White model. This model cannot be fitted to a particular yield curve.

  The Vasicek model generates an elastic random walk around a trend in the sense that it is mean-reverting. The model also does not guarantee the positivity of the interest rates and assumes that the variance of the process (i.e. spot rate around the average spot rate) is constant.

  #### Stochastic Differential Equation of the Vasicek Model

  The stochastic differential equation of the Vasicek model is:

  - `dr = adjustmentSpeed * (averageLongTermRate - r) * dt + sigma * dW`
  where the `adjustmentSpeed` is the reversion speed, `averageLongTermRate` the long term average rate of the spot rate, `sigma` is a measure of the spot rate volatility, `dr` roughly speaking is the change of the spot rate, `dt` is the corresponding change in time and `dW` represents the random variable.

  Parameters:
    `averageLongTermRate` - the long term average rate of the spot rate
    `adjustmentSpeed` - the reversion speed (towards the long term average value of the spot rate)
    `sigma` - a measure of the spot rate volatility
    `initialRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setBlackDermanToyRateModel

    public void setBlackDermanToyRateModel(Function phi,
                                           KOrderDiff sigma,
                                           double initialRate)
                                    throws EquityDerivativesDemoException

  Implements the Black, Derman & Toy (BDT) one factor stochastic spot rate model.

  #### Description oh BDT rate model

  The BDT spot rate process is a semi martingale which generates a model which can be fitted is historical price data.

  #### Models Stochastic Differential Equation

  The corresponding stochastic differential equation for this model is given by:

  - `d(log(r)) = (phi(t) - sigma'(t)/sigma(t) * log(r)) * dt + sigma(t) * dW`
  where `sigma'(t)` is the first derivative of `sigma(t)`.

  Parameters:
    `phi` - a function of one variable (some class implementing the `Function` interface).
    `sigma` - a smooth function of one variable (some class implementing the `KOrderDiff` interface).
    `initialRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setBlackKarasinskiRateModel

    public void setBlackKarasinskiRateModel(Function phi,
                                            Function modelFunction,
                                            Function sigma,
                                            double initialRate)
                                     throws EquityDerivativesDemoException

  Implements the Black & Karasinski is a one factor stochastic spot rate model.

  #### Description of the Rate Model

  The spot rate process is a semi martingale for which the resulting model can be fitted to market data.

  #### Models Stochastic Differential Equation

  The stochastic differential equation is:

  - `d(log(r)) = (phi(t) - a(t) * log(r)) * dt + sigma(t) * dW`

  Parameters:
    `phi` - a function of one variable (some class implementing the `Function` interface).
    `modelFunction` - a function of one variable (a class implementing the `Function` interface).
    `sigma` - a function of one variable (a class implementing the `Function` interface).
    `initialRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setBrennanSchwartzRateModel

    public void setBrennanSchwartzRateModel(double a1,
                                            double b1,
                                            double sigma1,
                                            double a2,
                                            double b2,
                                            double c2,
                                            double sigma2,
                                            double initialShortRate,
                                            double initialLongRate)
                                     throws EquityDerivativesDemoException

  Implements the Brennan & Schwartz two factor stochastic interest rate model.

  #### Models Stochastic Differential Equation

  The stochastic differential equations are:

  - `dr = (a1 + b1 * (l - r)) * dt + sigma1 * r * dW1`
  - `dl = l * (a2 - b2 * r + c2 * l) * dt + sigma2 * l * dW2`
  Where the first factor of the model `r`, is the spot rate, and the second factor of the model `l`, is the long rate (or unspecified maturity).

  Parameters:
    `a1` - real constant influencing the drift of the spot rate
    `b1` - real constant - the reversion of the spot rate to the long rate
    `sigma1` - a measure of the volatility of the spot rate
    `a2` - real constant influencing the drift of the long rate
    `b2` - real constant influencing the drift of the long rate
    `c2` - real constant influencing the drift of the long rate
    `sigma2` - a measure of the volatility of the long rate
    `initialShortRate` - the initial value of the spot rate
    `initialLongRate` - the initial value of the long rate
    `EquityDerivativesDemoException`

### setCoxIngersollRossRateModel

    public void setCoxIngersollRossRateModel(double equilibriumRate,
                                             double adjustmentSpeed,
                                             double sigma,
                                             double initialRate)
                                      throws EquityDerivativesDemoException

  Implements the Cox, Ingersoll and Ross interest rate model.

  #### Description of Model

  This model is an equilibrium model derived under the assumption that interest rates are determined by the supply and demand of individuals having a logarithmic utility function.

  This model is very similar to `Vasicek`, with the exception that its variance is proportional to the short rate, rather than being constant. It is also the case that this model guarantees the positivity of interest rates if the following condition is satisfied:
  `sigma * sigma < 2 * adjustmentSpeed * averageLongTermRate`

  #### Models Stochastic Differential Equation

  The spot rate process is a semi martingale and the models stochastic differential equation is:

  - `dr = adjustmentSpeed * (equilibriumRate - r) * dt + sigma * sqrt(r) * dW`
  where `adjustmentSpeed` represents the reversion speed of the spot rate towards the long term average value, `equilibriumRate` the equilibrium value of the spot rate and `sigma` is the measure of the spot rate volatility.

  Parameters:
    `equilibriumRate` - the equilibrium value of the spot rate
    `adjustmentSpeed` - represents the reversion speed of the spot rate towards the equilibrium rate
    `sigma` - a measure of the spot rate volatility
    `initialRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setFittedHoLeeRateModel

    public void setFittedHoLeeRateModel(double[] forwardRates,
                                        double[] maturities,
                                        int numberMaturities,
                                        BlackScholesConstants interpolationType,
                                        double currentTime,
                                        double sigma)
                                 throws EquityDerivativesDemoException

  Implements the Ho & Lee model of the spot rate with automatic yield curve fitting using forward rates.

  #### Calibration

  In order for the calibration process to work, the forward rate function must be differentiable and it should be used with an approximation algorithm consistent with market prices - so only `LINEAR` is suitable.

  Parameters:
    `forwardRates` - the vector of forward rates
    `maturities` - the vector of maturities. The maturities are given as absolute times, that is, the date 1st March 2004, would be represented as `2004.25`, since `currentTime = 2004 + 2. / 12`.
    `numberMaturities` - the number of rates (and maturities)
    `interpolationType` - can be either `CONSTANT`, `LINEAR` or `SPLINE`.
    `currentTime` - the current time (absolute time).
    `sigma` - a measure of the volatility.
    `EquityDerivativesDemoException`

### setFittedHullWhiteRateModel

    public void setFittedHullWhiteRateModel(double[] forwardRates,
                                            double[] maturities,
                                            int numberMaturities,
                                            BlackScholesConstants interpolationType,
                                            double currentTime,
                                            double adjustmentSpeed,
                                            double sigma)
                                     throws EquityDerivativesDemoException

  Implements the Hull & White model of the spot rate with automatic yield curve fitting using forward rates.

  #### Calibration

  In order for the calibration process to work, the forward rate function must be differentiable and it should be used with an approximation algorithm consistent with market prices - so only `LINEAR` is suitable.

  Parameters:
    `forwardRates` - the vector of forward rates
    `maturities` - the vector of maturities. The maturities are given as absolute times, that is, the date 1st March 2004, would be represented as `2004.25`, since `currentTime = 2004 + 2. / 12`.
    `numberMaturities` - the number of maturities (or rates) given.
    `interpolationType` - can be either `CONSTANT`, `LINEAR` or `SPLINE`.
    `currentTime` - the current time (absolute time).
    `sigma` - a measure of the volatility
    `EquityDerivativesDemoException`

### setFongVasicekRateModel

    public void setFongVasicekRateModel(double spotRateMean,
                                        double sqrVolMean,
                                        double meanReversionRateSpot,
                                        double meanReversionRateVariance,
                                        double volatilityVariance,
                                        double initialSpotRate,
                                        double initialSqrtVolatility)
                                 throws EquityDerivativesDemoException

  Implements the Fong & Vasicek model which is a two factor model providing both the spot rate and the volatility of the spot rate.

  #### Models Stochastic Differential Equation

  The stochastic differential equations are:

  - `dr = meanReversionRateSpot * (spotRateMean - r) * dt + sqrt(e) * dW1`
  - `de = meanReversionRateVariance * (varianceRateMean - e) * dt + volatilityVariance * sqrt(e) * dW2`
  where `r` is the spot rate, `e` is the variance (i.e. the volatility squared) of the spot rate, `meanReversionRateSpot` a constant indicating the mean-reversion speed of the spot rate to its long term trend rate, `meanReversionRateVariance` constant showing the mean-reversion speed of the variance to its long term trend rate and `volatilityVariance` the volatility of the variance.

  Parameters:
    `spotRateMean` - the long term trend rate around which the spot rate oscillates
    `meanReversionRateSpot` - a constant indicating the mean-reversion speed of the spot rate to its long term trend rate
    `meanReversionRateVariance` - constant showing the mean-reversion speed of the variance to its long term trend rate
    `volatilityVariance` - the volatility of the variance
    `initialSpotRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setHJMRateModel

    public void setHJMRateModel(double[][] historicZcbPrices,
                                double[] forwardRates,
                                double[] maturities,
                                int numberMaturities,
                                double tolerance,
                                int numberObservations,
                                int numberPCAVectors,
                                double dt,
                                double currentTime,
                                int internalMemorySteps)
                         throws EquityDerivativesDemoException

  Implements the Heath, Jarrow and Morton model of the forward rate curve.

  #### Description of Model

  This model uses instantaneous forward rates, rather than discrete ones as used in the case of `SimplifiedBGM`. Mathematically speaking, the HJM model is an infinite-factor model, in that it uses infinite-dimensional Brownian motions. In order to simulate this infinite dimensional model on a computer the model is discretized and only a finite number of dimensions or equivalently forward rates are used.

  #### Models Stochastic Differential Equation

  The stochastic differential equation for HJM is:

  - dF(t; T) = m(t, T) * dt + vol(t, T) * dW,

  where `F(t, T)` is the forward rate with maturity `T` at moment `t`; `m(t, T)` is the drift of the forward rate with maturity `T` and `vol(t, T)` is the volatility of the above mentioned rate.

  #### Applying the Model

  It is known that if the drifts of forward rates under the risk-neutral probability are entirely determined by their volatility (according to a certain formula) - the model is risk-neutral. You have thus the freedom to choose any volatility structure you want. The HJM specification is so general that almost all models are in fact particular cases of it.

  The volatility of the forward rates is automatically computed to fit the market data:

  - Model calibration using Principal Component Analysis: the historic values of zero coupon bond prices are required to compute the volatility structure.

  Parameters:
    `forwardRates` - the vector of forward rates
    `maturities` - the vector of maturities. The maturities are given as absolute times. Suppose today's date is 1-st of March 2004 => the absolute time is `currentTime = 2004 + 2. / 12`. Suppose that the rates are given at each month. => `maturities[0] = 2004 + 3. / 12 = 2004.25`; `maturities[1] = 2004 + 4. / 12 = 2004.33`; etc.
    `numberMaturities` - the number of rates (and maturities)
    `tolerance` - a tolerance used as stopping condition in the Power method for finding the eigenvectors of a matrix (needed in the PCA algorithm). A recommended value for this parameter is 1E-12.
    `numberObservations` - the number of historic values of zero coupon bond prices recorded for each maturity
    `numberPCAVectors` - the number of forward volatility stochastic factor you want to find using PCA
    `dt` - the fixed time interval between two consecutive observations of zero coupon bond prices
    `currentTime` - the initial moment
    `internalMemorySteps` - this parameter sets the length of an internal cache used to speed up the computations. Generally it is a good idea to set this parameter exactly as the number of timesteps in Monte Carlo.
    `EquityDerivativesDemoException`

### setHoLeeRateModel

    public void setHoLeeRateModel(Function drift,
                                  double sigma,
                                  double initialRate)
                           throws EquityDerivativesDemoException

  Implements the Ho & Lee one factor stochastic spot rate model which provide a spot rate process which is a semi martingale.

  #### Calibration

  The Ho&Lee model does not specify in any way the drift structure of the spot rate process, and thus we are able to apply a fitting technique to fit the model to appropriate market data. In particular, through a careful choice of the drift function the theoretical zero-coupon bonds prices produced by the model, will correspond to the market prices of the corresponding bonds. In this way we are able to calibrate the model using the available market prices of liquid contracts such as zero-coupon bonds, and then use the calibrated model to price contacts which are less liquid and hence for which market prices are generally not available and if available being unreliable.

  Remark: This class also allows you to implement your own calibration algorithm by providing the drift function. We also provide a version of the model with yield curve fitting for zero coupon bonds included see `setFittedHoLee`.

  #### Models Stochastic Differential Equation

  The stochastic differential equation is:

  - `dr = drift(t) * dt + sigma * dW`
  where `r` is the spot rate, `t` is time, `drift` is the drift function, `sigma` is the initial value of the spot rate and `W` is the random variable.

  Parameters:
    `drift` - the drift function which must implement the `Function` interface.
    `sigma` - a measure of volatility
    `initialRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setHullWhiteRateModel

    public void setHullWhiteRateModel(Function averageLongTermRate,
                                      double adjustmentSpeed,
                                      double sigma,
                                      double initialRate)
                               throws EquityDerivativesDemoException

  Implements the Hull & White one factor stochastic spot rate model.

  #### Calibration

  The Hull & White model does not specify the trend of the spot rate prices, and thus we are able to apply a fitting technique to fit the model to appropriate market data. This means that a careful choice of the trend function (i.e. `averageLongTermRate(t)`) will result in theoretical zero-coupon bonds prices, generated by the model being the same as the market prices of the same zero-coupon bonds. In this way we are able to calibrate the model using the available market prices of liquid contracts such as zero-coupon bonds, and then use the calibrated model to price contacts which are less liquid and hence for which market prices are generally not available and if available being unreliable.

  Remark: This class allows you to implement your own calibration algorithm by providing the drift function. If you want a version of the model with yield curve fitting for zero coupon bonds included see `FittedHullWhite`.

  #### Models Stochastic Differential Equation

  The spot rate process is a semi martingale and its evolution is modeled using the stochastic differential equation:

  - `dr = adjustmentSpeed * (averageLongTermRate(t) - r) * dt + sigma * dW`

  You can see that this is a generalization of the Vasicek model. The mean-reverting characteristic is present here, as is the constant variance.

  Parameters:
    `averageLongTermRate` - the trend function which is a function of time which returns the average expected long term spot rate at that point in time.
    `adjustmentSpeed` - the mean-reversion speed
    `sigma` - a measure of volatility
    `initialRate` - the initial value of the spot rate
    `EquityDerivativesDemoException`

### setLongstaffSchwartzRateModel

    public void setLongstaffSchwartzRateModel(double xMean,
                                              double yMean,
                                              double reversionX,
                                              double reversionY,
                                              double c,
                                              double d,
                                              double initialX,
                                              double initialY)
                                       throws EquityDerivativesDemoException

  Implements the Longstaff & Schwartz two factor stochastic interest rate model.

  #### Description of the Model

  Within this model neither of the two model variables are the spot rate. The spot rate is indirectly computed using a linear combination of the two variables. However, the variables themselves are modeled are components of the spot rate where each of these component variables has a mean-reversion characteristic:

  - `dx = reversionX * (xMean - x) * dt + sqrt(x) * dW1`
  - `dy = reversionY * (yMean - y) * dt + sqrt(y) * dW1`
  - `r = c * x + d * y`
  where `x` and `y` are the two component variables, and the other quantities are named in accordance with the naming of the parameters.

  Parameters:
    `xMean` - the long term trend of the first component
    `yMean` - the long term trend of the second component
    `reversionX` - the mean-reversion speed for the first component
    `reversionY` - the mean-reversion speed for the second component
    `c` - the coefficient corresponding to the first component variable of the third formulae given above
    `d` - the coefficient corresponding to the second component variable of the third formulae given above
    `initialX` - the initial value for the first component
    `initialY` - the initial value for the second component
    `EquityDerivativesDemoException`

### setSimplifiedBGMRateModel

    public void setSimplifiedBGMRateModel(double[] discreteCurrentForwardRate,
                                          double[] capletVolatilities,
                                          double[] resetDates,
                                          int forwardCurveSteps,
                                          double currentTime)
                                   throws EquityDerivativesDemoException

  Implements the Brace, Gatarek and Musiela (BGM) model (also known as the LIBOR market model) of the forward rate curve.

  #### Description of the Model

  This model has three parameters which describe volatility functions that must be calibrated so that the model recovers the volatility structure observed in the market. Within our implementation of this model Cap volatilities will need to used in order to calibrate these functions.

  #### Comparison with the `Heath, Jarrow and Morton (HJM) model`

  The model specification is natively discrete, so in this respect the model is superior to the `Heath, Jarrow and Morton (HJM) model`, which needs to be discretized in order to be used with numerical pricing algorithms such as Monte Carlo. The fact that the model is natively discrete also means that it is expressed in terms of the discrete forward rates (i.e. which is generally taken to be the LIBOR rates). Thus, the model can be classified as a market model, meaning that it uses trading instruments as state variables. Another advantage over `Heath, Jarrow and Morton (HJM) model` is that it assures positive interest rates while future interest rates never exponentially increase.

  Parameters:
    `discreteCurrentForwardRate` - a vector containing the initial forward (LIBOR) rates for different maturities (`resetDates`). In general `discreteCurrentForwardRate[i]` is the forward rate between times `resetDates[k]` and `resetDates[k + 1]`.
    `capletVolatilities` - the Black caplet volatilities used for model calibration. `capletVolatilities[k]` is the Black volatility for the caplet that corresponds to the period between times `resetDates[k]` and `resetDates[k + 1]`.
    `resetDates` - a vector containing the maturities of the forward (LIBOR) rates
    `forwardCurveSteps` - the number of rates and maturities
    `currentTime` - the current time
    `EquityDerivativesDemoException`

### setConstantPriceModel

    public void setConstantPriceModel(double price)
                               throws EquityDerivativesDemoException

  Implements the constant price model which assumes that the price is constant.

  Parameters:
    `price` - the constant value of the price.
    `EquityDerivativesDemoException`

### setDeterministPriceModel

    public void setDeterministPriceModel(KOrderDiff priceFunction,
                                         double currentTime)
                                  throws EquityDerivativesDemoException

  Implements a General Deterministic Price Model.

  Overview

  The asset price dynamics will follow a function given as a parameter. Therefore, this model is deterministic in nature.

  Parameters:
    `priceFunction` - a differentiable function of one real variable time which must be at least first order differentiable.
    `currentTime` - the current time from which the price model begins.
    `EquityDerivativesDemoException`

### setLognormalPriceModel

    public void setLognormalPriceModel(double initialPrice)
                                throws EquityDerivativesDemoException

  Implements the Lognormal model of the dynamics of the asset prices.

  #### Definition of the Model

  It is a one-factor stochastic model where the process of the price is a semi martingale. This is also the price model which is used within the classical Black-Scholes model.

  #### Models Stochastic Differential Equation

  The stochastic differential equation is:
  `dS = drift * S * dt + vol * S * dW`,

  where `S` represents the asset price, `t` is time, the `drift` is the (long term average) drift (i.e. a constant) of the asset, `vol` is the volatility of the assets (i.e. a constant) and `W` is the lognormal random variable.

  Parameters:
    `initialPrice` - the initial value of the price
    `EquityDerivativesDemoException`

### setPoissonPriceModel

    public void setPoissonPriceModel(double initialPrice,
                                     double intensity,
                                     double jumpStddev)
                              throws EquityDerivativesDemoException

  Implements the jump-diffusion price model for the dynamics of asset prices.

  #### Models Stochastic Differential Equation

  The stochastic differential equation for this model is:

  - `dS = drift * S * dt + vol * S * dW + (J - 1) * S * dq`,
  where `drift` and `vol` are external variables of the model; `J` is a measure of the jumps' magnitude and `dq` is a Poisson process. In this implementation `J` is also considered a stochastic variable, in particular `J` is given by:
  `J = 1 + jumpStddev * N(0, 1)`,
  where `N(0, 1)` is a variable taken from a standard normal distribution.

  Parameters:
    `initialPrice` - the initial value of the price of the asset considered.
    `intensity` - the intensity of the Poisson process
    `jumpStddev` - the standard deviation of the jump magnitude
    `EquityDerivativesDemoException`

### setConstantVolatilityModel

    public void setConstantVolatilityModel(double volatility)
                                    throws EquityDerivativesDemoException

  Implements the constant volatility model which is deterministic in nature.

  Parameters:
    `volatility` - the constant value of the volatility
    `EquityDerivativesDemoException`

### setDeterministVolatilityModel

    public void setDeterministVolatilityModel(KOrderDiff volatilityFunction,
                                              double value,
                                              double currentTime)
                                       throws EquityDerivativesDemoException

  Implements a General deterministic Volatility model.

  #### Description of the Model

  Here the user specifies the dynamics of the volatility by passing a function of one variable time of the type `KOrderDiff` as a parameter which take the values of the volatility with respect to time. The function provided must be a least first order differentiable. Since the volatility will follow a function (given as a parameter) the model is deterministic in nature.

  Parameters:
    `volatilityFunction` - a differentiable function of one real variable time which specifies the volatility. If this parameter is null, then the volatility will be assumed to be constant equal to the `value' given in the next parameter
    `value` - the value of the constant volatility function in the case when the `volatilityFunction` parameter is not `null`. If the volatility function is given then this parameters is ignored.
    `currentTime` - the current time from which the volatility model begins.
    `EquityDerivativesDemoException`

### setHullWhiteVolatilityModel

    public void setHullWhiteVolatilityModel(double adjustmentSpeed,
                                            double averageLongTermVariance,
                                            double varianceVolatility,
                                            double initialVariance)
                                     throws EvaluationException,
                                            EquityDerivativesDemoException

  Implements the Hull & White Stochastic model of the Variance (recall that, `volatility = sqrt(variance)`).

  #### Definition of the Model

  This model is based on the Hull & White analysis which showed that when the asset price and its volatility are uncorrelated then the fair value of an option on this asset is the average of the Black-Scholes values for the option taken over the distribution of the variance.

  #### Models Stochastic Differential Equation

  The variance process is a semi martingale and the stochastic differential equation of this model is:

  - `d var = adjustmentSpeed * (averageLongTermVariance - var) * dt + varianceVolatility * var * dW`
  where `var` is the variance, `t` is time and `W` is a random variable. The other three terms correspond to the parameters of the same name.

  Parameters:
    `adjustmentSpeed` - the reversion speed towards the equilibrium value of the variance
    `averageLongTermVariance` - the equilibrium value of the variance
    `varianceVolatility` - a measure of the variance of the volatility
    `initialVariance` - the initial value of the variance
  Throws:
    `EvaluationException`
    `EquityDerivativesDemoException`

### setHostonVolatilityModel

    public void setHostonVolatilityModel(double gamma,
                                         double delta,
                                         double initialVolatility)
                                  throws EvaluationException,
                                         EquityDerivativesDemoException

  Implements the Hoston Stochastic Volatility model.

  #### Models Stochastic Differential Equation

  The volatility process is a semi martingale with a stochastic differential equation of:

  - `d vol = -gamma * vol * dt + delta * dW`
  where `vol` is the volatility,

  Parameters:
    `gamma` - the drift multiplied by `-1`
    `delta` - a measure of the process' randomness
    `initialVolatility` - the initial value of the volatility
  Throws:
    `EvaluationException`
    `EquityDerivativesDemoException`

### runSimulation

    public void runSimulation(int monteCarloTimesteps,
                              int monteCarloRandomWalks,
                              double currentTime)
                       throws EvaluationException,
                              EquityDerivativesDemoException

  Performs the Monte Carlo simulation for a fixed number of random walks for the set (cash or derivative) contract, in accordance to the set price model, interest rate model and volatility model.

  #### Overview

  The Monte Carlo algorithm due to its stochastic nature, will produce differing results with each time it is run. That is, two sequential runs of the algorithm using the same model, contract and parameters, will return different prices. However, as the number of simulation used increases the results of Monte Carlo simulation converge to a normal distribution where the standard deviation of this distribution can be evaluated using `getStddev`. Therefore, for a given interval of values we are able to evaluate the confidence level that the true theoretical value lies within the interval considered.

  #### Confidence Interval and number of Simulations

  The higher the confidence level, the larger the interval considered will need to be in order to ensure that the true theoretical price lies within the interval. However, you can reduce the interval for a fixed confidence level, by increasing the number of simulations. In particular, by increasing the number of random walks by `100` times, the size of the confidence interval will be decreased by a factor of `10`. More generally, the factor reduction of the confidence interval is the square root of the multiple factor of the number of simulation increases.

  #### Sources of Error

  Monte Carlo pricing procedures offer an estimate of the price of an asset, which in its turn can be affected by other errors (such as size of the time steps, numerical algorithm errors, floating point imprecision, model error and so on). For further details, concerning the types of errors which can occur we refer the reader to the PDF documentation. In most cases however, these other sources of error are small in comparison with the Monte Carlo error. However, these other errors are difficult to control whereas the Monte Carlo error can be controlled and in particular reduced by increasing the number of simulations.

  #### Choosing between `runSimulation(int, int, double)` and

  Within this pricing framework we offer two means by which to run the required Monte Carlo simulation, namely:

  1. `runSimulation(int, int, double)` (this method) - Runs Monte Carlo using a prescribed number of simulations.
  2. - Runs Monte Carlo using the required number of simulations required in order to achieve a given level in expected accuracy determined by the confidence and the maximum relative error. Please note that we ensure that this method exits by requiring a maximum number of iterations which can be used to be set.
  The choice between these two methods will depend whether you wish specify the number of iterations used (that is, set the time before an estimate of the result is returned) or specify the confidence and maximum relative error for which the result will be found and then returned. In short, this method sets the number of simulations after which the result is returned, whereas the other procedure ``MC set accuracy'` will find the result to a given required accuracy which it will return.

  Parameters:
    `monteCarloTimesteps` - the number of time axis divisions for one random walk
    `monteCarloRandomWalks` - the number of random walks executed
    `currentTime` - the start moment for the simulation (the value date - contract is evaluated as of this moment)
    `EvaluationException`
    `EquityDerivativesDemoException`
  See Also:
    `runSimulation(int, double, double, int, double)`

### runSimulation

    public void runSimulation(int timeSteps,
                              double confidence,
                              double maxRelativeError,
                              int maxRandomWalks,
                              double timeToEvaluation)
                       throws EvaluationException,
                              EquityDerivativesDemoException

  Performs the Monte Carlo simulation for the set (cash or derivative) contract, in accordance to the set price model, interest rate model and volatility model; and returns the result found when it satisfies a given level in confidence and maximum relative error.

  #### Overview

  The Monte Carlo algorithm due to its stochastic nature, will produce differing results with each time it is run. That is, two sequential runs of the algorithm using the same model, contract and parameters, will return different prices. However, as the number of simulation used increases the results of Monte Carlo simulation converge to a normal distribution where the standard deviation of this distribution can be evaluated using `getStddev`. Therefore, for a given interval of values we are able to evaluate the confidence level that the true theoretical value lies within the interval considered.

  #### Confidence Interval and number of Simulations

  The higher the confidence level, the larger the interval considered will need to be in order to ensure that the true theoretical price lies within the interval. However, you can reduce the interval for a fixed confidence level, by increasing the number of simulations. In particular, by increasing the number of random walks by `100` times, the size of the confidence interval will be decreased by a factor of `10`. More generally, the factor reduction of the confidence interval is the square root of the multiple factor of the number of simulation increases.

  #### Sources of Error

  Monte Carlo pricing procedures offer an estimate of the price of an asset, which in its turn can be affected by other errors (such as size of the time steps, numerical algorithm errors, floating point imprecision, model error and so on). For further details, concerning the types of errors which can occur we refer the reader to the PDF documentation. In most cases however, these other sources of error are small in comparison with the Monte Carlo error. However, these other errors are difficult to control whereas the Monte Carlo error explicitly controlled within this methods by increasing the and decreasing the maximum relative values which is allowed. Note that whenever the accuracy required is increased it may be necessary to increase the maximum number of simulations which are allowed.

  #### Choosing between `runSimulation(int, int, double)` and

  Within this pricing framework we offer two means by which to run the required Monte Carlo simulation, namely:

  1. (this method) Runs Monte Carlo using the required number of simulations required in order to achieve a given level in expected accuracy determined by the confidence and the maximum relative error. Please note that we ensure that this method exits by requiring a maximum number of iterations which can be used to be set.
  2. `runSimulation(int, int, double)` - Runs Monte Carlo using a prescribed number of simulations.
  The choice between these two methods will depend on whether you wish specify the number of iterations used (that is, set the time before an estimate of the result is returned) or specify the confidence and maximum relative error for which the result will be found and then returned (assuming maximum number of simulations is not exceeded). In short, this method sets the accuracy required of the result and then run the number of simulations required to find the results to that level of accuracy whereas the other approach ``MC set number Simulations'` sets the number of simulations after which the result is returned.

  Parameters:
    `timeSteps` - the number of time axis divisions for one random walk
    `confidence` - the probability used to compute the uncertainty interval (and maximum relative error)
    `maxRelativeError` - the maximum acceptable relative error. This is equal with half_uncertainty_interval / (abs(price) * - half_uncertainty_interval) * 100. The error is given as a percentage.
    `maxRandomWalks` - the simulation will stop after this number of random walks even if the relative error is larger than `maxRelativeError`. This is given as a safety measure - to ensure that Monte Carlo will actually finish in a reasonable amount of time.
    `timeToEvaluation` - the start moment for the simulation (the value date - contract is evaluated as of this moment)
    `EvaluationException`
    `EquityDerivativesDemoException`
  See Also:
    `runSimulation(int, int, double)`

### getPrice

    public double getPrice()
                    throws EvaluationException,
                           EquityDerivativesDemoException

  Returns the price of the contract set (i.e. asset) priced in accordance with the price, volatility and interest rate models set using the Monte Carlo simulation performed.

  #### Dependencies of this method

  Before calling this method the contract considered, and the price, volatility and interest rate models should have already been set. In addition, you must have already performed the Monte Carlo simulation using one of the ``MC set accuracy'` or ``MC set number Simulations'`. After each Monte Carlo Simulation is performed the results are stored within private field which are then read by this method.

    `EvaluationException`
    `EquityDerivativesDemoException`

### getStddev

    public double getStddev()
                     throws EvaluationException,
                            EquityDerivativesDemoException

  Returns the standard deviation of the price estimate given by the last Monte Carlo simulation performed of the set contract (i.e. asset) in accordance with the price, volatility and interest rate models used.

  #### Dependencies of this method

  Before calling this method the contract considered, and the price, volatility and interest rate models should have already been set. In addition, you must have already performed the Monte Carlo simulation using one of the ``MC set accuracy'` or ``MC set number Simulations'`. After each Monte Carlo Simulation is performed the results are stored within private field which are then read by this method.

    `EvaluationException`
    `EquityDerivativesDemoException`

### getMinPrice

    public double getMinPrice(double confidence)
                       throws EvaluationException,
                              EquityDerivativesDemoException

  Returns the minimum value of the estimated price expected for a given confidence level for the last Monte Carlo simulation performed of the set contract (i.e. asset) in accordance with the price, volatility and interest rate models used.

  #### Dependencies of this method

  Before calling this method the contract considered, and the price, volatility and interest rate models should have already been set. In addition, you must have already performed the Monte Carlo simulation using one of the ``MC set accuracy'` or ``MC set number Simulations'`. After each Monte Carlo Simulation is performed the results are stored within private field which are then read by this method.

  Parameters:
    `confidence` - the probability for which the minimal value is calculated
    `EvaluationException`
    `EquityDerivativesDemoException`

### getMaxPrice

    public double getMaxPrice(double confidence)
                       throws EvaluationException,
                              EquityDerivativesDemoException

  Returns the maximum value of the estimated price expected for a given confidence level for the last Monte Carlo simulation performed of the set contract (i.e. asset) in accordance with the price, volatility and interest rate models used.

  #### Dependencies of this method

  Before calling this method the contract considered, and the price, volatility and interest rate models should have already been set. In addition, you must have already performed the Monte Carlo simulation using one of the ``MC set accuracy'` or ``MC set number Simulations'`. After each Monte Carlo Simulation is performed the results are stored within private field which are then read by this method.

  Parameters:
    `confidence` - the probability for which the maximal value is calculated
    `EvaluationException`
    `EquityDerivativesDemoException`

WebCab Options and Futures Demo v2.5 (J2SE Edition)