quant-econ Solutions: Python by Example

Exercise 1


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

factorial(4)


Out[28]:
24

Exercise 2


In [29]:
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[29]:
2

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 [30]:
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.1418

Exercise 4


In [31]:
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 [35]:
%matplotlib inline

In [36]:
from pylab import plot, show, legend
from random import normalvariate

alpha = 0.9
ts_length = 200
current_x = 0

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


Out[36]:
[<matplotlib.lines.Line2D at 0x3ae7d50>]

Exercise 6


In [37]:
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)
    plot(x_values, label='alpha = ' + str(alpha))
legend()


Out[37]:
<matplotlib.legend.Legend at 0x378e6d0>

In [ ]: