问题描述
我有一些关于使用蒙特卡罗模拟和 OLS 回归来估计一些系数的 Matlab 代码。 如何在 Python 中做到这一点?
see screenshot of code,or below
Define the true DGP parameters and distributions
% Set the parameters in the model
b1 = 5;
b2 = -2;
% The variance of the error term
sigma2 = 2;
% The sample length. We will play with three different sample sizes and see how this affects the results
N = [100 500 1000];
% The number of simulations
S = 1000;
Generate x data
% Generate the x values as draws from the multivariate normal distributions
% This is the correlation structure between the x's
Sigma = [0.7 0.4;
0.4 0.3];
% Simple way of drawing random numbers from the multivariate normal distribution
x = chol(Sigma)'*randn(2,max(N));
% Make the x1 and x2 variables
x1 = x(1,:)';
x2 = x(2,:)';
Monte Carlo simulation 1
y = b1*x1 + e is the true model
We will Now simulate data from this model and then use OLS to estimate two versions of the model:
y = b1mc*x1 + e and
y = b1mc_2*x1 + b2*x2 + e
% Always good practive to allocate empty output before loops
b1mc = nan(S,numel(N));
b1mc_2 = nan(S,numel(N));
% Simple counter to use when allocating results into b1mc below
cnt = 1;
for n = N % Loop over the different sample sizes N
for s = 1 : S
% generate random errors
u = randn(n,1)*sqrt(sigma2);
% simulate the process
y = b1*x1(1:n) + u;
% Estimate coefficients by OLS (easy in Matlab) and save
b1mc(s,cnt) = x1(1:n)\y;
tmp = [x1(1:n) x2(1:n)]\y;
b1mc_2(s,cnt) = tmp(1); % Only save the first parameter
end
cnt = cnt + 1;
end
解决方法
有一些方法可以在 python 中使用 MATLAB 代码!!...检查下面的链接