{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9396fdc0",
   "metadata": {},
   "source": [
    "# Quickstart for knockout option pricing model documentation\n",
    "\n",
    "Welcome! Let's get you started with the basic process of documenting models with ValidMind.\n",
    "\n",
    "A knockout option is a barrier option that ceases to exist if the underlying asset hits a predetermined price, known as the \"barrier.\" This barrier level, set above or below the current market price, determines whether the option will \"knock out\" before its expiration date. There are two types: \"up-and-out\" and \"down-and-out.\" In an up-and-out knockout option, the option expires if the asset price rises above the barrier, while in a down-and-out, it expires if the asset price falls below. Knockout options generally offer a lower premium than standard options since there is a chance they will expire worthless if the barrier is reached.\n",
    "\n",
    "Pricing knockout options involves accounting for the proximity of the asset's price to the barrier, as well as market volatility and the option’s time to expiration. High volatility and longer expiry increase the likelihood of the barrier being triggered, which reduces the option’s value. Models like modified Black-Scholes are used for simpler cases, while Monte Carlo simulations or binomial trees handle complex scenarios. Knockout options are useful for hedging or cost-effective investment strategies, allowing investors to save on premiums but with the risk of losing the option entirely if the barrier is hit.\n",
    "\n",
    "You will learn how to initialize the ValidMind Library, develop a option pricing model, and then write custom tests that can be used for sensitivity and stress testing to quickly generate documentation about model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4086bb1",
   "metadata": {},
   "source": [
    "<a id='toc0_'></a>\n",
    "\n",
    "## Contents    \n",
    "- [About ValidMind](#toc1_)    \n",
    "  - [Before you begin](#toc1_1_)    \n",
    "  - [New to ValidMind?](#toc1_2_)    \n",
    "  - [Key concepts](#toc1_3_)    \n",
    "- [Install the ValidMind Library](#toc2_)\n",
    "  - [Get your code snippet](#toc3_1_)\n",
    "- [Initialize the ValidMind Library](#toc3_)    \n",
    "- [Initialize the Python environment](#toc4_)    \n",
    "  - [Preview the documentation template](#toc4_1_)    \n",
    "- [Model development](#toc5_)   \n",
    "- [Data preparation](#toc6_)   \n",
    "  - [Synthetic data generation](#toc6_1_)\n",
    "  - [Data quality](#toc6_2_)\n",
    "  - [Model Calibration](#toc6_3_)    \n",
    "- [Model Evaluation](#toc7_)    \n",
    "  - [Benchmark Testing](#toc7_1_)    \n",
    "  - [Sensitivity Testing](#toc7_2_)  \n",
    "  - [Greeks](#toc7_3_)    \n",
    "  - [Stress Testing](#toc7_4_)    \n",
    "- [Next steps](#toc8_)    \n",
    "  - [Work with your model documentation](#toc8_1_)    \n",
    "  - [Discover more learning resources](#toc8_2_)    \n",
    "\n",
    "<!-- vscode-jupyter-toc-config\n",
    "\tnumbering=false\n",
    "\tanchor=true\n",
    "\tflat=false\n",
    "\tminLevel=2\n",
    "\tmaxLevel=4\n",
    "\t/vscode-jupyter-toc-config -->\n",
    "<!-- THIS CELL WILL BE REPLACED ON TOC UPDATE. DO NOT WRITE YOUR TEXT IN THIS CELL -->"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d02b7332",
   "metadata": {},
   "source": [
    "<a id='toc1_'></a>\n",
    "\n",
    "## About ValidMind\n",
    "\n",
    "ValidMind is a suite of tools for managing model risk, including risk associated with AI and statistical models.\n",
    "\n",
    "You use the ValidMind Library to automate documentation and validation tests, and then use the ValidMind Platform to collaborate on model documentation. Together, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.\n",
    "\n",
    "<a id='toc1_1_'></a>\n",
    "\n",
    "### Before you begin\n",
    "\n",
    "This notebook assumes you have basic familiarity with Python, including an understanding of how functions work. If you are new to Python, you can still run the notebook but we recommend further familiarizing yourself with the language. \n",
    "\n",
    "If you encounter errors due to missing modules in your Python environment, install the modules with `pip install`, and then re-run the notebook. For more help, refer to [Installing Python Modules](https://docs.python.org/3/installing/index.html).\n",
    "\n",
    "<a id='toc1_2_'></a>\n",
    "\n",
    "### New to ValidMind?\n",
    "\n",
    "If you haven't already seen our documentation on the [ValidMind Library](https://docs.validmind.ai/developer/validmind-library.html), we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models and running tests, as well as find code samples and our Python Library API reference.\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #f7e4ee; color: black; border: 1px solid black;\"><b>For access to all features available in this notebook, create a free ValidMind account.</b>\n",
    "<br></br>\n",
    "Signing up is FREE — <a href=\"https://docs.validmind.ai/guide/configuration/register-with-validmind.html\"><b>Register with ValidMind</b></a></div>\n",
    "\n",
    "<a id='toc1_3_'></a>\n",
    "\n",
    "### Key concepts\n",
    "\n",
    "**Model documentation**: A structured and detailed record pertaining to a model, encompassing key components such as its underlying assumptions, methodologies, data sources, inputs, performance metrics, evaluations, limitations, and intended uses. It serves to ensure transparency, adherence to regulatory requirements, and a clear understanding of potential risks associated with the model’s application.\n",
    "\n",
    "**Documentation template**: Functions as a test suite and lays out the structure of model documentation, segmented into various sections and sub-sections. Documentation templates define the structure of your model documentation, specifying the tests that should be run, and how the results should be displayed.\n",
    "\n",
    "**Tests**: A function contained in the ValidMind Library, designed to run a specific quantitative test on the dataset or model. Tests are the building blocks of ValidMind, used to evaluate and document models and datasets, and can be run individually or as part of a suite defined by your model documentation template.\n",
    "\n",
    "**Custom tests**: Custom tests are functions that you define to evaluate your model or dataset. These functions can be registered via the ValidMind Library to be used with the ValidMind Platform.\n",
    "\n",
    "**Inputs**: Objects to be evaluated and documented in the ValidMind Library. They can be any of the following:\n",
    "\n",
    "  - **model**: A single model that has been initialized in ValidMind with [`vm.init_model()`](https://docs.validmind.ai/validmind/validmind.html#init_model).\n",
    "  - **dataset**: Single dataset that has been initialized in ValidMind with [`vm.init_dataset()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset).\n",
    "  - **models**: A list of ValidMind models - usually this is used when you want to compare multiple models in your custom test.\n",
    "  - **datasets**: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom test. See this [example](https://docs.validmind.ai/notebooks/how_to/run_tests_that_require_multiple_datasets.html) for more information.\n",
    "\n",
    "**Parameters**: Additional arguments that can be passed when running a ValidMind test, used to pass additional information to a test, customize its behavior, or provide additional context.\n",
    "\n",
    "**Outputs**: Custom tests can return elements like tables or plots. Tables may be a list of dictionaries (each representing a row) or a pandas DataFrame. Plots may be matplotlib or plotly figures.\n",
    "\n",
    "**Test suites**: Collections of tests designed to run together to automate and generate model documentation end-to-end for specific use-cases.\n",
    "\n",
    "Example: the [`classifier_full_suite`](https://docs.validmind.ai/validmind/validmind/test_suites/classifier.html#ClassifierFullSuite) test suite runs tests from the [`tabular_dataset`](https://docs.validmind.ai/validmind/validmind/test_suites/tabular_datasets.html) and [`classifier`](https://docs.validmind.ai/validmind/validmind/test_suites/classifier.html) test suites to fully document the data and model sections for binary classification model use-cases.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d47fc11d",
   "metadata": {},
   "source": [
    "<a id='toc2_'></a>\n",
    "\n",
    "## Install the ValidMind Library\n",
    "\n",
    "To install the library:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f23a4ba9",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q validmind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bec2a94f",
   "metadata": {},
   "source": [
    "<a id='toc3_'></a>\n",
    "\n",
    "## Initialize the ValidMind Library\n",
    "\n",
    "ValidMind generates a unique _code snippet_ for each registered model to connect with your developer environment. You initialize the ValidMind Library with this code snippet, which ensures that your documentation and tests are uploaded to the correct model when you run the notebook.\n",
    "\n",
    "<a id='toc3_1_'></a>\n",
    "\n",
    "### Get your code snippet\n",
    "\n",
    "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/configuration/log-in-to-validmind.html).\n",
    "\n",
    "2. In the left sidebar, navigate to **Model Inventory** and click **+ Register Model**.\n",
    "\n",
    "3. Enter the model details and click **Continue**. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/register-models-in-inventory.html))\n",
    "\n",
    "   For example, to register a model for use with this notebook, select:\n",
    "\n",
    "   - Documentation template: `Capital markets`\n",
    "\n",
    "   You can fill in other options according to your preference.\n",
    "\n",
    "4. Go to **Getting Started** and click **Copy snippet to clipboard**.\n",
    "\n",
    "Next, [load your model identifier credentials from an `.env` file](https://docs.validmind.ai/developer/model-documentation/store-credentials-in-env-file.html) or replace the placeholder with your own code snippet:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "856dd312",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load your model identifier credentials from an `.env` file\n",
    "\n",
    "%load_ext dotenv\n",
    "%dotenv .env\n",
    "\n",
    "# Or replace with your code snippet\n",
    "\n",
    "import validmind as vm\n",
    "\n",
    "vm.init(\n",
    "    # api_host=\"...\",\n",
    "    # api_key=\"...\",\n",
    "    # api_secret=\"...\",\n",
    "    # model=\"...\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17c03181",
   "metadata": {},
   "source": [
    "<a id='toc4_'></a>\n",
    "\n",
    "## Initialize the Python environment\n",
    "\n",
    "Next, let's import the necessary libraries and set up your Python environment for data analysis:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "29d2c1a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.optimize import minimize\n",
    "\n",
    "from validmind.tests import run_test"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39f83e47",
   "metadata": {},
   "source": [
    "<a id='toc4_1_'></a>\n",
    "\n",
    "### Preview the documentation template\n",
    "\n",
    "A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.\n",
    "\n",
    "You will upload documentation and test results into this template later on. For now, take a look at the structure that the template provides with the `vm.preview_template()` function from the ValidMind library and note the empty sections:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "040681e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.preview_template()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d6a8447",
   "metadata": {},
   "source": [
    "<a id='toc5_'></a>\n",
    "\n",
    "## Model development"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "c3f5b0b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "class OptionPricing:\n",
    "    def __init__(self, S0, K, T, r):\n",
    "        self.S0 = S0\n",
    "        self.K = K\n",
    "        self.T = T\n",
    "        self.r = r\n",
    "\n",
    "    def monte_carlo_simulation(self, N, M):\n",
    "        raise NotImplementedError(\"Must be implemented by subclasses\")\n",
    "\n",
    "    def price_option(self, N, M):\n",
    "        raise NotImplementedError(\"Must be implemented by subclasses\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "d3748656",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "class BlackScholesModel(OptionPricing):\n",
    "    def __init__(self, S0, K, T, r, sigma):\n",
    "        super().__init__(S0, K, T, r)\n",
    "        self.sigma = sigma\n",
    "    def monte_carlo_simulation(self, N, M):\n",
    "        dt = self.T / M\n",
    "        price_paths = np.zeros((N, M + 1))\n",
    "        price_paths[:, 0] = self.S0\n",
    "        for t in range(1, M + 1):\n",
    "            Z = np.random.standard_normal(N)\n",
    "            price_paths[:, t] = price_paths[:, t - 1] * np.exp((self.r - 0.5 * self.sigma**2) * dt + self.sigma * np.sqrt(dt) * Z)\n",
    "        return price_paths\n",
    "\n",
    "    def price_option(self, N, M):\n",
    "        price_paths = self.monte_carlo_simulation(N, M)\n",
    "        payoffs = np.maximum(price_paths[:, -1] - self.K, 0)\n",
    "        return np.exp(-self.r * self.T) * np.mean(payoffs)\n",
    "    \n",
    "    def calibrate(self, market_prices, strikes, maturities):\n",
    "        def objective_function(params):\n",
    "            self.sigma = params[0]\n",
    "            for K, T in zip(strikes, maturities):\n",
    "                self.K = K\n",
    "                self.T = T\n",
    "                model_prices.append(self.price_option(10000, 100))\n",
    "            return np.sum((np.array(market_prices) - np.array(model_prices))**2)\n",
    "        result = minimize(objective_function, [self.sigma], bounds=[(0.01, 1.0)])\n",
    "        self.sigma = result.x[0]\n",
    "\n",
    "class StochasticVolatilityModel(OptionPricing):\n",
    "    def __init__(self, S0, K, T, r, v0, kappa, theta, xi, rho):\n",
    "        super().__init__(S0, K, T, r)\n",
    "        self.v0 = v0\n",
    "        self.kappa = kappa\n",
    "        self.theta = theta\n",
    "        self.xi = xi\n",
    "        self.rho = rho\n",
    "    def monte_carlo_simulation(self, N, M):\n",
    "        dt = self.T / M\n",
    "        price_paths = np.zeros((N, M + 1))\n",
    "        vol_paths = np.zeros((N, M + 1))\n",
    "        price_paths[:, 0] = self.S0\n",
    "        vol_paths[:, 0] = self.v0\n",
    "        for t in range(1, M + 1):\n",
    "            Z1 = np.random.standard_normal(N)\n",
    "            Z2 = np.random.standard_normal(N)\n",
    "            W1 = Z1\n",
    "            W2 = self.rho * Z1 + np.sqrt(1 - self.rho**2) * Z2\n",
    "            vol_paths[:, t] = np.abs(vol_paths[:, t - 1] + self.kappa * (self.theta - vol_paths[:, t - 1]) * dt + self.xi * np.sqrt(vol_paths[:, t - 1] * dt) * W1)\n",
    "            price_paths[:, t] = price_paths[:, t - 1] * np.exp((self.r - 0.5 * vol_paths[:, t - 1]) * dt + np.sqrt(vol_paths[:, t - 1] * dt) * W2)\n",
    "        return price_paths\n",
    "\n",
    "    def price_option(self, N, M):\n",
    "        price_paths = self.monte_carlo_simulation(N, M)\n",
    "        payoffs = np.maximum(price_paths[:, -1] - self.K, 0)\n",
    "        return np.exp(-self.r * self.T) * np.mean(payoffs)\n",
    "    \n",
    "    def calibrate(self, market_prices, strikes, maturities):\n",
    "        def objective_function(params):\n",
    "            self.v0, self.kappa, self.theta, self.xi, self.rho = params\n",
    "            model_prices = []\n",
    "            for K, T in zip(strikes, maturities):\n",
    "                self.K = K\n",
    "                self.T = T\n",
    "                model_prices.append(self.price_option(10000, 100))\n",
    "\n",
    "            return np.sum((np.array(market_prices) - np.array(model_prices))**2)\n",
    "        \n",
    "        initial_guess = [self.v0, self.kappa, self.theta, self.xi, self.rho]\n",
    "        bounds = [(0.01, 1.0), (0.01, 5.0), (0.01, 1.0), (0.01, 1.0), (-1.0, 1.0)]\n",
    "        result = minimize(objective_function, initial_guess, bounds=bounds)\n",
    "        self.v0, self.kappa, self.theta, self.xi, self.rho = result.x\n",
    "\n",
    "\n",
    "class KnockoutOption:\n",
    "    def __init__(self, model, S0, K, T, r, barrier):\n",
    "        self.model = model\n",
    "        self.S0 = S0\n",
    "        self.K = K\n",
    "        self.T = T\n",
    "        self.r = r\n",
    "        self.barrier = barrier\n",
    "\n",
    "    def price_knockout_option(self, N, M):\n",
    "        dt = self.T / M\n",
    "        price_paths = np.zeros((N, M + 1))\n",
    "        vol_paths = np.zeros((N, M + 1)) if isinstance(self.model, StochasticVolatilityModel) else None\n",
    "        price_paths[:, 0] = self.S0\n",
    "        if vol_paths is not None:\n",
    "            vol_paths[:, 0] = self.model.v0\n",
    "        \n",
    "        for t in range(1, M + 1):\n",
    "            Z1 = np.random.standard_normal(N)\n",
    "            if vol_paths is None:\n",
    "                # Black-Scholes Model\n",
    "                price_paths[:, t] = price_paths[:, t - 1] * np.exp(\n",
    "                    (self.r - 0.5 * self.model.sigma**2) * dt + self.model.sigma * np.sqrt(dt) * Z1\n",
    "                )\n",
    "            else:\n",
    "                # Stochastic Volatility Model\n",
    "                Z2 = np.random.standard_normal(N)\n",
    "                W1 = Z1\n",
    "                W2 = self.model.rho * Z1 + np.sqrt(1 - self.model.rho**2) * Z2\n",
    "                vol_paths[:, t] = np.abs(vol_paths[:, t - 1] + self.model.kappa * (self.model.theta - vol_paths[:, t - 1]) * dt + self.model.xi * np.sqrt(vol_paths[:, t - 1] * dt) * W1)\n",
    "                price_paths[:, t] = price_paths[:, t - 1] * np.exp(\n",
    "                    (self.r - 0.5 * vol_paths[:, t - 1]) * dt + np.sqrt(vol_paths[:, t - 1] * dt) * W2\n",
    "                )\n",
    "            \n",
    "            # Knockout condition\n",
    "            price_paths[:, t][price_paths[:, t] >= self.barrier] = 0\n",
    "        payoffs = np.maximum(price_paths[:, -1] - self.K, 0)\n",
    "        return np.exp(-self.r * self.T) * np.mean(payoffs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20f01365",
   "metadata": {},
   "source": [
    "<a id='toc6_'></a>\n",
    "\n",
    "## Data Preparation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e0c78b4",
   "metadata": {},
   "source": [
    "<a id='toc6_1'></a>\n",
    "### Synthetic data generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "42cb9070",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_synthetic_market_data(model, strikes, maturities):\n",
    "    market_prices = []\n",
    "    market_data = []\n",
    "    for K, T in zip(strikes, maturities):\n",
    "        model.K = K\n",
    "        model.T = T\n",
    "        market_prices.append(model.price_option(10000, 100))\n",
    "        market_data.append({\"strike\": K, \"option_price\": model.price_option(10000, 100)})\n",
    "    return market_prices, market_data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "c81282bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 10000\n",
    "M = 100\n",
    "\n",
    "# Parameters for synthetic data\n",
    "S0 = 100\n",
    "K = 100\n",
    "T = 1\n",
    "r = 0.05\n",
    "# BlackSholes\n",
    "true_sigma = 0.2\n",
    "\n",
    "# Stochastic Volatility\n",
    "true_v0 = 0.2\n",
    "true_kappa = 2.0\n",
    "true_theta = 0.2\n",
    "true_xi = 0.1\n",
    "true_rho = -0.5\n",
    "\n",
    "# Synthetic data generation parameters\n",
    "strikes = list(np.linspace(75, 130, 25))\n",
    "maturities = list(np.linspace(0.2, 3.0, 25))\n",
    "\n",
    "# Generate synthetic market data using the true parameters\n",
    "bs_model = BlackScholesModel(S0, K, T, r, true_sigma)\n",
    "bs_market_prices, bs_market_data = generate_synthetic_market_data(bs_model, strikes, maturities)\n",
    "\n",
    "\n",
    "sv_model = StochasticVolatilityModel(S0, K, T, r, true_v0, true_kappa, true_theta, true_xi, true_rho)\n",
    "sv_market_prices, sv_market_data = generate_synthetic_market_data(sv_model, strikes, maturities)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ee57be7",
   "metadata": {},
   "source": [
    "### Initialize the ValidMind datasets\n",
    "\n",
    "Before you can run tests, you must first initialize a ValidMind dataset object using the [`init_dataset`](https://docs.validmind.ai/validmind/validmind.html#init_dataset) function from the ValidMind (`vm`) module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "78cf5317",
   "metadata": {},
   "outputs": [],
   "source": [
    "bs_market_data_df = pd.DataFrame(bs_market_data)\n",
    "vm_bs_market_data = vm.init_dataset(\n",
    "    dataset=bs_market_data_df,\n",
    "    input_id=\"sv_market_data\",\n",
    ")\n",
    "\n",
    "sv_market_data_df = pd.DataFrame(sv_market_data)\n",
    "vm_sv_market_data = vm.init_dataset(\n",
    "    dataset=sv_market_data_df,\n",
    "    input_id=\"sv_market_data\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2079eda",
   "metadata": {},
   "source": [
    "### Data Quality\n",
    "Let's check quality of the data using outliers and missing data tests."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f52ac93",
   "metadata": {},
   "source": [
    "#### Outliers detection using IQR method\n",
    "Let's visualizes the distribution of outliers in the option_price feature using the Interquartile Range (IQR) method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1c1ab6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.IQROutliersBarPlot:BlackScholes\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_bs_market_data,\n",
    "    },\n",
    "    title=\"Outliers detection using IQR method for BlackScholes\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b5e8654",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.IQROutliersTable:BlackScholes\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_bs_market_data,\n",
    "    },\n",
    "    title=\"Outliers table using IQR method for BlackScholes\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d96f10c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.IQROutliersBarPlot:StochasticVolatility\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_sv_market_data,\n",
    "    },\n",
    "    title=\"Outliers detection using IQR method for StochasticVolatility\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5b821d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.IQROutliersTable:StochasticVolatility\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_sv_market_data,\n",
    "    },\n",
    "    title=\"Outliers table using IQR method for StochasticVolatility\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8dfc7cc3",
   "metadata": {},
   "source": [
    "#### Isolation Forest Outliers Test\n",
    "Let's detects anomalies in the dataset using the Isolation Forest algorithm, visualized through scatter plots."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9eb91453",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.IsolationForestOutliers:BlackScholes\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_bs_market_data,\n",
    "    },\n",
    "    title=\"Outliers detection using Isolation Forest for BlackScholes\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62c5dfad",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.IsolationForestOutliers:StochasticVolatility\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_sv_market_data,\n",
    "    },\n",
    "    title=\"Outliers detection using Isolation Forest for StochasticVolatility\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "048caf26",
   "metadata": {},
   "source": [
    "##### Missing Values Test\n",
    "Let's evaluates dataset quality by ensuring the missing value ratio across all features does not exceed a set threshold."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "805ddb1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"validmind.data_validation.MissingValues:BlackScholes\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_bs_market_data,\n",
    "    },\n",
    "    title=\"Missing Values detection for BlackScholes\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "950e5b39",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "result = run_test(\n",
    "    \"validmind.data_validation.MissingValues:StochasticVolatility\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_sv_market_data,\n",
    "    },\n",
    "    title=\"MissingValues detection for StochasticVolatility\",\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcb640a3",
   "metadata": {},
   "source": [
    "<a id='toc6_2'></a>\n",
    "### Model Calibration\n",
    "* Clearly state the purpose of the calibration process. For example, in the context of an option pricing model, calibration aims to adjust model parameters to fit market data (e.g., market option prices, volatility surfaces).\n",
    "* Specify whether the calibration is to historical data, current market data, or a blend of both."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "5e709e0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "@vm.test(\"my_custom_tests.SyntheticDataCalibrationTest\")\n",
    "def generate_synthetic_data_summary(option_pricing_model, strikes, maturities, synthetic_prices):\n",
    "    \"\"\"\n",
    "    This function will use synthetic prices to calibrate each model\n",
    "    and then generate derived prices based on the calibrated parameters.\n",
    "    It will output a DataFrame summarizing the strikes, maturities,\n",
    "    synthetic and derived prices, and the model parameters.\n",
    "\n",
    "    \"\"\"\n",
    "    derived_prices = []\n",
    "    for K, T in zip(strikes, maturities):\n",
    "        option_pricing_model.K = K\n",
    "        option_pricing_model.T = T\n",
    "        derived_prices.append(option_pricing_model.price_option(10000, 100))\n",
    "    \n",
    "    model_type = type(option_pricing_model).__name__\n",
    "    data = {\n",
    "        \"Strike\": strikes,\n",
    "        \"Maturity\": maturities,\n",
    "        \"Synthetic_Price\": synthetic_prices,\n",
    "        \"Derived_Price\": derived_prices,\n",
    "        \"Model_Type\": model_type,\n",
    "        \"S0\": [option_pricing_model.S0] * len(strikes),\n",
    "        \"K\": [option_pricing_model.K] * len(strikes),\n",
    "        \"T\": [option_pricing_model.T] * len(strikes),\n",
    "        \"r\": [option_pricing_model.r] * len(strikes)\n",
    "    }\n",
    "    \n",
    "    if model_type == \"BlackScholesModel\":\n",
    "        data[\"sigma\"] = [option_pricing_model.sigma] * len(strikes)\n",
    "    elif model_type == \"StochasticVolatilityModel\":\n",
    "        data[\"v0\"] = [option_pricing_model.v0] * len(strikes)\n",
    "        data[\"kappa\"] = [option_pricing_model.kappa] * len(strikes)\n",
    "        data[\"theta\"] = [option_pricing_model.theta] * len(strikes)\n",
    "        data[\"xi\"] = [option_pricing_model.xi] * len(strikes)\n",
    "        data[\"rho\"] = [option_pricing_model.rho] * len(strikes)\n",
    "    \n",
    "    df = pd.DataFrame(data)\n",
    "    return df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "883f1d52",
   "metadata": {},
   "source": [
    "### Synthetic Data Calibration Test\n",
    "Let's evaluates the accuracy of a stochastic volatility model by comparing synthetic prices with derived prices after model calibration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8309610e",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.SyntheticDataCalibrationTest\",\n",
    "    params={\n",
    "        \"option_pricing_model\": sv_model,\n",
    "        \"strikes\": strikes,\n",
    "        \"maturities\": maturities,\n",
    "        \"synthetic_prices\": sv_market_prices\n",
    "    },\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3066572",
   "metadata": {},
   "source": [
    "<a id='toc7_'></a>\n",
    "### Model Evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfbc333b",
   "metadata": {},
   "source": [
    "<a id='toc7_1'></a>\n",
    "#### Benchmark Testing\n",
    "* Compare the model’s performance with alternative models or industry-standard models to assess its relative effectiveness.\n",
    "* Ensure that the model is competitive in pricing, accuracy, and computational efficiency.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "ac733262",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.BenchmarkTest\")\n",
    "def benchmark_test(bs_model, sv_model, strikes, maturities):\n",
    "    \"\"\"\n",
    "    Comparison between Black Scholes and stochastic volatility model\n",
    "\n",
    "    \"\"\"\n",
    "    bs_model_type = type(bs_model).__name__\n",
    "    sv_model_type = type(sv_model).__name__\n",
    "\n",
    "    bs_derived_prices = []\n",
    "    sv_derived_prices = []\n",
    "    for K in strikes:\n",
    "        bs_model.K = K\n",
    "        bs_derived_prices.append(bs_model.price_option(10000, 100))\n",
    "        sv_model.K = K\n",
    "        sv_derived_prices.append(sv_model.price_option(10000, 100))\n",
    "\n",
    "    data = {\n",
    "        \"Strike\": strikes,\n",
    "        \"Maturities\": [sv_model.T] * len(strikes),\n",
    "        \"bs_model_price\": bs_derived_prices,\n",
    "        \"sv_model_price\": sv_derived_prices,\n",
    "\n",
    "    }\n",
    "    df1 = pd.DataFrame(data)\n",
    "\n",
    "    bs_derived_prices = []\n",
    "    sv_derived_prices = []\n",
    "    for T in maturities:\n",
    "        bs_model.T = T\n",
    "        bs_derived_prices.append(bs_model.price_option(10000, 100))\n",
    "        sv_model.T = T\n",
    "        sv_derived_prices.append(sv_model.price_option(10000, 100))\n",
    "\n",
    "    data = {\n",
    "        \"Strike\": [sv_model.K] * len(maturities),\n",
    "        \"Maturities\": maturities,\n",
    "        \"bs_model_price\": bs_derived_prices,\n",
    "        \"sv_model_price\": sv_derived_prices,\n",
    "    }\n",
    "\n",
    "    df2 = pd.DataFrame(data)\n",
    "\n",
    "    return {\"strikes variation benchmarking\": df1}, {\"maturities variation benchmarking\": df2}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46d16590",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.BenchmarkTest\",\n",
    "    params={\n",
    "        \"sv_model\": sv_model,\n",
    "        \"bs_model\": bs_model,\n",
    "        \"strikes\": strikes,\n",
    "        \"maturities\": maturities,\n",
    "    },\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65fa5b9c",
   "metadata": {},
   "source": [
    "##### Surface Volatility Test\n",
    "Let's calculates the implied volatility across different strikes and maturities based on market prices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "46e275e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.optimize import minimize\n",
    "import plotly.graph_objects as go\n",
    "\n",
    "@vm.test(\"my_custom_tests.ImpliedVolSurface\")\n",
    "def implied_vol_surface(market_prices, strikes, maturities, S0, r, barrier, N=10000, M=100):\n",
    "    \"\"\"\n",
    "    This is a test to compute the implied volatility surface for a given set of market prices,\n",
    "    strikes, and maturities.\n",
    "    \"\"\"\n",
    "    def implied_volatility(market_price, N, M, initial_guess=0.2):\n",
    "        def objective_function(sigma):\n",
    "            model.sigma = sigma\n",
    "            model_price = model.price_option(N, M)\n",
    "            return (model_price - market_price) ** 2\n",
    "\n",
    "        result = minimize(objective_function, initial_guess, bounds=[(0.01, 1.0)])\n",
    "        return result.x[0]\n",
    "    \n",
    "    implied_vols = np.zeros((len(strikes), len(maturities)))\n",
    "\n",
    "    for i, K in enumerate(strikes):\n",
    "        for j, T in enumerate(maturities):\n",
    "            market_price = market_prices[i]\n",
    "            model = BlackScholesModel(S0, K, T, r, sigma=0.2)\n",
    "\n",
    "            implied_vol = implied_volatility(market_price, N, M)\n",
    "            implied_vols[i, j] = implied_vol\n",
    "\n",
    "    # Create the 3D surface plot\n",
    "    X, Y = np.meshgrid(strikes, maturities)\n",
    "    Z = implied_vols.T  # Transpose to match the meshgrid orientation\n",
    "\n",
    "    fig = go.Figure(data=[go.Surface(x=X, y=Y, z=Z)])\n",
    "    \n",
    "    # Update the layout\n",
    "    fig.update_layout(\n",
    "        title=f'3D Surface Plot of Implied Volatility',\n",
    "        scene=dict(\n",
    "            xaxis_title='Strike',\n",
    "            yaxis_title='Maturity',\n",
    "            zaxis_title='Implied Volatility',\n",
    "            camera=dict(\n",
    "                up=dict(x=0, y=0, z=1),\n",
    "                center=dict(x=0, y=0, z=0),\n",
    "                eye=dict(x=1.5, y=1.5, z=1.5)\n",
    "            )\n",
    "        ),\n",
    "        width=900,\n",
    "        height=700,\n",
    "        margin=dict(l=65, r=50, b=65, t=90)\n",
    "    )\n",
    "\n",
    "    return fig"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82c76218",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.ImpliedVolSurface\",\n",
    "    params={\n",
    "        \"market_prices\": sv_market_prices,\n",
    "        \"strikes\": strikes,\n",
    "        \"maturities\": maturities,\n",
    "        \"S0\": S0,\n",
    "        \"r\": r,\n",
    "        \"barrier\": 120\n",
    "    }\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "127fa1b6",
   "metadata": {},
   "source": [
    "<a id='toc7_2'></a>\n",
    "#### Sensitivity Testing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "80492c82",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "@vm.test(\"my_custom_tests.Sensitivity\")\n",
    "def sensitivity_test(model_type, S0, T, r, N, M, strike=None, barrier=None, sigma=None, v0=None, kappa=None,theta=None, xi=None, rho=None):\n",
    "    \"\"\"\n",
    "    This is sensitivity test\n",
    "\"\"\"\n",
    "    if model_type == 'BS':\n",
    "        model = BlackScholesModel(S0, strike, T, r, sigma)\n",
    "    else:\n",
    "        model = StochasticVolatilityModel(S0, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "    \n",
    "    knockout_option = KnockoutOption(model, S0, strike, T, r, barrier)\n",
    "    price = knockout_option.price_knockout_option(N, M)\n",
    "\n",
    "    return pd.DataFrame({\"Option price\": [price]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9b9fbd9",
   "metadata": {},
   "source": [
    "##### Initialise parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "b2115371",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "strike_range = (min(strikes), max(strikes))\n",
    "barrier_range = (100, 120)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a798ff8",
   "metadata": {},
   "source": [
    "##### Common plot function\n",
    "Let's create a line plot using the default result output data and log it by passing the function through the `post_process_fn` parameter in the `run_test()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "d96969b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from plotly_express import bar\n",
    "from validmind.vm_models.figure import Figure\n",
    "from validmind.vm_models.result import TestResult\n",
    "import plotly.graph_objects as go\n",
    "import random\n",
    "\n",
    "def process_results(result: TestResult):\n",
    "\n",
    "    # Convert to DataFrame\n",
    "    df = pd.DataFrame(result.tables[0].data)\n",
    "    \n",
    "    # Get the first two column names\n",
    "    x_col = df.columns[0]\n",
    "    y_col = df.columns[1]\n",
    "    \n",
    "    # Create figure\n",
    "    fig = go.Figure()\n",
    "    fig.add_trace(\n",
    "        go.Scatter(\n",
    "            x=df[x_col],\n",
    "            y=df[y_col],\n",
    "            mode='lines',\n",
    "            name=y_col  # Use y-axis column name as trace name\n",
    "        )\n",
    "    )\n",
    "    \n",
    "    fig.update_layout(\n",
    "        xaxis_title=x_col,\n",
    "        yaxis_title=y_col,\n",
    "        showlegend=True,\n",
    "        template=\"plotly_white\"\n",
    "    )\n",
    "\n",
    "    result.add_figure(\n",
    "        Figure(\n",
    "            figure=fig,\n",
    "            key=\"sensitivity_plot_\" + str(random.randint(0, 1000000)),\n",
    "            ref_id=result.ref_id,\n",
    "        )\n",
    "    )\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43893a9a",
   "metadata": {},
   "source": [
    "##### Strike sensitivity Test\n",
    "Let's evaluates the sensitivity of a model's output value to changes in the strike price, while keeping other parameters constant.\n",
    "This test is crucial for understanding how variations in strike prices affect the valuation of financial derivatives, particularly options."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb8f1cab",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Sensitivity:S0\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\":[strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": list(np.linspace(S0-20, S0+20, 20)),\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "    },\n",
    "    post_process_fn= process_results\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "199af470",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Sensitivity:ToStrike\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": list(np.linspace(strike_range[0], strike_range[1], 20)),\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "    },\n",
    "    post_process_fn= process_results\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe2c8f65",
   "metadata": {},
   "source": [
    "##### Barrier Sensitivity Test\n",
    "Let's evaluates the sensitivity of a model's output to changes in the barrier level of a financial derivative, specifically a barrier option. This test is crucial for understanding how small changes in the barrier can impact the option's valuation, which is essential for risk management and pricing strategies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f2eab7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Sensitivity:ToBarrier\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": list(np.linspace(barrier_range[0], barrier_range[1], 20)),\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "    },\n",
    "    post_process_fn=process_results\n",
    "\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35d6d3cc",
   "metadata": {},
   "source": [
    "<a id='toc7_3'></a>\n",
    "#### Greeks \n",
    "These Greeks are crucial for traders and risk managers as they provide insights into the risk and potential price movements of options and derivatives, allowing for more informed decision-making and risk management strategies."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07cd8d2d",
   "metadata": {},
   "source": [
    "### Delta\n",
    "Let's measures the sensitivity of the option's price to a change in the price of the underlying asset. It indicates how much the price of an option is expected to move per $1 change in the underlying asset's price."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "31befc58",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.GreeksDelta\")\n",
    "def calculate_delta(model_type, S0, T, r, N, M, strike=None, barrier=None, \n",
    "                   sigma=None, v0=None, kappa=None, theta=None, xi=None, rho=None, \n",
    "                   h=0.001):  # h is the step size for finite difference\n",
    "    \"\"\"\n",
    "    Calculate delta using finite difference method.\n",
    "    Delta = (V(S0 + h) - V(S0 - h)) / (2h)\n",
    "    where V is the option price and h is a small increment\n",
    "    \"\"\"\n",
    "    # Initialize the model with S0 + h\n",
    "    if model_type == 'BS':\n",
    "        model_up = BlackScholesModel(S0 + h, strike, T, r, sigma)\n",
    "        model_down = BlackScholesModel(S0 - h, strike, T, r, sigma)\n",
    "    else:\n",
    "        model_up = StochasticVolatilityModel(S0 + h, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "        model_down = StochasticVolatilityModel(S0 - h, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "    \n",
    "\n",
    "    # Calculate option prices for up and down moves\n",
    "    knockout_up = KnockoutOption(model_up, S0 + h, strike, T, r, barrier)\n",
    "    knockout_down = KnockoutOption(model_down, S0 - h, strike, T, r, barrier)\n",
    "    \n",
    "    price_up = knockout_up.price_knockout_option(N, M)\n",
    "    price_down = knockout_down.price_knockout_option(N, M)\n",
    "    \n",
    "    # Calculate delta using central difference\n",
    "    delta = (price_up - price_down) / (2 * h)\n",
    "    df = pd.DataFrame({\"Delta\": [delta], \"Price_Up\": [price_up], \"Price_Down\": [price_down], \"h\": [h]})\n",
    "    return df\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4305e12",
   "metadata": {},
   "outputs": [],
   "source": [
    "# To analyze delta sensitivity to underlying price changes\n",
    "result = run_test(\n",
    "    \"my_custom_tests.GreeksDelta\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [1000000],\n",
    "        \"M\": [M],\n",
    "        \"strike\":[strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": list(np.linspace(S0-20, S0+20, 20)),\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "        \"h\": [0.001]\n",
    "    },\n",
    "post_process_fn=process_results  # Using the plotting function defined earlier\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27beb54f",
   "metadata": {},
   "source": [
    "### Gamma\n",
    "Let's measures the rate of change of Delta with respect to changes in the underlying asset's price. It indicates the curvature of the option's price relative to the underlying asset's price."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1878011",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.GreeksGamma\")\n",
    "def calculate_gamma(model_type, S0, T, r, N, M, strike=None, barrier=None, \n",
    "                   sigma=None, v0=None, kappa=None, theta=None, xi=None, rho=None, \n",
    "                   h=0.01):  # h is the step size for finite difference\n",
    "    \"\"\"\n",
    "    Calculate gamma using finite difference method.\n",
    "    Gamma = (V(S0 + h) - 2V(S0) + V(S0 - h)) / h^2\n",
    "    where V is the option price and h is a small increment\n",
    "    \"\"\"\n",
    "    # Initialize the models with S0 + h, S0, and S0 - h\n",
    "    if model_type == 'BS':\n",
    "        model_up = BlackScholesModel(S0 + h, strike, T, r, sigma)\n",
    "        model_center = BlackScholesModel(S0, strike, T, r, sigma)\n",
    "        model_down = BlackScholesModel(S0 - h, strike, T, r, sigma)\n",
    "    else:\n",
    "        model_up = StochasticVolatilityModel(S0 + h, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "        model_center = StochasticVolatilityModel(S0, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "        model_down = StochasticVolatilityModel(S0 - h, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "    \n",
    "    # Calculate option prices for up, center, and down moves\n",
    "    knockout_up = KnockoutOption(model_up, S0 + h, strike, T, r, barrier)\n",
    "    knockout_center = KnockoutOption(model_center, S0, strike, T, r, barrier)\n",
    "    knockout_down = KnockoutOption(model_down, S0 - h, strike, T, r, barrier)\n",
    "    \n",
    "    price_up = knockout_up.price_knockout_option(N, M)\n",
    "    price_center = knockout_center.price_knockout_option(N, M)\n",
    "    price_down = knockout_down.price_knockout_option(N, M)\n",
    "    \n",
    "    # Calculate gamma using second-order central difference\n",
    "    gamma = (price_up - 2*price_center + price_down) / (h * h)\n",
    "    \n",
    "    df = pd.DataFrame({\n",
    "        \"Gamma\": [gamma], \n",
    "        \"Price_Up\": [price_up], \n",
    "        \"Price_Center\": [price_center],\n",
    "        \"Price_Down\": [price_down], \n",
    "        \"h\": [h]\n",
    "    })\n",
    "    return df\n",
    "\n",
    "# To analyze gamma sensitivity to underlying price changes\n",
    "result = run_test(\n",
    "    \"my_custom_tests.GreeksGamma\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [1000000],\n",
    "        \"M\": [M],\n",
    "        \"strike\":[strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": list(np.linspace(S0-20, S0+20, 20)),\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "        \"h\": [0.1]\n",
    "    },\n",
    "    post_process_fn=process_results  # Using the plotting function defined earlier\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58ee0864",
   "metadata": {},
   "source": [
    "### Theta\n",
    "Let's measures the sensitivity of the option's price to the passage of time, also known as time decay. It indicates how much the price of an option is expected to decrease as the option approaches its expiration date."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20fa7300",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.GreeksTheta\")\n",
    "def calculate_theta(model_type, S0, T, r, N, M, strike=None, barrier=None, \n",
    "                   sigma=None, v0=None, kappa=None, theta=None, xi=None, rho=None, \n",
    "                   dt=1/365):  # dt is typically one day\n",
    "    \"\"\"\n",
    "    Calculate theta using finite difference method.\n",
    "    Theta = (V(t + dt) - V(t)) / dt\n",
    "    where V is the option price and dt is a small time increment (typically 1 day)\n",
    "    \"\"\"\n",
    "    # Initialize the models with T and T + dt\n",
    "    if model_type == 'BS':\n",
    "        model_current = BlackScholesModel(S0, strike, T, r, sigma)\n",
    "        model_future = BlackScholesModel(S0, strike, T + dt, r, sigma)\n",
    "    else:\n",
    "        model_current = StochasticVolatilityModel(S0, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "        model_future = StochasticVolatilityModel(S0, strike, T + dt, r, v0, kappa, theta, xi, rho)\n",
    "    \n",
    "    # Calculate option prices for current and future time\n",
    "    knockout_current = KnockoutOption(model_current, S0, strike, T, r, barrier)\n",
    "    knockout_future = KnockoutOption(model_future, S0, strike, T + dt, r, barrier)\n",
    "    \n",
    "    price_current = knockout_current.price_knockout_option(N, M)\n",
    "    price_future = knockout_future.price_knockout_option(N, M)\n",
    "    \n",
    "    # Calculate theta using forward difference\n",
    "    # Note: We divide by dt and multiply by -1 since theta represents the negative rate of change\n",
    "    theta_value = -1 * (price_future - price_current) / dt\n",
    "    \n",
    "    df = pd.DataFrame({\n",
    "        \"Theta\": [theta_value], \n",
    "        \"Price_Current\": [price_current],\n",
    "        \"Price_Future\": [price_future],\n",
    "        \"dt\": [dt]\n",
    "    })\n",
    "    return df\n",
    "\n",
    "# Example usage to analyze theta sensitivity across different underlying prices\n",
    "result = run_test(\n",
    "    \"my_custom_tests.GreeksTheta\",\n",
    "    param_grid={\n",
    "               \"model_type\": ['SV'],\n",
    "        \"N\": [1000000],\n",
    "        \"M\": [M],\n",
    "        \"strike\":[strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": list(np.linspace(S0-20, S0+20, 20)),\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "        \"dt\": [1/365]  # One day time step\n",
    "    },\n",
    "    post_process_fn=process_results  # Using the plotting function defined earlier\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4b3386e",
   "metadata": {},
   "source": [
    "### Vega\n",
    "Let's measures the sensitivity of the option's price to changes in the volatility of the underlying asset. It indicates how much the price of an option is expected to change with a 1% change in the underlying asset's volatility."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ffb40f67",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.GreeksVega\")\n",
    "def calculate_vega(model_type, S0, T, r, N, M, strike=None, barrier=None, \n",
    "                  sigma=None, v0=None, kappa=None, theta=None, xi=None, rho=None, \n",
    "                  h=0.001):  # h is the step size for finite difference\n",
    "    \"\"\"\n",
    "    Calculate vega using finite difference method.\n",
    "    For Black-Scholes: Vega = (V(σ + h) - V(σ - h)) / (2h)\n",
    "    For Stochastic Vol: Vega = (V(v0 + h) - V(v0 - h)) / (2h)\n",
    "    where V is the option price and h is a small increment in volatility\n",
    "    \"\"\"\n",
    "    if model_type == 'BS':\n",
    "        # For Black-Scholes, perturb sigma\n",
    "        model_up = BlackScholesModel(S0, strike, T, r, sigma + h)\n",
    "        model_down = BlackScholesModel(S0, strike, T, r, sigma - h)\n",
    "    else:\n",
    "        # For Stochastic Volatility, perturb v0\n",
    "        model_up = StochasticVolatilityModel(S0, strike, T, r, v0 + h, kappa, theta, xi, rho)\n",
    "        model_down = StochasticVolatilityModel(S0, strike, T, r, v0 - h, kappa, theta, xi, rho)\n",
    "    \n",
    "    # Calculate option prices for up and down moves in volatility\n",
    "    knockout_up = KnockoutOption(model_up, S0, strike, T, r, barrier)\n",
    "    knockout_down = KnockoutOption(model_down, S0, strike, T, r, barrier)\n",
    "    \n",
    "    price_up = knockout_up.price_knockout_option(N, M)\n",
    "    price_down = knockout_down.price_knockout_option(N, M)\n",
    "    \n",
    "    # Calculate vega using central difference\n",
    "    vega = (price_up - price_down) / (2 * h)\n",
    "    \n",
    "    df = pd.DataFrame({\n",
    "        \"Vega\": [vega], \n",
    "        \"Price_Up\": [price_up], \n",
    "        \"Price_Down\": [price_down], \n",
    "        \"h\": [h]\n",
    "    })\n",
    "    return df\n",
    "\n",
    "# Example usage to analyze vega sensitivity across different underlying prices\n",
    "result = run_test(\n",
    "    \"my_custom_tests.GreeksVega\",\n",
    "    param_grid={\n",
    "                \"model_type\": ['SV'],\n",
    "        \"N\": [1000000],\n",
    "        \"M\": [M],\n",
    "        \"strike\":[strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": list(np.linspace(S0-20, S0+20, 20)),\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "        \"h\": [0.0001]  # Small step size for better accuracy\n",
    "    },\n",
    "    post_process_fn=process_results  # Using the plotting function defined earlier\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f917f36f",
   "metadata": {},
   "source": [
    "### Rho\n",
    "Let's measures the sensitivity of the option's price to changes in the interest rate. It indicates how much the price of an option is expected to change with a 1% change in interest rates.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "618efa93",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.GreeksRho\")\n",
    "def calculate_rho(model_type, S0, T, r, N, M, strike=None, barrier=None, \n",
    "                 sigma=None, v0=None, kappa=None, theta=None, xi=None, rho=None, \n",
    "                 h=0.0001):  # h is the step size for finite difference\n",
    "    \"\"\"\n",
    "    Calculate rho using finite difference method.\n",
    "    Rho = (V(r + h) - V(r - h)) / (2h)\n",
    "    where V is the option price and h is a small increment in interest rate\n",
    "    \"\"\"\n",
    "    # Initialize the models with r + h and r - h\n",
    "    if model_type == 'BS':\n",
    "        model_up = BlackScholesModel(S0, strike, T, r + h, sigma)\n",
    "        model_down = BlackScholesModel(S0, strike, T, r - h, sigma)\n",
    "    else:\n",
    "        model_up = StochasticVolatilityModel(S0, strike, T, r + h, v0, kappa, theta, xi, rho)\n",
    "        model_down = StochasticVolatilityModel(S0, strike, T, r - h, v0, kappa, theta, xi, rho)\n",
    "    \n",
    "    # Calculate option prices for up and down moves in interest rate\n",
    "    knockout_up = KnockoutOption(model_up, S0, strike, T, r + h, barrier)\n",
    "    knockout_down = KnockoutOption(model_down, S0, strike, T, r - h, barrier)\n",
    "    \n",
    "    price_up = knockout_up.price_knockout_option(N, M)\n",
    "    price_down = knockout_down.price_knockout_option(N, M)\n",
    "    \n",
    "    # Calculate rho using central difference\n",
    "    rho_value = (price_up - price_down) / (2 * h)\n",
    "    \n",
    "    df = pd.DataFrame({\n",
    "        \"Rho\": [rho_value], \n",
    "        \"Price_Up\": [price_up], \n",
    "        \"Price_Down\": [price_down], \n",
    "        \"h\": [h]\n",
    "    })\n",
    "    return df\n",
    "\n",
    "# Example usage to analyze rho sensitivity across different underlying prices\n",
    "result = run_test(\n",
    "    \"my_custom_tests.GreeksRho\",\n",
    "    param_grid={\n",
    "               \"model_type\": ['SV'],\n",
    "        \"N\": [1000000],\n",
    "        \"M\": [M],\n",
    "        \"strike\":[strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": list(np.linspace(S0-20, S0+20, 20)),\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "        \"h\": [0.0001]  # Small step size for better accuracy\n",
    "    },\n",
    "    post_process_fn=process_results  # Using the plotting function defined earlier\n",
    ")\n",
    "result.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14fd2cd8",
   "metadata": {},
   "source": [
    "<a id='toc7_4'></a>\n",
    "#### Stress Testing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "7bdd02ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "@vm.test(\"my_custom_tests.Stressing\")\n",
    "def sensitivity_test(model_type, S0, T, r, N, M, strike=None, barrier=None, sigma=None, v0=None, kappa=None,theta=None, xi=None, rho=None):\n",
    "    \"\"\"\n",
    "    This is stress test\n",
    "    \"\"\"\n",
    "    if model_type == 'BS':\n",
    "        model = BlackScholesModel(S0, strike, T, r, sigma)\n",
    "    else:\n",
    "        model = StochasticVolatilityModel(S0, strike, T, r, v0, kappa, theta, xi, rho)\n",
    "    \n",
    "    knockout_option = KnockoutOption(model, S0, strike, T, r, barrier)\n",
    "    price = knockout_option.price_knockout_option(N, M)\n",
    "\n",
    "    return pd.DataFrame({\"Option price\": [price]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ac570d5",
   "metadata": {},
   "source": [
    "##### Rho (correlation) and Theta (long term vol) stress test\n",
    "First, we create a surface plot to visualize the option price with respect to two variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "77d49b6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def two_parameters_stress_surface_plot(result: TestResult):\n",
    "    import plotly.graph_objects as go\n",
    "    import numpy as np\n",
    "    import pandas as pd\n",
    "    # Convert to DataFrame\n",
    "    data = pd.DataFrame(result.tables[0].data)\n",
    "    \n",
    "    # Get column names (assuming first column is x, next two are y1 and y2)\n",
    "    z_col = data.columns[2]\n",
    "    x_col = data.columns[0]\n",
    "    y_col = data.columns[1]\n",
    "    \n",
    "    # Get unique values for x and y\n",
    "    x_unique = np.sort(data[x_col].unique())\n",
    "    y_unique = np.sort(data[y_col].unique())\n",
    "    \n",
    "    # Create meshgrid\n",
    "    X, Y = np.meshgrid(x_unique, y_unique)\n",
    "    \n",
    "    # Create Z matrix\n",
    "    Z = np.zeros_like(X)\n",
    "    for i, x_val in enumerate(x_unique):\n",
    "        for j, y_val in enumerate(y_unique):\n",
    "            mask = (data[x_col] == x_val) & (data[y_col] == y_val)\n",
    "            if mask.any():\n",
    "                Z[j, i] = data.loc[mask, z_col].iloc[0]\n",
    "    \n",
    "    # Create the 3D surface plot\n",
    "    fig = go.Figure(data=[go.Surface(x=X, y=Y, z=Z)])\n",
    "    \n",
    "    # Update the layout\n",
    "    fig.update_layout(\n",
    "        title=f'3D Surface Plot of {z_col}',\n",
    "        scene=dict(\n",
    "            xaxis_title=x_col,\n",
    "            yaxis_title=y_col,\n",
    "            zaxis_title=z_col,\n",
    "            camera=dict(\n",
    "                up=dict(x=0, y=0, z=1),\n",
    "                center=dict(x=0, y=0, z=0),\n",
    "                eye=dict(x=1.5, y=1.5, z=1.5)\n",
    "            )\n",
    "        ),\n",
    "        width=900,\n",
    "        height=700,\n",
    "        margin=dict(l=65, r=50, b=65, t=90)\n",
    "    )\n",
    "\n",
    "    result.add_figure(\n",
    "        Figure(\n",
    "            figure=fig,\n",
    "            key=\"sensitivity_plot_\" + str(random.randint(0, 1000000)),\n",
    "            ref_id=result.ref_id,\n",
    "        )\n",
    "    )\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b586190",
   "metadata": {},
   "source": [
    "Let's evaluates the sensitivity of a model's output to changes in the correlation parameter (rho) and the long-term variance parameter (theta) within a stochastic volatility framework.\n",
    "\n",
    "This test is useful for understanding how variations in these parameters affect the model's valuation, which is crucial for risk management and model validation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76a28f69",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheRhoAndThetaParameters\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": list(np.linspace(0,0.8, 10)),\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": list(np.linspace(-1,0.8, 10)),\n",
    "    },\n",
    "    post_process_fn=two_parameters_stress_surface_plot\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea1ab6a4",
   "metadata": {},
   "source": [
    "##### Rho (correlation) and Xi (vol of vol) stress test\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7fec6665",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheRhoAndXiParameters\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": list(np.linspace(0,0.8, 10)),\n",
    "        \"rho\": list(np.linspace(-1,0.8, 10)),\n",
    "    },\n",
    "    post_process_fn=two_parameters_stress_surface_plot\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "346377c5",
   "metadata": {},
   "source": [
    "##### Sigma stress test\n",
    "evaluates the sensitivity of a model's output to changes in the volatility parameter, sigma. This test is crucial for understanding how variations in market volatility impact the model's valuation of financial instruments, particularly options.\n",
    "\n",
    "This test is useful for risk management and model validation, as it helps identify the robustness of the model under different market conditions. By analyzing the changes in the model's output as sigma varies, stakeholders can assess the model's stability and reliability."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4990537",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheSigmaParameter\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['BS'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"sigma\": list(np.linspace(0.2, 0.8, 10)),\n",
    "    },\n",
    "    post_process_fn=process_results\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e36aebf",
   "metadata": {},
   "source": [
    "\n",
    "##### Stress kappa \n",
    "Let's evaluates the sensitivity of a model's output to changes in the kappa parameter, which is a mean reversion rate in stochastic volatility models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9fa285fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheKappaParameter\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": list(np.linspace(0, 8, 10)),\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "    },\n",
    "    post_process_fn=process_results\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bc156d2",
   "metadata": {},
   "source": [
    "##### Stress theta\n",
    "Stress Theta evaluates the sensitivity of a model's output to changes in the parameter theta, which represents the long-term variance in a stochastic volatility model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab6a8ebc",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheThetaParameter\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": list(np.linspace(0, 0.8, 10)),\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": [-0.5],\n",
    "    },\n",
    "    post_process_fn=process_results\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3db5fba1",
   "metadata": {},
   "source": [
    "##### Stress xi\n",
    "Stress Xi evaluates the sensitivity of a model's output to changes in the parameter xi, which represents the volatility of volatility in a stochastic volatility model. This test is crucial for understanding how variations in xi impact the model's valuation, particularly in financial derivatives pricing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78f120ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheXiParameter\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": list(np.linspace(0.05, 0.95, 10)),\n",
    "        \"rho\": [-0.5],\n",
    "    },\n",
    "    post_process_fn=process_results\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92d20559",
   "metadata": {},
   "source": [
    "##### Stress rho\n",
    "Stress rho test evaluates the sensitivity of a model's output to changes in the correlation parameter, rho, within a stochastic volatility (SV) model framework. This test is crucial for understanding how variations in rho, which represents the correlation between the asset price and its volatility, impact the model's valuation output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "682bd89b",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_test(\n",
    "    \"my_custom_tests.Stressing:TheRhoParameter\",\n",
    "    param_grid={\n",
    "        \"model_type\": ['SV'],\n",
    "        \"N\": [N],\n",
    "        \"M\": [M],\n",
    "        \"strike\": [strike_range[0]],\n",
    "        \"barrier\": [barrier_range[0]],\n",
    "        \"S0\": [S0],\n",
    "        \"T\": [T],\n",
    "        \"r\": [r],\n",
    "        \"v0\": [0.2],\n",
    "        \"kappa\": [2],\n",
    "        \"theta\": [0.2],\n",
    "        \"xi\": [0.1],\n",
    "        \"rho\": list(np.linspace(-1.0, 1.0, 20)),\n",
    "    },\n",
    "    post_process_fn=process_results\n",
    ")\n",
    "result.log()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb79c09e",
   "metadata": {},
   "source": [
    "<a id='toc8_'></a>\n",
    "\n",
    "## Next steps\n",
    "\n",
    "You can look at the results of this test suite right in the notebook where you ran the code, as you would expect. But there is a better way — use the ValidMind Platform to work with your model documentation.\n",
    "\n",
    "<a id='toc8_1_'></a>\n",
    "\n",
    "### Work with your model documentation\n",
    "\n",
    "1. From the **Model Inventory** in the ValidMind Platform, go to the model you registered earlier. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/working-with-model-inventory.html))\n",
    "\n",
    "2. Click and expand the **Model Development** section.\n",
    "\n",
    "What you see is the full draft of your model documentation in a more easily consumable version. From here, you can make qualitative edits to model documentation, view guidelines, collaborate with validators, and submit your model documentation for approval when it's ready. [Learn more ...](https://docs.validmind.ai/guide/model-documentation/working-with-model-documentation.html)\n",
    "\n",
    "<a id='toc8_2_'></a>\n",
    "\n",
    "### Discover more learning resources\n",
    "\n",
    "We offer many interactive notebooks to help you document models:\n",
    "\n",
    "- [Run tests & test suites](https://docs.validmind.ai/developer/model-testing/testing-overview.html)\n",
    "- [Code samples](https://docs.validmind.ai/developer/samples-jupyter-notebooks.html)\n",
    "\n",
    "Or, visit our [documentation](https://docs.validmind.ai/) to learn more about ValidMind."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "validmind-1QuffXMV-py3.10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
