{
"cells": [
{
"cell_type": "markdown",
"id": "12147667",
"metadata": {},
"source": [
"# Randomness\n",
"\n",
"**Prerequisites**\n",
"\n",
"- [Introduction to Numpy](https://datascience.quantecon.org/numpy_arrays.html) \n",
"- [Applied Linear Algebra](https://datascience.quantecon.org/applied_linalg.html) \n",
"\n",
"\n",
"**Outcomes**\n",
"\n",
"- Recall basic probability \n",
"- Draw random numbers from numpy \n",
"- Understand why simulation is useful \n",
"- Understand the basics of Markov chains and using the `quantecon` library to study them \n",
"- Simulate discrete and continuous random variables and processes "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5027dcf9",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# Uncomment following line to install on colab\n",
"#! pip install "
]
},
{
"cell_type": "markdown",
"id": "9cd20a6a",
"metadata": {},
"source": [
"## Randomness\n",
"\n",
"We will use the `numpy.random` package to simulate randomness in Python.\n",
"\n",
"This lecture will present various probability distributions and then use\n",
"numpy.random to numerically verify some of the facts associated with them.\n",
"\n",
"We import `numpy` as usual"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "49cdf594",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"id": "ca64dfd7",
"metadata": {},
"source": [
"### Probability\n",
"\n",
"Before we learn how to use Python to generate randomness, we should make sure\n",
"that we all agree on some basic concepts of probability.\n",
"\n",
"To think about the probability of some event occurring, we must understand what possible\n",
"events could occur – mathematicians refer to this as the *event space*.\n",
"\n",
"Some examples are\n",
"\n",
"- For a coin flip, the coin could either come up heads, tails, or land on its side. \n",
"- The inches of rain falling in a certain location on a given day could be any real\n",
" number between 0 and $ \\infty $. \n",
"- The change in an S&P500 stock price could be any real number between\n",
" $ - $ opening price and $ \\infty $. \n",
"- An individual’s employment status tomorrow could either be employed or unemployed. \n",
"- And the list goes on… \n",
"\n",
"\n",
"Notice that in some of these cases, the event space can be counted (coin flip and employment status)\n",
"while in others, the event space cannot be counted (rain and stock prices).\n",
"\n",
"We refer to random variables with countable event spaces as *discrete random variables* and\n",
"random variables with uncountable event spaces as *continuous random variables*.\n",
"\n",
"We then call certain numbers ‘probabilities’ and associate them with events from the event space.\n",
"\n",
"The following is true about probabilities.\n",
"\n",
"1. The probability of any event must be greater than or equal to 0. \n",
"1. The probability of all events from the event space must sum (or integrate) to 1. \n",
"1. If two events cannot occur at same time, then the probability that at least one of them occurs is\n",
" the sum of the probabilities that each event occurs (known as independence). \n",
"\n",
"\n",
"We won’t rely on these for much of what we learn in this class, but occasionally, these facts will\n",
"help us reason through what is happening."
]
},
{
"cell_type": "markdown",
"id": "48ff0741",
"metadata": {},
"source": [
"### Simulating Randomness in Python\n",
"\n",
"One of the most basic random numbers is a variable that has equal probability of being any value\n",
"between 0 and 1.\n",
"\n",
"You may have previously learned about this probability distribution as the Uniform(0, 1).\n",
"\n",
"Let’s dive into generating some random numbers.\n",
"\n",
"Run the code below multiple times and see what numbers you get."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d2835ced",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"np.random.rand()"
]
},
{
"cell_type": "markdown",
"id": "2dc0e5ff",
"metadata": {},
"source": [
"We can also generate arrays of random numbers."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3ed56523",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"np.random.rand(25)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "977821da",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"np.random.rand(5, 5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "65e669b3",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"np.random.rand(2, 3, 4)"
]
},
{
"cell_type": "markdown",
"id": "ea8722e9",
"metadata": {},
"source": [
"### Why Do We Need Randomness?\n",
"\n",
"As economists and data scientists, we study complex systems.\n",
"\n",
"These systems have inherent randomness, but they do not readily reveal their underlying distribution\n",
"to us.\n",
"\n",
"In cases where we face this difficulty, we turn to a set of tools known as Monte Carlo\n",
"methods.\n",
"\n",
"These methods effectively boil down to repeatedly simulating some event (or events) and looking at\n",
"the outcome distribution.\n",
"\n",
"This tool is used to inform decisions in search and rescue missions, election predictions, sports,\n",
"and even by the Federal Reserve.\n",
"\n",
"The reasons that Monte Carlo methods work is a mathematical theorem known as the *Law of Large\n",
"Numbers*.\n",
"\n",
"The Law of Large Numbers basically says that under relatively general conditions, the distribution of simulated outcomes will mimic the true distribution as the number of simulated events goes to infinity.\n",
"\n",
"We already know how the uniform distribution looks, so let’s demonstrate the Law of Large Numbers by approximating the uniform distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "93e7aa6a",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# Draw various numbers of uniform[0, 1] random variables\n",
"draws_10 = np.random.rand(10)\n",
"draws_200 = np.random.rand(200)\n",
"draws_10000 = np.random.rand(10_000)\n",
"\n",
"# Plot their histograms\n",
"fig, ax = plt.subplots(3)\n",
"\n",
"ax[0].set_title(\"Histogram with 10 draws\")\n",
"ax[0].hist(draws_10)\n",
"\n",
"ax[1].set_title(\"Histogram with 200 draws\")\n",
"ax[1].hist(draws_200)\n",
"\n",
"ax[2].set_title(\"Histogram with 10,000 draws\")\n",
"ax[2].hist(draws_10000)\n",
"\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"id": "e106400a",
"metadata": {},
"source": [
"### Exercise\n",
"\n",
"See exercise 1 in the [exercise list](#ex3-4)."
]
},
{
"cell_type": "markdown",
"id": "a86b6b6a",
"metadata": {},
"source": [
"### Discrete Distributions\n",
"\n",
"Sometimes we will encounter variables that can only take one of a\n",
"few possible values.\n",
"\n",
"We refer to this type of random variable as a discrete distribution.\n",
"\n",
"For example, consider a small business loan company.\n",
"\n",
"Imagine that the company’s loan requires a repayment of $ \\\\$25,000 $ and must be repaid 1 year\n",
"after the loan was made.\n",
"\n",
"The company discounts the future at 5%.\n",
"\n",
"Additionally, the loans made are repaid in full with 75% probability, while\n",
"$ \\\\$12,500 $ of loans is repaid with probability 20%, and no repayment with 5%\n",
"probability.\n",
"\n",
"How much would the small business loan company be willing to loan if they’d like to\n",
"– on average – break even?\n",
"\n",
"In this case, we can compute this by hand:\n",
"\n",
"The amount repaid, on average, is: $ 0.75(25,000) + 0.2(12,500) + 0.05(0) = 21,250 $.\n",
"\n",
"Since we’ll receive that amount in one year, we have to discount it:\n",
"$ \\frac{1}{1+0.05} 21,250 \\approx 20238 $.\n",
"\n",
"We can now verify by simulating the outcomes of many loans."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8dfa2ea6",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# You'll see why we call it `_slow` soon :)\n",
"def simulate_loan_repayments_slow(N, r=0.05, repayment_full=25_000.0,\n",
" repayment_part=12_500.0):\n",
" repayment_sims = np.zeros(N)\n",
" for i in range(N):\n",
" x = np.random.rand() # Draw a random number\n",
"\n",
" # Full repayment 75% of time\n",
" if x < 0.75:\n",
" repaid = repayment_full\n",
" elif x < 0.95:\n",
" repaid = repayment_part\n",
" else:\n",
" repaid = 0.0\n",
"\n",
" repayment_sims[i] = (1 / (1 + r)) * repaid\n",
"\n",
" return repayment_sims\n",
"\n",
"print(np.mean(simulate_loan_repayments_slow(25_000)))"
]
},
{
"cell_type": "markdown",
"id": "3ba0a5c6",
"metadata": {},
"source": [
"#### Aside: Vectorized Computations\n",
"\n",
"The code above illustrates the concepts we were discussing but is much slower than\n",
"necessary.\n",
"\n",
"Below is a version of our function that uses numpy arrays to perform computations\n",
"instead of only storing the values."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0c8fa499",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"def simulate_loan_repayments(N, r=0.05, repayment_full=25_000.0,\n",
" repayment_part=12_500.0):\n",
" \"\"\"\n",
" Simulate present value of N loans given values for discount rate and\n",
" repayment values\n",
" \"\"\"\n",
" random_numbers = np.random.rand(N)\n",
"\n",
" # start as 0 -- no repayment\n",
" repayment_sims = np.zeros(N)\n",
"\n",
" # adjust for full and partial repayment\n",
" partial = random_numbers <= 0.20\n",
" repayment_sims[partial] = repayment_part\n",
"\n",
" full = ~partial & (random_numbers <= 0.95)\n",
" repayment_sims[full] = repayment_full\n",
"\n",
" repayment_sims = (1 / (1 + r)) * repayment_sims\n",
"\n",
" return repayment_sims\n",
"\n",
"np.mean(simulate_loan_repayments(25_000))"
]
},
{
"cell_type": "markdown",
"id": "876a2c26",
"metadata": {},
"source": [
"We’ll quickly demonstrate the time difference in running both function versions."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b41eb462",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"%timeit simulate_loan_repayments_slow(250_000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "38255e6c",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"%timeit simulate_loan_repayments(250_000)"
]
},
{
"cell_type": "markdown",
"id": "5e2345e8",
"metadata": {},
"source": [
"The timings for my computer were 167 ms for `simulate_loan_repayments_slow` and 5.05 ms for\n",
"`simulate_loan_repayments`.\n",
"\n",
"This function is simple enough that both times are acceptable, but the 33x time difference could\n",
"matter in a more complicated operation.\n",
"\n",
"This illustrates a concept called *vectorization*, which is when computations\n",
"operate on an entire array at a time.\n",
"\n",
"In general, numpy code that is *vectorized* will perform better than numpy code that operates on one\n",
"element at a time.\n",
"\n",
"For more information see the\n",
"[QuantEcon lecture on performance Python](https://python-programming.quantecon.org/numba.html) code."
]
},
{
"cell_type": "markdown",
"id": "26a098e2",
"metadata": {},
"source": [
"### Aside: Using Class to Hold Parameters\n",
"\n",
"We have been using objects and classes both internal to python (e.g. `list`) from external libraries (e.g. `numpy.array`). Sometimes it is convenient to create your own classes to organize parameter, data, and functions.\n",
"\n",
"In this section we will reimplement our function using new classes to hold parameters.\n",
"\n",
"First, we rewrite `simulate_loan_repayments` so that instead of a collection of individual parameters, it takes in an object (titles `params`)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d4a5b5df",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"def simulate_loan_repayments_2(N, params): \n",
" # Extract fields from params object\n",
" r = params.r\n",
" repayment_part = params.repayment_part\n",
" repayment_full = params.repayment_full\n",
"\n",
" random_numbers = np.random.rand(N)\n",
"\n",
" # start as 0 -- no repayment\n",
" repayment_sims = np.zeros(N)\n",
"\n",
" # adjust for full and partial repayment\n",
" partial = random_numbers <= 0.20\n",
" repayment_sims[partial] = repayment_part\n",
"\n",
" full = ~partial & (random_numbers <= 0.95)\n",
" repayment_sims[full] = repayment_full\n",
"\n",
" repayment_sims = (1 / (1 + r)) * repayment_sims\n",
"\n",
" return repayment_sims"
]
},
{
"cell_type": "markdown",
"id": "74a38642",
"metadata": {},
"source": [
"Any object which fulfills `params.r, params.replayment_part` and `params.repayment_full` will work, so we will create a few versions of this to explore features of custom classes in Python.\n",
"\n",
"The most important function in a class is the `__init__` function which determines how it is constructed and creates an object of that type. This function has the special argument `self` which refers to the new object being created, and with which you can easily add new fields. For example,"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ac0dd34b",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"class LoanRepaymentParams:\n",
" # A special function 'constructor'\n",
" def __init__(self, r, repayment_full, repayment_part):\n",
" self.r = r\n",
" self.repayment_full = repayment_full\n",
" self.repayment_part = repayment_part\n",
"\n",
"# Create an instance of the class \n",
"params = LoanRepaymentParams(0.05, 50_000.0, 25_000)\n",
"print(params.r)"
]
},
{
"cell_type": "markdown",
"id": "8548bdaa",
"metadata": {},
"source": [
"The inside of the `__init__` function simply takes the arguments and assigns them as new fields in the `self`. Calling the `LoanRepaymentParams(...)` implicitly calls the `__init__` function and returns the new object.\n",
"\n",
"We can then use the new object to call the function `simulate_loan_repayments_2` as before."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1215169a",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"N = 1000\n",
"params = LoanRepaymentParams(0.05, 50_000.0, 25_000)\n",
"print(np.mean(simulate_loan_repayments_2(N, params)))"
]
},
{
"cell_type": "markdown",
"id": "345b5458",
"metadata": {},
"source": [
"One benefit of using a class is that you can do calculations in the constructor. For example, instead of passing in the partial repayment amount, we could pass in the fraction of the full repayment that is paid."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7972f61a",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"class LoanRepaymentParams2:\n",
" def __init__(self, r, repayment_full, partial_fraction = 0.3):\n",
" self.r = r\n",
" self.repayment_full = repayment_full\n",
" \n",
" # This does a calculation and sets a new value\n",
" self.repayment_part = repayment_full * partial_fraction\n",
"\n",
"# Create an instance of the class \n",
"params = LoanRepaymentParams2(0.05, 50_000.0, 0.5) \n",
"print(params.repayment_part) # Acccess the calculation\n",
"print(np.mean(simulate_loan_repayments_2(N, params)))"
]
},
{
"cell_type": "markdown",
"id": "e7e5a356",
"metadata": {},
"source": [
"This setup a default value for the `partial_fraction` so that we could also have called this with `LoanRepaymentParams2(0.05, 50_000)`.\n",
"\n",
"Finally, there are some special features we can use to create classes in python which automatically create the `__init__` function, allow for more easily setting default values. The easiest is to create a `dataclass` (see [documentation](https://docs.python.org/3/library/dataclasses.html))."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3d86404a",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"from dataclasses import dataclass\n",
"\n",
"@dataclass\n",
"class LoanRepaymentParams3:\n",
" r: float = 0.05\n",
" repayment_full: float = 50_000\n",
" repayment_part: float = 25_000\n",
"\n",
"params = LoanRepaymentParams3() # uses all defaults\n",
"params2 = LoanRepaymentParams3(repayment_full= 60_000) # changes the full repayment amount\n",
"\n",
"# show the objects\n",
"print(params)\n",
"print(params2)\n",
"\n",
"# simulate using the new object\n",
"print(np.mean(simulate_loan_repayments_2(N, params2)))"
]
},
{
"cell_type": "markdown",
"id": "6a59b49b",
"metadata": {},
"source": [
"The `@dataclass` is an example of a python decorator (see [documentation](https://docs.python.org/3/glossary.html#term-decorator)). Decorators take in a class (or function) and return a new class (or function) with some additional features. In this case, it automatically creates the `__init__` function, allows for default values, and adds a new `__repr__` function which determines how the object is printed."
]
},
{
"cell_type": "markdown",
"id": "6e55dff3",
"metadata": {},
"source": [
"#### Profitability Threshold\n",
"\n",
"Rather than looking for the break even point, we might be interested in the largest loan size that\n",
"ensures we still have a 95% probability of profitability in a year we make 250 loans.\n",
"\n",
"This is something that could be computed by hand, but it is much easier to answer through\n",
"simulation!\n",
"\n",
"If we simulate 250 loans many times and keep track of what the outcomes look like, then we can look\n",
"at the the 5th percentile of total repayment to find the loan size needed for 95% probability of\n",
"being profitable."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "94aad354",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"def simulate_year_of_loans(N=250, K=1000):\n",
"\n",
" # Create array where we store the values\n",
" avg_repayments = np.zeros(K)\n",
" for year in range(K):\n",
"\n",
" repaid_year = 0.0\n",
" n_loans = simulate_loan_repayments(N)\n",
" avg_repayments[year] = n_loans.mean()\n",
"\n",
" return avg_repayments\n",
"\n",
"loan_repayment_outcomes = simulate_year_of_loans(N=250)\n",
"\n",
"# Think about why we use the 5th percentile of outcomes to\n",
"# compute when we are profitable 95% of time\n",
"lro_5 = np.percentile(loan_repayment_outcomes, 5)\n",
"\n",
"print(\"The largest loan size such that we were profitable 95% of time is\")\n",
"print(lro_5)"
]
},
{
"cell_type": "markdown",
"id": "598b0499",
"metadata": {},
"source": [
"Now let’s consider what we could learn if our loan company had even more detailed information about\n",
"how the life of their loans progressed."
]
},
{
"cell_type": "markdown",
"id": "5506bfc4",
"metadata": {},
"source": [
"#### Loan States\n",
"\n",
"Loans can have 3 potential statuses (or states):\n",
"\n",
"1. Repaying: Payments are being made on loan. \n",
"1. Delinquency: No payments are currently being made, but they might be made in the future. \n",
"1. Default: No payments are currently being made and no more payments will be made in future. \n",
"\n",
"\n",
"The small business loans company knows the following:\n",
"\n",
"- If a loan is currently in repayment, then it has an 85% probability of continuing being repaid, a\n",
" 10% probability of going into delinquency, and a 5% probability of going into default. \n",
"- If a loan is currently in delinquency, then it has a 25% probability of returning to repayment, a\n",
" 60% probability of staying delinquent, and a 15% probability of going into default. \n",
"- If a loan is currently in default, then it remains in default with 100% probability. \n",
"\n",
"\n",
"For simplicity, let’s imagine that 12 payments are made during the life of a loan, even though\n",
"this means people who experience delinquency won’t be required to repay their remaining balance.\n",
"\n",
"Let’s write the code required to perform this dynamic simulation."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23c5f263",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"def simulate_loan_lifetime(monthly_payment):\n",
"\n",
" # Create arrays to store outputs\n",
" payments = np.zeros(12)\n",
" # Note: dtype 'U12' means a string with no more than 12 characters\n",
" statuses = np.array(4*[\"repaying\", \"delinquency\", \"default\"], dtype=\"U12\")\n",
"\n",
" # Everyone is repaying during their first month\n",
" payments[0] = monthly_payment\n",
" statuses[0] = \"repaying\"\n",
"\n",
" for month in range(1, 12):\n",
" rn = np.random.rand()\n",
"\n",
" if (statuses[month-1] == \"repaying\"):\n",
" if rn < 0.85:\n",
" payments[month] = monthly_payment\n",
" statuses[month] = \"repaying\"\n",
" elif rn < 0.95:\n",
" payments[month] = 0.0\n",
" statuses[month] = \"delinquency\"\n",
" else:\n",
" payments[month] = 0.0\n",
" statuses[month] = \"default\"\n",
" elif (statuses[month-1] == \"delinquency\"):\n",
" if rn < 0.25:\n",
" payments[month] = monthly_payment\n",
" statuses[month] = \"repaying\"\n",
" elif rn < 0.85:\n",
" payments[month] = 0.0\n",
" statuses[month] = \"delinquency\"\n",
" else:\n",
" payments[month] = 0.0\n",
" statuses[month] = \"default\"\n",
" else: # Default -- Stays in default after it gets there\n",
" payments[month] = 0.0\n",
" statuses[month] = \"default\"\n",
"\n",
" return payments, statuses"
]
},
{
"cell_type": "markdown",
"id": "7b09fcac",
"metadata": {},
"source": [
"We can use this model of the world to answer even more questions than the last model!\n",
"\n",
"For example, we can think about things like\n",
"\n",
"- For the defaulted loans, how many payments did they make before going into default? \n",
"- For those who partially repaid, how much was repaid before the 12 months was over? \n",
"\n",
"\n",
"Unbeknownst to you, we have just introduced a well-known mathematical concept known as a Markov\n",
"chain.\n",
"\n",
"A Markov chain is a random process (Note: Random process is a sequence of random variables\n",
"observed over time) where the probability of something happening tomorrow only depends on what we\n",
"can observe today.\n",
"\n",
"In our small business loan example, this just means that the small business loan’s repayment status\n",
"tomorrow only depended on what its repayment status was today.\n",
"\n",
"Markov chains often show up in economics and statistics, so we decided a simple introduction would\n",
"be helpful, but we leave out many details for the interested reader to find.\n",
"\n",
"A Markov chain is defined by three objects:\n",
"\n",
"1. A description of the possible states and their associated value. \n",
"1. A complete description of the probability of moving from one state to all other states. \n",
"1. An initial distribution over the states (often a vector of all zeros except for a single 1 for\n",
" some particular state). \n",
"\n",
"\n",
"For the example above, we’ll define each of these three things in the Python code below."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b553aef4",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# 1. State description\n",
"state_values = [\"repaying\", \"delinquency\", \"default\"]\n",
"\n",
"# 2. Transition probabilities: encoded in a matrix (2d-array) where element [i, j]\n",
"# is the probability of moving from state i to state j\n",
"P = np.array([[0.85, 0.1, 0.05], [0.25, 0.6, 0.15], [0, 0, 1]])\n",
"\n",
"# 3. Initial distribution: assume loans start in repayment\n",
"x0 = np.array([1, 0, 0])"
]
},
{
"cell_type": "markdown",
"id": "205f5d45",
"metadata": {},
"source": [
"Now that we have these objects defined, we can use the a `MarkovChain` class from the\n",
"[quantecon python library](https://github.com/QuantEcon/QuantEcon.py/) to analyze this model."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "47ac6ba4",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"import quantecon as qe\n",
"\n",
"mc = qe.markov.MarkovChain(P, state_values)"
]
},
{
"cell_type": "markdown",
"id": "e96c332b",
"metadata": {},
"source": [
"We can use the `mc` object to do common Markov chain operations.\n",
"\n",
"The `simulate` method will simulate the Markov chain for a specified number of steps:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9a39f83e",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"mc.simulate(12, init=\"repaying\")"
]
},
{
"cell_type": "markdown",
"id": "245459e3",
"metadata": {},
"source": [
"Suppose we were to simulate the Markov chain for an infinite number of steps.\n",
"\n",
"Given the random nature of transitions, we might end up taking different paths at any given moment.\n",
"\n",
"We can summarize all possible paths over time by keeping track of a distribution.\n",
"\n",
"Below, we will print out the distribution for the first 10 time steps,\n",
"starting from a distribution where the debtor is repaying in the first step."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dde7dd01",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"x = x0\n",
"for t in range(10):\n",
" print(f\"At time {t} the distribution is {x}\")\n",
" x = mc.P.T @ x"
]
},
{
"cell_type": "markdown",
"id": "55fc5a58",
"metadata": {},
"source": [
"#### Exercise\n",
"\n",
"See exercise 2 in the [exercise list](#ex3-4)."
]
},
{
"cell_type": "markdown",
"id": "fa690161",
"metadata": {},
"source": [
"#### Exercise\n",
"\n",
"See exercise 3 in the [exercise list](#ex3-4)."
]
},
{
"cell_type": "markdown",
"id": "01292f97",
"metadata": {},
"source": [
"### Continuous Distributions\n",
"\n",
"Recall that a continuous distribution is one where the value can take on an uncountable number of values.\n",
"\n",
"It differs from a discrete distribution in that the events are not\n",
"countable.\n",
"\n",
"We can use simulation to learn things about continuous distributions as we did with discrete\n",
"distributions.\n",
"\n",
"Let’s use simulation to study what is arguably the most commonly encountered\n",
"distributions – the normal distribution.\n",
"\n",
"The Normal (sometimes referred to as the Gaussian distribution) is bell-shaped and completely\n",
"described by the mean and variance of that distribution.\n",
"\n",
"The mean is often referred to as $ \\mu $ and the variance as $ \\sigma^2 $.\n",
"\n",
"Let’s take a look at the normal distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a36d8bb9",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# scipy is an extension of numpy, and the stats\n",
"# subpackage has tools for working with various probability distributions\n",
"import scipy.stats as st\n",
"\n",
"x = np.linspace(-5, 5, 100)\n",
"\n",
"# NOTE: first argument to st.norm is mean, second is standard deviation sigma (not sigma^2)\n",
"pdf_x = st.norm(0.0, 1.0).pdf(x)\n",
"\n",
"fig, ax = plt.subplots()\n",
"\n",
"ax.set_title(r\"Normal Distribution ($\\mu = 0, \\sigma = 1$)\")\n",
"ax.plot(x, pdf_x)"
]
},
{
"cell_type": "markdown",
"id": "ff127718",
"metadata": {},
"source": [
"Another common continuous distribution used in economics is the gamma distribution.\n",
"\n",
"A gamma distribution is defined for all positive numbers and described by both a shape\n",
"parameter $ k $ and a scale parameter $ \\theta $.\n",
"\n",
"Let’s see what the distribution looks like for various choices of $ k $ and $ \\theta $."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4b46d722",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"def plot_gamma(k, theta, x, ax=None):\n",
" if ax is None:\n",
" _, ax = plt.subplots()\n",
"\n",
" # scipy refers to the rate parameter beta as a scale parameter\n",
" pdf_x = st.gamma(k, scale=theta).pdf(x)\n",
" ax.plot(x, pdf_x, label=f\"k = {k} theta = {theta}\")\n",
"\n",
" return ax\n",
"\n",
"fig, ax = plt.subplots(figsize=(10, 6))\n",
"x = np.linspace(0.1, 20, 130)\n",
"plot_gamma(2.0, 1.0, x, ax)\n",
"plot_gamma(3.0, 1.0, x, ax)\n",
"plot_gamma(3.0, 2.0, x, ax)\n",
"plot_gamma(3.0, 0.5, x, ax)\n",
"ax.set_ylim((0, 0.6))\n",
"ax.set_xlim((0, 20))\n",
"ax.legend();"
]
},
{
"cell_type": "markdown",
"id": "33310c9a",
"metadata": {},
"source": [
"### Exercise\n",
"\n",
"See exercise 4 in the [exercise list](#ex3-4).\n",
"\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"id": "2930501e",
"metadata": {},
"source": [
"## Exercises"
]
},
{
"cell_type": "markdown",
"id": "38ebc668",
"metadata": {},
"source": [
"### Exercise 1\n",
"\n",
"Wikipedia and other credible statistics sources tell us that the mean and\n",
"variance of the Uniform(0, 1) distribution are (1/2, 1/12) respectively.\n",
"\n",
"How could we check whether the numpy random numbers approximate these\n",
"values?\n",
"\n",
"([back to text](#dir3-4-1))"
]
},
{
"cell_type": "markdown",
"id": "2db0ae7a",
"metadata": {},
"source": [
"### Exercise 2\n",
"\n",
"In this exercise, we explore the long-run, or stationary, distribution of the Markov chain.\n",
"\n",
"The stationary distribution of a Markov chain is the probability distribution that would\n",
"result after an infinite number of steps *for any initial distribution*.\n",
"\n",
"Mathematically, a stationary distribution $ x $ is a distribution where $ x = P'x $.\n",
"\n",
"In the code cell below, use the `stationary_distributions` property of `mc` to\n",
"determine the stationary distribution of our Markov chain.\n",
"\n",
"After doing your computation, think about the answer… think about why our transition\n",
"probabilities must lead to this outcome."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c01b5265",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# your code here"
]
},
{
"cell_type": "markdown",
"id": "647d526e",
"metadata": {},
"source": [
"([back to text](#dir3-4-2))"
]
},
{
"cell_type": "markdown",
"id": "34ac33e4",
"metadata": {},
"source": [
"### Exercise 3\n",
"\n",
"Let’s revisit the unemployment example from the [linear algebra lecture](https://datascience.quantecon.org/applied_linalg.html).\n",
"\n",
"We’ll repeat necessary details here.\n",
"\n",
"Consider an economy where in any given year, $ \\alpha = 5\\% $ of workers lose their jobs, and\n",
"$ \\phi = 10\\% $ of unemployed workers find jobs.\n",
"\n",
"Initially, 90% of the 1,000,000 workers are employed.\n",
"\n",
"Also suppose that the average employed worker earns 10 dollars, while an unemployed worker\n",
"earns 1 dollar per period.\n",
"\n",
"You now have four tasks:\n",
"\n",
"1. Represent this problem as a Markov chain by defining the three components defined above. \n",
"1. Construct an instance of the quantecon MarkovChain by using the objects defined in part 1. \n",
"1. Simulate the Markov chain 30 times for 50 time periods, and plot each chain over time (see\n",
" helper code below). \n",
"1. Determine the average long run payment for a worker in this setting \n",
"\n",
"\n",
"Think about the stationary distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "805b379a",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# define components here\n",
"\n",
"# construct Markov chain\n",
"\n",
"# simulate (see docstring for how to do many repetitions of\n",
"# the simulation in one function call)\n",
"# uncomment the lines below and fill in the blanks\n",
"# sim = XXXXX.simulate(XXXX)\n",
"# fig, ax = plt.subplots(figsize=(10, 8))\n",
"# ax.plot(range(50), sim.T, alpha=0.4)\n",
"\n",
"# Long-run average payment"
]
},
{
"cell_type": "markdown",
"id": "7a801988",
"metadata": {},
"source": [
"([back to text](#dir3-4-3))"
]
},
{
"cell_type": "markdown",
"id": "bcda8515",
"metadata": {},
"source": [
"### Exercise 4\n",
"\n",
"Assume you have been given the opportunity to choose between one of three financial assets:\n",
"\n",
"You will be given the asset for free, allowed to hold it indefinitely, and keeping all payoffs.\n",
"\n",
"Also assume the assets’ payoffs are distributed as follows:\n",
"\n",
"1. Normal with $ \\mu = 10, \\sigma = 5 $ \n",
"1. Gamma with $ k = 5.3, \\theta = 2 $ \n",
"1. Gamma with $ k = 5, \\theta = 2 $ \n",
"\n",
"\n",
"Use `scipy.stats` to answer the following questions:\n",
"\n",
"- Which asset has the highest average returns? \n",
"- Which asset has the highest median returns? \n",
"- Which asset has the lowest coefficient of variation (standard deviation divided by mean)? \n",
"- Which asset would you choose? Why? \n",
"\n",
"\n",
"There is not a single right answer here. Be creative\n",
"and express your preferences."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "39412ffd",
"metadata": {
"hide-output": false
},
"outputs": [],
"source": [
"# your code here"
]
},
{
"cell_type": "markdown",
"id": "ff1cb2f9",
"metadata": {},
"source": [
"([back to text](#dir3-4-4))"
]
}
],
"metadata": {
"date": 1689807042.2154396,
"filename": "randomness.md",
"kernelspec": {
"display_name": "Python",
"language": "python3",
"name": "python3"
},
"title": "Randomness"
},
"nbformat": 4,
"nbformat_minor": 5
}