{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pricing a European call with the Black-Scholes equation\n",
    "\n",
    "A European call gives the right to buy a share for the strike price $K$ at the\n",
    "maturity $T$. Under the Black-Scholes assumptions (log-normal share price $S$ with\n",
    "volatility $\\sigma$, constant risk-free rate $r$, no dividends, frictionless hedging)\n",
    "its value $V(S,\\tau)$, written in the time to maturity $\\tau=T-t$, obeys\n",
    "\n",
    "$$\\frac{\\partial V}{\\partial\\tau}=\\frac{\\sigma^2S^2}{2}\\frac{\\partial^2V}{\\partial S^2}\n",
    "  +rS\\frac{\\partial V}{\\partial S}-rV,\\qquad V(S,0)=\\max(S-K,0).$$\n",
    "\n",
    "In the variable $x=\\ln S$ the coefficients become constant:\n",
    "\n",
    "$$\\frac{\\partial V}{\\partial\\tau}+u\\,\\frac{\\partial V}{\\partial x}\n",
    "  =D\\,\\frac{\\partial^2V}{\\partial x^2}-r\\,V,\\qquad D=\\frac{\\sigma^2}{2},\\quad u=-\\Big(r-\\frac{\\sigma^2}{2}\\Big).$$\n",
    "\n",
    "This is exactly the balance of a diffusing, drifting and decaying species, so\n",
    "OneSimulation solves it with the `SpeciesTransport` model on a line in $x$ (diffusivity\n",
    "$D$, velocity $u$, decay rate $r$, \"time\" $\\tau$) with quadratic finite elements and\n",
    "BDF2 steps.\n",
    "\n",
    "A transport model normally holds a nonnegative amount; an option value is a signed\n",
    "quantity in the numerical sense (tiny undershoots far out of the money are harmless), so\n",
    "the model is declared with `nonnegative=False`. The delta $\\Delta=\\partial V/\\partial S\n",
    "=S^{-1}\\,\\partial V/\\partial x$ comes from the gradient of the finite-element solution.\n",
    "\n",
    "| Boundary | Condition on $V$ |\n",
    "|---|---|\n",
    "| $x_\\mathrm{min}=\\ln K-2.5$ (deep out of the money) | $V=0$ (call worthless) |\n",
    "| $x_\\mathrm{max}=\\ln K+2.5$ (deep in the money) | $V=S-K\\,e^{-r\\tau}$ |\n",
    "\n",
    "**Reference.** F. Black and M. Scholes, *The pricing of options and corporate\n",
    "liabilities*, J. Political Economy 81, 637-654 (1973); J. C. Hull, *Options, Futures,\n",
    "and Other Derivatives*, 10th ed., Pearson 2018, ch. 15:\n",
    "\n",
    "$$V=S\\,N(d_1)-K\\,e^{-r\\tau}N(d_2),\\qquad\n",
    "  d_{1,2}=\\frac{\\ln(S/K)+(r\\pm\\sigma^2/2)\\,\\tau}{\\sigma\\sqrt\\tau},\\qquad\n",
    "  \\Delta=\\frac{\\partial V}{\\partial S}=N(d_1).$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, Nitsche\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.chemistry import SpeciesTransport, TransportSpecies\n",
    "from onesim.simulation import PrescribedValueBoundary, Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.stats import norm\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Contract and market\n",
    "\n",
    "An at-the-money one-year call on a share of 100 with 20 % volatility and a 5 % rate.\n",
    "The line in $x=\\ln S$ covers share prices from 8 to 1218."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strike, volatility, rate, maturity = 100.0, 0.20, 0.05, 1.0\n",
    "low, high = np.log(strike) - 2.5, np.log(strike) + 2.5\n",
    "line = Line(start=(low, 0.0, 0.0), end=(high, 0.0, 0.0))\n",
    "print(\n",
    "    f\"diffusivity D = {0.5 * volatility**2:.4f}, velocity u = {-(rate - 0.5 * volatility**2):.4f}, decay r = {rate:.3f}; \"\n",
    "    f\"share prices {np.exp(low):.1f} to {np.exp(high):.0f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The species `V` is the call value, starting from the payoff at maturity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "model = SpeciesTransport(\n",
    "    domain=line.line,\n",
    "    velocity=-(rate - 0.5 * volatility**2),\n",
    "    nonnegative=False,\n",
    "    species=(TransportSpecies(\"V\", diffusivity=0.5 * volatility**2, decay_rate=rate),),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"European call\",\n",
    "    geometry=line,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        PrescribedValueBoundary(\n",
    "            physics=model,\n",
    "            boundary=line.boundaries.start,\n",
    "            value=lambda time, coordinate: {\"V\": 0.0},\n",
    "        ),\n",
    "        PrescribedValueBoundary(\n",
    "            physics=model,\n",
    "            boundary=line.boundaries.end,\n",
    "            value=lambda time, coordinate: {\n",
    "                \"V\": np.exp(high) - strike * np.exp(-rate * time)\n",
    "            },\n",
    "        ),\n",
    "    ),\n",
    "    initial_conditions=(\n",
    "        InitialValue(\n",
    "            model.concentration(\"V\"),\n",
    "            lambda x, y, z: np.maximum(np.exp(x) - strike, 0.0),\n",
    "        ),\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mesh study\n",
    "\n",
    "Four uniform meshes of 25 to 200 quadratic elements, 400 BDF2 steps to maturity each.\n",
    "The prices are compared at maturity between $S=60$ and $S=160$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "meshes = {\n",
    "    cells: StructuredLineMesher(cells=cells).generate(line)\n",
    "    for cells in (25, 50, 100, 200)\n",
    "}\n",
    "results = {\n",
    "    cells: Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=2), boundary_enforcement=Nitsche()\n",
    "            ),\n",
    "            nonlinear_solver=Newton(linear_solver=SparseDirect(), jacobian=\"analytic\"),\n",
    "            time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=maturity, time_step=maturity / 400)\n",
    "    for cells, mesh in meshes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the Black-Scholes formula\n",
    "\n",
    "The price on a fine line of share prices, at maturity and at two earlier times to\n",
    "maturity; the delta from the gradient of the solution in $x$, divided by $S$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def black_scholes(s, tau):\n",
    "    d1 = (np.log(s / strike) + (rate + 0.5 * volatility**2) * tau) / (\n",
    "        volatility * np.sqrt(tau)\n",
    "    )\n",
    "    return s * norm.cdf(d1) - strike * np.exp(-rate * tau) * norm.cdf(\n",
    "        d1 - volatility * np.sqrt(tau)\n",
    "    ), norm.cdf(d1)\n",
    "\n",
    "\n",
    "share = np.linspace(60.0, 160.0, 201)\n",
    "points = np.column_stack((np.log(share), np.zeros_like(share), np.zeros_like(share)))\n",
    "price = {\n",
    "    cells: np.asarray(\n",
    "        r.field(model.concentration(\"V\")).evaluate(points, time=maturity)\n",
    "    ).reshape(-1)\n",
    "    for cells, r in results.items()\n",
    "}\n",
    "delta = {\n",
    "    cells: r.field(model.concentration(\"V\")).gradient(points, time=maturity)[:, 0]\n",
    "    / share\n",
    "    for cells, r in results.items()\n",
    "}\n",
    "exact, exact_delta = black_scholes(share, maturity)\n",
    "print(\"  cells   h = dx    price at S = K   largest price error   largest delta error\")\n",
    "for cells in results:\n",
    "    print(\n",
    "        f\"{cells:7d} {(high - low) / cells:8.4f} {price[cells][share == strike][0]:16.6f} {np.abs(price[cells] - exact).max():21.2e} \"\n",
    "        f\"{np.abs(delta[cells] - exact_delta).max():21.2e}\"\n",
    "    )\n",
    "print(f\"Black-Scholes at S = K: {exact[share == strike][0]:.6f}\")\n",
    "errors = [np.abs(price[cells] - exact).max() for cells in results]\n",
    "delta_errors = [np.abs(delta[cells] - exact_delta).max() for cells in results]\n",
    "print(\n",
    "    f\"observed order of the price error: {np.log2(errors[-3] / errors[-2]):.2f}, {np.log2(errors[-2] / errors[-1]):.2f}; \"\n",
    "    f\"of the delta error: {np.log2(delta_errors[-3] / delta_errors[-2]):.2f}, {np.log2(delta_errors[-2] / delta_errors[-1]):.2f}\"\n",
    ")\n",
    "fine = results[200].field(model.concentration(\"V\"))\n",
    "earlier = {\n",
    "    tau: np.asarray(fine.evaluate(points, time=tau)).reshape(-1) for tau in (0.1, 0.4)\n",
    "}\n",
    "for tau, value in earlier.items():\n",
    "    print(\n",
    "        f\"τ = {tau:.1f} year, 200 elements: largest price error {np.abs(value - black_scholes(share, tau)[0]).max():.2e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Quadratic elements converge with the third power of the element size at these\n",
    "sample points; the delta, a derivative of the solution, one order lower.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The call value before maturity against the payoff and the formula; the delta; and the\n",
    "price error against the element size."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.line(\n",
    "    share,\n",
    "    {f\"τ = {tau:.1f} year\": value for tau, value in earlier.items()}\n",
    "    | {\"τ = 1.0 year\": price[200]},\n",
    "    reference={\n",
    "        f\"τ = {tau:.1f} year\": black_scholes(share, tau)[0] for tau in (0.1, 0.4, 1.0)\n",
    "    }\n",
    "    | {\"payoff max(S - K, 0)\": np.maximum(share - strike, 0.0)},\n",
    "    xlabel=\"share price S\",\n",
    "    ylabel=\"call value V\",\n",
    "    title=\"Call value (dashed: formula)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    share,\n",
    "    {\"FEM, 200 elements\": delta[200]},\n",
    "    reference={\"N(d1)\": exact_delta},\n",
    "    vlines={\"strike\": strike},\n",
    "    xlabel=\"share price S\",\n",
    "    ylabel=\"delta ∂V/∂S\",\n",
    "    title=\"Delta at τ = 1 year\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.convergence(\n",
    "    np.array([(high - low) / cells for cells in results]),\n",
    "    {\n",
    "        \"largest price error\": np.array(errors),\n",
    "        \"largest delta error\": np.array(delta_errors),\n",
    "    },\n",
    "    order=(3, 2),\n",
    "    xlabel=\"element size in ln S\",\n",
    "    ylabel=\"largest error, 60 ≤ S ≤ 160\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the payoff by $\\max(K-S,0)$ and the far-field values accordingly to price a\n",
    "put and check put-call parity $C-P=S-Ke^{-r\\tau}$. With a time-dependent rate or\n",
    "volatility the formula no longer applies, but the transport model still does. An\n",
    "American option adds the early-exercise constraint $V\\ge\\max(S-K,0)$, a free-boundary\n",
    "problem that needs a complementarity solver on top of this model."
   ]
  }
 ]
}
