Skip to content

Commit ca02674

Browse files
Add cobweb animation for naive expectations
Adds an animation to illustrate the cobweb dynamics under naive expectations.
1 parent 99fbdbf commit ca02674

1 file changed

Lines changed: 38 additions & 3 deletions

File tree

lectures/cobweb.md

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ We will use the following imports.
6060
```{code-cell} ipython3
6161
import numpy as np
6262
import matplotlib.pyplot as plt
63+
from matplotlib.animation import FuncAnimation
64+
from IPython.display import HTML
6365
```
6466

6567
## History
@@ -319,10 +321,43 @@ m = Market()
319321
```
320322

321323
```{code-cell} ipython3
322-
plot45(m, 0, 9, 2, num_arrows=3)
324+
fig, ax = plt.subplots(figsize=(9, 8))
325+
ax.set_xlabel('$p_t$')
326+
ax.set_ylabel('$p_{t+1}$')
327+
328+
ax.plot([0, 9], [0, 9], lw=1, alpha=0.7, label='45°')
329+
330+
p_grid = np.linspace(0, 9, 200)
331+
ax.plot(p_grid, [g(m, p) for p in p_grid], 'b-', lw=2, alpha=0.6, label='g')
332+
333+
ax.legend()
334+
335+
cobweb, = ax.plot([], [], lw=1.5)
336+
point, = ax.plot([], [], '.', markersize=20)
337+
338+
def animate(i):
339+
p0 = 2
340+
x, y = [p0], [p0]
341+
p = p0
342+
343+
for _ in range(i):
344+
p_next = g(m, p)
345+
x.extend([p, p])
346+
y.extend([p_next, p_next])
347+
x.append(p_next)
348+
y.append(p_next)
349+
p = p_next
350+
351+
cobweb.set_data(x, y)
352+
point.set_data([p], [p])
353+
return cobweb, point
354+
355+
anim = FuncAnimation(fig, animate, frames=20, interval=500, blit=True)
356+
plt.close()
357+
HTML(anim.to_jshtml())
323358
```
324359

325-
The plot shows the function $g$ defined in {eq}`def_g` and the 45-degree line.
360+
The animation shows the function $g$ defined in {eq}`def_g`, the 45-degree line, and the resulting price dynamics.
326361

327362
Think of $ p_t $ as a value on the horizontal axis.
328363

@@ -595,4 +630,4 @@ ts_plot_price_blae(m,
595630
```
596631

597632
```{solution-end}
598-
```
633+
```

0 commit comments

Comments
 (0)