Created
February 29, 2020 18:32
-
-
Save pdeffebach/bde7918687e9cfc0f1ca71128263b9f9 to your computer and use it in GitHub Desktop.
bug in finding error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Question 5 | |
module Q5 | |
using LinearAlgebra, Distributions, DataFrames | |
function make_data(T, N, β, σ) | |
T = map(1:T*N) do i | |
x = rand(Normal(0, sqrt(σ))) | |
u = rand(Normal(0, abs(x))) | |
y = x * β + u | |
x, y | |
end | |
first.(T), last.(T) | |
end | |
function get_β_FE(y, X, T, N) | |
Q = I - kron(I(N), ones(T,T) ./ T) | |
β = (X' * Q * X) \ (X' * Q * y) | |
end | |
function get_σ_2(β, X, y, T, N) | |
u_hat = y - X * β | |
X_bars = [mean(X[i:(i+T-1)]) for i in 1:N] | |
u_hat_bars = [mean(u_hat[i:(i+T-1)]) for i in 1:N] | |
S_xx = let s = 0.0 | |
for i in 1:N | |
sn = 0.0 | |
X_bar = X_bars[i] | |
for t in 1:T | |
sn += (X[i+t-1] - X_bar)^2 | |
end | |
s += sn^2 | |
end | |
s | |
end | |
diffsum_hat = let s = 0.0 | |
for i in 1:N | |
sn = 0.0 | |
X_bar = X_bars[i] | |
u_hat_bar = u_hat_bars[i] | |
for t in 1:T | |
sn += (X[i+t-1] - X_bar)*(u_hat[i+t-1] - u_hat_bar) | |
end | |
s += sn^2 | |
end | |
s | |
end | |
diffsum_tilde= let s = 0.0 | |
for i in 1:N | |
sn = 0.0 | |
X_bar = X_bars[i] | |
u_hat_bar = u_hat_bars[i] | |
for t in 1:T | |
sn += ((X[i+t-1] - X_bar)*(u_hat[i+t-1] - u_hat_bar))^2 | |
end | |
s += sn | |
end | |
s | |
end | |
return (σ_2_hat = diffsum_hat / S_xx^2, σ_2_tilde = diffsum_tilde / S_xx^2) | |
end | |
function make_estimates(T, N, β, σ_2) | |
X, y = make_data(T, N, β, σ_2) | |
β_hat = get_β_FE(y, X, T, N) | |
σ_2_hat, σ_2_tilde = get_σ_2(β, X, y, T, N) | |
σ_2_ols = 1 | |
#σ_2_ols = FE_error(\beta, X, Y, T, N) | |
return (β_hat = β_hat, | |
σ_2_hat = σ_2_hat, | |
σ_2_tilde = σ_2_tilde, | |
σ_2_ols = σ_2_ols) | |
end | |
function FE_error(β, X, y, T, N) | |
Q = I - kron(I(N), ones(T,T) ./ T) | |
X_dot = Q*X | |
u_hat = y - X * β | |
S_xx_inv = inv(X_dot' * X_dot) | |
V = S_xx_inv * X' * u_hat u_hat' * X * S_xx_inv | |
end | |
function main() | |
S = 1000 | |
T = 5 | |
N = 500 | |
β = 1 | |
σ_2 = 1 | |
make_estimates(T, N, β, σ_2) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment