var模型matlab代码
时间: 2023-10-11 09:06:25 浏览: 50
var模型是一种时间序列分析方法,可以用于预测未来的数据。下面是一个简单的VAR(2)模型的MATLAB代码示例:
```
% VAR(2) model
% Y(t) = A1*Y(t-1) + A2*Y(t-2) + E(t)
% where Y is a 2x1 vector of variables, A1 and A2 are 2x2 matrices, and E is a 2x1 vector of errors
% Generate some sample data
n = 100; % number of observations
Y = zeros(n,2);
Y(1,:) = [1 2];
for i = 2:n
Y(i,:) = [0.8 -0.3; 0.5 0.2]*Y(i-1,:)' + randn(2,1)';
end
% Estimate the VAR(2) model using OLS
X = zeros(n-2,4);
Ylag1 = Y(2:end-1,:);
Ylag2 = Y(1:end-2,:);
for i = 1:n-2
X(i,:) = [Ylag1(i,:) Ylag2(i,:)];
end
coeff = inv(X'*X)*X'*Y(3:end,:);
% Forecast using the estimated model
Yhat = zeros(10,2);
Yhat(1,:) = Y(end,:);
Yhat(2,:) = [coeff(1,1:2) coeff(2,1:2)]*Yhat(1,:)' + coeff(1,3:4)*Y(end-1,:)';
Yhat(3,:) = [coeff(1,1:2) coeff(2,1:2)]*Yhat(2,:)' + [coeff(1,3:4) coeff(2,3:4)]*Yhat(1,:)';
for i = 4:10
Yhat(i,:) = [coeff(1,1:2) coeff(2,1:2)]*Yhat(i-1,:)' + [coeff(1,3:4) coeff(2,3:4)]*Yhat(i-2,:)';
end
% Plot the data and forecasts
plot(Y(:,1),'b');
hold on;
plot(Y(:,2),'r');
plot(n+1:n+10,Yhat(:,1),'b--');
plot(n+1:n+10,Yhat(:,2),'r--');
legend('Variable 1','Variable 2','Forecast 1','Forecast 2');
```
这段代码生成了一个长度为100的2维时间序列,并使用OLS估计VAR(2)模型的系数。然后,使用估计的模型进行预测,并将原始数据和预测数据绘制在同一张图上。