Skip to content

Commit

Permalink
Use np.interp instead of interpolation.interp
Browse files Browse the repository at this point in the history
  • Loading branch information
kp992 committed Mar 4, 2024
1 parent 0ad4aeb commit 262f180
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 71 deletions.
1 change: 0 additions & 1 deletion lectures/BCG_complete_mkts.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ In addition to what's in Anaconda, this lecture will need the following librarie
tags: [hide-output]
---
!pip install --upgrade quantecon
!pip install interpolation
!conda install -y -c plotly plotly plotly-orca
```

Expand Down
53 changes: 28 additions & 25 deletions lectures/BCG_incomplete_mkts.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.16.1
kernelspec:
display_name: Python 3
display_name: Python 3 (ipykernel)
language: python
name: python3
---
Expand All @@ -26,12 +28,10 @@ kernelspec:

In addition to what's in Anaconda, this lecture will need the following libraries:

```{code-cell} ipython
---
tags: [hide-output]
---
```{code-cell} ipython3
:tags: [hide-output]
!pip install --upgrade quantecon
!pip install interpolation
!conda install -y -c plotly plotly plotly-orca
```

Expand Down Expand Up @@ -703,15 +703,14 @@ Parameters include:
- $\beta$: Discount factor. Default value is 0.96.
- bound: Bound for truncated normal distribution. Default value is 3.

```{code-cell} ipython
```{code-cell} ipython3
import numpy as np
from scipy.stats import truncnorm
from scipy.integrate import quad
from numba import njit
from interpolation import interp
```

```{code-cell} python3
```{code-cell} ipython3
class BCG_incomplete_markets:
# init method or constructor
Expand Down Expand Up @@ -784,7 +783,7 @@ class BCG_incomplete_markets:
rv = truncnorm(ta, tb, loc=𝜇, scale=𝜎)
𝜖_range = np.linspace(ta, tb, 1000000)
pdf_range = rv.pdf(𝜖_range)
self.g = njit(lambda 𝜖: interp(𝜖_range, pdf_range, 𝜖))
self.g = njit(lambda 𝜖: np.interp(𝜖, 𝜖_range, pdf_range))
#*************************************************************
Expand Down Expand Up @@ -1206,14 +1205,14 @@ Below we show some examples computed with the class `BCG_incomplete markets`.
In the first example, we set up an instance of the BCG incomplete
markets model with default parameter values.

```{code-cell} python3
:tags: ["hide-output"]
```{code-cell} ipython3
:tags: [hide-output]
mdl = BCG_incomplete_markets()
kss,bss,Vss,qss,pss,c10ss,c11ss,c20ss,c21ss,𝜃1ss = mdl.solve_eq(print_crit=False)
```

```{code-cell} python3
```{code-cell} ipython3
print(-kss+qss+pss*bss)
print(Vss)
print(𝜃1ss)
Expand All @@ -1229,7 +1228,7 @@ Thus, let’s see if the firm is actually maximizing its firm value given
the equilibrium pricing function $q(k,b)$ for equity and
$p(k,b)$ for bonds.

```{code-cell} python3
```{code-cell} ipython3
kgrid, bgrid, Vgrid, Qgrid, Pgrid = mdl.eq_valuation(c10ss, c11ss, c20ss, c21ss,N=30)
print('Maximum valuation of the firm value in the (k,B) grid: {:.5f}'.format(Vgrid.max()))
Expand All @@ -1246,7 +1245,7 @@ Below we will plot the firm’s value as a function of $k,b$.
We’ll also plot the equilibrium price functions $q(k,b)$ and
$p(k,b)$.

```{code-cell} python3
```{code-cell} ipython3
from IPython.display import Image
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
Expand Down Expand Up @@ -1367,7 +1366,7 @@ $$

The function also outputs agent 1’s bond holdings $\xi_1$.

```{code-cell} python3
```{code-cell} ipython3
def off_eq_check(mdl,kss,bss,e=0.1):
# Big K and big B
k = kss
Expand Down Expand Up @@ -1603,7 +1602,7 @@ structure for the firm.
We first check the case in which $b^{**} = b^* - e$ where
$e = 0.1$:

```{code-cell} python3
```{code-cell} ipython3
#====================== Experiment 1 ======================#
Ve1,ke1,be1,pe1,qe1,c10e1,c11e1,c20e1,c21e1,𝜉1e1 = off_eq_check(mdl,
kss,
Expand Down Expand Up @@ -1655,7 +1654,7 @@ Therefore, $(k^*,b^{*}-e)$ would not be an equilibrium.

Next, we check for $b^{**} = b^* + e$.

```{code-cell} python3
```{code-cell} ipython3
#====================== Experiment 2 ======================#
Ve2,ke2,be2,pe2,qe2,c10e2,c11e2,c20e2,c21e2,𝜉1e2 = off_eq_check(mdl,
kss,
Expand Down Expand Up @@ -1708,7 +1707,7 @@ want to hold corporate debt.

For example, $\xi^1 > 0$:

```{code-cell} python3
```{code-cell} ipython3
print('Bond holdings of agent 1: {:.3f}'.format(𝜉1e2))
```

Expand All @@ -1726,7 +1725,7 @@ It is also interesting to look at the equilibrium price functions
$q(k,b)$ and $p(k,b)$ faced by firms in our rational
expectations equilibrium.

```{code-cell} python3
```{code-cell} ipython3
# Equity Valuation
fig = go.Figure(data=[go.Scatter3d(x=[kss],
y=[bss],
Expand Down Expand Up @@ -1756,7 +1755,7 @@ Image(fig.to_image(format="png"))
# code locally
```

```{code-cell} python3
```{code-cell} ipython3
# Bond Valuation
fig = go.Figure(data=[go.Scatter3d(x=[kss],
y=[bss],
Expand Down Expand Up @@ -1815,8 +1814,8 @@ $$
The function `valuations_by_agent` is used in calculating these
valuations.

```{code-cell} python3
:tags: ["hide-output"]
```{code-cell} ipython3
:tags: [hide-output]
# Lists for storage
wlist = []
Expand Down Expand Up @@ -1864,7 +1863,7 @@ for i in range(10):
p2list.append(P2)
```

```{code-cell} python3
```{code-cell} ipython3
# Plot
fig, ax = plt.subplots(3,2,figsize=(12,12))
ax[0,0].plot(wlist,klist)
Expand Down Expand Up @@ -1909,7 +1908,7 @@ Now let’s see how the two types of agents value bonds and equities,
keeping in mind that the type that values the asset highest determines
the equilibrium price (and thus the pertinent set of Big $C$’s).

```{code-cell} python3
```{code-cell} ipython3
# Comparing the prices
fig, ax = plt.subplots(1,3,figsize=(16,6))
Expand Down Expand Up @@ -1943,3 +1942,7 @@ Agents of type 2 value bonds more highly (they want more hedging).

Taken together with our earlier plot of equity holdings, these graphs confirm our earlier conjecture that while both type
of agents hold equities, only agents of type 2 holds bonds.

```{code-cell} ipython3
```
42 changes: 18 additions & 24 deletions lectures/coase.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.16.1
kernelspec:
display_name: Python 3
display_name: Python 3 (ipykernel)
language: python
name: python3
---
Expand All @@ -24,14 +26,7 @@ kernelspec:
:depth: 2
```

In addition to what's in Anaconda, this lecture will need the following libraries:

```{code-cell} ipython
---
tags: [hide-output]
---
!pip install interpolation
```
+++

## Overview

Expand All @@ -57,12 +52,10 @@ Couldn't the associated within-firm planning be done more efficiently by the mar

We'll use the following imports:

```{code-cell} ipython
```{code-cell} ipython3
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.optimize import fminbound
from interpolation import interp
```

### Why Firms Exist
Expand Down Expand Up @@ -447,7 +440,7 @@ At each iterate, we will use continuous piecewise linear interpolation of functi

To begin, here's a class to store primitives and a grid:

```{code-cell} python3
```{code-cell} ipython3
class ProductionChain:
def __init__(self,
Expand All @@ -464,7 +457,7 @@ Now let's implement and iterate with $T$ until convergence.
Recalling that our initial condition must lie in $\mathcal P$, we set
$p_0 = c$

```{code-cell} python3
```{code-cell} ipython3
def compute_prices(pc, tol=1e-5, max_iter=5000):
"""
Compute prices by iterating with T
Expand All @@ -481,7 +474,7 @@ def compute_prices(pc, tol=1e-5, max_iter=5000):
while error > tol and i < max_iter:
for j, s in enumerate(grid):
Tp = lambda t: delta * interp(grid, p, t) + c(s - t)
Tp = lambda t: delta * np.interp(t, grid, p) + c(s - t)
new_p[j] = Tp(fminbound(Tp, 0, s))
error = np.max(np.abs(p - new_p))
p = new_p
Expand All @@ -492,14 +485,14 @@ def compute_prices(pc, tol=1e-5, max_iter=5000):
else:
print(f"Warning: iteration hit upper bound {max_iter}")
p_func = lambda x: interp(grid, p, x)
p_func = lambda x: np.interp(x, grid, p)
return p_func
```

The next function computes optimal choice of upstream boundary and range of
task implemented for a firm face price function p_function and with downstream boundary $s$.

```{code-cell} python3
```{code-cell} ipython3
def optimal_choices(pc, p_function, s):
"""
Takes p_func as the true function, minimizes on [0,s]
Expand All @@ -524,7 +517,7 @@ their respective upstream boundary, treating the previous firm's upstream bounda

In doing so, we start with firm 1, who has downstream boundary $s=1$.

```{code-cell} python3
```{code-cell} ipython3
def compute_stages(pc, p_function):
s = 1.0
transaction_stages = [s]
Expand All @@ -539,7 +532,7 @@ Let's try this at the default parameters.
The next figure shows the equilibrium price function, as well as the
boundaries of firms as vertical lines

```{code-cell} python3
```{code-cell} ipython3
pc = ProductionChain()
p_star = compute_prices(pc)
Expand All @@ -558,7 +551,7 @@ plt.show()
Here's the function $\ell^*$, which shows how large a firm with
downstream boundary $s$ chooses to be

```{code-cell} python3
```{code-cell} ipython3
ell_star = np.empty(pc.n)
for i, s in enumerate(pc.grid):
t, e = optimal_choices(pc, p_star, s)
Expand Down Expand Up @@ -590,9 +583,9 @@ Check your intuition by computing the number of firms at delta in (1.01, 1.05, 1
```{solution-start} coa_ex1
:class: dropdown
```
Here is one solution
Here is one solution

```{code-cell} python3
```{code-cell} ipython3
for delta in (1.01, 1.05, 1.1):
pc = ProductionChain(delta=delta)
Expand All @@ -601,6 +594,7 @@ for delta in (1.01, 1.05, 1.1):
num_firms = len(transaction_stages)
print(f"When delta={delta} there are {num_firms} firms")
```

```{solution-end}
```

Expand Down Expand Up @@ -636,7 +630,7 @@ associated with diminishing returns to management --- which induce convexity ---

Here's one way to compute and graph value added across firms

```{code-cell} python3
```{code-cell} ipython3
pc = ProductionChain()
p_star = compute_prices(pc)
stages = compute_stages(pc, p_star)
Expand All @@ -654,4 +648,4 @@ plt.show()
```

```{solution-end}
```
```
Loading

1 comment on commit 262f180

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.