Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
robertopucp
GitHub Repository: robertopucp/1eco35_2022_2
Path: blob/main/Trabajo_grupal/WG1/Solution/jl_script.ipynb
4587 views
Kernel: Julia 1.7.3

" Homework 1 - solution " " @author: Roberto Mendoza " " @date: 12/09/2020 "

using Random using Distributions using DataFrames using Statistics using LinearAlgebra
Random.seed!(756) x1 = rand(500) # uniform distribution x2 = rand(500) # uniform distribution x3 = rand(500) # uniform distribution x4 = rand(500) # uniform distribution e = randn(500) # normal dsitribution mean = 0 y sd = 1 Y = ones(500) + 0.8.*x1 + 1.2.*x2 + 0.5.*x3 + 1.5.*x4 + e X = hcat(ones(500),x1,x2,x3,x4) z = randn(500)
500-element Vector{Float64}: 1.2161218700987348 -0.9926126764602828 0.19191592562045984 -0.15086947966621472 -0.6389125810461639 -1.3942144444104163 -0.705889215799248 0.37351476592213184 1.1746314413492067 -0.9545887894895217 0.39410363435252194 2.7466082381229593 -1.0373997619198814 ⋮ 0.13025908043652165 -0.12163806225317268 0.43155933378570865 -0.2831212753900742 -0.30073565141764164 1.935178430836171 -0.11737482834931355 -1.034540049333148 0.25990723232112944 0.5935131458905702 0.20677712273119342 1.0340990198372546
function ols(X, Y , standar::Bool = true, Pvalue::Bool = true , instrumento=nothing, index=nothing) if standar && Pvalue && isnothing(instrumento) && isnothing(index) beta = inv(transpose(X) * X) * (transpose(X) * Y) y_est = X*beta n = size(X)[1] k = size(X)[2] df = n-k error_vector = Y-y_est sigma = sum(error_vector.^(2))/df Var = sigma*inv(transpose(X) * X) sd = Var[diagind(Var)].^(0.5) t_test = abs.(beta./sd) dist = TDist(df) pvalue = 2*(1 .- cdf(dist, t_test)) table = DataFrame(Coeff =beta, Standar_error =sd , P_value = pvalue) elseif !isnothing(instrumento) && !isnothing(index) beta = inv(transpose(X) * X) * (transpose(X) * Y) index = index +1 Z = X Z[:,index] = z beta_x = inv(transpose(Z) * Z) * (transpose(Z) * X[:,index]) x_est = Z * beta_x X[:,index] = x_est beta_iv = inv(transpose(X) * X) * (transpose(X) * Y) table = DataFrame(OLS= beta, OLS_IV = beta_iv) end return table end
ols (generic function with 5 methods)
ols(X,Y)
5×3 DataFrame Row Coeff Standar_error P_value Float64 Float64 Float64 ─────┼─────────────────────────────────────── 1 │ 1.39969 0.14981 0.0 2 │ 0.0235243 0.0470551 0.617347 3 │ 1.38447 0.165582 6.66134e-16 4 │ 0.565652 0.161536 0.000504135 5 │ 1.33924 0.163545 2.22045e-15
ols(X,Y,false,false, z,1)
5×2 DataFrame Row OLS OLS_IV Float64 Float64 ─────┼────────────────────── 1 │ 1.39969 1.39969 2 │ 0.0235243 0.0235243 3 │ 1.38447 1.38447 4 │ 0.565652 0.565652 5 │ 1.33924 1.33924