using InstantiateFromURL github_project("QuantEcon/quantecon-notebooks-julia", version = "0.2.0") using LinearAlgebra, Statistics, Compat using DataFrames, Parameters, Plots UncertaintyTrapEcon = @with_kw (a = 1.5, # risk aversion γ_x = 0.5, # production shock precision ρ = 0.99, # correlation coefficient for θ σ_θ = 0.5, # standard dev. of θ shock num_firms = 100, # number of firms σ_F = 1.5, # standard dev. of fixed costs c = -420.0, # external opportunity cost μ_init = 0.0, # initial value for μ γ_init = 4.0, # initial value for γ θ_init = 0.0, # initial value for θ σ_x = sqrt(a / γ_x)) # standard dev. of shock econ = UncertaintyTrapEcon() @unpack ρ, σ_θ, γ_x = econ # simplify names # grid for γ and γ_{t+1} γ = range(1e-10, 3, length = 200) M_range = 0:6 γp = 1 ./ (ρ^2 ./ (γ .+ γ_x .* M_range') .+ σ_θ^2) labels = ["0", "1", "2", "3", "4", "5", "6"] plot(γ, γ, lw = 2, label = "45 Degree") plot!(γ, γp, lw = 2, label = labels) plot!(xlabel = "Gamma", ylabel = "Gamma'", legend_title = "M", legend = :bottomright) function simulate(uc, capT = 2_000) # unpack parameters @unpack a, γ_x, ρ, σ_θ, num_firms, σ_F, c, μ_init, γ_init, θ_init, σ_x = uc # draw standard normal shocks w_shocks = randn(capT) # aggregate functions # auxiliary function ψ function ψ(γ, μ, F) temp1 = -a * (μ - F) temp2 = 0.5 * a^2 / (γ + γ_x) return (1 - exp(temp1 + temp2)) / a - c end # compute X, M function gen_aggregates(γ, μ, θ) F_vals = σ_F * randn(num_firms) M = sum(ψ.(Ref(γ), Ref(μ), F_vals) .> 0) # counts number of active firms if any(ψ(γ, μ, f) > 0 for f in F_vals) # ∃ an active firm x_vals = θ .+ σ_x * randn(M) X = mean(x_vals) else X = 0.0 end return (X = X, M = M) end # initialize dataframe X_init, M_init = gen_aggregates(γ_init, μ_init, θ_init) df = DataFrame(γ = γ_init, μ = μ_init, θ = θ_init, X = X_init, M = M_init) # update dataframe for t in 2:capT # unpack old variables θ_old, γ_old, μ_old, X_old, M_old = (df.θ[end], df.γ[end], df.μ[end], df.X[end], df.M[end]) # define new beliefs θ = ρ * θ_old + σ_θ * w_shocks[t-1] μ = (ρ * (γ_old * μ_old + M_old * γ_x * X_old))/(γ_old + M_old * γ_x) γ = 1 / (ρ^2 / (γ_old + M_old * γ_x) + σ_θ^2) # compute new aggregates X, M = gen_aggregates(γ, μ, θ) push!(df, (γ = γ, μ = μ, θ = θ, X = X, M = M)) end # return return df end df = simulate(econ) plot(eachindex(df.μ), df.μ, lw = 2, label = "Mu") plot!(eachindex(df.θ), df.θ, lw = 2, label = "Theta") plot!(xlabel = "x", ylabel = "y", legend_title = "Variable", legend = :bottomright) len = eachindex(df.θ) yvals = [df.θ, df.μ, df.γ, df.M] vars = ["Theta", "Mu", "Gamma", "M"] plt = plot(layout = (4,1), size = (600, 600)) for i in 1:4 plot!(plt[i], len, yvals[i], xlabel = "t", ylabel = vars[i], label = "") end plot(plt)