{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9e4009d3",
   "metadata": {},
   "source": [
    "$$\n",
    "\\newcommand{\\argmax}{arg\\,max}\n",
    "\\newcommand{\\argmin}{arg\\,min}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "197132c9",
   "metadata": {},
   "source": [
    "\n",
    "<a id='observed-distributions'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "993045ab",
   "metadata": {},
   "source": [
    "# Observed Distributions\n",
    "\n",
    "\n",
    "<a id='index-0'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c637938b",
   "metadata": {},
   "source": [
    "## Outline\n",
    "\n",
    "In the lecture on [probability distributions](https://intro.quantecon.org/prob_dist.html) we studied\n",
    "probability distributions, which are mathematical objects.\n",
    "\n",
    "In this lecture we turn to observed data — sets of numbers that we measure or\n",
    "collect.\n",
    "\n",
    "We discuss how to summarize and visualize such data, and how observed data\n",
    "connects back to probability distributions.\n",
    "\n",
    "A third lecture, [Fitting Distributions to Data](https://intro.quantecon.org/fitting_distributions.html), then takes up the question of\n",
    "which probability distribution best describes a given data set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44b3a2cc",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "!pip install yfinance  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07fc70b7",
   "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",
    "import seaborn as sns\n",
    "\n",
    "np.set_printoptions(legacy='1.25')   # print scalars as plain numbers"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5641c090",
   "metadata": {},
   "source": [
    "Sometimes we refer to observed data or measurements as “distributions”.\n",
    "\n",
    "For example, let’s say we observe the income of 10 people over a year:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "421c56d4",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "data = [['Hiroshi', 1200], \n",
    "        ['Ako', 1210], \n",
    "        ['Emi', 1400],\n",
    "        ['Daiki', 990],\n",
    "        ['Chiyo', 1530],\n",
    "        ['Taka', 1210],\n",
    "        ['Katsuhiko', 1240],\n",
    "        ['Daisuke', 1124],\n",
    "        ['Yoshi', 1330],\n",
    "        ['Rie', 1340]]\n",
    "\n",
    "df = pd.DataFrame(data, columns=['name', 'income'])\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c0cd15c",
   "metadata": {},
   "source": [
    "In this situation, we might refer to the set of their incomes as the “income distribution.”\n",
    "\n",
    "The terminology is confusing because this set is not a probability distribution\n",
    "— it’s just a collection of numbers.\n",
    "\n",
    "However, as we will see, there are connections between observed distributions (i.e., sets of\n",
    "numbers like the income distribution above) and probability distributions.\n",
    "\n",
    "Below we explore some observed distributions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cc7096a",
   "metadata": {},
   "source": [
    "## Sample moments\n",
    "\n",
    "Suppose we have an observed distribution with values $ \\{x_1, \\ldots, x_n\\} $\n",
    "\n",
    "The **sample mean** of this distribution is defined as\n",
    "\n",
    "$$\n",
    "\\bar x = \\frac{1}{n} \\sum_{i=1}^n x_i\n",
    "$$\n",
    "\n",
    "The **sample variance** is defined as\n",
    "\n",
    "$$\n",
    "s^2 = \\frac{1}{n} \\sum_{i=1}^n (x_i - \\bar x)^2\n",
    "$$\n",
    "\n",
    "and the **sample standard deviation** $ s $ is its square root.\n",
    "\n",
    "For the income distribution given above, we can calculate these numbers via"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b640dfa",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x = df['income']\n",
    "x.mean(), x.var(), x.std()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "356ba162",
   "metadata": {},
   "source": [
    "Each of these statistics is the sample counterpart of one of the population\n",
    "quantities defined in [Probability Distributions](https://intro.quantecon.org/prob_dist.html): we replace the probability distribution\n",
    "by the observed data, weighting each observation equally.\n",
    "\n",
    "The same idea extends to higher moments.\n",
    "\n",
    "The **sample skewness** and **sample kurtosis** are\n",
    "\n",
    "$$\n",
    "\\hat S = \\frac{1}{n} \\sum_{i=1}^n \\left( \\frac{x_i - \\bar x}{s} \\right)^3\n",
    "\\qquad \\text{and} \\qquad\n",
    "\\hat K = \\frac{1}{n} \\sum_{i=1}^n \\left( \\frac{x_i - \\bar x}{s} \\right)^4\n",
    "$$\n",
    "\n",
    "and the sample excess kurtosis is $ \\hat K - 3 $.\n",
    "\n",
    "Recall from [Probability Distributions](https://intro.quantecon.org/prob_dist.html) that a normal distribution has skewness zero and\n",
    "excess kurtosis zero.\n",
    "\n",
    "This gives us a first, purely numerical, way to ask whether a data set looks\n",
    "normal.\n",
    "\n",
    "Let’s try it on the heights of US adult women, which we saw were well described\n",
    "by a normal distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af565a81",
   "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",
    "scipy.stats.skew(female), scipy.stats.kurtosis(female)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36fae78a",
   "metadata": {},
   "source": [
    "Both numbers are close to zero, which is consistent with what we saw in the\n",
    "figures.\n",
    "\n",
    "Now let’s look at a data set that is far from normal.\n",
    "\n",
    "The next cell reads in the sale prices of 2,930 houses sold in Ames, Iowa\n",
    "between 2006 and 2010, along with a few characteristics of each house\n",
    "[[De Cock, 2011](https://intro.quantecon.org/zreferences.html#id282)]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ab979c3",
   "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",
    "houses.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d272ef0",
   "metadata": {},
   "source": [
    "Let’s compute the same statistics for the sale prices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41880b52",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "price = houses['price']\n",
    "scipy.stats.skew(price), scipy.stats.kurtosis(price)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ce77ce3",
   "metadata": {},
   "source": [
    "The skewness is large and positive, telling us that the data has a long right\n",
    "tail — a small number of houses sell for far more than the typical price.\n",
    "\n",
    "The excess kurtosis is also large, telling us that extreme values are much more\n",
    "common than they would be for a normal distribution.\n",
    "\n",
    "We saw exactly this combination in [Probability Distributions](https://intro.quantecon.org/prob_dist.html) when we looked at the\n",
    "lognormal distribution.\n",
    "\n",
    "That suggests taking logarithms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9adaa550",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "log_price = np.log(price)\n",
    "scipy.stats.skew(log_price), scipy.stats.kurtosis(log_price)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "628339c2",
   "metadata": {},
   "source": [
    "The skewness is now almost exactly zero.\n",
    "\n",
    "In other words, the *logarithm* of the sale price looks far more normal than the\n",
    "sale price itself, which is the defining property of the lognormal distribution.\n",
    "\n",
    "Our last example runs in the opposite direction.\n",
    "\n",
    "The next cell reads the number of deaths in Japan in 2023 at each single year of\n",
    "age, from the [World Population\n",
    "Prospects](https://population.un.org/wpp/) of the United Nations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "901303c0",
   "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",
    "deaths.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e496f88",
   "metadata": {},
   "source": [
    "The data arrive as counts, so we expand them into a data set with one\n",
    "observation per death."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43e05b05",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "age_at_death = np.repeat(deaths['age'], deaths['deaths_total'])\n",
    "len(age_at_death)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a1d4f08",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "scipy.stats.skew(age_at_death), scipy.stats.kurtosis(age_at_death)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61578cdc",
   "metadata": {},
   "source": [
    "Now the skewness is large and *negative*.\n",
    "\n",
    "Deaths cluster at high ages, with a long tail running down towards zero — the\n",
    "mirror image of the house price data.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">The last age is recorded as “100 and over”, so every death above age 100 is\n",
    "counted as 100.\n",
    "\n",
    "This is not a negligible group in Japan: it accounts for 3.3% of all deaths and\n",
    "5.7% of female deaths.\n",
    "\n",
    "We will see it below as a spike at the right-hand end of the histograms, which\n",
    "is an artifact of how the data are recorded rather than a feature of the data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8d083e0",
   "metadata": {},
   "source": [
    "## Exercise 7.1\n",
    "\n",
    "If you try to check that the formulas given above for the sample mean and sample\n",
    "variance produce the same numbers, you will see that the variance isn’t quite\n",
    "right.  This is because Pandas uses $ 1/(n-1) $ instead of $ 1/n $ as the term at the\n",
    "front of the variance. (Some books define the sample variance this way.)\n",
    "Confirm.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">The same issue arises with skewness and kurtosis, where different conventions\n",
    "adjust the estimates in different ways.\n",
    "\n",
    "The Pandas methods `x.skew()` and `x.kurt()` apply such adjustments, so they do\n",
    "not agree exactly with the formulas above, while `scipy.stats.skew` and\n",
    "`scipy.stats.kurtosis` use the plain $ 1/n $ versions.\n",
    "\n",
    "The differences are small when $ n $ is large.\n",
    "\n",
    "Recall also that `scipy.stats.kurtosis` returns $ \\hat K - 3 $ rather than\n",
    "$ \\hat K $, which is why we read its output as the excess kurtosis."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4b60afc",
   "metadata": {},
   "source": [
    "## Sample quantiles\n",
    "\n",
    "Not every useful summary statistic is a moment.\n",
    "\n",
    "If we sort the observations from smallest to largest, then the **sample\n",
    "$ \\tau $-quantile** is the value below which a fraction $ \\tau $ of the\n",
    "observations fall.\n",
    "\n",
    "The 0.5 quantile is the **sample median** and the 0.25 and 0.75 quantiles are\n",
    "the first and third **sample quartiles**.\n",
    "\n",
    "Here are these values for the income data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "981c4d36",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x.median(), x.quantile(0.25), x.quantile(0.75)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41853ec0",
   "metadata": {},
   "source": [
    "Sample quantiles are useful because they are barely affected by a small number\n",
    "of extreme observations.\n",
    "\n",
    "To see this, let’s replace the largest income in our data set with a very large\n",
    "value and recompute the mean and the median."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e781c1ce",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x_outlier = x.copy()\n",
    "x_outlier.iloc[x.argmax()] = 10_000_000\n",
    "\n",
    "x.mean(), x_outlier.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ddd7b56b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x.median(), x_outlier.median()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed0b3a27",
   "metadata": {},
   "source": [
    "The mean shifts enormously while the median does not move at all.\n",
    "\n",
    "The same issue arises with real data whenever the distribution is skewed.\n",
    "\n",
    "Here are the mean and the median sale price of houses in Ames:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25bf3ff0",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "price.mean(), price.median()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1670be6",
   "metadata": {},
   "source": [
    "The mean exceeds the median by around 13%, pulled up by the expensive houses in\n",
    "the right tail.\n",
    "\n",
    "This is why house prices are almost always reported as medians.\n",
    "\n",
    "For the age at death data the inequality runs the other way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd99d8c4",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "age_at_death.mean(), age_at_death.median()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9713e816",
   "metadata": {},
   "source": [
    "Here the mean is pulled *below* the median, by deaths at young ages.\n",
    "\n",
    "In general, the mean sits on the side of the median towards which the data are\n",
    "skewed.\n",
    "\n",
    "We will return to this point in [Heavy-Tailed Distributions](https://intro.quantecon.org/heavy_tails.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ab5e870",
   "metadata": {},
   "source": [
    "## Visualization\n",
    "\n",
    "Summary statistics compress a data set down to a few numbers.\n",
    "\n",
    "Visualization goes the other way, showing us the whole shape of the data.\n",
    "\n",
    "We will cover\n",
    "\n",
    "- histograms  \n",
    "- empirical distribution functions  \n",
    "- kernel density estimates  \n",
    "- box-and-whisker plots and  \n",
    "- violin plots  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51c67b6e",
   "metadata": {},
   "source": [
    "### Histograms\n",
    "\n",
    "We can histogram the income distribution we just constructed as follows"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d66aa24",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.hist(x, bins=5, density=True, histtype='bar')\n",
    "ax.set_xlabel('income')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57c363ca",
   "metadata": {},
   "source": [
    "Here is a histogram of the Ames house prices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5d14fcc",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.hist(price, bins=50, density=True)\n",
    "ax.set_xlabel('sale price (US$)')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9bee9c4",
   "metadata": {},
   "source": [
    "The long right tail that the skewness told us about is clearly visible.\n",
    "\n",
    "Let’s compare this with the histogram of the log prices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24bafa4b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.hist(log_price, bins=50, density=True)\n",
    "ax.set_xlabel('log of sale price')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18df8b5d",
   "metadata": {},
   "source": [
    "The second histogram is far more symmetric, as the sample skewness led us to expect.\n",
    "\n",
    "Here is the age at death data, which we found to have negative skewness."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecbe1829",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.hist(age_at_death, bins=101, density=True)\n",
    "ax.set_xlabel('age at death')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0dbf436",
   "metadata": {},
   "source": [
    "The long tail now runs to the left, towards zero.\n",
    "\n",
    "Let’s also compare men and women, using the sex-specific counts in the data\n",
    "set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06761630",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "for sex in ('male', 'female'):\n",
    "    ax.hist(deaths['age'], weights=deaths[f'deaths_{sex}'], \n",
    "            bins=101, density=True, alpha=0.6, label=sex)\n",
    "ax.set_xlabel('age at death')\n",
    "ax.set_ylabel('density')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93029beb",
   "metadata": {},
   "source": [
    "The two distributions have a similar shape but the female distribution sits to\n",
    "the right of the male distribution.\n",
    "\n",
    "The median age at death is 82 for men and 88 for women.\n",
    "\n",
    "The spike at the right-hand end is the “100 and over” category discussed above,\n",
    "which is far larger for women.\n",
    "\n",
    "(Notice that we did not need to expand the counts here, since `hist` accepts\n",
    "the counts directly as weights.)\n",
    "\n",
    "Let’s look at another distribution from real data.\n",
    "\n",
    "In particular, we will look at the monthly return on Amazon shares between 2000/1/1 and 2024/1/1.\n",
    "\n",
    "The monthly return is calculated as the percent change in the share price over each month.\n",
    "\n",
    "So we will have one observation for each month."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d02ba4e",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "df = yf.download('AMZN', '2000-1-1', '2024-1-1', interval='1mo')\n",
    "prices = df['Close']\n",
    "x_amazon = prices.pct_change()[1:] * 100\n",
    "x_amazon.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e9fe4be",
   "metadata": {},
   "source": [
    "The first observation is the monthly return (percent change) over January 2000, which was"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcc35550",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x_amazon.iloc[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8db9d0bf",
   "metadata": {},
   "source": [
    "Let’s turn the return observations into an array and histogram it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "483552ef",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.hist(x_amazon, bins=20)\n",
    "ax.set_xlabel('monthly return (percent change)')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3cda3f4",
   "metadata": {},
   "source": [
    "### Empirical cumulative distribution functions\n",
    "\n",
    "A histogram estimates the density of the data.\n",
    "\n",
    "The **empirical cumulative distribution function** (ECDF) does the same job\n",
    "for the CDF.\n",
    "\n",
    "For a sample $ \\{x_1, \\ldots, x_n\\} $ it is defined as\n",
    "\n",
    "$$\n",
    "F_n(x) = \\frac{1}{n} \\sum_{i=1}^n \\mathbb 1 \\{x_i \\leq x\\}\n",
    "$$\n",
    "\n",
    "In words, $ F_n(x) $ is just the fraction of observations that are less than or\n",
    "equal to $ x $.\n",
    "\n",
    "The ECDF is a step function that jumps up by $ 1/n $ at each observation.\n",
    "\n",
    "Here is a function that plots it, obtained by sorting the data and stepping up\n",
    "as we move from left to right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96e91953",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "def plot_ecdf(sample, ax, **kwargs):\n",
    "    x_sorted = np.sort(sample)\n",
    "    n = len(x_sorted)\n",
    "    ax.step(x_sorted, np.arange(1, n+1) / n, where='post', **kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0679413b",
   "metadata": {},
   "source": [
    "Let’s apply it to the house price data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f82a54bf",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "plot_ecdf(price, ax)\n",
    "ax.set_xlabel('sale price (US$)')\n",
    "ax.set_ylabel('ECDF')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e5e7383",
   "metadata": {},
   "source": [
    "Unlike a histogram, the ECDF requires no choice of bin width — it uses the data\n",
    "exactly as they are.\n",
    "\n",
    "This makes it a good tool for comparing a data set with a probability\n",
    "distribution, since we can simply plot the two curves on the same axes.\n",
    "\n",
    "Let’s compare the log prices with the CDF of the normal distribution that has\n",
    "the same mean and standard deviation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "241ba0a6",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "u = scipy.stats.norm(log_price.mean(), log_price.std())\n",
    "x_grid = np.linspace(log_price.min(), log_price.max(), 200)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "plot_ecdf(log_price, ax, label='ECDF of log prices')\n",
    "ax.plot(x_grid, u.cdf(x_grid), 'k--', alpha=0.7, label='normal CDF')\n",
    "ax.set_xlabel('log of sale price')\n",
    "ax.set_ylabel('probability')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9023e843",
   "metadata": {},
   "source": [
    "The two curves are close, although the fit is not perfect.\n",
    "\n",
    "(Seaborn provides `sns.ecdfplot`, which produces the same figure with less code.)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bafa6cd",
   "metadata": {},
   "source": [
    "### Kernel density estimates\n",
    "\n",
    "Kernel density estimates (KDE) provide a simple way to estimate and visualize the density of a distribution.\n",
    "\n",
    "If you are not familiar with KDEs, you can think of them as a smoothed\n",
    "histogram.\n",
    "\n",
    "Let’s have a look at a KDE formed from the Amazon return data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08d17bba",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "sns.kdeplot(x_amazon, ax=ax)\n",
    "ax.set_xlabel('monthly return (percent change)')\n",
    "ax.set_ylabel('KDE')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dcf9826",
   "metadata": {},
   "source": [
    "The smoothness of the KDE is dependent on how we choose the bandwidth."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d47702fe",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "sns.kdeplot(x_amazon, ax=ax, bw_adjust=0.1, alpha=0.5, label=\"bw=0.1\")\n",
    "sns.kdeplot(x_amazon, ax=ax, bw_adjust=0.5, alpha=0.5, label=\"bw=0.5\")\n",
    "sns.kdeplot(x_amazon, ax=ax, bw_adjust=1, alpha=0.5, label=\"bw=1\")\n",
    "ax.set_xlabel('monthly return (percent change)')\n",
    "ax.set_ylabel('KDE')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1931d9fe",
   "metadata": {},
   "source": [
    "When we use a larger bandwidth, the KDE is smoother.\n",
    "\n",
    "A suitable bandwidth is not too smooth (underfitting) or too wiggly (overfitting).\n",
    "\n",
    "Since a KDE is a smoothed histogram, it is often helpful to show the two\n",
    "together.\n",
    "\n",
    "Here is the log sale price data, with the histogram faded into the background."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f997199e",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.hist(log_price, bins=50, density=True, alpha=0.25, color='C0')\n",
    "sns.kdeplot(log_price, ax=ax, color='C0', lw=2)\n",
    "ax.set_xlabel('log of sale price')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31f6dbea",
   "metadata": {},
   "source": [
    "The KDE traces out the shape of the histogram while smoothing away the\n",
    "bin-to-bin variation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fa164e3",
   "metadata": {},
   "source": [
    "### Box-and-whisker plots\n",
    "\n",
    "A box-and-whisker plot (or box plot) summarizes a distribution using the sample\n",
    "quantiles discussed above.\n",
    "\n",
    "The box spans the first and third quartiles, so its width is the interquartile\n",
    "range, and the line inside it is the median.\n",
    "\n",
    "The whiskers extend to the most extreme observations lying within 1.5\n",
    "interquartile ranges of the box, and observations beyond them are plotted\n",
    "individually.\n",
    "\n",
    "Box plots discard a lot of information, which makes them well suited to\n",
    "comparing many groups at once.\n",
    "\n",
    "For example, let’s compare house prices across houses with different numbers of\n",
    "bedrooms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cbc7e4b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "bedroom_counts = (1, 2, 3, 4, 5)\n",
    "groups = [price[houses['bedrooms'] == b] for b in bedroom_counts]\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.boxplot(groups, tick_labels=bedroom_counts)\n",
    "ax.set_xlabel('bedrooms')\n",
    "ax.set_ylabel('sale price (US$)')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9564b1b",
   "metadata": {},
   "source": [
    "The figure carries a warning about reading too much into group averages.\n",
    "\n",
    "Houses with four bedrooms do sell for more than houses with three, but\n",
    "one-bedroom houses have a *higher* median price than two-bedroom houses.\n",
    "\n",
    "Moreover, the spread within every group is far larger than the differences\n",
    "across groups.\n",
    "\n",
    "Evidently the number of bedrooms tells us relatively little about the price of a\n",
    "house.\n",
    "\n",
    "Notice also that the individually plotted points sit almost entirely above the\n",
    "whiskers rather than below them.\n",
    "\n",
    "This is the right skew again, now visible group by group."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c1d53d5",
   "metadata": {},
   "source": [
    "### Exercise 7.2\n",
    "\n",
    "The data set also records the floor area of each house, in square feet, in the\n",
    "column `living_area_sqft`.\n",
    "\n",
    "Split the houses into four groups of equal size according to floor area (the\n",
    "Pandas function `qcut` will do this for you) and produce a box plot of sale\n",
    "price for each group.\n",
    "\n",
    "Is floor area a better predictor of price than the number of bedrooms?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8924e62",
   "metadata": {},
   "source": [
    "### Solution\n",
    "\n",
    "Here is one solution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42f692e2",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "area_quartile = pd.qcut(houses['living_area_sqft'], 4, \n",
    "                        labels=['Q1', 'Q2', 'Q3', 'Q4'])\n",
    "groups = [price[area_quartile == q] for q in ('Q1', 'Q2', 'Q3', 'Q4')]\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.boxplot(groups, tick_labels=['Q1', 'Q2', 'Q3', 'Q4'])\n",
    "ax.set_xlabel('quartile of floor area')\n",
    "ax.set_ylabel('sale price (US$)')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7134a85e",
   "metadata": {},
   "source": [
    "Now the medians increase steadily from one group to the next, and the gaps\n",
    "between the groups are large relative to the spread within them.\n",
    "\n",
    "Floor area is clearly the better predictor.\n",
    "\n",
    "\n",
    "<a id='violin-plots'></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "018f11cc",
   "metadata": {},
   "source": [
    "### Violin plots\n",
    "\n",
    "Another way to display an observed distribution is via a violin plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dd50a26",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.violinplot(x_amazon)\n",
    "ax.set_ylabel('monthly return (percent change)')\n",
    "ax.set_xlabel('KDE')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a2aae00",
   "metadata": {},
   "source": [
    "Violin plots are particularly useful when we want to compare different distributions.\n",
    "\n",
    "For example, let’s compare the monthly returns on Amazon shares with the monthly return on Costco shares."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f155192b",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "df = yf.download('COST', '2000-1-1', '2024-1-1', interval='1mo')\n",
    "prices = df['Close']\n",
    "x_costco = prices.pct_change()[1:] * 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "574fc4d8",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.violinplot([x_amazon['AMZN'], x_costco['COST']])\n",
    "ax.set_ylabel('monthly return (percent change)')\n",
    "ax.set_xlabel('retailers')\n",
    "\n",
    "ax.set_xticks([1, 2])\n",
    "ax.set_xticklabels(['Amazon', 'Costco'])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d2910a1",
   "metadata": {},
   "source": [
    "As a second comparison, let’s return to the age at death data and separate men\n",
    "from women."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "230c8594",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "male_deaths = np.repeat(deaths['age'], deaths['deaths_male'])\n",
    "female_deaths = np.repeat(deaths['age'], deaths['deaths_female'])\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.violinplot([male_deaths, female_deaths], showmedians=True)\n",
    "ax.set_ylabel('age at death')\n",
    "ax.set_xlabel('sex')\n",
    "\n",
    "ax.set_xticks([1, 2])\n",
    "ax.set_xticklabels(['male', 'female'])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78b06edc",
   "metadata": {},
   "source": [
    "The violin plot shows the whole shape of each distribution, rather than the\n",
    "five numbers that a box plot reduces it to.\n",
    "\n",
    "Here that matters: both distributions are strongly left-skewed, with a thin\n",
    "tail of deaths at young ages, and the female distribution is both shifted\n",
    "upwards and more concentrated at the top."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8864b5fb",
   "metadata": {},
   "source": [
    "## Connection to probability distributions\n",
    "\n",
    "Let’s discuss the connection between observed distributions and probability distributions.\n",
    "\n",
    "Sometimes it’s helpful to imagine that an observed distribution is generated by a particular probability distribution.\n",
    "\n",
    "For example, we might look at the returns from Amazon above and imagine that they were generated by a normal distribution.\n",
    "\n",
    "(Even though this is not true, it *might* be a helpful way to think about the data.)\n",
    "\n",
    "Here we match a normal distribution to the Amazon monthly returns by setting the\n",
    "sample mean to the mean of the normal distribution and the sample variance equal\n",
    "to the variance.\n",
    "\n",
    "(This recipe is called the method of moments, and [Fitting Distributions to Data](https://intro.quantecon.org/fitting_distributions.html)\n",
    "develops it in full.)\n",
    "\n",
    "Then we plot the density and the histogram."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3dc5b0e7",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "μ = x_amazon.mean()\n",
    "σ_squared = x_amazon.var()\n",
    "σ = np.sqrt(σ_squared)\n",
    "u = scipy.stats.norm(μ, σ)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab0d5a7c",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x_grid = np.linspace(-50, 65, 200)\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(x_grid, u.pdf(x_grid))\n",
    "ax.hist(x_amazon, density=True, bins=40)\n",
    "ax.set_xlabel('monthly return (percent change)')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfaf4486",
   "metadata": {},
   "source": [
    "The match between the histogram and the density is not bad but also not very good.\n",
    "\n",
    "One reason is that the normal distribution is not really a good fit for this observed data — we will discuss this point again when we talk about [heavy tailed distributions](https://intro.quantecon.org/heavy_tails.html#heavy-tail).\n",
    "\n",
    "Of course, if the data really *is* generated by the normal distribution, then the fit will be better.\n",
    "\n",
    "Let’s see this in action\n",
    "\n",
    "- first we generate random draws from the normal distribution  \n",
    "- then we histogram them and compare with the density.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbc0b4db",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "μ, σ = 0, 1\n",
    "u = scipy.stats.norm(μ, σ)\n",
    "N = 2000  # Number of observations\n",
    "x_draws = u.rvs(N)\n",
    "x_grid = np.linspace(-4, 4, 200)\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(x_grid, u.pdf(x_grid))\n",
    "ax.hist(x_draws, density=True, bins=40)\n",
    "ax.set_xlabel('x')\n",
    "ax.set_ylabel('density')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "129ae875",
   "metadata": {},
   "source": [
    "Note that if you keep increasing $ N $, which is the number of observations, the fit will get better and better.\n",
    "\n",
    "We investigate this convergence in the next section."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed9b2242",
   "metadata": {},
   "source": [
    "## Larger samples\n",
    "\n",
    "Throughout this lecture we have used observed data to say something about an\n",
    "underlying distribution.\n",
    "\n",
    "This only works if a larger sample tells us more.\n",
    "\n",
    "Let’s check that it does, using the ECDF, since it estimates the CDF without\n",
    "requiring us to choose a bin width or a bandwidth.\n",
    "\n",
    "We draw samples of increasing size from a fixed distribution and compare each\n",
    "ECDF with the CDF that generated it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6e4689f",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "u = scipy.stats.lognorm(s=0.5)\n",
    "x_grid = np.linspace(0, 5, 200)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "for n in (10, 100, 1000):\n",
    "    plot_ecdf(u.rvs(n, random_state=1234), ax, alpha=0.7, label=f'$n = {n}$')\n",
    "ax.plot(x_grid, u.cdf(x_grid), 'k--', lw=2, label='true CDF')\n",
    "ax.set_xlabel('x')\n",
    "ax.set_ylabel('probability')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6d27157",
   "metadata": {},
   "source": [
    "The ECDF is ragged when $ n = 10 $ and almost indistinguishable from the true CDF\n",
    "by the time $ n = 1000 $.\n",
    "\n",
    "The sample moments behave the same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3998f0e9",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "for n in (10, 100, 1000, 1_000_000):\n",
    "    x_draws = u.rvs(n, random_state=1234)\n",
    "    print(f'n = {n:>9,}:  sample mean = {x_draws.mean():.4f}')\n",
    "print(f'{\"\":16}population mean = {u.mean():.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e1a40dc",
   "metadata": {},
   "source": [
    "This convergence is a version of the *law of large numbers*, which we discuss\n",
    "in [LLN and CLT](https://intro.quantecon.org/lln_clt_intro.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ceebc43",
   "metadata": {},
   "source": [
    "### The role of independence\n",
    "\n",
    "The convergence above is not automatic.\n",
    "\n",
    "It depends on a property of the sample that is easy to overlook, because\n",
    "`rvs` supplies it silently: the draws it returns are **independent**.\n",
    "\n",
    "To see why this matters, suppose we take a single draw $ X $ from our\n",
    "distribution and then set\n",
    "\n",
    "$$\n",
    "X_i = X\n",
    "\\qquad \\text{for } i = 1, \\ldots, n\n",
    "$$\n",
    "\n",
    "Every $ X_i $ now has exactly the right distribution.\n",
    "\n",
    "Judged one at a time, these are perfectly good observations.\n",
    "\n",
    "But they are useless as a sample, as the next figure shows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e2b3931",
   "metadata": {
    "hide-output": false
   },
   "outputs": [],
   "source": [
    "x = u.rvs(random_state=1234)         # a single draw\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "for n in (10, 100, 1000):\n",
    "    x_draws = np.full(n, x)          # repeated n times\n",
    "    plot_ecdf(x_draws, ax, alpha=0.7, label=f'$n = {n}$')\n",
    "ax.plot(x_grid, u.cdf(x_grid), 'k--', lw=2, label='true CDF')\n",
    "ax.set_xlabel('x')\n",
    "ax.set_ylabel('probability')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "943f9167",
   "metadata": {},
   "source": [
    "The three ECDFs lie exactly on top of one another: each is a single step at\n",
    "$ X $, and increasing $ n $ changes nothing.\n",
    "\n",
    "The sample never approaches the distribution it came from, no matter how large\n",
    "we make it.\n",
    "\n",
    "The reason is that the observations after the first one carry no information we\n",
    "did not already have.\n",
    "\n",
    ">**Note**\n",
    ">\n",
    ">Independence is a clean sufficient condition rather than a necessary one.\n",
    "\n",
    "Many dependent samples work perfectly well — the monthly returns we\n",
    "histogrammed above are certainly not independent, since volatile months tend to\n",
    "follow volatile months.\n",
    "\n",
    "What matters is that new observations keep bringing new information, which the\n",
    "example above destroys entirely.\n",
    "\n",
    "The general question of what a sample can tell us about its distribution is\n",
    "taken up in [LLN and CLT](https://intro.quantecon.org/lln_clt_intro.html)."
   ]
  }
 ],
 "metadata": {
  "date": 1795846200.4348931,
  "filename": "observed_distributions.md",
  "kernelspec": {
   "display_name": "Python",
   "language": "python3",
   "name": "python3"
  },
  "title": "Observed Distributions"
 },
 "nbformat": 4,
 "nbformat_minor": 5
}