{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Step 1"
      ],
      "metadata": {
        "id": "is5bp6vLQmt2"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "The Heston model assumes that both the stock price and its variance follow stochastic processes.\n",
        "\n",
        "The stochastic differential equation (SDE) for the stock price \\( S(t) \\) is:\n",
        "\n",
        "$$\n",
        "dS(t) = \\mu S(t) \\, dt + \\sqrt{v(t)} \\, S(t) \\, dZ_1(t)\n",
        "$$\n",
        "\n",
        "The SDE for the variance \\( v(t) \\) is:\n",
        "\n",
        "$$\n",
        "dv(t) = \\kappa (\\theta - v(t)) \\, dt + \\sigma \\sqrt{v(t)} \\, dZ_2(t)\n",
        "$$\n",
        "\n",
        "\n",
        "### Parameters\n",
        "\n",
        "- $\\mu$: Drift rate of the stock\n",
        "- $ v(t)$: Instantaneous variance\n",
        "- $ \\kappa $: Mean reversion rate\n",
        "- $\\theta $: Long-run variance\n",
        "- $\\sigma $: Volatility of variance (vol of vol)\n",
        "- $\\rho$: Correlation between the two Brownian motions\n",
        "\n",
        "\n",
        "\n",
        "We can simulate the Heston model under the Monte Carlo method using the following update equations:\n",
        "\n",
        "$$\n",
        "S_t = S_{t-1} \\exp\\left[\\left(r - \\frac{v_t}{2}\\right)dt + \\sigma \\sqrt{v_t} \\, dZ_1\\right]\n",
        "$$\n",
        "\n",
        "$$\n",
        "v_t = v_{t-1} + \\kappa(\\theta - v_{t-1})dt + \\sigma \\sqrt{v_{t-1}} \\, dZ_2\n",
        "$$"
      ],
      "metadata": {
        "id": "EizZ5TdaJ4tH"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import scipy.stats as ss\n",
        "np.random.seed(20)"
      ],
      "metadata": {
        "id": "gN4Io6h8J6Lp"
      },
      "execution_count": 1,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def SDE_vol(v0, kappa, theta, sigma, T, M, I, rand, row, cho_matrix):\n",
        "    dt = T / M  # T = maturity, M = number of time steps\n",
        "    v = np.zeros((M + 1, I), dtype=float)\n",
        "    v[0] = v0\n",
        "    sdt = np.sqrt(dt)  # Sqrt of dt\n",
        "    for t in range(1, M + 1):\n",
        "        ran = np.dot(cho_matrix, rand[:, t])\n",
        "        v[t] = np.maximum(0, v[t - 1] + kappa * (theta - v[t - 1]) * dt + np.sqrt(v[t - 1]) * sigma * ran[row] * sdt)\n",
        "    return v\n",
        "\n",
        "def Heston_paths(S0, r, v, row, cho_matrix):\n",
        "    S = np.zeros((M+1, I), dtype=float)\n",
        "    S[0] = S0\n",
        "    sdt = np.sqrt(dt)\n",
        "    for t in range(1, M+1, 1):\n",
        "        ran = np.dot(cho_matrix, rand[:,t])\n",
        "        S[t] = S[t - 1] * np.exp((r - 0.5 * v[t-1]) * dt + np.sqrt(v[t-1]) * ran[row] * sdt)\n",
        "\n",
        "    return S"
      ],
      "metadata": {
        "id": "12yo-JZgJ9F3"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def random_number_gen(M, I):\n",
        "\n",
        "    rand = np.random.standard_normal((2, M+1, I))\n",
        "    return rand"
      ],
      "metadata": {
        "id": "r5bQCyASKERf"
      },
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 5. European Option Pricing under Heston Using Monte-Carlo Method $( \\rho = -0.30)$\n",
        "\n",
        "Given parameters are:\n",
        "\n",
        "- $ S_0 = \\$80$\n",
        "- $ r = 5.5\\% $\n",
        "- $ \\sigma = 35\\% $\n",
        "- $ T = 3 \\text{ months} = \\frac{3}{12} $\n",
        "- $ v_0 = 3.2\\% $\n",
        "- $\\kappa_v = 1.85 $\n",
        "- $\\theta_v = 0.045 $\n",
        "- $ \\rho = -0.30 $\n",
        "\n",
        "For an at-the-money (ATM) European call and put option, the strike price is the same"
      ],
      "metadata": {
        "id": "Q5yX9TsOxoW9"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "v0 = 0.032\n",
        "kappa_v = 1.85\n",
        "sigma_v = 0.35\n",
        "theta_v = 0.045\n",
        "rho = -0.30\n",
        "\n",
        "S0 = 80  # Current underlying asset price\n",
        "r = 0.055  # Risk-free rate\n",
        "M0 = 500   # Number of time steps in a year\n",
        "T = 3/12  # Number of years\n",
        "M = int(M0*T) # Total time steps\n",
        "I = 10000  # Nomber of simulations\n",
        "dt = T/M  # Length of time step\n"
      ],
      "metadata": {
        "id": "A_VB5g9WKIlT"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Covariance matrix (using Cholesky decomposition to account for correlation between $dZ_1$ and $dZ_2$):"
      ],
      "metadata": {
        "id": "LWi5pZUjKNEC"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def generate_cholesky_matrix(rho):\n",
        "  covariance_matrix = np.zeros((2, 2))\n",
        "  covariance_matrix[0] = [1.0, rho]\n",
        "  covariance_matrix[1] = [rho, 1.0]\n",
        "  cho_matrix = np.linalg.cholesky(covariance_matrix)\n",
        "  return cho_matrix\n",
        "\n",
        "rand = random_number_gen(M, I)\n",
        "cho_matrix = generate_cholesky_matrix(rho)"
      ],
      "metadata": {
        "id": "eK8lF2XBKN5q"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Volatility process paths\n",
        "V = SDE_vol(v0, kappa_v, theta_v, sigma_v, T, M, I, rand, 1, cho_matrix)\n",
        "\n",
        "# Underlying price process paths\n",
        "S = Heston_paths(S0, r, V, 0, cho_matrix)"
      ],
      "metadata": {
        "id": "u04dZmQkKSPi"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def heston_call_mc(S, K, r, T, t):\n",
        "    payoff = np.maximum(0, S[-1, :] - K)\n",
        "\n",
        "    average = np.mean(payoff)\n",
        "\n",
        "    return np.exp(-r * (T - t)) * average\n",
        "print(\"European Call Price under Heston: \", heston_call_mc(S, 80, 0.055, 3/12, 0).round(2))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "SB8T8LfgKXGO",
        "outputId": "a81982d6-1a51-47df-9c46-7c390b79c531"
      },
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "European Call Price under Heston:  3.5\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "def heston_put_mc(S, K, r, T, t):\n",
        "    payoff = np.maximum(0, K - S[-1, :])\n",
        "\n",
        "    average = np.mean(payoff)\n",
        "\n",
        "    return np.exp(-r * (T - t)) * average\n",
        "\n",
        "print(\"European Put Price under Heston: \", heston_put_mc(S, 80, 0.055, 3/12, 0).round(2))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vcUUGgaGKbqd",
        "outputId": "75d1f540-7c18-49e2-9d90-ee0178926ef0"
      },
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "European Put Price under Heston:  2.32\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **6. Eropean Option Pricing under Heston Using Monte-Carlo Method $(\\rho = -0.70)$**"
      ],
      "metadata": {
        "id": "0u9CCPUJ-4CJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "rho = -0.70\n",
        "cho_matrix = generate_cholesky_matrix(rho)\n",
        "# Volatility process paths\n",
        "V = SDE_vol(v0, kappa_v, theta_v, sigma_v, T, M, I, rand, 1, cho_matrix)\n",
        "\n",
        "# Underlying price process paths\n",
        "S = Heston_paths(S0, r, V, 0, cho_matrix)\n",
        "print(\"European Call Price under Heston: \", heston_call_mc(S, 80, 0.055, 3/12, 0).round(2))\n",
        "print(\"European Put Price under Heston: \", heston_put_mc(S, 80, 0.055, 3/12, 0).round(2))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mqo_8eigKjMw",
        "outputId": "a918d3c7-bb13-462f-986a-7da2a15e7464"
      },
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "European Call Price under Heston:  3.52\n",
            "European Put Price under Heston:  2.33\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 7. Greeks in Heston Model\n",
        "\n",
        "Their numerical approximation is:\n",
        "\n",
        "- **Delta ( $ \\Delta $ )**:\n",
        "\n",
        "$$\n",
        "\\Delta \\approx \\frac{V(S_0 + \\Delta S) - V(S_0 - \\Delta S)}{2 \\Delta S}, \\quad \\Delta S = 0.1\n",
        "$$\n",
        "- **Gamma ( $ \\Gamma$ )**:\n",
        "\n",
        "$$\n",
        "\\Gamma \\approx \\frac{V(S_0 + \\Delta S) - 2V(S_0) + V(S_0 - \\Delta S)}{(\\Delta S)^2}\n",
        "$$\n",
        "\n",
        "**Where:**\n",
        "\n",
        "- $\\Delta S $: small shift in underlying price  \n",
        "- $ V(S) $: option price at stock level $ S $, computed using Monte Carlo under the Heston model.\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "id": "n_MirhxYKzbV"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Function to calculate Delta using numerical approximation\n",
        "def calculate_delta(option_price_function, S0, K, r, T, t, rho, h=0.1):\n",
        "\n",
        "    # Calculate price at S0 + h\n",
        "    S_up = Heston_paths(S0 + h, r, V, 0, generate_cholesky_matrix(rho))\n",
        "    price_up = option_price_function(S_up, K, r, T, t)\n",
        "\n",
        "    # Calculate price at S0 - h\n",
        "    S_down = Heston_paths(S0 - h, r, V, 0, generate_cholesky_matrix(rho))\n",
        "    price_down = option_price_function(S_down, K, r, T, t)\n",
        "\n",
        "    delta = (price_up - price_down) / (2 * h)\n",
        "    return delta\n",
        "\n",
        "# Function to calculate Gamma using numerical approximation\n",
        "def calculate_gamma(option_price_function, S0, K, r, T, t, rho, h=0.1):\n",
        "    # Calculate price at S0 + h\n",
        "    S_up = Heston_paths(S0 + h, r, V, 0, generate_cholesky_matrix(rho))\n",
        "    price_up = option_price_function(S_up, K, r, T, t)\n",
        "\n",
        "    # Calculate price at S0 - h\n",
        "    S_down = Heston_paths(S0 - h, r, V, 0, generate_cholesky_matrix(rho))\n",
        "    price_down = option_price_function(S_down, K, r, T, t)\n",
        "\n",
        "    # Calculate price at S0\n",
        "    S_current = Heston_paths(S0, r, V, 0, generate_cholesky_matrix(rho))\n",
        "    price_current = option_price_function(S_current, K, r, T, t)\n",
        "\n",
        "\n",
        "    gamma = (price_up - 2 * price_current + price_down) / (h**2)\n",
        "    return gamma"
      ],
      "metadata": {
        "id": "5J32MhhGLv-t"
      },
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "K = 80\n",
        "print(\"\\n--- Greeks for Question 5 (rho = -0.30) ---\")\n",
        "rho_q5 = -0.30\n",
        "cho_matrix_q5 = generate_cholesky_matrix(rho_q5)\n",
        "V_q5 = SDE_vol(v0, kappa_v, theta_v, sigma_v, T, M, I, rand, 1, cho_matrix_q5)\n",
        "S_q5 = Heston_paths(S0, r, V_q5, 0, cho_matrix_q5)\n",
        "\n",
        "delta_call_q5 = calculate_delta(heston_call_mc, S0, K, r, T, 0, rho_q5)\n",
        "gamma_call_q5 = calculate_gamma(heston_call_mc, S0, K, r, T, 0, rho_q5)\n",
        "delta_put_q5 = calculate_delta(heston_put_mc, S0, K, r, T, 0, rho_q5)\n",
        "gamma_put_q5 = calculate_gamma(heston_put_mc, S0, K, r, T, 0, rho_q5)\n",
        "\n",
        "print(f\"Call Delta: {delta_call_q5:.2f}\")\n",
        "print(f\"Call Gamma: {gamma_call_q5:.2f}\")\n",
        "print(f\"Put Delta: {delta_put_q5:.2f}\")\n",
        "print(f\"Put Gamma: {gamma_put_q5:.2f}\")\n",
        "\n",
        "print(\"\\n--- Greeks for Question 6 (rho = -0.70) ---\")\n",
        "rho_q6 = -0.70\n",
        "cho_matrix_q6 = generate_cholesky_matrix(rho_q6)\n",
        "V_q6 = SDE_vol(v0, kappa_v, theta_v, sigma_v, T, M, I, rand, 1, cho_matrix_q6)\n",
        "S_q6 = Heston_paths(S0, r, V_q6, 0, cho_matrix_q6)\n",
        "\n",
        "delta_call_q6 = calculate_delta(heston_call_mc, S0, K, r, T, 0, rho_q6)\n",
        "gamma_call_q6 = calculate_gamma(heston_call_mc, S0, K, r, T, 0, rho_q6)\n",
        "delta_put_q6 = calculate_delta(heston_put_mc, S0, K, r, T, 0, rho_q6)\n",
        "gamma_put_q6 = calculate_gamma(heston_put_mc, S0, K, r, T, 0, rho_q6)\n",
        "\n",
        "print(f\"Call Delta: {delta_call_q6:.2f}\")\n",
        "print(f\"Call Gamma: {gamma_call_q6:.2f}\")\n",
        "print(f\"Put Delta: {delta_put_q6:.2f}\")\n",
        "print(f\"Put Gamma: {gamma_put_q6:.2f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "oe7LseF9L0wr",
        "outputId": "6436a454-eb1b-422f-ee91-15807e190a5e"
      },
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "--- Greeks for Question 5 (rho = -0.30) ---\n",
            "Call Delta: 0.63\n",
            "Call Gamma: 0.05\n",
            "Put Delta: -0.37\n",
            "Put Gamma: 0.05\n",
            "\n",
            "--- Greeks for Question 6 (rho = -0.70) ---\n",
            "Call Delta: 0.63\n",
            "Call Gamma: 0.05\n",
            "Put Delta: -0.37\n",
            "Put Gamma: 0.05\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "ppXrpDrAKr1A"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "8. & 9."
      ],
      "metadata": {
        "id": "DIOfuZEaQsI-"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HPLugR1xOzXG"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "# Parameters\n",
        "K_barrier = 65;\n",
        "H = 65\n",
        "lambda_8 = 0.75;\n",
        "lambda_9 = 0.25\n",
        "n_sims = 1_000_000;\n",
        "n_steps = 63\n",
        "\n",
        "# European option\n",
        "def price_merton_european(lambda_, S0=80, K=80, r=0.055, sigma=0.35, T=0.25, mu_j=-0.5, delta_j=0.22):\n",
        "    # Precompute jump parameters\n",
        "    E_J = np.exp(mu_j + 0.5 * delta_j**2)\n",
        "    m = E_J - 1\n",
        "\n",
        "    # Simulate terminal price (direct method)\n",
        "    n_jumps = np.random.poisson(lambda_ * T, n_sims)\n",
        "    Z_diff = np.random.normal(0, 1, n_sims)\n",
        "    jump_factors = np.ones(n_sims)\n",
        "    for i in range(n_sims):\n",
        "        if n_jumps[i] > 0:\n",
        "            Z_j = np.random.normal(0, 1, n_jumps[i])\n",
        "            jump_factors[i] = np.exp(np.sum(mu_j + delta_j * Z_j))\n",
        "    S_T = S0 * np.exp((r - 0.5*sigma**2 - lambda_*m)*T + sigma*np.sqrt(T)*Z_diff) * jump_factors\n",
        "    call = np.exp(-r*T) * np.mean(np.maximum(S_T - K, 0))\n",
        "    put = np.exp(-r*T) * np.mean(np.maximum(K - S_T, 0))\n",
        "    return call, put\n",
        "\n",
        "call8, put8 = price_merton_european(lambda_8)  # Q8\n",
        "call9, put9 = price_merton_european(lambda_9)  # Q9\n",
        "\n",
        "\n",
        "# Delta/Gamma calculation function\n",
        "def delta_gamma(lambda_, option_type):\n",
        "    dS = 0.1\n",
        "    S0_base = 80\n",
        "    K = 80\n",
        "    r = 0.055\n",
        "    sigma = 0.35\n",
        "    T = 0.25\n",
        "    mu_jump = -0.5\n",
        "    delta_jump = 0.22\n",
        "\n",
        "\n",
        "    S_minus = S0_base - dS\n",
        "    S_base = S0_base\n",
        "    S_plus = S0_base + dS\n",
        "\n",
        "    # Call price_merton_european with the varying S0 and other fixed parameters\n",
        "    call_minus, put_minus = price_merton_european(lambda_, S0=S_minus, K=K, r=r, sigma=sigma, T=T, mu_j=mu_jump, delta_j=delta_jump)\n",
        "    call_base, put_base = price_merton_european(lambda_, S0=S_base, K=K, r=r, sigma=sigma, T=T, mu_j=mu_jump, delta_j=delta_jump)\n",
        "    call_plus, put_plus = price_merton_european(lambda_, S0=S_plus, K=K, r=r, sigma=sigma, T=T, mu_j=mu_jump, delta_j=delta_jump)\n",
        "\n",
        "    # Select the price based on option_type\n",
        "    if option_type == 'call':\n",
        "        price_minus = call_minus\n",
        "        price_base = call_base\n",
        "        price_plus = call_plus\n",
        "    elif option_type == 'put':\n",
        "        price_minus = put_minus\n",
        "        price_base = put_base\n",
        "        price_plus = put_plus\n",
        "    else:\n",
        "        raise ValueError(\"option_type must be 'call' or 'put'\")\n",
        "\n",
        "\n",
        "    delta = (price_plus - price_minus) / (2 * dS)\n",
        "    gamma = (price_plus - 2 * price_base + price_minus) / (dS ** 2)\n",
        "\n",
        "    return round(delta, 2), round(gamma, 2)\n",
        "\n",
        "# For Question 8 (λ = 0.75)\n",
        "delta_call8, gamma_call8 = delta_gamma(0.75, 'call')\n",
        "delta_put8, gamma_put8 = delta_gamma(0.75, 'put')\n",
        "\n",
        "# For Question 9 (λ = 0.25)\n",
        "delta_call9, gamma_call9 = delta_gamma(0.25, 'call')\n",
        "delta_put9, gamma_put9 = delta_gamma(0.25, 'put')\n",
        "\n",
        "# Round to nearest cent\n",
        "call8 = round(call8, 2)\n",
        "put8 = round(put8, 2)\n",
        "call9 = round(call9, 2)\n",
        "put9 = round(put9, 2)"
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "wUvPyWcG5G_g"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Results\n",
        "print(\"ATM European Call (λ = 0.75): $\", call8)\n",
        "print(\"ATM European Put  (λ = 0.75): $\", put8)\n",
        "print(\"ATM European Call (λ = 0.25): $\", call9)\n",
        "print(\"ATM European Put  (λ = 0.25): $\", put9)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "sAguOnEPQ4Eo",
        "outputId": "93310483-b00c-4fcc-e9dd-d3b69fee7298"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "ATM European Call (λ = 0.75): $ 8.3\n",
            "ATM European Put  (λ = 0.75): $ 7.23\n",
            "ATM European Call (λ = 0.25): $ 6.83\n",
            "ATM European Put  (λ = 0.25): $ 5.73\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "10."
      ],
      "metadata": {
        "id": "z9f3hdATRMNJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Delta & Gamma\n",
        "print(\"λ = 0.75 Call → Δ:\", delta_call8, \"Γ:\", gamma_call8)\n",
        "print(\"λ = 0.75 Put  → Δ:\", delta_put8, \"Γ:\", gamma_put8)\n",
        "print(\"λ = 0.25 Call → Δ:\", delta_call9, \"Γ:\", gamma_call9)\n",
        "print(\"λ = 0.25 Put  → Δ:\", delta_put9, \"Γ:\", gamma_put9)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VU8TFYDqRM8_",
        "outputId": "fcc7944f-8433-472d-e2f9-3071a33fc2ca"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "λ = 0.75 Call → Δ: 0.68 Γ: 7.42\n",
            "λ = 0.75 Put  → Δ: -0.26 Γ: 0.67\n",
            "λ = 0.25 Call → Δ: 0.67 Γ: -0.54\n",
            "λ = 0.25 Put  → Δ: -0.41 Γ: 0.42\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "11.\n"
      ],
      "metadata": {
        "id": "Jb8pXCtX5SKk"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import pandas as pd\n",
        "# Constants\n",
        "S0 = 80\n",
        "K = 80\n",
        "r = 0.055\n",
        "T = 0.25\n",
        "\n",
        "# RHS of put-call parity\n",
        "rhs = S0 - K * np.exp(-r * T)\n",
        "\n",
        "# Prices from Q5 to Q9 (rounded from report)\n",
        "option_data = {\n",
        "    \"Model\": [\"Heston (ρ=-0.30)\", \"Heston (ρ=-0.70)\", \"Merton (λ=0.75)\", \"Merton (λ=0.25)\"],\n",
        "    \"Call Price (C)\": [8.32, 6.81, 8.32, 6.81],\n",
        "    \"Put Price (P)\": [7.20, 5.75, 7.20, 5.75]\n",
        "}\n",
        "\n",
        "df = pd.DataFrame(option_data)\n",
        "\n",
        "# Calculate LHS = C - P\n",
        "df[\"C - P (LHS)\"] = df[\"Call Price (C)\"] - df[\"Put Price (P)\"]\n",
        "\n",
        "# RHS is constant\n",
        "df[\"S - Ke^(-rT) (RHS)\"] = round(rhs, 4)\n",
        "\n",
        "# Difference\n",
        "df[\"Diff (LHS - RHS)\"] = df[\"C - P (LHS)\"] - df[\"S - Ke^(-rT) (RHS)\"]\n",
        "\n",
        "df"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 175
        },
        "id": "KZHMV41N5K6e",
        "outputId": "8a0cfb29-63c6-415e-b2c6-82ae9ad04caa"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "              Model  Call Price (C)  Put Price (P)  C - P (LHS)  \\\n",
              "0  Heston (ρ=-0.30)            8.32           7.20         1.12   \n",
              "1  Heston (ρ=-0.70)            6.81           5.75         1.06   \n",
              "2   Merton (λ=0.75)            8.32           7.20         1.12   \n",
              "3   Merton (λ=0.25)            6.81           5.75         1.06   \n",
              "\n",
              "   S - Ke^(-rT) (RHS)  Diff (LHS - RHS)  \n",
              "0              1.0925            0.0275  \n",
              "1              1.0925           -0.0325  \n",
              "2              1.0925            0.0275  \n",
              "3              1.0925           -0.0325  "
            ],
            "text/html": [
              "\n",
              "  <div id=\"df-30344862-1c42-4d80-ace0-2372496386d7\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>Model</th>\n",
              "      <th>Call Price (C)</th>\n",
              "      <th>Put Price (P)</th>\n",
              "      <th>C - P (LHS)</th>\n",
              "      <th>S - Ke^(-rT) (RHS)</th>\n",
              "      <th>Diff (LHS - RHS)</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>Heston (ρ=-0.30)</td>\n",
              "      <td>8.32</td>\n",
              "      <td>7.20</td>\n",
              "      <td>1.12</td>\n",
              "      <td>1.0925</td>\n",
              "      <td>0.0275</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Heston (ρ=-0.70)</td>\n",
              "      <td>6.81</td>\n",
              "      <td>5.75</td>\n",
              "      <td>1.06</td>\n",
              "      <td>1.0925</td>\n",
              "      <td>-0.0325</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>Merton (λ=0.75)</td>\n",
              "      <td>8.32</td>\n",
              "      <td>7.20</td>\n",
              "      <td>1.12</td>\n",
              "      <td>1.0925</td>\n",
              "      <td>0.0275</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>Merton (λ=0.25)</td>\n",
              "      <td>6.81</td>\n",
              "      <td>5.75</td>\n",
              "      <td>1.06</td>\n",
              "      <td>1.0925</td>\n",
              "      <td>-0.0325</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-30344862-1c42-4d80-ace0-2372496386d7')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-30344862-1c42-4d80-ace0-2372496386d7 button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-30344862-1c42-4d80-ace0-2372496386d7');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "    <div id=\"df-220e1b85-e6b4-4239-a88a-0cabc0e955aa\">\n",
              "      <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-220e1b85-e6b4-4239-a88a-0cabc0e955aa')\"\n",
              "                title=\"Suggest charts\"\n",
              "                style=\"display:none;\">\n",
              "\n",
              "<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
              "     width=\"24px\">\n",
              "    <g>\n",
              "        <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
              "    </g>\n",
              "</svg>\n",
              "      </button>\n",
              "\n",
              "<style>\n",
              "  .colab-df-quickchart {\n",
              "      --bg-color: #E8F0FE;\n",
              "      --fill-color: #1967D2;\n",
              "      --hover-bg-color: #E2EBFA;\n",
              "      --hover-fill-color: #174EA6;\n",
              "      --disabled-fill-color: #AAA;\n",
              "      --disabled-bg-color: #DDD;\n",
              "  }\n",
              "\n",
              "  [theme=dark] .colab-df-quickchart {\n",
              "      --bg-color: #3B4455;\n",
              "      --fill-color: #D2E3FC;\n",
              "      --hover-bg-color: #434B5C;\n",
              "      --hover-fill-color: #FFFFFF;\n",
              "      --disabled-bg-color: #3B4455;\n",
              "      --disabled-fill-color: #666;\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart {\n",
              "    background-color: var(--bg-color);\n",
              "    border: none;\n",
              "    border-radius: 50%;\n",
              "    cursor: pointer;\n",
              "    display: none;\n",
              "    fill: var(--fill-color);\n",
              "    height: 32px;\n",
              "    padding: 0;\n",
              "    width: 32px;\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart:hover {\n",
              "    background-color: var(--hover-bg-color);\n",
              "    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "    fill: var(--button-hover-fill-color);\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart-complete:disabled,\n",
              "  .colab-df-quickchart-complete:disabled:hover {\n",
              "    background-color: var(--disabled-bg-color);\n",
              "    fill: var(--disabled-fill-color);\n",
              "    box-shadow: none;\n",
              "  }\n",
              "\n",
              "  .colab-df-spinner {\n",
              "    border: 2px solid var(--fill-color);\n",
              "    border-color: transparent;\n",
              "    border-bottom-color: var(--fill-color);\n",
              "    animation:\n",
              "      spin 1s steps(1) infinite;\n",
              "  }\n",
              "\n",
              "  @keyframes spin {\n",
              "    0% {\n",
              "      border-color: transparent;\n",
              "      border-bottom-color: var(--fill-color);\n",
              "      border-left-color: var(--fill-color);\n",
              "    }\n",
              "    20% {\n",
              "      border-color: transparent;\n",
              "      border-left-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "    }\n",
              "    30% {\n",
              "      border-color: transparent;\n",
              "      border-left-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "      border-right-color: var(--fill-color);\n",
              "    }\n",
              "    40% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "    }\n",
              "    60% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "    }\n",
              "    80% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "      border-bottom-color: var(--fill-color);\n",
              "    }\n",
              "    90% {\n",
              "      border-color: transparent;\n",
              "      border-bottom-color: var(--fill-color);\n",
              "    }\n",
              "  }\n",
              "</style>\n",
              "\n",
              "      <script>\n",
              "        async function quickchart(key) {\n",
              "          const quickchartButtonEl =\n",
              "            document.querySelector('#' + key + ' button');\n",
              "          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.\n",
              "          quickchartButtonEl.classList.add('colab-df-spinner');\n",
              "          try {\n",
              "            const charts = await google.colab.kernel.invokeFunction(\n",
              "                'suggestCharts', [key], {});\n",
              "          } catch (error) {\n",
              "            console.error('Error during call to suggestCharts:', error);\n",
              "          }\n",
              "          quickchartButtonEl.classList.remove('colab-df-spinner');\n",
              "          quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
              "        }\n",
              "        (() => {\n",
              "          let quickchartButtonEl =\n",
              "            document.querySelector('#df-220e1b85-e6b4-4239-a88a-0cabc0e955aa button');\n",
              "          quickchartButtonEl.style.display =\n",
              "            google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "        })();\n",
              "      </script>\n",
              "    </div>\n",
              "\n",
              "  <div id=\"id_15347261-88dc-48b9-8bf9-738ad2bfaa13\">\n",
              "    <style>\n",
              "      .colab-df-generate {\n",
              "        background-color: #E8F0FE;\n",
              "        border: none;\n",
              "        border-radius: 50%;\n",
              "        cursor: pointer;\n",
              "        display: none;\n",
              "        fill: #1967D2;\n",
              "        height: 32px;\n",
              "        padding: 0 0 0 0;\n",
              "        width: 32px;\n",
              "      }\n",
              "\n",
              "      .colab-df-generate:hover {\n",
              "        background-color: #E2EBFA;\n",
              "        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "        fill: #174EA6;\n",
              "      }\n",
              "\n",
              "      [theme=dark] .colab-df-generate {\n",
              "        background-color: #3B4455;\n",
              "        fill: #D2E3FC;\n",
              "      }\n",
              "\n",
              "      [theme=dark] .colab-df-generate:hover {\n",
              "        background-color: #434B5C;\n",
              "        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "        fill: #FFFFFF;\n",
              "      }\n",
              "    </style>\n",
              "    <button class=\"colab-df-generate\" onclick=\"generateWithVariable('df')\"\n",
              "            title=\"Generate code using this dataframe.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
              "       width=\"24px\">\n",
              "    <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "    <script>\n",
              "      (() => {\n",
              "      const buttonEl =\n",
              "        document.querySelector('#id_15347261-88dc-48b9-8bf9-738ad2bfaa13 button.colab-df-generate');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      buttonEl.onclick = () => {\n",
              "        google.colab.notebook.generateWithVariable('df');\n",
              "      }\n",
              "      })();\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "dataframe",
              "variable_name": "df",
              "summary": "{\n  \"name\": \"df\",\n  \"rows\": 4,\n  \"fields\": [\n    {\n      \"column\": \"Model\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 4,\n        \"samples\": [\n          \"Heston (\\u03c1=-0.70)\",\n          \"Merton (\\u03bb=0.25)\",\n          \"Heston (\\u03c1=-0.30)\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Call Price (C)\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.8717989064763354,\n        \"min\": 6.81,\n        \"max\": 8.32,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          6.81,\n          8.32\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Put Price (P)\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.8371578903249575,\n        \"min\": 5.75,\n        \"max\": 7.2,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          5.75,\n          7.2\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"C - P (LHS)\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.03464101615137783,\n        \"min\": 1.0599999999999996,\n        \"max\": 1.12,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          1.0599999999999996,\n          1.12\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"S - Ke^(-rT) (RHS)\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.0,\n        \"min\": 1.0925,\n        \"max\": 1.0925,\n        \"num_unique_values\": 1,\n        \"samples\": [\n          1.0925\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"Diff (LHS - RHS)\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0.03464101615137783,\n        \"min\": -0.03250000000000042,\n        \"max\": 0.02750000000000008,\n        \"num_unique_values\": 2,\n        \"samples\": [\n          -0.03250000000000042\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}"
            }
          },
          "metadata": {},
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "12.\n"
      ],
      "metadata": {
        "id": "8_R8EnxH7EHA"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "S0 = 80\n",
        "r = 0.055\n",
        "sigma = 0.35\n",
        "T = 0.25\n",
        "n_sim = 10000\n",
        "n_steps = 50\n",
        "dt = T / n_steps\n",
        "\n",
        "# Strike prices based on moneyness\n",
        "moneyness = np.array([0.85, 0.90, 0.95, 1.00, 1.05, 1.10, 1.15])\n",
        "strikes = S0 / moneyness\n",
        "\n",
        "# --- Heston Parameters ---\n",
        "v0 = 0.032   # initial variance\n",
        "kappa = 1.85\n",
        "theta = 0.045\n",
        "sigma_v = 0.3\n",
        "rho = -0.3   # correlation between asset and volatility shocks\n",
        "\n",
        "# --- Merton Parameters ---\n",
        "jump_mu = -0.5\n",
        "jump_sigma = 0.22\n",
        "lambda_jump = 0.75\n",
        "\n",
        "# --- Simulate Heston ---\n",
        "def heston_mc_call_price(K, rho):\n",
        "    prices = np.full(n_sim, S0, dtype=np.float64)\n",
        "    v = np.full(n_sim, v0, dtype=np.float64)\n",
        "    for _ in range(n_steps):\n",
        "        z1 = np.random.normal(size=n_sim)\n",
        "        z2 = rho * z1 + np.sqrt(1 - rho**2) * np.random.normal(size=n_sim)\n",
        "        v = np.maximum(v, 0)\n",
        "        prices *= np.exp((r - 0.5 * v) * dt + np.sqrt(v * dt) * z1)\n",
        "        v += kappa * (theta - v) * dt + sigma_v * np.sqrt(v * dt) * z2\n",
        "    payoff = np.maximum(prices - K, 0)\n",
        "    return np.exp(-r * T) * np.mean(payoff)\n",
        "\n",
        "# Simulate Merton\n",
        "def merton_mc_call_price(K, lam):\n",
        "    dt_m = T\n",
        "    drift = (r - 0.5 * sigma*2 - lam * (np.exp(jump_mu + 0.5 * jump_sigma*2) - 1)) * dt_m\n",
        "    Z = np.random.normal(size=n_sim)\n",
        "    N_jump = np.random.poisson(lam * dt_m, size=n_sim)\n",
        "    jump_component = np.random.normal(jump_mu, jump_sigma, size=n_sim) * N_jump\n",
        "    ST = S0 * np.exp(drift + sigma * np.sqrt(dt_m) * Z + jump_component)\n",
        "    payoff = np.maximum(ST - K, 0)\n",
        "    return np.exp(-r * T) * np.mean(payoff)\n",
        "\n",
        "# Run simulations for each strike\n",
        "results = []\n",
        "for K in strikes:\n",
        "    heston_price = heston_mc_call_price(K, rho)\n",
        "    merton_price = merton_mc_call_price(K, lambda_jump)\n",
        "    results.append({\n",
        "        \"Strike (K)\": round(K, 2),\n",
        "        \"Heston Call Price\": round(heston_price, 2),\n",
        "        \"Merton Call Price\": round(merton_price, 2)\n",
        "    })\n",
        "\n",
        "\n",
        "df_prices = pd.DataFrame(results)\n",
        "print(df_prices)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ucrPsRB_7Gas",
        "outputId": "b1269918-93f9-415f-86ee-f49b5d118557"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "   Strike (K)  Heston Call Price  Merton Call Price\n",
            "0       94.12               0.14               1.06\n",
            "1       88.89               0.58               1.74\n",
            "2       84.21               1.64               2.93\n",
            "3       80.00               3.50               4.10\n",
            "4       76.19               6.00               5.88\n",
            "5       72.73               8.75               7.35\n",
            "6       69.57              11.58               9.24\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "13."
      ],
      "metadata": {
        "id": "GCx9hNq37jjs"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.linear_model import LinearRegression\n",
        "\n",
        "# --- Constants ---\n",
        "S0 = 80\n",
        "K = 80\n",
        "r = 0.055\n",
        "T = 0.25\n",
        "v0 = 0.032\n",
        "kappa = 1.85\n",
        "theta = 0.045\n",
        "sigma_v = 0.3\n",
        "rho = -0.3\n",
        "\n",
        "n_sim = 10000\n",
        "n_steps = 50\n",
        "dt = T / n_steps\n",
        "discount = np.exp(-r * dt)\n",
        "\n",
        "# --- Simulate Heston paths ---\n",
        "def simulate_heston_paths():\n",
        "    prices = np.full((n_sim, n_steps + 1), S0, dtype=np.float64)\n",
        "    variances = np.full((n_sim, n_steps + 1), v0, dtype=np.float64)\n",
        "    for t in range(1, n_steps + 1):\n",
        "        z1 = np.random.normal(size=n_sim)\n",
        "        z2 = rho * z1 + np.sqrt(1 - rho ** 2) * np.random.normal(size=n_sim)\n",
        "        v_prev = np.maximum(variances[:, t - 1], 0)\n",
        "        variances[:, t] = np.maximum(\n",
        "            variances[:, t - 1] + kappa * (theta - v_prev) * dt + sigma_v * np.sqrt(v_prev) * np.sqrt(dt) * z2, 0\n",
        "        )\n",
        "        prices[:, t] = prices[:, t - 1] * np.exp((r - 0.5 * v_prev) * dt + np.sqrt(v_prev) * np.sqrt(dt) * z1)\n",
        "    return prices\n",
        "\n",
        "# --- Least-Squares Monte Carlo for American Call Option ---\n",
        "def lsm_american_call(S_paths):\n",
        "    payoffs = np.maximum(S_paths[:, -1] - K, 0)\n",
        "    cashflows = payoffs.copy()\n",
        "    for t in range(n_steps - 1, 0, -1):\n",
        "        itm = S_paths[:, t] > K\n",
        "        X = S_paths[itm, t]\n",
        "        Y = cashflows[itm] * discount\n",
        "\n",
        "        if len(X) == 0:\n",
        "            continue\n",
        "\n",
        "        # Regression basis: [1, X, X^2]\n",
        "        A = np.vstack([np.ones_like(X), X, X**2]).T\n",
        "        model = LinearRegression().fit(A, Y)\n",
        "        continuation = model.predict(A)\n",
        "\n",
        "        exercise = np.maximum(S_paths[itm, t] - K, 0) > continuation\n",
        "        cashflows[itm] = np.where(\n",
        "            exercise,\n",
        "            np.maximum(S_paths[itm, t] - K, 0),\n",
        "            cashflows[itm] * discount\n",
        "        )\n",
        "    return np.mean(cashflows) * np.exp(-r * dt)\n",
        "\n",
        "# --- European call under Heston model ---\n",
        "def european_heston_price(S_shift):\n",
        "    prices = np.full(n_sim, S_shift, dtype=np.float64)\n",
        "    v = np.full(n_sim, v0, dtype=np.float64)\n",
        "    for _ in range(n_steps):\n",
        "        z1 = np.random.normal(size=n_sim)\n",
        "        z2 = rho * z1 + np.sqrt(1 - rho**2) * np.random.normal(size=n_sim)\n",
        "        v = np.maximum(v, 0)\n",
        "        prices *= np.exp((r - 0.5 * v) * dt + np.sqrt(v * dt) * z1)\n",
        "        v += kappa * (theta - v) * dt + sigma_v * np.sqrt(v * dt) * z2\n",
        "    payoff = np.maximum(prices - K, 0)\n",
        "    return np.exp(-r * T) * np.mean(payoff)\n",
        "\n",
        "# --- Run pricing ---\n",
        "S_paths = simulate_heston_paths()\n",
        "american_price = lsm_american_call(S_paths)\n",
        "\n",
        "# --- Estimate Greeks for European Option ---\n",
        "eps = 0.1\n",
        "call_p_plus = european_heston_price(S0 + eps)\n",
        "call_p = european_heston_price(S0)\n",
        "call_p_minus = european_heston_price(S0 - eps)\n",
        "\n",
        "delta = (call_p_plus - call_p_minus) / (2 * eps)\n",
        "gamma = (call_p_plus - 2 * call_p + call_p_minus) / (eps ** 2)\n",
        "\n",
        "# --- Output Results ---\n",
        "results = {\n",
        "    \"Option Type\": \"American Call (Heston)\",\n",
        "    \"Option Price\": round(american_price, 2),\n",
        "    \"Delta (European)\": round(delta, 4),\n",
        "    \"Gamma (European)\": round(gamma, 4)\n",
        "}\n",
        "\n",
        "print(pd.DataFrame([results]))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "FKtbuxvk7lNL",
        "outputId": "cc4117cc-6585-483b-a6e6-3aaaa7cfc70a"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "              Option Type  Option Price  Delta (European)  Gamma (European)\n",
            "0  American Call (Heston)          3.41            0.1086           -8.6186\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "13. American call Option Pricing under Heston Using Monte-Carlo Method (ρ= -0.30)\n",
        "American options allow early exercise at any time before expiration, which creates an optimal stopping problem. Because of this, there's no exact formula to price them under the Heston model. Instead, methods like Monte Carlo simulation with Least Squares Regression (Longstaff-Schwartz approach) or finite difference techniques are used to estimate their value.\n",
        "Price of American call option: $ 2.60\n",
        "American call Delta: 1.39\n",
        "American call Gamma: 1.42\n",
        "The price of a European call option is higher than that of an American call option. Additionally, under the Heston model, the Delta and Gamma of American options are greater than those of European options.\n"
      ],
      "metadata": {
        "id": "-i16xlYwMTQv"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "\n",
        "def heston_mc_american_call(S0, K, T, r, kappa, theta, sigma, rho, V0, N, M):\n",
        "    dt = T / M\n",
        "    S = np.zeros((N, M+1))\n",
        "    V = np.zeros((N, M+1))\n",
        "    S[:, 0] = S0\n",
        "    V[:, 0] = V0\n",
        "\n",
        "    for i in range(1, M+1):\n",
        "        Z1 = np.random.standard_normal(N)\n",
        "        Z2 = rho * Z1 + np.sqrt(1 - rho**2) * np.random.standard_normal(N)\n",
        "        V[:, i] = np.maximum(V[:, i-1] + kappa * (theta - V[:, i-1]) * dt + sigma * np.sqrt(V[:, i-1]) * np.sqrt(dt) * Z2, 0)\n",
        "        S[:, i] = S[:, i-1] * np.exp((r - 0.5 * V[:, i-1]) * dt + np.sqrt(V[:, i-1]) * np.sqrt(dt) * Z1)\n",
        "\n",
        "    payoff = np.maximum(S - K, 0)\n",
        "\n",
        "    # Longstaff-Schwartz method for early exercise\n",
        "    for t in range(M-1, 0, -1):\n",
        "        in_the_money = payoff[:, t] > 0\n",
        "        if np.any(in_the_money):\n",
        "            regression = np.polyfit(S[in_the_money, t], payoff[in_the_money, t+1] * np.exp(-r * dt), 2)\n",
        "            continuation_value = np.polyval(regression, S[in_the_money, t])\n",
        "            exercise = payoff[in_the_money, t] > continuation_value\n",
        "            payoff[in_the_money, t] = np.where(exercise, payoff[in_the_money, t], payoff[in_the_money, t+1] * np.exp(-r * dt))\n",
        "\n",
        "    return np.mean(payoff[:, 1]) * np.exp(-r * dt)\n",
        "\n",
        "# Example usage\n",
        "option_price = heston_mc_american_call(S0=100, K=100, T=1, r=0.05, kappa=2, theta=0.04, sigma=0.3, rho=-0.5, V0=0.04, N=10000, M=50)\n",
        "print(f\"American Call Option Price: {option_price:.2f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "7IQ-SfWRMXlI",
        "outputId": "45334ea8-ff4c-4fb1-f5ae-e3dac72ffc33"
      },
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "American Call Option Price: 2.64\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Delta and Gamma calculation for the American Option using the new function\n",
        "print(\"\\n--- Greeks for American Call Option ---\")\n",
        "\n",
        "# Calculate Delta for American Call\n",
        "def calculate_delta_american_call(S0, K, T, r, kappa, theta, sigma, rho, V0, N, M, h=0.1):\n",
        "    price_up = heston_mc_american_call(S0 + h, K, T, r, kappa, theta, sigma, rho, V0, N, M)\n",
        "    price_down = heston_mc_american_call(S0 - h, K, T, r, kappa, theta, sigma, rho, V0, N, M)\n",
        "    delta = (price_up - price_down) / (2 * h)\n",
        "    return delta\n",
        "\n",
        "# Calculate Gamma for American Call\n",
        "def calculate_gamma_american_call(S0, K, T, r, kappa, theta, sigma, rho, V0, N, M, h=0.1):\n",
        "    price_up = heston_mc_american_call(S0 + h, K, T, r, kappa, theta, sigma, rho, V0, N, M)\n",
        "    price_down = heston_mc_american_call(S0 - h, K, T, r, kappa, theta, sigma, rho, V0, N, M)\n",
        "    price_current = heston_mc_american_call(S0, K, T, r, kappa, theta, sigma, rho, V0, N, M)\n",
        "    gamma = (price_up - 2 * price_current + price_down) / (h**2)\n",
        "    return gamma\n",
        "\n",
        "delta_american_call = calculate_delta_american_call(S0, K, T, r, kappa_v, theta_v, sigma_v, rho, v0, I, M)\n",
        "gamma_american_call = calculate_gamma_american_call(S0, K, T, r, kappa_v, theta_v, sigma_v, rho, v0, I, M)\n",
        "\n",
        "print(f\"American Call Delta: {delta_american_call:.2f}\")\n",
        "print(f\"American Call Gamma: {gamma_american_call:.2f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3MMv1nKRM0bk",
        "outputId": "eb5120a4-3628-484a-b236-477bb33358a7"
      },
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "--- Greeks for American Call Option ---\n",
            "American Call Delta: 0.73\n",
            "American Call Gamma: 1.05\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 14. Price Up and In Call Option (CUI):\n",
        "\n",
        "- **Barrier level (H):** \\$95  \n",
        "- **Strike price (K):** \\$95  \n",
        "\n",
        "**Payoff:**  \n",
        "$$\n",
        "\\max(S_t - K, 0) \\quad \\text{if } S_t > B, \\text{ else } 0.\n",
        "$$\n"
      ],
      "metadata": {
        "id": "vkTtzSr-Mhyj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "\n",
        "def heston_cui_mc(S, K, r, T, t, barrier):\n",
        "  # Check if the barrier is ever reached for each path\n",
        "  barrier_reached = np.max(S, axis=0) >= barrier\n",
        "\n",
        "  # Calculate the payoff for paths where the barrier was reached\n",
        "  payoff = np.where(barrier_reached, np.maximum(S[-1, :] - K, 0), 0)\n",
        "\n",
        "  average = np.mean(payoff)\n",
        "\n",
        "  return np.exp(-r * (T - t)) * average\n",
        "\n",
        "# Parameters for the European up-and-in call option\n",
        "barrier = 95\n",
        "K_cui = 95\n",
        "\n",
        "# Ensure S is generated with the correct rho for Question 6 (-0.70)\n",
        "rho = -0.70\n",
        "cho_matrix = generate_cholesky_matrix(rho)\n",
        "V = SDE_vol(v0, kappa_v, theta_v, sigma_v, T, M, I, rand, 1, cho_matrix)\n",
        "S = Heston_paths(S0, r, V, 0, cho_matrix)\n",
        "\n",
        "# Price the European up-and-in call option\n",
        "cui_price = heston_cui_mc(S, K_cui, r, T, 0, barrier)\n",
        "print(f\"\\nEuropean Up-and-In Call Price (Barrier={barrier}, Strike={K_cui}) under Heston: {cui_price:.2f}\")\n",
        "\n",
        "# Price the simple European call option with the same strike for comparison\n",
        "european_call_price = heston_call_mc(S, K_cui, r, T, 0)\n",
        "print(f\"Simple European Call Price (Strike={K_cui}) under Heston: {european_call_price:.2f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "batAgHSKMsF-",
        "outputId": "ff733ee3-d1b0-4405-819b-c66fc85c28dc"
      },
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "European Up-and-In Call Price (Barrier=95, Strike=95) under Heston: 0.03\n",
            "Simple European Call Price (Strike=95) under Heston: 0.03\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Step 2"
      ],
      "metadata": {
        "id": "m3kuqNLjRajf"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "15."
      ],
      "metadata": {
        "id": "HWdarqJERfen"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "\n",
        "def price_merton_pdi_put(S0 = 80, K=65, B=65, r=0.055, sigma=0.35, T=0.25,\n",
        "                         mu_jump=-0.5, delta_jump=0.22, lambda_jump=0.75,\n",
        "                         n_simulations=100000, n_steps=100):\n",
        "    dt = T / n_steps\n",
        "    k = np.exp(mu_jump + 0.5 * delta_jump**2) - 1\n",
        "\n",
        "    payoffs = []\n",
        "\n",
        "    for _ in range(n_simulations):\n",
        "        S = S0\n",
        "        path = [S]\n",
        "\n",
        "        for _ in range(n_steps):\n",
        "            Z = np.random.normal()\n",
        "            Nj = np.random.poisson(lambda_jump * dt)\n",
        "            jumps = np.sum(np.random.normal(mu_jump, delta_jump, Nj)) if Nj > 0 else 0\n",
        "            S *= np.exp((r - 0.5 * sigma**2 - lambda_jump * k) * dt + sigma * np.sqrt(dt) * Z + jumps)\n",
        "            path.append(S)\n",
        "\n",
        "        if min(path) <= B:\n",
        "            payoff = max(K - path[-1], 0)\n",
        "        else:\n",
        "            payoff = 0\n",
        "\n",
        "        payoffs.append(np.exp(-r * T) * payoff)\n",
        "\n",
        "    return round(np.mean(payoffs), 2)\n",
        "\n",
        "# Call the function and assign the result to pdi_put\n",
        "pdi_put = price_merton_pdi_put()\n",
        "print(\"Down-and-In Put (PDI):\", pdi_put)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "2w5L64mHReXg",
        "outputId": "d20e8623-30c9-40c8-d5af-c7c61828ec74"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Down-and-In Put (PDI): 2.74\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"European Put (λ = 0.75): $\", put8)\n",
        "print(\"Down-and-In Put (PDI): $\", pdi_put)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "d2uXPoHlRirk",
        "outputId": "43daab46-baad-48ce-880a-8a5fb1627b6e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "European Put (λ = 0.75): $ 7.2\n",
            "Down-and-In Put (PDI): $ 2.74\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "btVh6oiWkILy"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}