{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9a1928e2",
   "metadata": {},
   "source": [
    "$$\n",
    "\\newcommand{\\argmax}{arg\\,max}\n",
    "\\newcommand{\\argmin}{arg\\,min}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "753d5ddc",
   "metadata": {},
   "source": [
    "# Introduction to Bayesian Methods"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e50c2ff",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "In this lecture we study one of the most important ideas in statistics: how to\n",
    "update our beliefs about an unknown quantity as new data arrives.\n",
    "\n",
    "The technique we will use is called **Bayesian updating**, named after [Thomas\n",
    "Bayes](https://en.wikipedia.org/wiki/Thomas_Bayes).\n",
    "\n",
    "We start with a belief about some unknown number.\n",
    "\n",
    "As we observe data, we revise that belief in a way that is mathematically precise.\n",
    "\n",
    "The figure below illustrates the idea: we combine a **prior belief** with\n",
    "observed **data** to arrive at an **updated belief**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d496c62b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.patches import Ellipse, FancyArrowPatch\n",
    "\n",
    "def add_node(ax, xy, text, color):\n",
    "    ax.add_patch(Ellipse(xy, width=0.34, height=0.20,\n",
    "                         facecolor=color, edgecolor='black', lw=1.0, alpha=0.35))\n",
    "    ax.annotate(text, xy, ha='center', va='center', fontsize=12)\n",
    "\n",
    "def add_arrow(ax, start, end):\n",
    "    ax.add_patch(FancyArrowPatch(start, end, arrowstyle='-|>',\n",
    "                                 mutation_scale=18, lw=1.2, color='black'))\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(7, 3.5))\n",
    "\n",
    "add_node(ax, (0.22, 0.75), \"prior belief\", 'C0')\n",
    "add_node(ax, (0.22, 0.25), \"data\",         'C1')\n",
    "add_node(ax, (0.78, 0.50), \"updated belief\", 'C2')\n",
    "\n",
    "add_arrow(ax, (0.39, 0.70), (0.61, 0.54))\n",
    "add_arrow(ax, (0.39, 0.30), (0.61, 0.46))\n",
    "\n",
    "ax.set_xlim(0, 1)\n",
    "ax.set_ylim(0, 1)\n",
    "ax.axis('off')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8c88797",
   "metadata": {},
   "source": [
    "We will develop these ideas through an example drawn from development\n",
    "finance: estimating the default rate on a new type of loan.\n",
    "\n",
    "Along the way we will meet conditional probability, Bayes’ law, the Bernoulli\n",
    "and binomial distributions, and the beta distribution.\n",
    "\n",
    "Let’s begin by importing the libraries we need."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fcfd4a8",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.lines import Line2D\n",
    "from scipy.stats import beta, binom"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d14d5b7",
   "metadata": {},
   "source": [
    "## Conditional probability\n",
    "\n",
    "Before we can talk about updating beliefs, we need to recall the idea of **conditional probability**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "289d2fa8",
   "metadata": {},
   "source": [
    "### Definition\n",
    "\n",
    "Suppose $ A $ and $ B $ are two events with $ P(B) > 0 $.\n",
    "\n",
    "The probability of $ A $ given that $ B $ has occurred is written $ P(A \\mid B) $ and defined by\n",
    "\n",
    "\n",
    "<a id='equation-eq-cond-prob'></a>\n",
    "$$\n",
    "P(A \\mid B) = \\frac{P(A \\cap B)}{P(B)}. \\tag{15.1}\n",
    "$$\n",
    "\n",
    "Here $ A \\cap B $ is the event that both $ A $ and $ B $ occur.\n",
    "\n",
    "The intuition is that learning $ B $ has occurred restricts us to the world in which $ B $ is true.\n",
    "\n",
    "Within that restricted world, we ask how likely $ A $ is."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95e8d894",
   "metadata": {},
   "source": [
    "### Example: risky borrowing\n",
    "\n",
    "A bank classifies its borrowers as either *low risk* or *high risk*.\n",
    "\n",
    "Among all borrowers, 80% are low risk and 20% are high risk.\n",
    "\n",
    "The conditional default probabilities are:\n",
    "\n",
    "- low-risk borrowers: 0.05  \n",
    "- high-risk borrowers: 0.40  \n",
    "\n",
    "\n",
    "Suppose we pick a borrower at random and find that they defaulted.\n",
    "\n",
    "What is the probability that the borrower was high risk?\n",
    "\n",
    "Let $ H = $ high risk, $ L = $ low risk and $ D = $ default.\n",
    "\n",
    "We know that $ P(H) = 0.2 $, $ P(L) = 0.8 $, $ P(D \\mid H) = 0.40 $ and $ P(D \\mid L) = 0.05 $.\n",
    "\n",
    "The probability that a borrower is both high risk and defaults is\n",
    "\n",
    "$$\n",
    "P(H \\cap D) = P(D \\mid H)\\, P(H) = 0.40 \\times 0.2 = 0.08.\n",
    "$$\n",
    "\n",
    "The overall probability of default can be computed from the [law of total probability](https://en.wikipedia.org/wiki/Law_of_total_probability):\n",
    "\n",
    "$$\n",
    "P(D) = P(D \\mid H)\\, P(H) + P(D \\mid L)\\, P(L) = 0.40 \\times 0.2 + 0.05 \\times 0.8 = 0.08 + 0.04 = 0.12.\n",
    "$$\n",
    "\n",
    "Applying [(15.1)](#equation-eq-cond-prob), we get\n",
    "\n",
    "$$\n",
    "P(H \\mid D) = \\frac{P(H \\cap D)}{P(D)} = \\frac{0.08}{0.12} \\approx 0.667.\n",
    "$$\n",
    "\n",
    "So observing a default raises our assessment that the borrower is high risk from 20% to about 67%."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd5ac2d7",
   "metadata": {},
   "source": [
    "### Bayes’ law\n",
    "\n",
    "The last computation was, in fact, a typical Bayesian calculation.\n",
    "\n",
    "Let’s clarify further by returning to a setting with two abstract events $ A $ and $ B $.\n",
    "\n",
    "Notice that the event $ A \\cap B $ (both $ A $ and $ B $ occur) is the same as $ B \\cap A $.\n",
    "\n",
    "Hence, applying definition [(15.1)](#equation-eq-cond-prob) two ways, we have\n",
    "\n",
    "$$\n",
    "P(A \\mid B)\\, P(B) = P(A \\cap B) = P(B \\mid A)\\, P(A).\n",
    "$$\n",
    "\n",
    "Dividing through by $ P(B) $ gives **Bayes’ law**:\n",
    "\n",
    "\n",
    "<a id='equation-eq-bayes-law'></a>\n",
    "$$\n",
    "P(A \\mid B) = \\frac{P(B \\mid A)\\, P(A)}{P(B)}. \\tag{15.2}\n",
    "$$\n",
    "\n",
    "In this setting, we call\n",
    "\n",
    "- $ P(A) $ the **prior** — our belief about $ A $ before seeing data,  \n",
    "- $ P(B \\mid A) $ the **likelihood** — how probable the data $ B $ is when $ A $ is true, and  \n",
    "- $ P(A \\mid B) $ the **posterior** — our updated belief about $ A $ after seeing $ B $.  \n",
    "\n",
    "\n",
    "The denominator $ P(B) $ is a normalizing constant that makes the posterior probabilities sum to one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a328e17",
   "metadata": {},
   "source": [
    "**Example 15.1**\n",
    "\n",
    "The borrower calculation we completed above was an application of Bayes’ law with $ A = H $ and $ B = D $.\n",
    "\n",
    "Bayes’ law tells us how to convert $ P(D \\mid H) $, which was assumed to be known, into $ P(H \\mid D) $, which we want."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee7ee935",
   "metadata": {},
   "source": [
    "## A microloan default problem\n",
    "\n",
    "Now we turn to our main example.\n",
    "\n",
    "A development bank is entering a new lending market — say, smallholder farmers in a region where no historical lending data exists.\n",
    "\n",
    "The bank makes a series of small loans (microloans).\n",
    "\n",
    "Each loan either **defaults** or is **repaid**.\n",
    "\n",
    "We encode the outcome of loan $ i $ as a random variable $ Y_i $, where\n",
    "\n",
    "$$\n",
    "Y_i =\n",
    "    \\begin{cases}\n",
    "    1 & \\text{if loan } i \\text{ defaults}, \\\\\n",
    "    0 & \\text{if loan } i \\text{ is repaid}.\n",
    "    \\end{cases}\n",
    "$$\n",
    "\n",
    "Let $ \\theta $ be the probability that any given loan defaults.\n",
    "\n",
    "We assume that, given $ \\theta $, the outcomes $ Y_1, Y_2, \\ldots $ are independent draws with\n",
    "\n",
    "$$\n",
    "P(Y_i = 1 \\mid \\theta) = \\theta,\n",
    "    \\qquad\n",
    "    P(Y_i = 0 \\mid \\theta) = 1 - \\theta.\n",
    "$$\n",
    "\n",
    "A random variable of this form is called a **Bernoulli** random variable with parameter $ \\theta $.\n",
    "\n",
    "The catch is that the bank does **not** know $ \\theta $.\n",
    "\n",
    "Since the market is new, $ \\theta $ is uncertain.\n",
    "\n",
    "At the same time, the bank has experience in similar markets, so it does not start from total ignorance.\n",
    "\n",
    "The Bayesian approach is to treat $ \\theta $ as a random quantity and describe our beliefs about it with a probability density $ \\pi $ on the interval $ [0, 1] $.\n",
    "\n",
    "This density is called the **prior**.\n",
    "\n",
    "One possible option for $ \\pi $ is to use a [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution), whose density on $ [0,1] $ is\n",
    "\n",
    "$$\n",
    "\\pi(\\theta) = \\frac{\\theta^{a - 1} (1 - \\theta)^{b - 1}}{B(a, b)},\n",
    "    \\qquad\n",
    "    B(a, b) = \\int_0^1 t^{a-1}(1-t)^{b-1}\\, dt,\n",
    "$$\n",
    "\n",
    "for parameters $ a > 0 $ and $ b > 0 $.\n",
    "\n",
    "The denominator $ B(a, b) $ is called the **beta function**, and it is simply the\n",
    "constant that makes the density integrate to one.\n",
    "\n",
    "For our purposes the important part is the shape, $ \\theta^{a-1}(1-\\theta)^{b-1} $, which is all that depends on $ \\theta $.\n",
    "\n",
    "One nice property of the beta distribution is that, by varying $ a $ and $ b $, we can represent a wide range of beliefs.\n",
    "\n",
    "The four examples below range from “no idea at all” to at least some opinion as to whether $ \\theta $ is\n",
    "likely to take a low or high value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b25ca612",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "θ_grid = np.linspace(0, 1, 500)\n",
    "plot_grid = np.linspace(0.001, 0.999, 500)   # avoids the spikes at the endpoints\n",
    "params = [(0.5, 0.5), (1, 1), (2, 5), (8, 3)]\n",
    "\n",
    "fig, axes = plt.subplots(2, 2, figsize=(10, 6))\n",
    "for (a, b), ax in zip(params, axes.flatten()):\n",
    "    ax.plot(plot_grid, beta.pdf(plot_grid, a, b), lw=2)\n",
    "    ax.set_title(f\"Beta({a}, {b})\")\n",
    "    ax.set_xlabel(r\"$\\theta$\")\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1054e00",
   "metadata": {},
   "source": [
    "The shapes are strikingly different.\n",
    "\n",
    "$ \\text{Beta}(1, 1) $ is flat — it expresses complete ignorance, treating every default rate as equally likely.\n",
    "\n",
    "$ \\text{Beta}(0.5, 0.5) $ piles weight near 0 and 1, a belief that the market is probably either very safe or very risky.\n",
    "\n",
    "$ \\text{Beta}(2, 5) $ leans toward low default rates, while $ \\text{Beta}(8, 3) $ leans toward high ones."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "373b5dc3",
   "metadata": {},
   "source": [
    "## A one-step update\n",
    "\n",
    "Now suppose the bank observes the outcome of a single loan.\n",
    "\n",
    "Call this outcome $ y \\in \\{0, 1\\} $.\n",
    "\n",
    "We want to update the prior $ \\pi(\\theta) $ into a **posterior** $ \\pi(\\theta \\mid y) $.\n",
    "\n",
    "The probability of $ y $ given $ \\theta $ is\n",
    "\n",
    "\n",
    "<a id='equation-eq-bernoulli-lik'></a>\n",
    "$$\n",
    "p(y \\mid \\theta) = \\theta^{y} (1 - \\theta)^{1 - y}. \\tag{15.3}\n",
    "$$\n",
    "\n",
    "This formula (which is called the Bernoulli distribution) gives us the right numbers:\n",
    "\n",
    "- The default outcome $ y = 1 $ yields $ \\theta^1 (1-\\theta)^0 = \\theta $, the probability of a default.  \n",
    "- The repayment outcome $ y = 0 $ yields $ \\theta^0 (1-\\theta)^1 = 1 - \\theta $, the probability of repayment.  \n",
    "\n",
    "\n",
    "Bayes’ law for a continuous parameter takes the form\n",
    "\n",
    "\n",
    "<a id='equation-eq-bayes-density'></a>\n",
    "$$\n",
    "\\pi(\\theta \\mid y) = \\frac{p(y \\mid \\theta)\\, \\pi(\\theta)}{\\int_0^1 p(y \\mid t)\\, \\pi(t)\\, dt}. \\tag{15.4}\n",
    "$$\n",
    "\n",
    "This is the exact analogue of [(15.2)](#equation-eq-bayes-law).\n",
    "\n",
    "The numerator is likelihood times prior.\n",
    "\n",
    "The denominator is an integral that sums the numerator over all possible values of $ \\theta $, ensuring the posterior integrates to one.\n",
    "\n",
    "Substituting the Bernoulli likelihood [(15.3)](#equation-eq-bernoulli-lik) gives our complete one-step update rule:\n",
    "\n",
    "\n",
    "<a id='equation-eq-bayes-update'></a>\n",
    "$$\n",
    "\\pi(\\theta \\mid y) = \\frac{\\theta^{y}(1-\\theta)^{1-y}\\, \\pi(\\theta)}{\\int_0^1 t^{y}(1-t)^{1-y}\\, \\pi(t)\\, dt}. \\tag{15.5}\n",
    "$$\n",
    "\n",
    "This rule is valid for any $ \\theta $.\n",
    "\n",
    "Hence we can think of it as taking any prior density $ \\pi(\\cdot) $ and any single\n",
    "observation $ y $ and converting it into the posterior density $ \\pi(\\cdot \\mid y) $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f42210a0",
   "metadata": {},
   "source": [
    "## Computing the update numerically\n",
    "\n",
    "How can we compute the posterior density?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56bd5059",
   "metadata": {},
   "source": [
    "### Prior\n",
    "\n",
    "First let’s set up the prior.\n",
    "\n",
    "For our development bank we will begin with the prior $ \\pi = \\text{Beta}(2, 5) $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09ae2e6d",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "a_0, b_0 = 2, 5\n",
    "\n",
    "def pi(θ):\n",
    "    return beta.pdf(θ, a_0, b_0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acb4ad32",
   "metadata": {},
   "source": [
    "This prior was shown above.\n",
    "\n",
    "It puts most of its weight on default rates below 0.5, with a peak around 0.2, reflecting cautious optimism (most borrowers don’t default) together with significant uncertainty."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e938842",
   "metadata": {},
   "source": [
    "### Normalizing constant\n",
    "\n",
    "Next we need to compute the constant in the denominator of [(15.4)](#equation-eq-bayes-density),\n",
    "which is the integrated likelihood times the prior:\n",
    "\n",
    "$$\n",
    "c(y) := \\int_0^1 p(y \\mid t)\\, \\pi(t)\\, dt .\n",
    "$$\n",
    "\n",
    "One general approach is to compute $ c(y) $ numerically, using a technique\n",
    "such as the [trapezoidal rule](https://en.wikipedia.org/wiki/Trapezoidal_rule).\n",
    "\n",
    "The idea of the trapezoidal rule is to\n",
    "\n",
    "1. fix a grid of points across $ [0, 1] $,  \n",
    "1. join neighboring grid points by straight lines, and  \n",
    "1. sum the areas of the resulting trapezoids.  \n",
    "\n",
    "\n",
    "The figure below illustrates this for the integrand $ p(y \\mid \\theta)\\, \\pi(\\theta) $ with $ y = 1 $, using a coarse grid so the trapezoids are visible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fea8ca6",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fine = np.linspace(0, 1, 500)\n",
    "integrand = fine * beta.pdf(fine, a_0, b_0)        # θ^1 (1-θ)^0 × prior\n",
    "\n",
    "coarse = np.linspace(0, 1, 9)                       # eight trapezoids\n",
    "heights = coarse * beta.pdf(coarse, a_0, b_0)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(fine, integrand, lw=2, label=r\"$p(y \\mid \\theta)\\,\\pi(\\theta)$\")\n",
    "ax.fill_between(coarse, heights, alpha=0.3,\n",
    "                label=\"trapezoidal approximation\")\n",
    "ax.plot(coarse, heights, 'o-', color='C1', lw=1, ms=4)\n",
    "for x, h in zip(coarse, heights):\n",
    "    ax.plot([x, x], [0, h], color='C1', lw=0.8, alpha=0.6)\n",
    "ax.set_xlabel(r\"$\\theta$\")\n",
    "ax.set_ylabel(\"integrand\")\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03beffdf",
   "metadata": {},
   "source": [
    "The finer the grid, the closer the shaded region gets to the true area under the curve.\n",
    "\n",
    "The function below uses this method to compute an approximation of $ c(y) $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "679165a4",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def normalizing_constant(y):\n",
    "    \"Compute the denominator of Bayes' law: likelihood times prior, integrated.\"\n",
    "    t_grid = np.linspace(0, 1, 100)  # linear grid of 100 points\n",
    "    likelihood_vals = t_grid**y * (1 - t_grid)**(1 - y)\n",
    "    prior_vals = pi(t_grid)\n",
    "    integrand = likelihood_vals * prior_vals\n",
    "    return np.trapezoid(integrand, t_grid)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33c6f28c",
   "metadata": {},
   "source": [
    "### Calculating the posterior\n",
    "\n",
    "The second step divides the (unnormalized) product of likelihood and prior by this constant.\n",
    "\n",
    "The result is the posterior density, evaluated on the grid."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fbd4fda",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def update(y, θ_grid):\n",
    "    \"\"\"\n",
    "    Compute posterior values pi(θ, y) on the set of grid points θ_grid\n",
    "    after observing outcome y.\n",
    "    \"\"\"\n",
    "    likelihood_vals = θ_grid**y * (1 - θ_grid)**(1 - y)\n",
    "    prior_vals = pi(θ_grid)\n",
    "    return likelihood_vals * prior_vals / normalizing_constant(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b669ce4",
   "metadata": {},
   "source": [
    "Let’s start from our Beta(2, 5) prior and suppose that we observe a single default ($ y = 1 $)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cded0ed7",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "θ_grid = np.linspace(0, 1, 500)\n",
    "prior_vals = pi(θ_grid)\n",
    "posterior_vals = update(y=1, θ_grid=θ_grid)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(θ_grid, prior_vals, lw=2, label=\"prior\")\n",
    "ax.plot(θ_grid, posterior_vals, lw=2, label=\"posterior after one default\")\n",
    "ax.set_xlabel(r\"$\\theta$\")\n",
    "ax.set_ylabel(\"density\")\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43833252",
   "metadata": {},
   "source": [
    "Observing a default shifts the posterior to the right, toward higher default probabilities.\n",
    "\n",
    "This makes sense: a default is evidence that $ \\theta $ might be larger than we thought.\n",
    "\n",
    "If instead the loan had been repaid, the posterior would shift left."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20496a66",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "posterior_repaid = update(y=0, θ_grid=θ_grid)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(θ_grid, prior_vals, lw=2, label=\"prior\")\n",
    "ax.plot(θ_grid, posterior_repaid, lw=2, label=\"posterior after one repayment\")\n",
    "ax.set_xlabel(r\"$\\theta$\")\n",
    "ax.set_ylabel(\"density\")\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e142540",
   "metadata": {},
   "source": [
    "## Iterating the update\n",
    "\n",
    "Here is a key observation: the posterior after one step is itself a perfectly good prior for the next step.\n",
    "\n",
    "So we can repeat the update as each new loan resolves.\n",
    "\n",
    "Starting from a prior $ \\pi_0 $, observing $ Y_1 $ gives a posterior $ \\pi_1 $.\n",
    "\n",
    "Treating $ \\pi_1 $ as the new prior and observing $ Y_2 $ gives $ \\pi_2 $, and so on.\n",
    "\n",
    "This produces a sequence of densities $ \\pi_0, \\pi_1, \\pi_2, \\ldots $ that captures our evolving beliefs.\n",
    "\n",
    "Let’s simulate a stream of loan outcomes and watch the beliefs evolve.\n",
    "\n",
    "We will generate data from a “true” default rate $ \\theta^* = 0.15 $, which the bank does not know."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd95cfe9",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "θ_true = 0.15\n",
    "n = 100\n",
    "rng = np.random.default_rng(seed=42)\n",
    "# Generate n draws from the Bernoulli distribution with θ = θ_true\n",
    "outcomes = (rng.random(n) < θ_true).astype(int)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b13ae208",
   "metadata": {},
   "source": [
    "Now we iterate the grid update over these outcomes, recording the posterior at a sequence of stages and showing each in its own panel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8da1a363",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "snapshots = [0, 1, 2, 3, 5, 8, 12, 16, 20]   # 0 = prior\n",
    "\n",
    "# Iterate the grid update, saving the density at each snapshot\n",
    "current_vals = pi(θ_grid)\n",
    "saved = {0: current_vals.copy()}\n",
    "for i in range(1, max(snapshots) + 1):\n",
    "    y = outcomes[i - 1]\n",
    "    likelihood_vals = θ_grid**y * (1 - θ_grid)**(1 - y)\n",
    "    current_vals = likelihood_vals * current_vals\n",
    "    current_vals /= np.trapezoid(current_vals, θ_grid)\n",
    "    if i in snapshots:\n",
    "        saved[i] = current_vals.copy()\n",
    "\n",
    "# Use a common y-axis so the concentration over time is visible\n",
    "y_max = max(vals.max() for vals in saved.values())\n",
    "\n",
    "fig, axes = plt.subplots(3, 3, figsize=(6.2, 6.2), sharex=True, sharey=True)\n",
    "for ax, k in zip(axes.flatten(), snapshots):\n",
    "    ax.fill_between(θ_grid, saved[k], color='C0', alpha=0.3)\n",
    "    ax.plot(θ_grid, saved[k], color='k', lw=1)\n",
    "    ax.axvline(θ_true, color='k', ls=':', lw=1)\n",
    "    ax.set_title(\"prior\" if k == 0 else f\"{k} loans\", fontsize=10)\n",
    "    ax.set_ylim(0, y_max * 1.05)\n",
    "    ax.set_box_aspect(1)             # force each panel to be square\n",
    "for ax in axes[-1, :]:\n",
    "    ax.set_xlabel(r\"$\\theta$\")\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61ea1464",
   "metadata": {},
   "source": [
    "Two things stand out.\n",
    "\n",
    "First, the posterior **concentrates** around the true value $ \\theta^* = 0.15 $ as more loans resolve.\n",
    "\n",
    "Second, the posterior becomes **tighter** — our uncertainty about $ \\theta $ steadily shrinks.\n",
    "\n",
    "Early on, the prior has a strong influence on our beliefs.\n",
    "\n",
    "As data accumulates, that influence fades and the data takes over."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b7407c6",
   "metadata": {},
   "source": [
    "## Further observations\n",
    "\n",
    "Let’s make two additional observations regarding the model described above.\n",
    "\n",
    "The first shows that we can do the update steps above with pencil and paper in\n",
    "the special case of a beta prior.\n",
    "\n",
    "The second observation concerns batch updating."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d3aa7d1",
   "metadata": {},
   "source": [
    "### A closed form: the beta prior\n",
    "\n",
    "The numerical updating rule provided above always works, regardless of our\n",
    "choice of prior.\n",
    "\n",
    "But in the beta case we get a nice analytical approach as well.\n",
    "\n",
    "Recall that this prior is proportional to $ \\theta^{a-1}(1-\\theta)^{b-1} $.\n",
    "\n",
    "When we multiply this expression by the Bernoulli likelihood $ \\theta^{y}(1-\\theta)^{1-y} $, we get\n",
    "\n",
    "$$\n",
    "\\theta^{y}(1-\\theta)^{1-y} \\cdot \\theta^{a-1}(1-\\theta)^{b-1}\n",
    "    = \\theta^{(a + y) - 1}(1-\\theta)^{(b + 1 - y) - 1}.\n",
    "$$\n",
    "\n",
    "The right-hand side has the form of another beta density.\n",
    "\n",
    "So if the prior is $ \\text{Beta}(a, b) $, the posterior is again a beta distribution — with updated parameters.\n",
    "\n",
    "We say that the beta distribution is a **conjugate prior** for the Bernoulli likelihood.\n",
    "\n",
    "The update rule for the parameters is very simple:\n",
    "\n",
    "- a default ($ y = 1 $) sends $ (a, b) \\mapsto (a + 1,\\, b) $,  \n",
    "- a repayment ($ y = 0 $) sends $ (a, b) \\mapsto (a,\\, b + 1) $.  \n",
    "\n",
    "\n",
    "Let’s verify that this closed form agrees with our numerical computation.\n",
    "\n",
    "We overlay the analytical $ \\text{Beta}(a_0 + 1, b_0) $ posterior on the grid posterior after one default."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60373d6a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "closed_form = beta.pdf(θ_grid, a_0 + 1, b_0)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(θ_grid, posterior_vals, lw=4, alpha=0.5, label=\"numerical posterior\")\n",
    "ax.plot(θ_grid, closed_form, ls='--', lw=2, label=f\"Beta({a_0 + 1}, {b_0})\")\n",
    "ax.set_xlabel(r\"$\\theta$\")\n",
    "ax.set_ylabel(\"density\")\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5521bf6",
   "metadata": {},
   "source": [
    "The two curves lie exactly on top of one another, confirming that our numerics and the closed form agree."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f821fc5e",
   "metadata": {},
   "source": [
    "### The batch update via the binomial likelihood\n",
    "\n",
    "There is a second, equally natural way to think about the problem of belief\n",
    "updating given loan outcome data.\n",
    "\n",
    "Instead of processing outcomes one at a time, suppose we wait and observe all $ n $ outcomes $ Y_1, \\ldots, Y_n $ together.\n",
    "\n",
    "Then we update directly from the prior $ \\pi_0 $ to the posterior $ \\pi_n $ in a single step.\n",
    "\n",
    "Let the total number of defaults be given by\n",
    "\n",
    "$$\n",
    "k = \\sum_{i=1}^n Y_i.\n",
    "$$\n",
    "\n",
    "The probability of observing exactly $ k $ defaults out of $ n $ loans is given by the **binomial** distribution:\n",
    "\n",
    "\n",
    "<a id='equation-eq-binom-lik'></a>\n",
    "$$\n",
    "p(k \\mid \\theta) = \\binom{n}{k} \\theta^{k} (1 - \\theta)^{n - k}. \\tag{15.6}\n",
    "$$\n",
    "\n",
    "Bayes’ law then gives the one-shot update\n",
    "\n",
    "$$\n",
    "\\pi_n(\\theta) = \\frac{p(k \\mid \\theta)\\, \\pi_0(\\theta)}{\\int_0^1 p(k \\mid t)\\, \\pi_0(t)\\, dt}.\n",
    "$$\n",
    "\n",
    "With a $ \\text{Beta}(a, b) $ prior, conjugacy again gives a clean closed form.\n",
    "\n",
    "The binomial likelihood is proportional to $ \\theta^{k}(1-\\theta)^{n-k} $, so the posterior is\n",
    "\n",
    "$$\n",
    "\\text{Beta}(a + k,\\ b + n - k).\n",
    "$$\n",
    "\n",
    "In words: add the number of defaults to $ a $, and add the number of repayments to $ b $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e6b71b5",
   "metadata": {},
   "source": [
    "## Sequential and batch updates agree\n",
    "\n",
    "We now have two routes from prior to posterior.\n",
    "\n",
    "One processes the $ n $ outcomes one at a time; the other processes them all at once.\n",
    "\n",
    "Reassuringly, they give exactly the same answer.\n",
    "\n",
    "We can see why with a short algebraic argument.\n",
    "\n",
    "The likelihood of the full sequence $ Y_1, \\ldots, Y_n $, for given $ \\theta $, is the product of the individual Bernoulli likelihoods:\n",
    "\n",
    "$$\n",
    "\\prod_{i=1}^n \\theta^{Y_i}(1-\\theta)^{1 - Y_i}\n",
    "    = \\theta^{k}(1-\\theta)^{n-k}.\n",
    "$$\n",
    "\n",
    "This is identical to the binomial likelihood [(15.6)](#equation-eq-binom-lik), except for the factor $ \\binom{n}{k} $.\n",
    "\n",
    "But $ \\binom{n}{k} $ does not depend on $ \\theta $, so it cancels between the numerator and denominator when we normalize.\n",
    "\n",
    "Hence the two posteriors are equal.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">It might appear that the sequential update never used the assumption that the outcomes are independent, while the batch update clearly did.\n",
    "\n",
    "In fact both rely on it.\n",
    "\n",
    "The honest update at step $ i $ conditions on everything seen so far:\n",
    "\n",
    "$$\n",
    "\\pi_i(\\theta) \\propto p(Y_i \\mid \\theta, Y_1, \\ldots, Y_{i-1})\\, \\pi_{i-1}(\\theta).\n",
    "$$\n",
    "\n",
    "When we replace $ p(Y_i \\mid \\theta, Y_1, \\ldots, Y_{i-1}) $ by the single-outcome likelihood $ p(Y_i \\mid \\theta) $, we are assuming that, given $ \\theta $, the new outcome is independent of the past.\n",
    "\n",
    "This is exactly the conditional independence that lets the batch likelihood factor into a product.\n",
    "\n",
    "So the assumption is doing the same work in both routes — it is just hidden in the sequential one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "763af2bb",
   "metadata": {},
   "source": [
    "## From posterior to loan pricing\n",
    "\n",
    "Why does any of this matter for the bank?\n",
    "\n",
    "The whole point of estimating $ \\theta $ is to make better lending decisions.\n",
    "\n",
    "Let’s discuss how this can be done."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c9aece0",
   "metadata": {},
   "source": [
    "### Expected loss\n",
    "\n",
    "Suppose each loan has size 1, and the bank loses the full amount when a loan defaults.\n",
    "\n",
    "Then the **expected loss** on a new loan is just the probability of default.\n",
    "\n",
    "Given the data, our best estimate of that probability is the **posterior mean**.\n",
    "\n",
    "Recall that the posterior is $ \\text{Beta}(a + k,\\ b + n - k) $.\n",
    "\n",
    "The [mean of a beta distribution](https://en.wikipedia.org/wiki/Beta_distribution) $ \\text{Beta}(\\alpha, \\beta) $ is $ \\alpha / (\\alpha + \\beta) $, so here\n",
    "\n",
    "$$\n",
    "\\mathbb{E}[\\theta \\mid \\text{data}] = \\frac{a + k}{a + b + n}.\n",
    "$$\n",
    "\n",
    "This is the number the bank should plug into its pricing: to break even, the interest rate must at least cover the expected loss.\n",
    "\n",
    "Let’s track how the expected loss, and our uncertainty about it, evolve as loans resolve."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86f35b23",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "cum_defaults = np.cumsum(outcomes)\n",
    "loans = np.arange(1, n + 1)\n",
    "\n",
    "a_n = a_0 + cum_defaults\n",
    "b_n = b_0 + loans - cum_defaults\n",
    "\n",
    "# Posterior mean at every n (vectorized); reused later for pricing\n",
    "post_mean = a_n / (a_n + b_n)\n",
    "\n",
    "# Draw the full posterior at a selection of sample sizes as violins\n",
    "sample_points = [1, 5, 10, 20, 50, 100]\n",
    "draw_rng = np.random.default_rng(12345)\n",
    "samples = [beta.rvs(a_n[m - 1], b_n[m - 1], size=10_000, random_state=draw_rng)\n",
    "           for m in sample_points]\n",
    "means = [post_mean[m - 1] for m in sample_points]\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "positions = np.arange(len(sample_points))\n",
    "ax.violinplot(samples, positions=positions,\n",
    "              showmeans=False, showextrema=False)\n",
    "ax.hlines(means, positions - 0.25, positions + 0.25, color='k', lw=3, zorder=3)\n",
    "true_line = ax.axhline(θ_true, color='k', ls=':', lw=1)\n",
    "\n",
    "# Use a short horizontal bar (not the hlines handle) for the mean in the legend\n",
    "mean_proxy = Line2D([0], [0], color='k', lw=3)\n",
    "ax.legend([mean_proxy, true_line],\n",
    "          [\"posterior mean (expected loss)\", r\"true $\\theta^*$\"])\n",
    "ax.set_xticks(positions)\n",
    "ax.set_xticklabels(sample_points)\n",
    "ax.set_xlabel(\"number of loans observed\")\n",
    "ax.set_ylabel(r\"$\\theta$\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f678a929",
   "metadata": {},
   "source": [
    "As the bank observes more loans, its estimate of the expected loss settles down near the true default rate.\n",
    "\n",
    "At the same time, the violins narrow, showing that the posterior tightens around that estimate.\n",
    "\n",
    "This is the practical payoff of Bayesian updating: the bank can price cautiously when data is scarce, and sharpen its pricing as experience accumulates."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0597f914",
   "metadata": {},
   "source": [
    "### The break-even interest rate\n",
    "\n",
    "Let’s turn the expected loss into an actual interest rate.\n",
    "\n",
    "Consider a loan of size 1, carrying interest rate $ r $.\n",
    "\n",
    "If the borrower repays, the bank receives $ 1 + r $.\n",
    "\n",
    "If the borrower defaults, the bank receives nothing.\n",
    "\n",
    "Suppose the bank is risk neutral, faces no funding costs, and operates in a competitive market that drives expected profits to zero.\n",
    "\n",
    "The zero-profit condition sets the expected repayment equal to the amount lent:\n",
    "\n",
    "$$\n",
    "(1 - \\theta)(1 + r) = 1 .\n",
    "$$\n",
    "\n",
    "Solving for $ r $ gives the break-even interest rate\n",
    "\n",
    "$$\n",
    "r = \\frac{\\theta}{1 - \\theta} .\n",
    "$$\n",
    "\n",
    "This rate has a clean interpretation: the expected interest income $ (1 - \\theta) r $ exactly equals the expected loss $ \\theta $.\n",
    "\n",
    "Of course the bank does not know $ \\theta $.\n",
    "\n",
    "Because the bank is risk neutral, only the mean of $ \\theta $ enters the calculation, so it replaces $ \\theta $ by its posterior mean $ \\hat\\theta = \\mathbb{E}[\\theta \\mid \\text{data}] $:\n",
    "\n",
    "$$\n",
    "r = \\frac{\\hat\\theta}{1 - \\hat\\theta} .\n",
    "$$\n",
    "\n",
    "Let’s see how this break-even rate evolves as the loan book grows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c73f1923",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "implied_rate = post_mean / (1 - post_mean)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(loans, implied_rate, lw=2, label=\"break-even rate\")\n",
    "ax.axhline(θ_true / (1 - θ_true), color='k', ls=':',\n",
    "           label=r\"rate at true $\\theta^*$\")\n",
    "ax.set_xlabel(\"number of loans observed\")\n",
    "ax.set_ylabel(r\"interest rate $r$\")\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4db136bb",
   "metadata": {},
   "source": [
    "Early on, with little data, the rate reflects the prior and is somewhat unstable.\n",
    "\n",
    "As loans resolve, it settles toward $ \\theta^* / (1 - \\theta^*) \\approx 0.176 $, the rate the bank would charge if it knew the true default probability."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79da22b2",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b2a2c3b",
   "metadata": {},
   "source": [
    "## Exercise 15.1\n",
    "\n",
    "The prior matters a lot when data is scarce, but its influence should fade as data accumulates.\n",
    "\n",
    "Illustrate this by repeating the iteration of the previous sections from two very different priors:\n",
    "\n",
    "- an *optimistic* prior $ \\text{Beta}(2, 8) $, which expects a low default rate, and  \n",
    "- a *skeptical* prior $ \\text{Beta}(8, 2) $, which expects a high default rate.  \n",
    "\n",
    "\n",
    "Use the same simulated data (with $ \\theta^* = 0.15 $) for both.\n",
    "\n",
    "Plot the two posterior means as a function of the number of loans observed, and confirm that they converge as $ n $ grows."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4854aec5",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "We can use the conjugate update rule directly, since both priors are beta distributions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c37a7a62",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "priors = {\"optimistic Beta(2, 8)\": (2, 8),\n",
    "          \"skeptical Beta(8, 2)\": (8, 2)}\n",
    "\n",
    "cum_defaults = np.cumsum(outcomes)\n",
    "loans = np.arange(1, n + 1)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "for label, (a, b) in priors.items():\n",
    "    a_seq = a + cum_defaults\n",
    "    b_seq = b + loans - cum_defaults\n",
    "    ax.plot(loans, a_seq / (a_seq + b_seq), lw=2, label=label)\n",
    "\n",
    "ax.axhline(θ_true, color='k', ls=':', label=r\"true $\\theta^*$\")\n",
    "ax.set_xlabel(\"number of loans observed\")\n",
    "ax.set_ylabel(\"posterior mean\")\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acc39046",
   "metadata": {},
   "source": [
    "The two estimates start far apart, reflecting the disagreement between the priors.\n",
    "\n",
    "As loans accumulate, both are pulled toward the true value $ \\theta^* = 0.15 $ and the gap between them shrinks.\n",
    "\n",
    "With enough data, the choice of prior barely matters — the data dominates."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9764c382",
   "metadata": {},
   "source": [
    "## Exercise 15.2\n",
    "\n",
    "Suppose the bank starts with a $ \\text{Beta}(2, 5) $ prior and then observes 200 loans, of which 26 default.\n",
    "\n",
    "1. Compute the posterior mean default rate.  \n",
    "1. Compute a 90% **credible interval** for $ \\theta $ — an interval that contains $ \\theta $ with posterior probability 0.90.  \n",
    "\n",
    "\n",
    "For the credible interval, use the 5th and 95th percentiles of the posterior, available via `beta.ppf`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70602884",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "The posterior is $ \\text{Beta}(a_0 + k,\\ b_0 + n - k) $ with $ a_0 = 2 $, $ b_0 = 5 $, $ n = 200 $ and $ k = 26 $."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5d9d1ef",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "a_post = 2 + 26\n",
    "b_post = 5 + (200 - 26)\n",
    "\n",
    "post_mean = a_post / (a_post + b_post)\n",
    "lower, upper = beta.ppf([0.05, 0.95], a_post, b_post)\n",
    "\n",
    "print(f\"Posterior: Beta({a_post}, {b_post})\")\n",
    "print(f\"Posterior mean default rate: {post_mean:.4f}\")\n",
    "print(f\"90% credible interval: ({lower:.4f}, {upper:.4f})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01ab8cd6",
   "metadata": {},
   "source": [
    "The bank’s best estimate of the default rate is about 13.5%, and it is 90% sure that the true rate lies within the reported interval.\n",
    "\n",
    "These two numbers — a point estimate and a measure of uncertainty — are exactly what is needed to price the loans."
   ]
  }
 ],
 "metadata": {
  "date": 1795846195.024491,
  "filename": "bayes_intro.md",
  "kernelspec": {
   "display_name": "Python",
   "language": "python3",
   "name": "python3"
  },
  "title": "Introduction to Bayesian Methods"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}