```
\n",
"```\n",
"\n",
"The Python interpreter performs the following:\n",
"\n",
"- For each element of the `sequence`, it \\\"binds\\\" the name\n",
" `variable_name` to that element and then executes the code block.\n",
"\n",
"The `sequence` object can in fact be a very general object, as we\\'ll\n",
"see soon enough.\n",
"\n",
"### A Comment on Indentation\n",
"\n",
"In discussing the `for` loop, we explained that the code blocks being\n",
"looped over are delimited by indentation.\n",
"\n",
"In fact, in Python, **all** code blocks (i.e., those occurring inside\n",
"loops, if clauses, function definitions, etc.) are delimited by\n",
"indentation.\n",
"\n",
"Thus, unlike most other languages, whitespace in Python code affects the\n",
"output of the program.\n",
"\n",
"Once you get used to it, this is a good thing: It\n",
"\n",
"- forces clean, consistent indentation, improving readability\n",
"- removes clutter, such as the brackets or end statements used in\n",
" other languages\n",
"\n",
"On the other hand, it takes a bit of care to get right, so please\n",
"remember:\n",
"\n",
"- The line before the start of a code block always ends in a colon\n",
" - `for i in range(10):`\n",
" - `if x > y:`\n",
" - `while x < 100:`\n",
" - etc., etc.\n",
"- All lines in a code block **must have the same amount of indentation**.\n",
"- The Python standard is 4 spaces, and that\\'s what you should use.\n",
"\n",
"### While Loops\n",
"\n",
"The `for` loop is the most common technique for iteration in Python.\n",
"\n",
"But, for the purpose of illustration, let\\'s modify\n",
"{ref}`the program above
```` to use\n",
"a `while` loop instead.\n",
"\n",
"(whileloopprog)="
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "75d87fc4",
"metadata": {},
"outputs": [],
"source": [
"ts_length = 100\n",
"ϵ_values = []\n",
"i = 0\n",
"while i < ts_length:\n",
" e = np.random.randn()\n",
" ϵ_values.append(e)\n",
" i = i + 1\n",
"plt.plot(ϵ_values)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "06aa0a93",
"metadata": {},
"source": [
"Note that\n",
"\n",
"- the code block for the `while` loop is again delimited only by indentation\n",
"- the statement `i = i + 1` can be replaced by `i += 1`\n",
"\n",
"## Another Application\n",
"\n",
"Let\\'s do one more application before we turn to exercises.\n",
"\n",
"In this application, we plot the balance of a bank account over time.\n",
"\n",
"There are no withdraws over the time period, the last date of which is\n",
"denoted by $T$.\n",
"\n",
"The initial balance is $b_0$ and the interest rate is $r$.\n",
"\n",
"The balance updates from period $t$ to $t+1$ according to\n",
"\n",
"```{math}\n",
":label: ilom\n",
" b_{t+1} = (1 + r) b_t\n",
"```\n",
"\n",
"In the code below, we generate and plot the sequence $b_0, b_1, \\ldots, b_T$\n",
"generated by {eq}`ilom`.\n",
"\n",
"Instead of using a Python list to store this sequence, we will use a\n",
"NumPy array."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04204bf4",
"metadata": {},
"outputs": [],
"source": [
"r = 0.025 # interest rate\n",
"T = 50 # end date\n",
"b = np.empty(T+1) # an empty NumPy array, to store all b_t\n",
"b[0] = 10 # initial balance\n",
"\n",
"for t in range(T):\n",
" b[t+1] = (1 + r) * b[t]\n",
"\n",
"plt.plot(b, label='bank balance')\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "00a7d7bc",
"metadata": {},
"source": [
"The statement `b = np.empty(T+1)` allocates storage in memory for `T+1`\n",
"(floating point) numbers.\n",
"\n",
"These numbers are filled in by the `for` loop.\n",
"\n",
"Allocating memory at the start is more efficient than using a Python\n",
"list and `append`, since the latter must repeatedly ask for storage\n",
"space from the operating system.\n",
"\n",
"Notice that we added a legend to the plot --- a feature you will be\n",
"asked to use in the exercises.\n",
"\n",
"## Exercises\n",
"\n",
"Now we turn to exercises. It is important that you complete them before\n",
"continuing, since they present new concepts we will need.\n",
"\n",
"### Exercise 1\n",
"\n",
"Your first task is to simulate and plot the correlated time series\n",
"\n",
"$$\n",
"x_{t+1} = \\alpha \\, x_t + \\epsilon_{t+1}\n",
"\\quad \\text{where} \\quad\n",
"x_0 = 0\n",
"\\quad \\text{and} \\quad t = 0,\\ldots,T\n",
"$$\n",
"\n",
"The sequence of shocks $\\{\\epsilon_t\\}$ is assumed to be IID and\n",
"standard normal.\n",
"\n",
"In your solution, restrict your import statements to"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c449f5ee",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"id": "cfe26232",
"metadata": {},
"source": [
"Set $T=200$ and $\\alpha = 0.9$.\n",
"\n",
"### Exercise 2\n",
"\n",
"Starting with your solution to exercise 2, plot three simulated time\n",
"series, one for each of the cases $\\alpha=0$, $\\alpha=0.8$ and\n",
"$\\alpha=0.98$.\n",
"\n",
"Use a `for` loop to step through the $\\alpha$ values.\n",
"\n",
"If you can, add a legend, to help distinguish between the three time\n",
"series.\n",
"\n",
"Hints:\n",
"\n",
"- If you call the `plot()` function multiple times before calling\n",
" `show()`, all of the lines you produce will end up on the same\n",
" figure.\n",
"- For the legend, noted that the expression `'foo' + str(42)`\n",
" evaluates to `'foo42'`.\n",
"\n",
"### Exercise 3\n",
"\n",
"Similar to the previous exercises, plot the time series\n",
"\n",
"$$\n",
"x_{t+1} = \\alpha \\, |x_t| + \\epsilon_{t+1}\n",
"\\quad \\text{where} \\quad\n",
"x_0 = 0\n",
"\\quad \\text{and} \\quad t = 0,\\ldots,T\n",
"$$\n",
"\n",
"Use $T=200$, $\\alpha = 0.9$ and $\\{\\epsilon_t\\}$ as before.\n",
"\n",
"Search online for a function that can be used to compute the absolute\n",
"value $|x_t|$.\n",
"\n",
"### Exercise 4\n",
"\n",
"One important aspect of essentially all programming languages is\n",
"branching and conditions.\n",
"\n",
"In Python, conditions are usually implemented with if--else syntax.\n",
"\n",
"Here\\'s an example, that prints -1 for each negative number in an array\n",
"and 1 for each nonnegative number"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c1d96b67",
"metadata": {},
"outputs": [],
"source": [
"numbers = [-9, 2.3, -11, 0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1d6c28ac",
"metadata": {},
"outputs": [],
"source": [
"for x in numbers:\n",
" if x < 0:\n",
" print(-1)\n",
" else:\n",
" print(1)"
]
},
{
"cell_type": "markdown",
"id": "2c71e63f",
"metadata": {},
"source": [
"Now, write a new solution to Exercise 3 that does not use an existing\n",
"function to compute the absolute value.\n",
"\n",
"Replace this existing function with an if--else condition.\n",
"\n",
"(pbe_ex3)=\n",
"\n",
"### Exercise 5\n",
"\n",
"Here\\'s a harder exercise, that takes some thought and planning.\n",
"\n",
"The task is to compute an approximation to $\\pi$ using [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method).\n",
"\n",
"Use no imports besides"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2cd27df7",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "markdown",
"id": "898a22ba",
"metadata": {},
"source": [
"Your hints are as follows:\n",
"\n",
"- If $U$ is a bivariate uniform random variable on the unit square\n",
" $(0, 1)^2$, then the probability that $U$ lies in a subset $B$ of\n",
" $(0,1)^2$ is equal to the area of $B$.\n",
"- If $U_1,\\ldots,U_n$ are IID copies of $U$, then, as $n$ gets large,\n",
" the fraction that falls in $B$, converges to the probability of\n",
" landing in $B$.\n",
"- For a circle, $area = \\pi * radius^2$.\n",
"\n",
"## Solutions\n",
"\n",
"### Exercise 1\n",
"\n",
"Here\\'s one solution."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3621e16c",
"metadata": {},
"outputs": [],
"source": [
"α = 0.9\n",
"T = 200\n",
"x = np.empty(T+1)\n",
"x[0] = 0\n",
"\n",
"for t in range(T):\n",
" x[t+1] = α * x[t] + np.random.randn()\n",
"\n",
"plt.plot(x)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "f54c6a8a",
"metadata": {},
"source": [
"### Exercise 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "777cb89e",
"metadata": {},
"outputs": [],
"source": [
"α_values = [0.0, 0.8, 0.98]\n",
"T = 200\n",
"x = np.empty(T+1)\n",
"\n",
"for α in α_values:\n",
" x[0] = 0\n",
" for t in range(T):\n",
" x[t+1] = α * x[t] + np.random.randn()\n",
" plt.plot(x, label=f'$\\\\alpha = {α}$')\n",
"\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "8ab49d78",
"metadata": {},
"source": [
"### Exercise 3\n",
"\n",
"Here\\'s one solution:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "485b833a",
"metadata": {},
"outputs": [],
"source": [
"α = 0.9\n",
"T = 200\n",
"x = np.empty(T+1)\n",
"x[0] = 0\n",
"\n",
"for t in range(T):\n",
" x[t+1] = α * np.abs(x[t]) + np.random.randn()\n",
"\n",
"plt.plot(x)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "a27890b8",
"metadata": {},
"source": [
"### Exercise 4\n",
"\n",
"Here\\'s one way:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cbbd3f39",
"metadata": {},
"outputs": [],
"source": [
"α = 0.9\n",
"T = 200\n",
"x = np.empty(T+1)\n",
"x[0] = 0\n",
"\n",
"for t in range(T):\n",
" if x[t] < 0:\n",
" abs_x = - x[t]\n",
" else:\n",
" abs_x = x[t]\n",
" x[t+1] = α * abs_x + np.random.randn()\n",
"\n",
"plt.plot(x)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "43173adf",
"metadata": {},
"source": [
"Here\\'s a shorter way to write the same thing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cbee3ef6",
"metadata": {},
"outputs": [],
"source": [
"α = 0.9\n",
"T = 200\n",
"x = np.empty(T+1)\n",
"x[0] = 0\n",
"\n",
"for t in range(T):\n",
" abs_x = - x[t] if x[t] < 0 else x[t]\n",
" x[t+1] = α * abs_x + np.random.randn()\n",
"\n",
"plt.plot(x)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "8ecfefce",
"metadata": {},
"source": [
"### Exercise 5\n",
"\n",
"Consider the circle of diameter 1 embedded in the unit square.\n",
"\n",
"Let $A$ be its area and let $r=1/2$ be its radius.\n",
"\n",
"If we know $\\pi$ then we can compute $A$ via $A = \\pi r^2$.\n",
"\n",
"But here the point is to compute $\\pi$, which we can do by\n",
"$\\pi = A / r^2$.\n",
"\n",
"Summary: If we can estimate the area of a circle with diameter 1, then\n",
"dividing by $r^2 = (1/2)^2 = 1/4$ gives an estimate of $\\pi$.\n",
"\n",
"We estimate the area by sampling bivariate uniforms and looking at the\n",
"fraction that falls into the circle."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "30cd9ceb",
"metadata": {},
"outputs": [],
"source": [
"n = 100000\n",
"\n",
"count = 0\n",
"for i in range(n):\n",
" u, v = np.random.uniform(), np.random.uniform()\n",
" d = np.sqrt((u - 0.5)**2 + (v - 0.5)**2)\n",
" if d < 0.5:\n",
" count += 1\n",
"\n",
"area_estimate = count / n\n",
"\n",
"print(area_estimate * 4) # dividing by radius**2"
]
}
],
"metadata": {
"jupytext": {
"text_representation": {
"extension": ".md",
"format_name": "myst",
"format_version": 0.13,
"jupytext_version": "1.11.3"
}
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"source_map": [
12,
59,
61,
69,
76,
100,
104,
106,
110,
114,
166,
170,
174,
178,
195,
199,
227,
237,
264,
267,
278,
282,
285,
300,
304,
308,
310,
315,
319,
321,
329,
333,
350,
354,
415,
425,
456,
468,
503,
506,
555,
559,
565,
582,
584,
602,
613,
617,
630,
636,
647,
653,
668,
672,
684,
703
]
},
"nbformat": 4,
"nbformat_minor": 5
}