quant-econ Solutions: Python by Example

Exercise 1


In [1]:
def factorial(n):
    k = 1
    for i in range(n):
        k = k * (i + 1)
    return k

factorial(4)


Out[1]:
24

Exercise 2


In [2]:
from random import uniform

def binomial_rv(n, p):
    count = 0
    for i in range(n):
        U = uniform(0, 1)
        if U < p:
            count = count + 1    # Or count += 1
    return count

binomial_rv(10, 0.5)


Out[2]:
6

Exercise 3

Consider the circle of diameter 1 embedded in the unit square

Let $A$ be its area and let $r=1/2$ be its radius

If we know $\pi$ then we can compute $A$ via $A = \pi r^2$

But here the point is to compute $\pi$, which we can do by $\pi = A / r^2$

Summary: If we can estimate the area of the unit circle, then dividing by $r^2 = (1/2)^2 = 1/4$ gives an estimate of $\pi$

We estimate the area by sampling bivariate uniforms and looking at the fraction that fall into the unit circle


In [3]:
from __future__ import division  # Omit if using Python 3.x
from math import sqrt

n = 100000

count = 0
for i in range(n):
    u, v = uniform(0, 1), uniform(0, 1)
    d = sqrt((u - 0.5)**2 + (v - 0.5)**2)
    if d < 0.5:
        count += 1

area_estimate = count / n

print(area_estimate * 4)  # dividing by radius**2


3.14008

Exercise 4


In [4]:
payoff = 0
count = 0

for i in range(10):
    U = uniform(0, 1)
    count = count + 1 if U < 0.5 else 0
    if count == 3:
        payoff = 1

print(payoff)


1

Exercise 5

The next line embeds all subsequent figures in the browser itself


In [5]:
%matplotlib inline

In [6]:
import matplotlib.pyplot as plt
from random import normalvariate

alpha = 0.9
ts_length = 200
current_x = 0

x_values = []
for i in range(ts_length + 1):
    x_values.append(current_x)
    current_x = alpha * current_x + normalvariate(0, 1)
plt.plot(x_values, 'b-')


Out[6]:
[<matplotlib.lines.Line2D at 0x7f40ce124a50>]

Exercise 6


In [7]:
alphas = [0.0, 0.8, 0.98]
ts_length = 200

for alpha in alphas:
    x_values = []
    current_x = 0
    for i in range(ts_length):
        x_values.append(current_x)
        current_x = alpha * current_x + normalvariate(0, 1)
    plt.plot(x_values, label='alpha = ' + str(alpha))
plt.legend()


Out[7]:
<matplotlib.legend.Legend at 0x7f40ce1a1f50>

In [ ]: