### Use QuantEcon Package Source: https://github.com/quantecon/quantecon.jl/blob/master/docs/src/index.md Include this command in your Julia session to start using the QuantEcon package after installation. ```julia using QuantEcon ``` -------------------------------- ### LQ Constructor Example Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lq-control.md Demonstrates how to initialize an LQ type for a simple consumption-savings problem and solve for the infinite horizon stationary values. ```julia using QuantEcon # Simple consumption-savings problem # Minimize E[sum(beta^t * (x_t^2 + u_t^2))] # Subject to: x_{t+1} = 0.9*x_t + u_t + w_t Q = 1.0 # cost of control R = 1.0 # cost of deviation A = 0.9 # state transition B = 1.0 # control effect C = 1.0 # shock effect lq = LQ(Q, R, A, B, C; bet=0.95) # Solve for infinite horizon stationary_values!(lq) println("Policy F: ", lq.F) println("Value P: ", lq.P) ``` -------------------------------- ### Linear Quadratic Control in Julia Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/README.md Illustrates the setup and usage of Linear Quadratic (LQ) control problems with QuantEcon.jl. Ensure the QuantEcon package is installed. ```julia using QuantEcon lq = LQ(1.0, 1.0, 0.95, 1.0, 0.1; bet=0.95) P, F, d = stationary_values(lq) x0 = 1.0 x_path, u_path, w_path = compute_sequence(lq, x0, ts_length=100) ``` -------------------------------- ### Install QuantEcon Package Source: https://github.com/quantecon/quantecon.jl/blob/master/docs/src/index.md Use this command to install the QuantEcon package using the Julia package manager. ```julia Pkg.add("QuantEcon") ``` -------------------------------- ### DiscreteDP Constructor Example (Dense) Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-dp.md Demonstrates how to create a DiscreteDP problem instance using the dense formulation with reward and transition matrices. This is suitable for smaller problems where all state-action transitions are explicitly defined. ```julia using QuantEcon # Simple 2-state, 2-action problem R = [10.0 5.0; # state 1: action 1 gives 10, action 2 gives 5 8.0 2.0] # state 2: action 1 gives 8, action 2 gives 2 Q = zeros(2, 2, 2) # State 1 transitions: Q[1, 1, :] = [0.8, 0.2] # action 1 Q[1, 2, :] = [0.6, 0.4] # action 2 # State 2 transitions: Q[2, 1, :] = [0.7, 0.3] # action 1 Q[2, 2, :] = [0.5, 0.5] # action 2 ddp = DiscreteDP(R, Q, 0.95) # Check number of states println(num_states(ddp)) # 2 ``` -------------------------------- ### Install QuantEcon Package in Julia Source: https://github.com/quantecon/quantecon.jl/blob/master/README.md To install the QuantEcon package, open the Julia package manager (Pkg) and type 'add QuantEcon'. This is the standard method for adding Julia packages. ```julia add QuantEcon ``` -------------------------------- ### LAE Constructor and Estimation Example Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lae.md Demonstrates how to create a Look-Ahead Estimator (LAE) instance with a custom kernel and observed data, then estimate the stationary density at multiple points. Requires QuantEcon and Distributions packages. ```julia using QuantEcon using Distributions # Univariate AR(1) example # y_{t+1} = 0.9*y_t + σ*ε_t, ε_t ~ N(0,1) rho = 0.9 sigma = 0.1 # Stochastic kernel (transition density) function kernel(x, y) # Density of y given x under AR(1) mu = rho .* x sig = sigma return pdf.(Normal.(mu, sig), y) end # Simulate data n = 1000 X = zeros(n) for i in 2:n X[i] = rho * X[i-1] + sigma * randn() end # Create estimator lae = LAE(kernel, X) # Estimate density at various points y_vals = -0.5:0.1:0.5 psi_hat = lae_est(lae, y_vals) println("Estimated density: ", psi_hat) ``` -------------------------------- ### Kalman Filter Smoothing Example Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/kalman.md Demonstrates how to set up a Kalman filter, generate synthetic data, and then smooth the state estimates using the `smooth` function. Ensure the Kalman filter is initialized with prior state and covariance. ```julia using QuantEcon # Setup A = [0.95]' G = [1.0]' Q = [0.01]' R = [0.1]' kal = Kalman(A, G, Q, R) set_state!(kal, [0.0], [1.0]) # Generate synthetic data and smooth T = 100 true_states = randn(1, T) y = G * true_states + sqrt(0.1) * randn(1, T) x_sm, logL, Sigma_sm = smooth(kal, y) println("Log-likelihood: ", logL) ``` -------------------------------- ### Example: Integrating exp(x) using do_quad Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/quadrature.md Demonstrates how to use `do_quad` with nodes and weights generated by `qnwlege` to numerically integrate the exponential function. It also prints the absolute error compared to the true integral. ```julia using QuantEcon # Integrate exp(x) from 0 to 1 nodes, weights = qnwlege(20, 0.0, 1.0) integral = do_quad(exp, nodes, weights) true_integral = exp(1) - 1 println("Error: ", abs(integral - true_integral)) ``` -------------------------------- ### Example: Simple Consumption Problem with Robustness Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/robust-lq.md Demonstrates how to set up and solve a simple consumption problem with robustness using the RBLQ type and the `robust_rule` function. ```julia using QuantEcon # Simple consumption problem with robustness Q = 1.0 # cost of control R = 1.0 # cost of deviation A = 0.95 # state persistence B = 1.0 # control effect C = 0.1 # shock volatility beta = 0.99 theta = 0.1 # robustness parameter rlq = RBLQ(Q, R, A, B, C, beta, theta) # Solve F, K, P = robust_rule(rlq) println("Optimal policy F: ", F) println("Worst-case K: ", K) ``` -------------------------------- ### Demonstrate file handling during branch checkout Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching This example shows how Git handles committed and uncommitted files when switching branches. Only committed files are updated; uncommitted files remain. ```bash qe_website|master ⇒ git checkout -b topic Switched to a new branch 'topic' qe_website|topic ⇒ echo "This is file1" > file1.txt qe_website|topic ⇒ echo "This is file2" > file2.txt qe_website|topic ⇒ git add file1.txt qe_website|topic ⇒ git commit -m "Added file1.txt" [topic 0b07059] Added file1.txt 1 file changed, 1 insertion(+) create mode 100644 file1.txt qe_website|topic ⇒ git status On branch topic Untracked files: (use "git add ..." to include in what will be committed) file2.txt nothing added to commit but untracked files present (use "git add" to track) qe_website|topic ⇒ ls file*.txt file1.txt file2.txt qe_website|topic ⇒ git checkout master Switched to branch 'master' Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) qe_website|master ⇒ git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Untracked files: (use "git add ..." to include in what will be committed) file2.txt nothing added to commit but untracked files present (use "git add" to track) qe_website|master ⇒ ls file*.txt file2.txt ``` -------------------------------- ### Kalman Filter Example: 1D Local Level Model Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/kalman.md Demonstrates initializing and using the Kalman filter for a 1D local level model. It shows how to set the initial state estimate and perform an update with an observation. ```julia using QuantEcon # 1D example: local level model A = [1.0] G = [1.0] Q = [0.1] R = [1.0] kal = Kalman(A, G, Q, R) # Set initial state estimate set_state!(kal, [0.0], [1.0]) # Filter observation y = 0.5 update!(kal, y) println("Updated estimate: ", kal.cur_x_hat) ``` -------------------------------- ### Create and Checkout a New Branch Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Use this command to create a new branch and switch to it in a single step. This is useful for starting new features or fixes in isolation. ```git git checkout -b ``` -------------------------------- ### Kalman Filter Update Example: Multiple Observations Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/kalman.md Demonstrates the complete one-step Kalman filter update process using multiple observations. It initializes the filter, sets the initial state, and then iteratively updates the filter with each observation, printing the filtered estimate. ```julia using QuantEcon # Create filter A = [0.9]' G = [1.0]' Q = [0.1]' R = [0.5]' kal = Kalman(A, G, Q, R) # Initial state set_state!(kal, [0.0], [1.0]) # Process observations observations = [0.1, 0.2, 0.15, 0.25, 0.3] for y in observations update!(kal, [y]) println("Filtered estimate: ", kal.cur_x_hat[1]) end ``` -------------------------------- ### Compute Optimal State and Control Sequences Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lq-control.md Generates the optimal state and control sequences for a given LQ problem starting from an initial state x0 and a specified time series length. ```julia function compute_sequence(lq::LQ, x0::ScalarOrArray, ts_length::Integer=100) ``` -------------------------------- ### Kalman Filter Initialization and Update in Julia Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/README.md Demonstrates initializing and updating a Kalman filter for state space models using QuantEcon.jl. Requires the QuantEcon package and observation data. ```julia using QuantEcon A = [0.95]' G = [1.0]' Q = [0.1]' R = [0.5]' kal = Kalman(A, G, Q, R) set_state!(kal, [0.0], [1.0]) # Process observations for y in observations update!(kal, [y]) end ``` -------------------------------- ### Get Period of Markov Chain Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Calculates and returns the period of a Markov chain, which is the GCD of cycle lengths. ```julia function period(mc::MarkovChain) end ``` -------------------------------- ### Get Number of States in Markov Chain Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Retrieves the total number of states in a given MarkovChain object. ```julia mc = MarkovChain([0.9 0.1; 0.2 0.8]) n = n_states(mc) # Returns 2 ``` -------------------------------- ### Markov Chain Analysis and Simulation in Julia Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/README.md Demonstrates how to create, simulate, and analyze a Markov chain using QuantEcon.jl. Requires the QuantEcon package. ```julia using QuantEcon # Create chain P = [0.9 0.1; 0.2 0.8] mc = MarkovChain(P) # Simulate path = simulate(mc, 100; init=1) # Analyze statdists = stationary_distributions(mc) println(is_irreducible(mc)) ``` -------------------------------- ### LSS Constructor and Usage Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lss.md Demonstrates how to create an LSS instance and simulate a path. The LSS type represents Gaussian linear state space models. ```APIDOC ## LSS Constructor and Usage ### Description This section shows how to instantiate the `LSS` type and use it to simulate state and observation paths. The `LSS` type is fundamental for working with Gaussian linear state space models in QuantEcon.jl. ### Constructor ```julia LSS(A, C, G, H, mu_0, Sigma_0=zeros(size(G,2), size(G,2))) LSS(A, C, G; H=zeros(size(G,1)), mu_0=zeros(size(G,2)), Sigma_0=zeros(size(G,2), size(G,2))) ``` ### Parameters | Parameter | Type | Required | Default | |---|---|---|---| | `A` | `Matrix` | Yes | — | | `C` | `Matrix` | Yes | — | | `G` | `Matrix` | Yes | — | | `H` | `Matrix` | No | `zeros(k)` | | `mu_0` | `Vector` | No | `zeros(n)` | | `Sigma_0` | `Matrix` | No | `zeros(n,n)` | ### Example ```julia using QuantEcon # AR(1) model: x_{t+1} = 0.9*x_t + w_t, y_t = x_t + v_t A = [0.9] C = [1.0] G = [1.0] H = [0.1] lss = LSS(A, C, G, H=H) # Simulate x, y = simulate(lss, 100) println("State shape: ", size(x)) # (1, 100) println("Observation shape: ", size(y)) # (1, 100) ``` ``` -------------------------------- ### Create and Inspect a MarkovChain Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Demonstrates how to create a MarkovChain instance with custom state values and access its properties. ```julia using QuantEcon # Create a 2-state Markov chain P = [0.9 0.1; 0.2 0.8] mc = MarkovChain(P, ["Good", "Bad"]) # Access properties println(n_states(mc)) # 2 println(mc.state_values) # ["Good", "Bad"] ``` -------------------------------- ### Discrete Dynamic Programming Solver in Julia Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/README.md Illustrates setting up and solving a discrete dynamic programming problem using QuantEcon.jl with the Value Function Iteration (VFI) algorithm. Ensure QuantEcon is imported. ```julia using QuantEcon R = [10.0 5.0; 8.0 2.0] Q = zeros(2, 2, 2) Q[1, 1, :] = [0.8, 0.2] Q[1, 2, :] = [0.6, 0.4] Q[2, 1, :] = [0.7, 0.3] Q[2, 2, :] = [0.5, 0.5] ddp = DiscreteDP(R, Q, 0.95) result = solve(ddp, algorithm=VFI()) ``` -------------------------------- ### Get Impulse Response of ARMA Process Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/arma.md Retrieves the impulse response of an ARMA model for a specified horizon length. The impulse_length must be greater than or equal to the number of AR coefficients (p). Includes visualization using Plots. ```julia arma = ARMA([0.8, 0.1], [0.5, 0.2], 1.0) psi = impulse_response(arma, impulse_length=50) # Visualize the response import Plots Plots.plot(psi, xlabel="Lag", ylabel="Response", title="Impulse Response") ``` -------------------------------- ### compute_fixed_point Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/fixed-point.md Finds the fixed point of a function `T` by repeatedly applying it starting from an initial guess `v` until convergence or a maximum number of iterations is reached. It supports various convergence tolerances, verbosity levels, and works with different data types for `v`. ```APIDOC ## compute_fixed_point ### Description Finds the fixed point of a function `T` by repeatedly applying it starting from an initial guess `v` until convergence or a maximum number of iterations is reached. It supports various convergence tolerances, verbosity levels, and works with different data types for `v`. ### Signature ```julia function compute_fixed_point(T::Function, v::TV; err_tol=1e-4, max_iter=100, verbose=2, print_skip=10) where TV ``` ### Parameters #### Path Parameters - **T** (Function) - Required - Operator function: v_new = T(v_old) - **v** (Object) - Required - Initial guess for fixed point #### Query Parameters - **err_tol** (Real) - Optional - Convergence tolerance. Default: `1e-4` - **max_iter** (Integer) - Optional - Maximum number of iterations. Default: `100` - **verbose** (Integer) - Optional - Verbosity level (0, 1, or 2). Default: `2` - **print_skip** (Integer) - Optional - Print interval when verbose=2. Default: `10` ### Returns - **v** (TV) - Fixed point approximation (same type as input) ### Example ```julia using QuantEcon # Find fixed point of T(x) = 4μx(1-x) for μ=0.3 mu = 0.3 T(x) = 4.0 * mu * x * (1.0 - x) x_star = compute_fixed_point(x -> T(x), 0.4) println("Fixed point: ", x_star) println("T(x*) - x* = ", T(x_star) - x_star) # With vector valued function A = [0.9 0.1; 0.1 0.9] b = [1.0, 1.0] T_mat(v) = A*v + b v_star = compute_fixed_point(T_mat, [0.0, 0.0]) println("Fixed point vector: ", v_star) ``` ``` -------------------------------- ### ARMA Process Analysis and Simulation in Julia Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/README.md Shows how to define and analyze an Autoregressive Moving-Average (ARMA) process using QuantEcon.jl. The QuantEcon package must be loaded. ```julia using QuantEcon arma = ARMA(0.5, 0.0, 1.0) w, spect = spectral_density(arma) acov = autocovariance(arma) path = simulation(arma, ts_length=1000) ``` -------------------------------- ### DiscreteDP Constructor (State-Action) Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-dp.md Constructs a DiscreteDP problem using the state-action formulation. This is efficient for problems with sparse or structured state-action spaces. ```APIDOC ## DiscreteDP Constructor (State-Action) ### Description Constructs a `DiscreteDP` object for a state-action formulation. ### Signature ```julia DiscreteDP(R::Vector{T}, Q::Matrix{T}, beta::Real, s_indices::Vector, a_indices::Vector) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `R` | `Vector{T}` | Yes | — | Reward vector (L) | | `Q` | `Matrix{T}` | Yes | — | Transition probability matrix (L×n) | | `beta` | `Real` | Yes | — | Discount factor ∈ [0,1] | | `s_indices` | `Vector` | Yes | — | State indices for each state-action pair | | `a_indices` | `Vector` | Yes | — | Action indices for each state-action pair | ``` -------------------------------- ### simulate! Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Fills a pre-allocated array with sample paths of a Markov chain. This is an in-place operation that can be more memory-efficient for large simulations. It supports specifying initial states for multiple paths. ```APIDOC ## simulate! ### Description Fill a pre-allocated array with sample paths of a Markov chain. This is an in-place operation. ### Method `simulate!(X::Union{AbstractVector,AbstractMatrix}, mc::MarkovChain; init=rand(1:n_states(mc), size(X,2))) ### Parameters #### Path Parameters - **X** (Matrix) - Required - Pre-allocated n×m matrix to fill with m sample paths of length n - **mc** (MarkovChain) - Required - Markov chain instance - **init** (Union{Int, Vector}) - Optional - Random - Initial state(s): scalar or vector of length matching number of paths ### Notes - If `init` is scalar, same initial state used for all paths - If `init` is vector with fewer elements than columns in X, init cycles through columns - State values from mc.state_values appear in X, not indices ### Returns - **X** (Matrix) - The input array filled with sample paths ``` -------------------------------- ### Create and Commit to a New Branch Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Create a new file, add it to staging, and commit it to the current branch. Use 'git status' to observe changes. ```bash qe_website|olg-basic ⇒ vim website/olg_basic.rst # then edit file and save qe_website|olg-basic ⇒ cat website/olg_basic.rst # display file contents .. _olg_basic: ************************************ Overlapping Generations (OLG) Models ************************************ Overview ======== The OLG model is the macro workhorse model for exploring life-cycle dynamics of economic agnets. qe_website|olg-basic ⇒ git status On branch olg-basic Untracked files: (use "git add ..." to include in what will be committed) website/olg_basic.rst nothing added to commit but untracked files present (use "git add" to track) qe_website|olg-basic ⇒ git add . qe_website|olg-basic ⇒ git commit -m "OLG: added stub for basic olg module" [olg-basic 4e0b68b] OLG: added stub for basic olg module 1 file changed, 11 insertions(+) create mode 100644 website/olg_basic.rst qe_website|olg-basic ⇒ git status On branch olg-basic nothing to commit, working directory clean ``` -------------------------------- ### Create and switch to a new branch Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Use the shortcut `git checkout -b ` to create a new branch and immediately switch to it. ```bash qe_website|olg-basic ⇒ git checkout -b olg-basic Switched to a new branch 'olg-basic' ``` -------------------------------- ### Define and Sample DiscreteRV Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-rv.md Demonstrates how to create a DiscreteRV object with given probabilities and draw a single sample or multiple samples from it. ```julia using QuantEcon # Create a discrete RV with probabilities [0.2, 0.5, 0.3] q = [0.2, 0.5, 0.3] drv = DiscreteRV(q) # Draw a sample (returns 1-based index) sample = rand(drv) println("Drew state: ", sample) # Draw multiple samples samples = rand(drv, 1000) ``` -------------------------------- ### DiscreteRV Constructor and Usage Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-rv.md Demonstrates how to create a DiscreteRV object and draw samples from it. The constructor automatically computes the cumulative distribution function and validates the probabilities. ```APIDOC ## DiscreteRV Type for discrete random variable with specified probability distribution. ### Signature ```julia mutable struct DiscreteRV{TV1<:AbstractVector, TV2<:AbstractVector} q::TV1 # Probabilities (must sum to 1) Q::TV2 # Cumulative probabilities end ``` ### Constructor ```julia DiscreteRV(q::AbstractVector) ``` Automatically computes cumulative sum. Validates that probabilities sum to 1 (within 1e-10 tolerance). ### Example ```julia using QuantEcon # Create a discrete RV with probabilities [0.2, 0.5, 0.3] q = [0.2, 0.5, 0.3] drv = DiscreteRV(q) # Draw a sample (returns 1-based index) sample = rand(drv) println("Drew state: ", sample) # Draw multiple samples samples = rand(drv, 1000) ``` ``` -------------------------------- ### Simulate Markov Chain Path into Pre-allocated Array Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Fills a pre-allocated array with sample paths of a Markov chain. This is useful for performance when generating many paths. The `init` parameter can be a scalar or a vector for multiple initial states. ```julia function simulate!(X::Union{AbstractVector,AbstractMatrix}, mc::MarkovChain; init=rand(1:n_states(mc), size(X,2))) # ... implementation details ... end ``` -------------------------------- ### Kalman Filter Constructor Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/kalman.md Initializes a Kalman filter instance. It sets the state transition matrix (A), observation matrix (G), state noise covariance (Q), and observation noise covariance (R). Initial state estimate and covariance are set to zeros. ```julia Kalman(A, G, Q, R) ``` -------------------------------- ### Simulate Bernoulli Trials Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-rv.md Shows how to use DiscreteRV to simulate a Bernoulli random variable and count outcomes from multiple trials. ```julia using QuantEcon # Bernoulli(0.7) drv = DiscreteRV([0.3, 0.7]) # Simulate coin flips flips = rand(drv, 100) # 1 = heads (prob 0.3), 2 = tails (prob 0.7) println("Heads: ", count(x -> x == 1, flips)) ``` -------------------------------- ### simulate Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Generates one sample path of a Markov chain. The path contains state values. You can specify the initial state or let it be chosen randomly. ```APIDOC ## simulate ### Description Generate one sample path of a Markov chain. The path contains state values. ### Method `simulate(mc::MarkovChain, ts_length::Int; init::Int=rand(1:n_states(mc))) ### Parameters #### Path Parameters - **mc** (MarkovChain) - Required - Markov chain instance - **ts_length** (Int) - Required - Length of sample path - **init** (Int) - Optional - Random - Initial state index (1-based) #### Response - **X** (Vector) - Sample path of length ts_length with state values ### Request Example ```julia mc = MarkovChain([0.9 0.1; 0.2 0.8], ["Good", "Bad"]) path = simulate(mc, 100; init=1) println(path[1:10]) # First 10 periods ``` ``` -------------------------------- ### DiscreteDP Constructor (Dense) Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-dp.md Constructs a DiscreteDP problem using the dense formulation. This is suitable for problems where the number of states and actions are relatively small. ```APIDOC ## DiscreteDP Constructor (Dense) ### Description Constructs a `DiscreteDP` object for a dense problem formulation. ### Signature ```julia DiscreteDP(R::Array{T,2}, Q::AbstractArray{T,3}, beta::Real) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `R` | `Matrix{T}` | Yes | — | Reward matrix (n×m) | | `Q` | `AbstractArray{T,3}` | Yes | — | Transition probability tensor (n×m×n) | | `beta` | `Real` | Yes | — | Discount factor ∈ [0,1] | ``` -------------------------------- ### gridmake! Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/utilities.md An in-place version of `gridmake` that fills a pre-allocated output matrix with all combinations of the input arrays. ```APIDOC ## gridmake! ### Description In-place version of gridmake. ### Signature ```julia function gridmake!(out::AbstractMatrix, arrays::Union{AbstractVector,AbstractMatrix}...) ``` ### Parameters #### Parameters - **out** (`AbstractMatrix`) - Pre-allocated output array - **arrays** (`Union{Vector, Matrix}...`) - Input arrays ### Returns - **out** (`AbstractMatrix`) - The filled output array ``` -------------------------------- ### In-place Grid Generation with gridmake! Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/utilities.md An in-place version of `gridmake` that fills a pre-allocated output array with all combinations of input arrays. This can be more memory-efficient for large datasets. ```julia function gridmake!(out::AbstractMatrix, arrays::Union{AbstractVector,AbstractMatrix}...) # ... implementation details ... end ``` -------------------------------- ### LQ Constructor Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lq-control.md Constructs an LQ type instance for representing and solving linear quadratic optimal control problems. It supports both infinite and finite horizon formulations. ```APIDOC ## LQ Constructor ### Description Constructs an LQ type instance for representing and solving linear quadratic optimal control problems. It supports both infinite and finite horizon formulations. ### Signature ```julia LQ(Q, R, A, B, C=fill(zero(eltype(R)), size(R,1)), N=zero(B'A); bet=1.0, capT=nothing, rf=fill(NaN, size(R)...)) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `Q` | `ScalarOrArray` | Yes | — | k×k payoff for control, symmetric nonnegative definite | | `R` | `ScalarOrArray` | Yes | — | n×n payoff for state, symmetric nonnegative definite | | `A` | `ScalarOrArray` | Yes | — | n×n state transition coefficient | | `B` | `ScalarOrArray` | Yes | — | n×k control transition coefficient | | `C` | `ScalarOrArray` | No | `zeros(n)` | n×j shock transition coefficient | | `N` | `ScalarOrArray` | No | `zeros(k,n)` | k×n cross product term | | `bet` | `Real` | No | `1.0` | Discount factor ∈ [0,1] | | `capT` | `Union{Int, Nothing}` | No | `nothing` | Terminal period; `nothing` means infinite | | `rf` | `ScalarOrArray` | No | `fill(NaN,...)` | n×n terminal payoff matrix | ``` -------------------------------- ### MVNSampler Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/other-functions.md Initializes a multivariate normal sampler. ```APIDOC ## MVNSampler ### Description Multivariate normal sampler. ### Signature ```julia MVNSampler(mu::Vector, Sigma::Matrix) ``` ### Methods - `rand(sampler)` — Draw one sample - `rand(sampler, n)` — Draw n samples ``` -------------------------------- ### LAE Estimation at Single and Multiple Points Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lae.md Shows how to use the `lae_est` function to estimate the stationary density at a single point and across a grid of values. Includes plotting the estimated density. Requires QuantEcon. ```julia using QuantEcon # Create kernel rho = 0.9 sigma = 0.1 function kernel(x, y) mu = rho .* x return pdf.(Normal.(mu, sigma), y) end # Simulate AR(1) n = 1000 X = zeros(n) for i in 2:n X[i] = rho * X[i-1] + sigma * randn() end lae = LAE(kernel, X) # Estimate at single point psi_at_zero = lae_est(lae, 0.0) println("ψ(0) ≈ ", psi_at_zero) # Estimate at multiple points y_grid = range(-1, 1, length=50) psi_vals = lae_est(lae, y_grid) using Plots plot(y_grid, psi_vals, label="Estimated density") ``` -------------------------------- ### Simulate and Plot ARMA Process Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/arma.md Simulates an ARMA process with specified parameters and plots the resulting time series. Ensure the Plots package is imported. ```julia arma = ARMA(0.7, [0.1, -0.3], 1.0) path = simulation(arma, ts_length=1000, impulse_length=50) # Plot the simulated path import Plots Plots.plot(path, xlabel="Time", ylabel="Value", label="Simulated ARMA Process") ``` -------------------------------- ### Compute Agent's Best Response (K_to_F) Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/robust-lq.md Calculates agent 1's best response policy (F) and the corresponding value function (P) given the worst-case shock response (K). Use this when determining optimal strategies against an adversary. ```julia function K_to_F(rlq::RBLQ, K::Matrix) # ... implementation details ... end ``` -------------------------------- ### Define ARMA Process Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/arma.md Creates an ARMA(1,2) process with specified AR and MA parameters and noise standard deviation. Demonstrates accessing the p, q, and sigma fields of the created ARMA instance. ```julia using QuantEcon # Create an ARMA(1,2) process phi = 0.5 theta = [0.0, -0.8] sigma = 1.0 arma = ARMA(phi, theta, sigma) # Access fields println(arma.p) # 1 println(arma.q) # 2 println(arma.sigma) # 1.0 ``` -------------------------------- ### simulate Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lss.md Simulates one path of the LSS model for a specified length of time. ```APIDOC ## simulate ### Description Simulates one path of the LSS model, generating sequences of state and observation values over a given time period. ### Signature ```julia function simulate(lss::LSS, ts_length=100) ``` ### Parameters | Parameter | Type | Required | Default | |---|---|---|---| | `lss` | `LSS` | Yes | — | | `ts_length` | `Int` | No | `100` | ### Returns - `x::Matrix` — n×ts_length matrix of state values - `y::Matrix` — k×ts_length matrix of observation values ### Notes - The initial state is drawn from a multivariate normal distribution defined by `mu_0` and `Sigma_0`. - Each column in the returned matrices represents a single time step. ### Example ```julia lss = LSS([0.9], [0.1], [1.0]) x, y = simulate(lss, 500) using Plots plot(y', label="Observations", xlabel="Time") ``` ``` -------------------------------- ### Simulate Markov Chain Path Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Generates a sample path of a Markov chain. Specify the chain, desired path length, and an optional initial state. ```julia mc = MarkovChain([0.9 0.1; 0.2 0.8], ["Good", "Bad"]) path = simulate(mc, 100; init=1) println(path[1:10]) # First 10 periods ``` -------------------------------- ### Equidistributed Quadrature Nodes and Weights Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/quadrature.md Generates equidistributed or grid quadrature nodes and weights for a given number of nodes and interval. ```julia function qnwequi(n::Int, a::Real, b::Real) ``` -------------------------------- ### Checkout Master and Create New Branch Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Switch to the main branch and create a new branch for independent development, ensuring it's based on the latest stable code. ```git git checkout master git pull origin master git checkout -b industry-dyn ``` -------------------------------- ### Simulate Markov Chain Path (Indices) Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Generates a sample path of a Markov chain, returning state indices instead of state values. Useful when the state names are not needed. ```julia function simulate_indices(mc::MarkovChain, ts_length::Int; init::Int=rand(1:n_states(mc))) # ... implementation details ... end ``` -------------------------------- ### set_state! Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/kalman.md Sets the initial state estimate (mean and covariance) for the Kalman filter. ```APIDOC ## set_state! Set the current state estimate of the Kalman filter. ### Signature ```julia function set_state!(k::Kalman, x_hat, Sigma) ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | `k` | `Kalman` | Kalman filter instance | | `x_hat` | `Vector` | State mean estimate | | `Sigma` | `Matrix` | State covariance estimate | ### Returns - `nothing` — Modifies the filter in-place ### Notes Sets both `k.cur_x_hat` and `k.cur_sigma` to provided values. ``` -------------------------------- ### List branches after checkout Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Verify the current branch after using `git checkout` by listing all branches. ```bash qe_website|olg-basic ⇒ git branch david-evans-model master * olg-basic ``` -------------------------------- ### backward_induction Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-dp.md Solves a finite horizon discrete dynamic programming problem using the backward induction method. ```APIDOC ## backward_induction ### Description Solve finite horizon DP by backward induction. ### Signature ```julia function backward_induction(ddp::DiscreteDP) ``` ### Parameters #### Parameters - `ddp` (DiscreteDP) - Problem instance ``` -------------------------------- ### qnwunif Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/quadrature.md Computes quadrature nodes and weights for the Uniform distribution. ```APIDOC ## qnwunif ### Description Quadrature nodes and weights for Uniform distribution. ### Signature ```julia function qnwunif(n::Int, a::Real, b::Real) ``` ``` -------------------------------- ### replicate Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lss.md Simulates multiple replications of the LSS model at a fixed time point. ```APIDOC ## replicate ### Description Simulates multiple independent paths of the LSS model up to a specified time point `t`, allowing for the analysis of distributions at that specific time. ### Signature ```julia function replicate(lss::LSS, t::Integer, num_reps::Integer=100) replicate(lss::LSS; t::Integer=10, num_reps::Integer=100) ``` ### Parameters | Parameter | Type | Required | Default | |---|---|---|---| | `lss` | `LSS` | Yes | — | | `t` | `Int` | No | `10` | | `num_reps` | `Int` | No | `100` | ### Returns - `x::Matrix` — n×num_reps matrix of state values at time t - `y::Matrix` — k×num_reps matrix of observation values at time t ### Example ```julia lss = LSS([0.9], [0.1], [1.0]) x_t, y_t = replicate(lss, t=50, num_reps=1000) # Compute sample mean at t=50 mean_y = mean(y_t, dims=2) ``` ``` -------------------------------- ### Generate All Combinations with gridmake Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/utilities.md Creates all possible combinations of elements from input arrays (Cartesian product). The first array varies fastest. Use for generating all possible states or parameter combinations. ```julia using QuantEcon x = [1, 2, 3] y = [10, 20] z = [100, 200] grid = gridmake(x, y, z) # Result: 12×3 matrix with all combinations # (1,10,100), (2,10,100), (3,10,100), (1,20,100), ... # Or with integers: grid = gridmake((3, 2)) # All combinations of 1:3 and 1:2 ``` -------------------------------- ### Uniform Distribution Quadrature Nodes and Weights Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/quadrature.md Computes quadrature nodes and weights for the Uniform distribution. ```julia function qnwunif(n::Int, a::Real, b::Real) ``` -------------------------------- ### RBLQ Constructor Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/robust-lq.md Constructs an RBLQ object for robust linear quadratic control problems. It automatically reshapes scalar or vector inputs to the appropriate matrix dimensions. ```APIDOC ## RBLQ Constructor ### Signature ```julia RBLQ(Q::ScalarOrArray, R::ScalarOrArray, A::ScalarOrArray, B::ScalarOrArray, C::ScalarOrArray, bet::Real, theta::Real) ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | `Q` | `Matrix` | k×k control cost matrix (symmetric, positive definite) | | `R` | `Matrix` | n×n state cost matrix (symmetric, nonnegative definite) | | `A` | `Matrix` | n×n state transition | | `B` | `Matrix` | n×k control coefficient | | `C` | `Matrix` | n×j shock coefficient | | `bet` | `Real` | Discount factor ∈ [0,1] | | `theta` | `Real` | Robustness parameter > 0 | ``` -------------------------------- ### Tauchen's Method for AR(1) Approximation Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-approx.md Approximates an AR(1) process using Tauchen's method. Requires specifying the number of grid points, persistence, and standard deviation of innovation. ```julia using QuantEcon # AR(1): y_t = 0.9*y_{t-1} + 0.1*ε_t mc = tauchen(9, 0.9, 0.1) # Simulate path = simulate(mc, 100) println("Grid points: ", mc.state_values) println("Transition matrix (3×3):") println(mc.p[1:3, 1:3]) ``` -------------------------------- ### Checkout to Existing Branch Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Switch back to a previously worked-on branch to continue development, ensuring the working directory is clean first. ```git git status git checkout olg-basic ``` -------------------------------- ### simulate_indices! Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/markov-chain.md Fills a pre-allocated array with state indices from Markov chain simulations. This in-place version is efficient for generating multiple index paths. ```APIDOC ## simulate_indices! ### Description Fill a pre-allocated array with state indices from Markov chain simulations. This is an in-place operation. ### Method `simulate_indices!(X::Union{AbstractVector{T},AbstractMatrix{T}}, mc::MarkovChain; init=rand(1:n_states(mc), size(X,2)))) where T<:Integer ### Parameters #### Path Parameters - **X** (AbstractMatrix{Int}) - Required - Pre-allocated matrix to fill with indices - **mc** (MarkovChain) - Required - Markov chain instance - **init** (Union{Int, Vector}) - Optional - Random - Initial state(s) ### Returns - **X** (AbstractMatrix{Int}) - The input array filled with state indices ``` -------------------------------- ### Backward Induction Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/discrete-dp.md Solves finite horizon discrete dynamic programming problems using the backward induction method. Requires only the discrete dynamic programming problem instance. ```julia function backward_induction(ddp::DiscreteDP) ``` -------------------------------- ### Brent's Method Variant for Root Finding Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/other-functions.md A variant of Brent's method for root finding. Tolerances and maximum iterations can be specified. ```julia function brent(f, a, b; tol=1e-6, max_iter=100) end ``` -------------------------------- ### Brent's Method for Root Finding Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/other-functions.md Finds the root of a function within a given interval using Brent's method. Tolerances and maximum iterations can be specified. ```julia function brenth(f, a, b; tol=1e-6, max_iter=100) end ``` -------------------------------- ### List all branches Source: https://github.com/quantecon/quantecon.jl/wiki/Git:-Branching Execute `git branch` to see a list of all local branches, with an asterisk indicating the current branch. ```bash qe_website|master ⇒ git branch david-evans-model * master olg-basic ``` -------------------------------- ### is_stable Source: https://github.com/quantecon/quantecon.jl/blob/master/_autodocs/api-reference/lss.md Tests the stability of a linear state space system. ```APIDOC ## is_stable ### Description Tests whether a linear state space system is stable by checking if all eigenvalues of the system matrix A have a modulus less than 1. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters - **lss** (`LSS`) - Required - LSS instance ### Returns - **stable** (`Bool`) - True if all eigenvalues of A have modulus < 1 ### Notes Removes constant rows/columns before checking eigenvalues. ```