Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MAINT: Simplify pages and migrate to gh-pages based deployments #6

Merged
merged 18 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Build Project [using jupyter-book]
on: [push]
jobs:
preview:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
# Push website files to netlify
- name: Preview Deploy to Netlify
uses: nwtgck/actions-netlify@v2
with:
publish-dir: website
production-branch: main
github-token: ${{ secrets.GITHUB_TOKEN }}
deploy-message: "Preview Deploy from GitHub Actions"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
18 changes: 18 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Assemble & Publish to GH-PAGES
on:
push:
tags:
- 'publish*'
jobs:
publish:
if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Deploy website to gh-pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: website
cname: dp.quantecon.org
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
.DS_Store
*./DS_Store
*./DS_Store
.ipynb_checkpoints
__pycache__
29 changes: 29 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2022, QuantEcon
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ Public repo for the textbook **Dynamic Programming Volume 1** by [Thomas J.
Sargent](http://www.tomsargent.com/) and [John
Stachurski](https://johnstachurski.net/).

## Website
| Folder | Description |
|--------|-------------|
| website | HTML files that build the website |
| pdf | PDF of the book |
| code | Public source of `py` and `jl` code |

The website is currently being built with `jekyll`
## PDF

The PDF is available in `pdf/dp.pdf`

Comments and feedback are very welcome.
The easiest way to provide feedback is to open an issue above.
4 changes: 4 additions & 0 deletions code/jl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
The source code here is read into the private repo via a symbolic link.

If you edit a jl file here and rerun to produce a PDF, it needs to be shifted to
code_book/figures, which is also connected to the private repo via a sym link.
153 changes: 153 additions & 0 deletions code/jl/american_option.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""
Valuation for finite-horizon American call options in discrete time.

"""

include("s_approx.jl")
using QuantEcon, LinearAlgebra, IterTools

"Creates an instance of the option model with log S_t = Z_t + W_t."
function create_american_option_model(;
n=100, μ=10.0, # Markov state grid size and mean value
ρ=0.98, ν=0.2, # persistence and volatility for Markov state
s=0.3, # volatility parameter for W_t
r=0.01, # interest rate
K=10.0, T=200) # strike price and expiration date
t_vals = collect(1:T+1)
mc = tauchen(n, ρ, ν)
z_vals, Q = mc.state_values .+ μ, mc.p
w_vals, φ, β = [-s, s], [0.5, 0.5], 1 / (1 + r)
e(t, i_w, i_z) = (t ≤ T) * (z_vals[i_z] + w_vals[i_w] - K)
return (; t_vals, z_vals, w_vals, Q, φ, T, β, K, e)
end

"The continuation value operator."
function C(h, model)
(; t_vals, z_vals, w_vals, Q, φ, T, β, K, e) = model
Ch = similar(h)
z_idx, w_idx = eachindex(z_vals), eachindex(w_vals)
for (t, i_z) in product(t_vals, z_idx)
out = 0.0
for (i_w′, i_z′) in product(w_idx, z_idx)
t′ = min(t + 1, T + 1)
out += max(e(t′, i_w′, i_z′), h[t′, i_z′]) *
Q[i_z, i_z′] * φ[i_w′]
end
Ch[t, i_z] = β * out
end
return Ch
end

"Compute the continuation value function by successive approx."
function compute_cvf(model)
h_init = zeros(length(model.t_vals), length(model.z_vals))
h_star = successive_approx(h -> C(h, model), h_init)
return h_star
end


# Plots

using PyPlot
using LaTeXStrings
PyPlot.matplotlib[:rc]("text", usetex=true) # allow tex rendering
fontsize=16


function plot_contours(; savefig=false,
figname="./figures/american_option_1.pdf")

model = create_american_option_model()
(; t_vals, z_vals, w_vals, Q, φ, T, β, K, e) = model
h_star = compute_cvf(model)

fig, axes = plt.subplots(3, 1, figsize=(7, 11))
z_idx, w_idx = eachindex(z_vals), eachindex(w_vals)
H = zeros(length(w_vals), length(z_vals))

for (ax_index, t) in zip(1:3, (1, 195, 199))

ax = axes[ax_index, 1]

for (i_w, i_z) in product(w_idx, z_idx)
H[i_w, i_z] = e(t, i_w, i_z) - h_star[t, i_z]
end

cs1 = ax.contourf(w_vals, z_vals, transpose(H), alpha=0.5)
ctr1 = ax.contour(w_vals, z_vals, transpose(H), levels=[0.0])
plt.clabel(ctr1, inline=1, fontsize=13)
plt.colorbar(cs1, ax=ax) #, format="%.6f")

ax.set_title(L"t=" * "$t", fontsize=fontsize)
ax.set_xlabel(L"w", fontsize=fontsize)
ax.set_ylabel(L"z", fontsize=fontsize)

end

fig.tight_layout()
if savefig
fig.savefig(figname)
end
plt.show()
end


function plot_strike(; savefig=false,
fontsize=12,
figname="./figures/american_option_2.pdf")

model = create_american_option_model()
(; t_vals, z_vals, w_vals, Q, φ, T, β, K, e) = model
h_star = compute_cvf(model)

# Built Markov chains for simulation
z_mc = MarkovChain(Q, z_vals)
P_φ = zeros(length(w_vals), length(w_vals))
for i in eachindex(w_vals) # Build IID chain
P_φ[i, :] = φ
end
w_mc = MarkovChain(P_φ, w_vals)


y_min = minimum(z_vals) + minimum(w_vals)
y_max = maximum(z_vals) + maximum(w_vals)
fig, axes = plt.subplots(3, 1, figsize=(7, 12))

for ax in axes

# Generate price series
z_draws = simulate_indices(z_mc, T, init=Int(length(z_vals) / 2 - 10))
w_draws = simulate_indices(w_mc, T)
s_vals = z_vals[z_draws] + w_vals[w_draws]

# Find the exercise date, if any.
exercise_date = T + 1
for t in 1:T
if e(t, w_draws[t], z_draws[t]) ≥ h_star[w_draws[t], z_draws[t]]
exercise_date = t
end
end

@assert exercise_date ≤ T "Option not exercised."

# Plot
ax.set_ylim(y_min, y_max)
ax.set_xlim(1, T)
ax.fill_between(1:T, ones(T) * K, ones(T) * y_max, alpha=0.2)
ax.plot(1:T, s_vals, label=L"S_t")
ax.plot((exercise_date,), (s_vals[exercise_date]), "ko")
ax.vlines((exercise_date,), 0, (s_vals[exercise_date]), ls="--", colors="black")
ax.legend(loc="upper left", fontsize=fontsize)
ax.text(-10, 11, "in the money", fontsize=fontsize, rotation=90)
ax.text(-10, 7.2, "out of the money", fontsize=fontsize, rotation=90)
ax.text(exercise_date-20, 6, #s_vals[exercise_date]+0.8,
"exercise date", fontsize=fontsize)
ax.set_xticks((1, T))
ax.set_yticks((y_min, y_max))
end

if savefig
fig.savefig(figname)
end
plt.show()
end
97 changes: 97 additions & 0 deletions code/jl/ar1_spec_rad.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""

Compute r(L) for model

Zₜ = μ (1 - ρ) + ρ Zₜ₋₁ + σ εₜ
β_t = b(Z_t)

The process is discretized using the Tauchen method with n states.
"""

using LinearAlgebra, QuantEcon

function compute_mc_spec_rad(n, ρ, σ, μ, m, b)
mc = tauchen(n, ρ, σ, μ * (1 - ρ), m)
state_values, P = mc.state_values, mc.p

L = zeros(n, n)
for i in 1:n
for j in 1:n
L[i, j] = b(state_values[i]) * P[i, j]
end
end
r = maximum(abs.(eigvals(L)))
return r
end

# Hubmer et al parameter values, p. 24 of May 17 2020 version.

n = 15
ρ = 0.992
σ = 0.0006
μ = 0.944
m = 4
b(z) = z

println("Spectral radius of L in Hubmer et al.:")
println(compute_mc_spec_rad(n, ρ, σ, μ, m, b))

# ## Hills et al 2019 EER

# For the empirical model,
#
# $$
# Z_{t+1} = 1 - \rho + \rho Z_t + \sigma \epsilon_{t+1},
# \quad \beta_t = \beta Z_t
# $$
#
# with
#
# $$
# \beta = 0.99875, \; \rho = 0.85, \; \sigma = 0.0062
# $$
#
# They use 15 grid points on $[1-4.5\sigma_\delta, 1+4.5\sigma_\delta]$.

n = 15
ρ = 0.85
σ = 0.0062
μ = 1
m = 4.5
beta = 0.99875
b(z) = beta * z

println("Spectral radius of L in Hills et al.:")
println(compute_mc_spec_rad(n, ρ, σ, μ, m, b))

# Let's run a simulation of the discount process.
# Plots

using PyPlot
using LaTeXStrings
PyPlot.matplotlib[:rc]("text", usetex=true) # allow tex rendering
fs=14

function plot_beta_sim(; T=80,
savefig=false,
figname="./figures/ar1_spec_rad.pdf")
β_vals = zeros(T)
Z = 1
for t in 1:T
β_vals[t] = beta * Z
Z = 1 - ρ + ρ * Z + σ * randn()
end

fig, ax = plt.subplots(figsize=(6, 3.8))

ax.plot(β_vals, label=L"\beta_t")
ax.plot(1:T, ones(T), "k--", alpha=0.5, label=L"\beta=1")
ax.set_yticks((0.97, 1.0, 1.03))
ax.set_xlabel("time")
ax.legend(frameon=false, fontsize=fs)

if savefig
fig.savefig(figname)
end
plt.show()
end
Loading
Loading