All files / src/pricing-models MonteCarloSimulation.js

97.01% Statements 65/67
87.5% Branches 21/24
100% Functions 9/9
96.42% Lines 54/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185                                  4x 4x 40000x     4x 4x 4x 4x 20000x     4x   20000x   4x   40000x   40000x     4x                     3x 56x 56x 6x   6x   56x     6x   56x                 7x 7x 40028x 40028x 80112x         80112x       7x 7x 7x 40028x     7x 3x                   7x     40028x                                               7x 3x 3x 3x   4x 4x     7x   7x         7x         7x   7x 7x 7x 7x       7x     7x       7x                           7x        
import { quadraticRegression } from "../utils/MathUtils.js";
import { createFilledMatrix, zeros } from "../utils/MatrixUtils.js";
import { calculateExerciseValue } from "../utils/OptionUtils.js";
import { randn } from "../utils/RandomUtils.js";
import { isNumberGreaterThanZero } from "../utils/ValidationUtils.js";
 
function initializeSpotPriceMatrix(
  M,
  N,
  S0,
  vol,
  dt,
  drift,
  prngName,
  prngSeed,
  prngAdvancePast
) {
  const spotPriceMatrix = zeros(M, N);
  for (let i = 0; i < M; i += 1) {
    spotPriceMatrix[i][0] = S0;
  }
 
  const randNumGenerator = randn(prngName, prngSeed, prngAdvancePast);
  for (let j = 1; j < N; j += 1) {
    let brownianMotion = [];
    for (let i = 0; i < M / 2; i += 1) {
      brownianMotion.push(randNumGenerator());
    }
    // antithetic variables
    brownianMotion = [
      ...brownianMotion,
      ...brownianMotion.map((randNum) => -randNum),
    ];
    for (let i = 0; i < M; i += 1) {
      const St =
        spotPriceMatrix[i][j - 1] *
        Math.exp(drift + vol * brownianMotion[i] * Math.sqrt(dt));
      spotPriceMatrix[i][j] = St;
    }
  }
  return spotPriceMatrix;
}
 
function leastSquaresLongstaffSchwartz(
  V,
  spotPriceMatrix,
  exerciseValueMatrix,
  M,
  N,
  discount
) {
  for (let k = N - 2; k > 0; k -= 1) {
    const x = spotPriceMatrix.map((row) => row[k]);
    const y = V.map((row) => row[k + 1] * discount);
    const regressors = quadraticRegression(x, y);
 
    const continuationValue = spotPriceMatrix.map(
      (row) =>
        regressors[0] + regressors[1] * row[k] + regressors[2] * row[k] ** 2
    );
 
    for (let i = 0; i < M; i += 1) {
      // eslint-disable-next-line no-param-reassign
      V[i][k] =
        exerciseValueMatrix[i][k] > continuationValue[i]
          ? exerciseValueMatrix[i][k]
          : V[i][k + 1] * discount;
    }
  }
}
 
function calculatePrice(option, spotPriceMatrix, M, N, mu, dt) {
  const exerciseValueMatrix = [];
  for (let i = 0; i < M; i += 1) {
    exerciseValueMatrix.push([]);
    for (let k = 0; k < N; k += 1) {
      const exerciseValue = calculateExerciseValue(
        option,
        spotPriceMatrix[i][k],
        k === N - 1 ? option.timeToMaturity : k * dt
      );
      exerciseValueMatrix[i].push(exerciseValue);
    }
  }
 
  const discount = Math.exp(-mu * dt);
  const V = createFilledMatrix(M, N, 0);
  for (let i = 0; i < M; i += 1) {
    V[i][N - 1] = exerciseValueMatrix[i][N - 1];
  }
 
  if (N > 2) {
    leastSquaresLongstaffSchwartz(
      V,
      spotPriceMatrix,
      exerciseValueMatrix,
      M,
      N,
      discount
    );
  }
 
  return (
    V.reduce(
      (previousValue, currentValue) =>
        previousValue + currentValue[1] * discount,
      0
    ) / M
  );
}
 
/**
 * Calculates the price of an option using a Monte Carlo Simulation.
 * Early exercise is handled using the least-squares Monte Carlo approach (with a fixed degree of 2) proposed by Longstaff and Schwartz (https://www.researchgate.net/publication/5216848_Valuing_American_Options_by_Simulation_A_Simple_Least-Squares_Approach).
 * @param {Option} option option to price
 * @param {object} params
 * @param {number} params.simulations number of simulated price paths (> 0)
 * @param {number} [params.timeSteps=1] number of time steps to simulate for each path (> 0)
 * @param {string} [params.prngName="Math.random()"] name of the pseudorandom number generator to use
 * @param {string} [params.prngSeed=Math.random().toString()] initial seed state of the PRNG
 * @param {number} [params.prngAdvancePast=0] initial number of generated random numbers to discard
 * @returns price of the option
 * @throws if params.simulations is not a number greater than zero
 * @throws if params.timeSteps is not a number greater than zero
 */
function price(option, params) {
  let M;
  let timeSteps;
  // allow spot price matrix override for testing purposes
  if (Object.hasOwn(params, "spotPriceMatrixOverride")) {
    const { spotPriceMatrixOverride } = params;
    M = spotPriceMatrixOverride.length;
    timeSteps = spotPriceMatrixOverride[0].length - 1;
  } else {
    M = params.simulations;
    timeSteps = Object.hasOwn(params, "timeSteps") ? params.timeSteps : 1;
  }
  // simulations must be even for generating brownian motion
  M += M % 2;
 
  Iif (!isNumberGreaterThanZero(M)) {
    throw new Error(
      `invalid simulations (${M}), must be a number greater than zero.`
    );
  }
  Iif (!isNumberGreaterThanZero(timeSteps)) {
    throw new Error(
      `invalid time steps (${timeSteps}), must be a number greater than zero.`
    );
  }
  const N = timeSteps + 1;
 
  const dt = option.timeToMaturity / (N - 1);
  const mu = option.riskFreeRate - option.dividendYield;
  const drift = (mu - option.volatility ** 2 / 2) * dt;
  const prngName = Object.hasOwn(params, "prngName")
    ? params.prngName
    : "Math.random()";
  const prngSeed =
    Object.hasOwn(params, "prngSeed") && params.prngSeed !== ""
      ? params.prngSeed
      : Math.random().toString();
  const prngAdvancePast = Object.hasOwn(params, "prngAdvancePast")
    ? params.prngAdvancePast
    : 0;
 
  const spotPriceMatrix = Object.hasOwn(params, "spotPriceMatrixOverride")
    ? params.spotPriceMatrixOverride
    : initializeSpotPriceMatrix(
        M,
        N,
        option.initialSpotPrice,
        option.volatility,
        dt,
        drift,
        prngName,
        prngSeed,
        prngAdvancePast
      );
 
  return calculatePrice(option, spotPriceMatrix, M, N, mu, dt);
}
 
export { price };