BLP
Introduction This note presents the Random Coefficient Logit model, often referred to as the “BLP” model, proposed by Berry et al. (1995). This model offers a method for estimating demand that considers the varying demand responses to changes in price while addressing issues related to price endoegeneity. Outline Begin by establishing a indirect utility function for consumer i consuming product j in market m. Transform the indirect utiltiy function into a composite of mean utility, which applies uniformly to all consumers using product j in market m, and individual-specific random components that capture consumer tastes (preferences)....
Datatable basics in R
To be updated
LASSO
To be updated
SQL basics
Create database Select columns Select rows Joins
The McCall Search Model
Set up An agent decides whether to delay her employment later (keep searching) or take the job (settle). An agent’s action is binary (keep searching or take the job). If she takes the job, she will get constant wage indefinitely. If she rejects the job, she receives unemployment compensation c and reconsider her choice next period. The probability of observing wage offer is uniformly distributed. There are n states of wages with equal probability....
Broadcasting in Julia
By using Ref(), it protects the object inside it from being iterated over. Supoose we define the following function fun. See the examples below that demonstrate how broadcasting works: fun(a,x)=a.-x Case 1: fun.([1,2], [3,4]) Note that without Ref(), both arguments of function fun are interated over from broadcasting. This implies that each element within each argument will be computed element-wise. ([1-3, 2-4]) 2-element Vector{Int64}: -2 -2 Case 2: fun.([1,2], Ref([3,4])) Note that Ref() protects [3,4]....
pop! and push!
push! Continuing on previous post, let’s start with creating an Dictionary object. eng2kor=Dict( "one"=>"일", "two"=>"이", "three"=>"삼", "four"=>"사" ) Output: Dict{String, String} with 4 entries: "two" => "이" "four" => "사" "one" => "일" "three" => "삼" push! allows us to add one additional key-value pair if the added key is not present in the existing Dictionary, or if it is present, replace existing key with different value. # replace with existing key with different value push!...
Dictionaries in Julia
What comprise Dictionaries? Keys Values Example codes eng2kor=Dict( "one"=>"일", "two"=>"이", "three"=>"삼", "four"=>"사" ) function histogram(s) d = Dict() for c in s if c ∉ keys(d) d[c] = 1 else d[c] += 1 end end d end Output: Dict{Any, Any} with 3 entries: '보… => 2 '장… => 2 '윤… => 2 Reference https://benlauwens.github.io/ThinkJulia.jl/latest/book.html#_a_dictionary_is_a_mapping
Multi-threading
How to check the number of threads Threads.nthreads() Output: 8 For me, I have eight threads at my disposal for code execution. How to check thread id Threads.threadid() Output: 1 Since we are on the master thread, Threads.threadid() will return 1. @threads Macro Below we create a with 10 elements in it, then use multi-threads to put thread id used to process the given for loop. To use multi-thread, we use Threads....
reshape and permutedims
The elements in the reshaped matrix will always be orderded column-wise. For example, consider the following code: using LinearAlgra C = [1,2,3,4,5,6] reshape(C, (2,3)) Output: 2×3 Matrix{Int64}: 1 3 5 2 4 6 Notice that number 2 is placed in the first column of the second row, instead of the second column of the first row. Suppose that we want to create a 2-by-3 matrix where the first row is initially filled and the second row is filled afterwards....
Argmax
Today I explore argmax and argmin function defined in Base package. armax returns a maximal index, while argmin returns a minimal index. A = [1 2; 3 4] argmax(A) Output: CartesianIndex(2, 2) B=[-1 2; 10 -10] argmax(B) Output: CartesianIndex(2, 1) argmin(B) Output: CartesianIndex(2, 2) argmax can have a function as the first argument (say f) and the domain of the function (say x) as the second argument and it will still find a value of x that maximizes f(x) ....
Markov Chain (example codes)
Simulation of Markov Chain The following code excerpts are from julia.quantecon.org. I added explanations to each line of codes. function mc_sample_path(P; init=1, sample_size=1000) # transition matrix, P, should be a square matrix @assert size(P)[1] == size(P)[2] # N be the number of rows of P matrix (or the number of initial states) N = size(P)[1] # dists be the state transition probabilities for each initial state; for example dists[1] will be state-transition probabilities of state 1 transitioning to state 1 and 2 respectively dists = [Categorical(P[i, :]) for i in 1:N] # create X that stores samples X = fill(0, sample_size) # put init as the first element of X X[1] = init # loop over from 2 to the `sample_size` that draws randomly of states (either 1 or 2) by the last state's transition distribution for t in 2:sample_size dist=dists[X[t-1]] X[t]=rand(dist) end return X end P=[0....
AR(1) model
Suppose we have following AR(1) model (autoregressive model of order 1) defined by: $$ X_{t+1}=aX_t + b+ cW_{t+1} $$ where \(X_0\) and \(W_{t}\) are independent, [a,b,c] are scalar-valued parameters, the state space is \(\mathbb{R}\), the process \(W_{t}\) is independently distributed and standard normal, and initial condition \(X_0\) is drawn from the normal distribution of mean \(\mu_0\) and standard error of \(\nu_0\). Iterating backward from time \(t\), we have $$ X_t = a^tX_0 + b \sum_{j=0}^{t-1}a^j + c\sum_{j=0}^{t-1}a^jW_{t-j}, $$ which implies that \(X_t\) depends on parameter [a,b,c], initial condition \(X_0\), and the sequence of shocks from period 1 throughout t represented by \(W_1, \cdots, W_t\)....
Dynamics in One Dimension
Consider a law of motion for the Solow growth model, in which the trajectory of capital is determined non-linearly: $$ k_{t+1} = Ask_{t}^\alpha + (1-\delta)k_t $$ Here \(k\) is capital stock, and \([A,s, \alpha, \delta] \) are positive parameters. The following code excerpts are from julia.quantecon.org. g(k;p) is a function that represents the capital transition function, given the parameter set p and argument k. g(k; p) = p.A * p.s * k^p....
Julia Essentials
; We add ; to suppress output returned. For example let’s compare two codes with and without ; at the end. x=2 would return 2 in the console as an output while x=2; will not return anything in the console. enumerate() enumerate() returns both the index and the value of an element in an array. collect(enumerate(countries)) Output: (1, "Korea") (2, "Japan") (3, "China") countries = ("Korea", "Japan", "China") for (index, country) in enumerate(countries) println("Country $(country) in index $(index)") end Output:...
Matrix Decomposition
Matrix decomposition example Let N be the number of possible simulated paths, T be the number of time periods, and P be the number of parameters to estimate. For now, let’s suppose that N = 4, T=2 and P=2. Below is an example with T-by-N matrix. The rows indicates different time periods, and the columns indicate different simulated paths \(n \in \{1,2,3,4\} \). For example, $$ A = \begin{bmatrix} a_{11}\theta + b_{11}\rho & a_{12}\theta + b_{12}\rho & a_{13}\theta + b_{13}\rho & a_{14}\theta + b_{14}\rho \newline \beta(a_{21}\theta + b_{21}\rho) & \beta(a_{22}\theta + b_{22}\rho) & \beta(a_{23}\theta + b_{23}\rho) & \beta(a_{24}\theta + b_{24}\rho) \end{bmatrix} \newline $$ When n =1, $$ \begin{bmatrix} 1 & \beta \end{bmatrix} \begin{bmatrix} a_{11} & b_{11} \newline a_{21} & b_{21} \end{bmatrix} \begin{bmatrix} \theta \newline \rho \end{bmatrix} $$ When n =2, $$ \begin{bmatrix} 1 & \beta \end{bmatrix} \begin{bmatrix} a_{12} & b_{12} \newline a_{22} & b_{22} \end{bmatrix} \begin{bmatrix} \theta \newline \rho \end{bmatrix} $$ When n =3, $$ \begin{bmatrix} 1 & \beta \end{bmatrix} \begin{bmatrix} a_{13} & b_{13} \newline a_{23} & b_{23} \end{bmatrix} \begin{bmatrix} \theta \newline \rho \end{bmatrix} $$ When n =4, $$ \begin{bmatrix} 1 & \beta \end{bmatrix} \begin{bmatrix} a_{14} & b_{14} \newline a_{24} & b_{24} \end{bmatrix} \begin{bmatrix} \theta \newline \rho \end{bmatrix} $$...
Quantitative Economics with Julia
for loop in, ∈, = Below three for loops return the same output. Note that in, ∈, = can be used interchangeably to indicate that i loops over the following array, 1:2:10 which indicates that the array ranges from 1 to 10 with an increment of 2. for i in 1:2:10 println(i) end for i ∈ 1:2:10 println(i) end for i = 1:2:10 println(i) end Output: 1 3 5 7 9 eachindex I also introduce in this post eachindex, which returns the index of a given vector....
DataFrames.jl (3) and Pipe
Selecting and transforming columns When selecting variables of a data frame, we do add : to indicate that it’s a variable name. Thus for example, if we want to select column with variable x, we use :x inside select(). First let’s construct some 500 by 3 dimensional data frame called df that contains three columns each of which has name of A, B, and C. using DataFrames df = DataFrame( A=1:2:1000, B= repeat(1:10, inner=50), C= 1:500) Each of below codes produces 500 by 1 dataframe, a data frame that only contains column A....
AI and Workforce Competition
Some argue that those who fail to utilize AI cannot keep up with their competitors. But is that necessarily true? To answer this question, we need to consider how AI affects workforce competition. Suppose that two candidates, one with high-skills (referred to as worker A) and the other with low-skills (referred to as worker B) are competing for a job at some company C. Now that AI is readily available to both workers, they would both use it, assuming that AI improves their competitiveness....
SymPy.jl
SymPy.jl When functions are linear in parameters, we can decompose a matrix of polynomials into a matrix of coefficients and a matrix of variables. To achieve this, we can use the SymPy package. First we need to ensure that Julia recognizes variables and treats them as symbols. using SymPy x, y = symbols("x, y") Then we can simply invoke thecoeff() method to extract coefficients from the polynomials. p = x + 0....