{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Financial Risk Management\n",
        "\n**Opening question:** How much could be lost, how often should that threshold be exceeded, and what happens beyond it?\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "rng = np.random.default_rng(25)\n",
        "returns = 0.01 * rng.standard_t(df=5, size=2_000)\n",
        "losses = -returns\n",
        "q = 0.99\n",
        "var = np.quantile(losses, q)\n",
        "es = losses[losses >= var].mean()\n",
        "print(round(var, 4), round(es, 4), int((losses >= var).sum()))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Interpretation check:** Interpretation. At the 99th percentile, roughly 20 of 2,000 simulated observations lie in the tail used for ES, illustrating tail-sample scarcity.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "threshold = np.full_like(losses, var)\n",
        "exceed = losses > threshold\n",
        "expected = len(losses) * (1-q)\n",
        "print(exceed.sum(), round(expected, 1), round(exceed.mean(), 4))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Interpretation check:** Interpretation. The unconditional exceedance rate matches by construction for an in-sample historical quantile. A real backtest must forecast each threshold using only prior information.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "rng = np.random.default_rng(25)\n",
        "returns = 0.01 * rng.standard_t(df=5, size=2_000)\n",
        "var = np.quantile(losses, q)\n",
        "es = losses[losses >= var].mean()\n",
        "print(round(var, 4), round(es, 4), int((losses >= var).sum()))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Verified source output\n",
        "\n",
        "```text\n0.0383 0.0518 20\n```\n\n```text\n20 20.0 0.01\n```\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3"
    },
    "ceteris_lab": {
      "course_slug": "fundamentals-python-econometrics",
      "source_derived": true,
      "course_title": "Fundamentals of Python for Financial Econometrics",
      "chapter": 44,
      "source_origin": "source-derived"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
