{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8529ec71",
   "metadata": {},
   "source": [
    "$$\n",
    "\\newcommand{\\argmax}{arg\\,max}\n",
    "\\newcommand{\\argmin}{arg\\,min}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03f402ca",
   "metadata": {},
   "source": [
    "\n",
    "<a id='fitting-distributions'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a51a460",
   "metadata": {},
   "source": [
    "# Fitting Distributions to Data\n",
    "\n",
    "\n",
    "<a id='index-0'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7b1e997",
   "metadata": {},
   "source": [
    "## Outline\n",
    "\n",
    "In [Probability Distributions](https://intro.quantecon.org/prob_dist.html) we studied a collection of common probability distributions.\n",
    "\n",
    "In [Observed Distributions](https://intro.quantecon.org/observed_distributions.html) we studied observed data.\n",
    "\n",
    "In this lecture we connect the two, by asking a question that arises constantly\n",
    "in applied work:\n",
    "\n",
    "*given a data set, which probability distribution should we use to describe it?*\n",
    "\n",
    "The question has two parts.\n",
    "\n",
    "First, we must choose a **parametric class** — a set of distributions indexed\n",
    "by a small number of parameters.\n",
    "\n",
    "For example, the normal distributions form a parametric class, indexed by the\n",
    "mean $ \\mu $ and the standard deviation $ \\sigma $.\n",
    "\n",
    "The Poisson distributions form another, indexed by the single parameter\n",
    "$ \\lambda $.\n",
    "\n",
    "Second, having chosen a class, we must choose the **parameters** within it that\n",
    "make the fit as close as possible.\n",
    "\n",
    "This lecture is mainly about the first part.\n",
    "\n",
    "For the second we use just one technique, called the method of moments, leaving\n",
    "a fuller treatment to [Maximum Likelihood Estimation](https://intro.quantecon.org/mle_intro.html).\n",
    "\n",
    "Even so, we start with the parameters, since we have to be able to fit a class\n",
    "before we can judge it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fad850d",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "!pip install yfinance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad9c0759",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import yfinance as yf\n",
    "import scipy.stats\n",
    "\n",
    "np.set_printoptions(legacy='1.25')   # print scalars as plain numbers"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "267c3074",
   "metadata": {},
   "source": [
    "Let’s use the Ames house price data that we met in [Observed Distributions](https://intro.quantecon.org/observed_distributions.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "573dcaf9",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "url = ('https://github.com/QuantEcon/data-lectures/raw/main/'\n",
    "       'lectures/ames_house_prices.csv')\n",
    "houses = pd.read_csv(url)\n",
    "price = houses['price']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6ab50ce",
   "metadata": {},
   "source": [
    "## The method of moments\n",
    "\n",
    "Suppose we have settled on a parametric class and now want to choose its\n",
    "parameters.\n",
    "\n",
    "One simple and general strategy is the **method of moments**.\n",
    "\n",
    "If the class has $ k $ parameters, we\n",
    "\n",
    "1. compute the first $ k $ sample moments of the data,  \n",
    "1. write down the corresponding population moments as functions of the\n",
    "  parameters, and  \n",
    "1. choose the parameters that make the two sets of numbers equal.  \n",
    "\n",
    "\n",
    "In effect we are asking the distribution to reproduce the features of the data\n",
    "that we consider most important.\n",
    "\n",
    "We have already used this idea once, in [Probability Distributions](https://intro.quantecon.org/prob_dist.html), when we fitted a\n",
    "normal distribution to the heights of US adults.\n",
    "\n",
    "The normal distribution has two parameters, so we used two moments: we set\n",
    "$ \\mu $ equal to the sample mean and $ \\sigma $ equal to the sample standard\n",
    "deviation.\n",
    "\n",
    "Let’s apply the same idea to the house price data, using two classes that live\n",
    "on $ (0, \\infty) $ and hence respect the fact that prices are positive.\n",
    "\n",
    "The **lognormal** distribution has parameters $ \\mu $ and $ \\sigma $, with\n",
    "\n",
    "$$\n",
    "\\mathbb{E}[X] = \\exp \\left( \\mu + \\frac{\\sigma^2}{2} \\right)\n",
    "\\qquad \\text{and} \\qquad\n",
    "\\mathbb{V}[X] = \\left[ \\exp(\\sigma^2) - 1 \\right] \\exp(2\\mu + \\sigma^2)\n",
    "$$\n",
    "\n",
    "Setting these equal to the sample mean $ \\bar x $ and sample variance $ s^2 $ and\n",
    "solving gives\n",
    "\n",
    "$$\n",
    "\\hat \\sigma^2 = \\ln \\left( 1 + \\frac{s^2}{\\bar x^2} \\right)\n",
    "\\qquad \\text{and} \\qquad\n",
    "\\hat \\mu = \\ln \\bar x - \\frac{\\hat \\sigma^2}{2}\n",
    "$$\n",
    "\n",
    "The **gamma** distribution has parameters $ \\alpha $ and $ \\beta $, with mean\n",
    "$ \\alpha / \\beta $ and variance $ \\alpha / \\beta^2 $.\n",
    "\n",
    "Solving in the same way is easier here:\n",
    "\n",
    "$$\n",
    "\\hat \\alpha = \\frac{\\bar x^2}{s^2}\n",
    "\\qquad \\text{and} \\qquad\n",
    "\\hat \\beta = \\frac{\\bar x}{s^2}\n",
    "$$\n",
    "\n",
    "Let’s implement all three fits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22f4f783",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def fit_normal(sample):\n",
    "    return scipy.stats.norm(sample.mean(), sample.std())\n",
    "\n",
    "def fit_lognormal(sample):\n",
    "    m, v = sample.mean(), sample.var()\n",
    "    σ_squared = np.log(1 + v / m**2)\n",
    "    μ = np.log(m) - σ_squared / 2\n",
    "    return scipy.stats.lognorm(s=np.sqrt(σ_squared), scale=np.exp(μ))\n",
    "\n",
    "def fit_gamma(sample):\n",
    "    m, v = sample.mean(), sample.var()\n",
    "    return scipy.stats.gamma(a=m**2 / v, scale=v / m)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "275c48cb",
   "metadata": {},
   "source": [
    "Each function returns a distribution object of the kind we worked with in\n",
    "[Probability Distributions](https://intro.quantecon.org/prob_dist.html).\n",
    "\n",
    "Let’s check that the fitted lognormal reproduces the mean and variance of the\n",
    "data, as it was constructed to do."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b42084e",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "u = fit_lognormal(price)\n",
    "u.mean(), price.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57e6baf7",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "u.var(), price.var()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9ba1d6d",
   "metadata": {},
   "source": [
    "Now let’s plot the three fitted densities against a histogram of the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "416a56f3",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fits = {'normal': fit_normal(price),\n",
    "        'lognormal': fit_lognormal(price),\n",
    "        'gamma': fit_gamma(price)}\n",
    "\n",
    "x_grid = np.linspace(0, price.max(), 400)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.hist(price, bins=50, density=True, alpha=0.25, color='C0')\n",
    "for label, u in fits.items():\n",
    "    ax.plot(x_grid, u.pdf(x_grid), lw=2, alpha=0.8, label=label)\n",
    "ax.set_xlabel('sale price (US$)')\n",
    "ax.set_ylabel('density')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61b53916",
   "metadata": {},
   "source": [
    "The normal density is visibly wrong: it is symmetric, while the data are not,\n",
    "and it puts weight on negative prices.\n",
    "\n",
    "The other two look plausible.\n",
    "\n",
    "To choose between them we need something sharper than a glance at a figure.\n",
    "\n",
    "\n",
    "<a id='qq-plots'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4de37867",
   "metadata": {},
   "source": [
    "## Q-Q plots\n",
    "\n",
    "A **Q-Q plot** (short for quantile-quantile plot) compares two distributions by\n",
    "plotting their quantiles against each other.\n",
    "\n",
    "To compare a sample with a fitted distribution, we sort the data\n",
    "\n",
    "$$\n",
    "x_{(1)} \\leq x_{(2)} \\leq \\cdots \\leq x_{(n)}\n",
    "$$\n",
    "\n",
    "Which quantile does $ x_{(i)} $ estimate?\n",
    "\n",
    "Recall from [Observed Distributions](https://intro.quantecon.org/observed_distributions.html) that the ECDF steps up by $ 1/n $ at\n",
    "each observation.\n",
    "\n",
    "At $ x_{(i)} $ it steps up from $ (i-1)/n $ to $ i/n $.\n",
    "\n",
    "In other words, a fraction $ (i-1)/n $ of the observations lie strictly below\n",
    "$ x_{(i)} $, while a fraction $ i/n $ lie at or below it.\n",
    "\n",
    "So the data do not single out one order for $ x_{(i)} $ to estimate — they\n",
    "supply a small interval of them.\n",
    "\n",
    "The usual compromise is to split the difference and treat $ x_{(i)} $ as an\n",
    "estimate of the quantile of order $ (i - 0.5)/n $.\n",
    "\n",
    "This choice also avoids a problem at the top of the sample.\n",
    "\n",
    "Had we used $ i/n $, the largest observation would be matched with the quantile\n",
    "of order $ n/n = 1 $, which is $ +\\infty $ for the normal, the lognormal and the\n",
    "other unbounded distributions we work with.\n",
    "\n",
    "If the fitted distribution is a good description of the data, then $ x_{(i)} $\n",
    "should be close to the corresponding quantile of that distribution, which is\n",
    "\n",
    "$$\n",
    "F^{-1} \\left( \\frac{i - 0.5}{n} \\right)\n",
    "$$\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Other conventions are in use, such as $ i/(n+1) $ and $ (i - 0.375)/(n + 0.25) $.\n",
    "\n",
    "They are called *plotting positions*, and the choice between them affects only\n",
    "the two ends of the figure, by an amount that shrinks as $ n $ grows.\n",
    "\n",
    "So we plot the fitted quantiles on the horizontal axis and the sample values on\n",
    "the vertical axis.\n",
    "\n",
    "A good fit puts the points on the 45 degree line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0ab27aa",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def qq_plot(sample, u, ax, **kwargs):\n",
    "    \"Plot sample quantiles against the quantiles of the distribution u.\"\n",
    "    x_sorted = np.sort(sample)\n",
    "    n = len(x_sorted)\n",
    "    p = (np.arange(1, n+1) - 0.5) / n\n",
    "    ax.plot(u.ppf(p), x_sorted, '.', ms=3, alpha=0.6, **kwargs)\n",
    "    lo, hi = u.ppf(p[0]), u.ppf(p[-1])\n",
    "    ax.plot([lo, hi], [lo, hi], 'k--', lw=2)\n",
    "    ax.set_xlabel('fitted quantiles')\n",
    "    ax.set_ylabel('sample quantiles')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4899f155",
   "metadata": {},
   "source": [
    "Let’s start with a case where we expect a good fit.\n",
    "\n",
    "In [Observed Distributions](https://intro.quantecon.org/observed_distributions.html) we found that the heights of US adult women\n",
    "have sample skewness and excess kurtosis close to zero."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00a8b2b2",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "url = ('https://github.com/QuantEcon/data-lectures/raw/main/'\n",
    "       'lectures/us_adult_heights.csv')\n",
    "heights = pd.read_csv(url)\n",
    "female = heights[heights['sex'] == 'female']['height_cm']\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "qq_plot(female, fit_normal(female), ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8117105e",
   "metadata": {},
   "source": [
    "The points lie almost exactly on the line, apart from mild wandering at the two\n",
    "ends, where the sample contains few observations and the quantile estimates are\n",
    "noisy.\n",
    "\n",
    "Now let’s try the house prices against a fitted normal."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f499f54a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "qq_plot(price, fit_normal(price), ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "447cd1eb",
   "metadata": {},
   "source": [
    "This is a very different picture.\n",
    "\n",
    "The points curve away from the line, and the departure has a clear meaning:\n",
    "towards the right, the sample quantiles are far larger than the fitted ones, so\n",
    "the data have a longer right tail than the normal distribution allows.\n",
    "\n",
    "The shape of a departure tells us how the fit fails.\n",
    "\n",
    "- Points curving upwards, as here, indicate skewness to the right.  \n",
    "- Points forming an S-shape — below the line on the left, above it on the\n",
    "  right — indicate that *both* tails of the data are heavier than the fitted\n",
    "  distribution.  \n",
    "\n",
    "\n",
    "Let’s check the second case by taking logs, which we know makes the house price\n",
    "data roughly symmetric."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5abf6c3",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "log_price = np.log(price)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "qq_plot(log_price, fit_normal(log_price), ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa93577d",
   "metadata": {},
   "source": [
    "The curvature is gone, confirming what the sample skewness told us in\n",
    "[Observed Distributions](https://intro.quantecon.org/observed_distributions.html).\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">The `statsmodels` package provides `sm.qqplot`, which produces such figures in\n",
    "one line, comparing the data with a normal distribution by default.\n",
    "\n",
    "We have built our own instead, partly because the construction is worth\n",
    "understanding and partly because our version compares the data with any\n",
    "distribution we choose, as we do below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b2667ea",
   "metadata": {},
   "source": [
    "## The Kolmogorov-Smirnov statistic\n",
    "\n",
    "Q-Q plots are informative but they require us to judge a picture.\n",
    "\n",
    "Sometimes we want a single number that measures how far the data are from a\n",
    "fitted distribution.\n",
    "\n",
    "One natural measure compares the ECDF of the data, which we met in\n",
    "[Observed Distributions](https://intro.quantecon.org/observed_distributions.html), with the CDF of the fitted distribution.\n",
    "\n",
    "The **Kolmogorov-Smirnov statistic** is the largest vertical gap between them:\n",
    "\n",
    "$$\n",
    "D = \\max_x \\, | F_n(x) - F(x) |\n",
    "$$\n",
    "\n",
    "Since $ F_n $ only jumps at the observations, we can compute $ D $ by checking the\n",
    "gap immediately before and after each jump."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e79aafe",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def ks_statistic(sample, u):\n",
    "    \"Largest vertical distance between the ECDF of the sample and the CDF of u.\"\n",
    "    x_sorted = np.sort(sample)\n",
    "    n = len(x_sorted)\n",
    "    F = u.cdf(x_sorted)\n",
    "    above = np.arange(1, n+1) / n - F     # gap just after each jump\n",
    "    below = F - np.arange(0, n) / n       # gap just before each jump\n",
    "    return max(above.max(), below.max())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a081662b",
   "metadata": {},
   "source": [
    "Let’s see what it measures, by drawing the ECDF and the fitted CDF for the log\n",
    "prices together with the gap that attains the maximum."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea13e664",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "u = fit_normal(log_price)\n",
    "x_sorted = np.sort(log_price)\n",
    "n = len(x_sorted)\n",
    "F = u.cdf(x_sorted)\n",
    "\n",
    "# locate the largest gap\n",
    "gaps = np.maximum(np.arange(1, n+1) / n - F, F - np.arange(0, n) / n)\n",
    "i = gaps.argmax()\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.step(x_sorted, np.arange(1, n+1) / n, where='post', lw=2, label='ECDF')\n",
    "x_grid = np.linspace(x_sorted[0], x_sorted[-1], 200)\n",
    "ax.plot(x_grid, u.cdf(x_grid), 'k--', lw=2, alpha=0.7, label='fitted normal CDF')\n",
    "ax.vlines(x_sorted[i], F[i], (i+1) / n, color='C3', lw=3, label='largest gap')\n",
    "ax.set_xlabel('log of sale price')\n",
    "ax.set_ylabel('probability')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2e67e25",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "ks_statistic(log_price, u)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91eb43af",
   "metadata": {},
   "source": [
    "The statistic is small, which tells us that the ECDF never strays far from the\n",
    "fitted CDF.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">You might expect that we can now *test* whether the data came from the fitted\n",
    "distribution, by asking whether $ D $ is larger than chance alone would produce.\n",
    "\n",
    "This is exactly what the Kolmogorov-Smirnov test does, and `scipy` implements\n",
    "it as `scipy.stats.kstest`.\n",
    "\n",
    "We do not pursue it here, because it requires knowing how $ D $ behaves when the\n",
    "distribution really is correct, which needs more theory than we have developed.\n",
    "\n",
    "There is also a trap: the usual theory assumes that the distribution is\n",
    "specified in advance, whereas we chose its parameters using the same data.\n",
    "\n",
    "\n",
    "<a id='choosing-class'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cd84c48",
   "metadata": {},
   "source": [
    "## Choosing a parametric class\n",
    "\n",
    "We now have a way to choose between candidate classes.\n",
    "\n",
    "For each class, we fit the parameters by the method of moments and then\n",
    "compute $ D $.\n",
    "\n",
    "The class with the smallest $ D $ is the one whose CDF stays closest to the data.\n",
    "\n",
    "Let’s apply this to the house prices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71c01b83",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "results = pd.Series({label: ks_statistic(price, u) for label, u in fits.items()})\n",
    "results.sort_values()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5073d53b",
   "metadata": {},
   "source": [
    "The lognormal distribution wins, with the gamma second and the normal a distant\n",
    "third.\n",
    "\n",
    "This agrees with what we found in [Observed Distributions](https://intro.quantecon.org/observed_distributions.html), where taking\n",
    "logs of the price data produced a sample skewness of almost exactly zero.\n",
    "\n",
    "Here are the three fitted CDFs against the ECDF of the data, which shows the\n",
    "same ranking."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6611cc14",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.step(np.sort(price), np.arange(1, len(price)+1) / len(price),\n",
    "        where='post', color='k', lw=2, label='ECDF')\n",
    "x_grid = np.linspace(price.min(), price.max(), 400)\n",
    "for label, u in fits.items():\n",
    "    ax.plot(x_grid, u.cdf(x_grid), lw=2, alpha=0.7, label=label)\n",
    "ax.set_xlabel('sale price (US$)')\n",
    "ax.set_ylabel('probability')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ff98511",
   "metadata": {},
   "source": [
    "Three warnings are in order.\n",
    "\n",
    "First, the comparison is only fair when the classes have the same number of\n",
    "parameters, as they do here.\n",
    "\n",
    "A class with more parameters can bend itself closer to any data set, and $ D $\n",
    "does not charge it for the privilege.\n",
    "\n",
    "In particular, if one class is a special case of another, the larger class\n",
    "can never do worse.\n",
    "\n",
    "Second, $ D $ is most sensitive in the middle of the distribution, where the CDF\n",
    "is changing quickly, and least sensitive in the tails.\n",
    "\n",
    "If we care mainly about extreme outcomes, as we often do in economics and\n",
    "finance, then a small $ D $ can be misleading.\n",
    "\n",
    "Third, the winner is only the best of the candidates we happened to try.\n",
    "\n",
    "Nothing here tells us that the winning class is a good description of the data\n",
    "— only that it is better than the alternatives.\n",
    "\n",
    "We take up that point below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "047d2d9d",
   "metadata": {},
   "source": [
    "## Count data\n",
    "\n",
    "So far our data have been continuous.\n",
    "\n",
    "The method of moments applies just as well to discrete data.\n",
    "\n",
    "Consider the **Poisson** distribution, which we met in [Probability Distributions](https://intro.quantecon.org/prob_dist.html) as a\n",
    "model for the number of events in a fixed interval.\n",
    "\n",
    "It has a single parameter $ \\lambda $, and its mean is $ \\lambda $, so the method\n",
    "of moments gives\n",
    "\n",
    "$$\n",
    "\\hat \\lambda = \\bar x\n",
    "$$\n",
    "\n",
    "Let’s try it on the number of goals scored in football matches.\n",
    "\n",
    "The data set contains the full-time score of every match in ten seasons of the\n",
    "English Premier League."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "062a4cb4",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "url = ('https://github.com/QuantEcon/data-lectures/raw/main/'\n",
    "       'lectures/epl_match_goals.csv')\n",
    "matches = pd.read_csv(url)\n",
    "matches.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74f7f444",
   "metadata": {},
   "source": [
    "We are interested in the total number of goals scored in each match."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf9a9b49",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "goals = matches['home_goals'] + matches['away_goals']\n",
    "len(goals), goals.mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3014f5b7",
   "metadata": {},
   "source": [
    "The Poisson distribution has the unusual property that its variance equals its\n",
    "mean.\n",
    "\n",
    "This gives us a diagnostic that we can apply before fitting anything."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3933d22b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "goals.mean(), goals.var()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c8a472e",
   "metadata": {},
   "source": [
    "These are close, which is encouraging.\n",
    "\n",
    "Let’s fit the distribution and compare the fitted probabilities with the\n",
    "observed frequencies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d493f861",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "u = scipy.stats.poisson(goals.mean())\n",
    "\n",
    "counts = goals.value_counts().sort_index()\n",
    "frequencies = counts / counts.sum()\n",
    "S = np.arange(counts.index.max() + 1)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.bar(counts.index, frequencies, alpha=0.4, label='observed frequency')\n",
    "ax.plot(S, u.pmf(S), linestyle='', marker='o', color='C1', label='fitted Poisson')\n",
    "ax.vlines(S, 0, u.pmf(S), lw=0.5, color='C1')\n",
    "ax.set_xlabel('goals per match')\n",
    "ax.set_ylabel('probability')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad60c503",
   "metadata": {},
   "source": [
    "The fit is good.\n",
    "\n",
    "This is a well-known empirical regularity, and the reason for it is worth\n",
    "stating: goals are rare events, arising at a roughly constant rate over the\n",
    "course of a match, and largely independently of each other.\n",
    "\n",
    "Those are exactly the conditions under which the Poisson distribution arises."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0baa5661",
   "metadata": {},
   "source": [
    "## When the normal fails\n",
    "\n",
    "When we [compared classes](#choosing-class) above, we took a list of\n",
    "candidate classes, fitted each one to the data, and kept the one with the\n",
    "smallest KS distance.\n",
    "\n",
    "Such a procedure always produces a winner.\n",
    "\n",
    "But it is important to remember that the winner can still be a poor description\n",
    "of the data, since it is only the best of the candidates we happened to try.\n",
    "\n",
    "The remedy is to look at the fit as well as ranking it, and, when it fails, to\n",
    "let the way it fails suggest a better candidate.\n",
    "\n",
    "Let’s see how this works, returning to the monthly returns on Amazon shares that\n",
    "we studied in [Observed Distributions](https://intro.quantecon.org/observed_distributions.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4688902",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "data = yf.download('AMZN', '2000-1-1', '2024-1-1', interval='1mo')\n",
    "prices = data['Close']['AMZN']\n",
    "returns = prices.pct_change().dropna() * 100"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24ffed3b",
   "metadata": {},
   "source": [
    "Returns take both signs, so of our continuous classes only the normal is\n",
    "available.\n",
    "\n",
    "Let’s look at the Q-Q plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28ca1f20",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "qq_plot(returns, fit_normal(returns), ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10baf366",
   "metadata": {},
   "source": [
    "This is the S-shape described above: the smallest returns are more negative\n",
    "than the fitted normal predicts, and the largest are more positive.\n",
    "\n",
    "In other words, both tails of the data are heavier than the normal distribution\n",
    "allows.\n",
    "\n",
    "Now let’s compute the KS statistic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9121736f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "ks_statistic(returns, fit_normal(returns))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b438071e",
   "metadata": {},
   "source": [
    "Taken on its own, the number looks unremarkable.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Values of $ D $ should not be compared across data sets of different size.\n",
    "\n",
    "Even when the fitted distribution is exactly right, $ D $ shrinks as $ n $ grows,\n",
    "so a small value from a small sample means less than the same value from a\n",
    "large one.\n",
    "\n",
    "The point here is not that $ D $ is smaller or larger than some earlier number,\n",
    "but that it gives no hint of the trouble that the Q-Q plot displays so\n",
    "plainly.\n",
    "\n",
    "This illustrates the second warning above.\n",
    "\n",
    "The normal distribution describes the middle of the return data reasonably\n",
    "well, and that is the region the KS statistic looks at.\n",
    "\n",
    "The failure is in the tails, and the tails are precisely what a study of asset\n",
    "returns cares about, since they contain the large losses.\n",
    "\n",
    "The lesson is that a single summary number is never a substitute for looking at\n",
    "the data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a67dad3",
   "metadata": {},
   "source": [
    "### A heavier-tailed candidate\n",
    "\n",
    "The Q-Q plot did more than tell us that the normal distribution fails.\n",
    "\n",
    "It told us *how* it fails: the data have heavier tails than the fitted normal.\n",
    "\n",
    "That points to a remedy, which is to try a class with heavier tails.\n",
    "\n",
    "One such class is the **Student’s t distributions**, which are symmetric and\n",
    "bell-shaped like the normal but carry an additional parameter $ \\nu > 0 $, called\n",
    "the *degrees of freedom*, governing the weight in the tails.\n",
    "\n",
    "Small values of $ \\nu $ produce heavy tails, and as $ \\nu \\to \\infty $ the\n",
    "distribution converges to the normal.\n",
    "\n",
    "Shifting and scaling gives us a three-parameter class, so the method of moments\n",
    "calls for three moments.\n",
    "\n",
    "The first two are the mean and the variance, as before.\n",
    "\n",
    "The third moment is of no use here, because every member of the class is\n",
    "symmetric and hence has zero skewness, whatever $ \\nu $ may be.\n",
    "\n",
    "So we use the fourth instead, exploiting the fact that a member of this class\n",
    "has excess kurtosis $ 6/(\\nu - 4) $ when $ \\nu > 4 $.\n",
    "\n",
    "Matching it to the sample excess kurtosis $ \\hat K $ gives\n",
    "\n",
    "$$\n",
    "\\hat \\nu = 4 + \\frac{6}{\\hat K}\n",
    "$$\n",
    "\n",
    "and the variance $ \\nu \\sigma^2 / (\\nu - 2) $ then pins down the scale."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c010ea14",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def fit_t(sample):\n",
    "    m, s = sample.mean(), sample.std()\n",
    "    ν = 4 + 6 / scipy.stats.kurtosis(sample)\n",
    "    return scipy.stats.t(df=ν, loc=m, scale=s * np.sqrt((ν - 2) / ν))\n",
    "\n",
    "u = fit_t(returns)\n",
    "u.kwds['df']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e11b417b",
   "metadata": {},
   "source": [
    "Let’s see whether it does better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c35fca85",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "qq_plot(returns, u, ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fc88eeb",
   "metadata": {},
   "source": [
    "The systematic S-shape is gone.\n",
    "\n",
    "Apart from a handful of the most extreme observations, where the fitted\n",
    "quantiles now overshoot slightly, the points sit close to the line.\n",
    "\n",
    "The KS distance falls by about 40% as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43d2a342",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "ks_statistic(returns, u)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2172d0dc",
   "metadata": {},
   "source": [
    "So it is not true that nothing fits these data — we simply had not yet tried a\n",
    "class that allows for heavy tails.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">We should not put too much weight on the fitted value of $ \\nu $.\n",
    "\n",
    "Our estimate of it came from the sample kurtosis, which is a fourth moment, and\n",
    "higher moments are estimated poorly precisely when the tails are heavy.\n",
    "\n",
    "Fitting this distribution by maximum likelihood instead, as we do in\n",
    "[Maximum Likelihood Estimation](https://intro.quantecon.org/mle_intro.html), gives $ \\nu \\approx 3.6 $ rather than $ 5.8 $, and a smaller KS distance\n",
    "again.\n",
    "\n",
    "The method of moments is simple and general, but it is not always the best use\n",
    "of the data.\n",
    "\n",
    "Distributions with heavy tails, and the ways in which they change how we think\n",
    "about risk, are the subject of [Heavy-Tailed Distributions](https://intro.quantecon.org/heavy_tails.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "794370b2",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "The next data set records every earthquake of magnitude 5 and above in the\n",
    "region around Japan between 2000 and 2024, as reported by the\n",
    "[US Geological Survey](https://earthquake.usgs.gov/earthquakes/search/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "712b66dd",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "url = ('https://github.com/QuantEcon/data-lectures/raw/main/'\n",
    "       'lectures/japan_earthquakes.csv')\n",
    "quakes = pd.read_csv(url)\n",
    "quakes.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78cf1ca5",
   "metadata": {},
   "source": [
    "## Exercise 8.1\n",
    "\n",
    "Earthquakes are often modeled as arriving randomly and independently at some\n",
    "constant rate.\n",
    "\n",
    "If that is true, then the time between successive earthquakes is exponentially\n",
    "distributed.\n",
    "\n",
    "Using the data above, compute the time in days between successive earthquakes,\n",
    "fit an exponential distribution by the method of moments, and assess the fit.\n",
    "\n",
    "(The exponential distribution has one parameter $ \\lambda $ and mean $ 1/\\lambda $.)\n",
    "\n",
    "Does the model hold up?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc4c8257",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "Here is one solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "117b499a",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "times = pd.to_datetime(quakes['time'], format='ISO8601')\n",
    "gaps = times.diff().dropna().dt.total_seconds() / (60 * 60 * 24)\n",
    "\n",
    "u = scipy.stats.expon(scale=gaps.mean())\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "qq_plot(gaps, u, ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bbcf100",
   "metadata": {},
   "source": [
    "The fit fails badly, with the largest gaps far longer than the exponential\n",
    "distribution predicts.\n",
    "\n",
    "A second diagnostic makes the problem clearer.\n",
    "\n",
    "For the exponential distribution the standard deviation equals the mean."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2c55595",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "gaps.mean(), gaps.std()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abefa47a",
   "metadata": {},
   "source": [
    "The standard deviation is around half again the mean, so the data are much more\n",
    "variable than the model allows.\n",
    "\n",
    "The reason is that earthquakes are *not* independent.\n",
    "\n",
    "Large earthquakes are followed by aftershocks, so events arrive in clusters,\n",
    "with long quiet periods in between.\n",
    "\n",
    "We can see this directly by counting events per month."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f239d76",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "monthly = quakes.set_index(times).resample('MS').size()\n",
    "monthly.mean(), monthly.var()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae38772d",
   "metadata": {},
   "source": [
    "If the arrivals were Poisson, these two numbers would be roughly equal.\n",
    "\n",
    "Instead the variance is many times the mean, which is the signature of\n",
    "clustering.\n",
    "\n",
    "This connects to the discussion of independence in\n",
    "[Observed Distributions](https://intro.quantecon.org/observed_distributions.html): a sample tells us about a distribution only when\n",
    "its observations bring new information, and an aftershock tells us mostly what\n",
    "the main shock already did."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d88acba9",
   "metadata": {},
   "source": [
    "## Exercise 8.2\n",
    "\n",
    "In [Observed Distributions](https://intro.quantecon.org/observed_distributions.html) we found that the ages at death in Japan have\n",
    "sample skewness of about $ -1.6 $.\n",
    "\n",
    "Fit a normal distribution to that data by the method of moments and use a Q-Q\n",
    "plot to display the failure.\n",
    "\n",
    "Which way do the points bend, and why?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04de5510",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "Here is one solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d24eeb3",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "url = ('https://github.com/QuantEcon/data-lectures/raw/main/'\n",
    "       'lectures/japan_deaths_by_age.csv')\n",
    "deaths = pd.read_csv(url)\n",
    "age_at_death = np.repeat(deaths['age'], deaths['deaths_total'])\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "qq_plot(age_at_death, fit_normal(age_at_death), ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aed3f9a7",
   "metadata": {},
   "source": [
    "The points bend downwards, which is the mirror image of the house price figure.\n",
    "\n",
    "At the left-hand end the sample quantiles fall well below the fitted ones,\n",
    "because the data have a long left tail of deaths at young ages that the normal\n",
    "distribution cannot reproduce.\n",
    "\n",
    "The figure also shows a second, unrelated problem: the points run flat along\n",
    "$ y = 100 $ at the right-hand end.\n",
    "\n",
    "That is the “100 and over” category discussed in [Observed Distributions](https://intro.quantecon.org/observed_distributions.html),\n",
    "which caps every age at 100.\n",
    "\n",
    "A Q-Q plot displays such recording conventions very clearly, since they show up\n",
    "as flat segments where many observations share a single value."
   ]
  }
 ],
 "metadata": {
  "date": 1795846195.8794017,
  "filename": "fitting_distributions.md",
  "kernelspec": {
   "display_name": "Python",
   "language": "python3",
   "name": "python3"
  },
  "title": "Fitting Distributions to Data"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}