在MATLAB中计算一组协方差矩阵的平均值

时间:2014-03-09 19:10:33

标签: matlab matrix statistics finance

我试图从历史数据中分析误差在均值 - 方差分析中的影响。特别是,我试图计算平均有效边界。我得到了所考虑的五种资产的收益和标准差,以及五种资产的相关矩阵。我使用函数mvnrnd为有效边界生成月度回报和frontcon。生成回报后,我计算出这些回归的协方差。我运行了10,000次模拟。

我已经编写了下面的功能来做我需要的功能,但是在150年的尝试中失败了以下信息。这是我第一次在MATLAB中编写任何东西(我需要使用它),所以我不能100%确定我的代码。它确实产生了2年和30年时间段的图表,但我不知道150年的失败是否是由于我的错误编程造成的。特别是我不确定如何计算10,000次模拟中的平均协方差。我尽可能地在其他地方搜索,但如果答案存在,那么我找不到正确的措辞来找到它。任何帮助将不胜感激。我的代码在错误消息下面。

> Warning: Candidate solution is infeasible due to a bad pivot.

> In lcprog>lcprealitycheck at 294 
> In lcprog at 251 In qplcprog at 247 
> In portopt at 249 
> In frontcon at 231 In AverageEfficientFrontiers at 36 
> Error using portopt (line 256)
> 
> No portfolios satisfy all input constraints for maximum-return
> portfolio. Possibly unbounded problem.
> 
> Error in frontcon (line 231)    [PRisk, PRoR, PWts] = portopt(ERet,
> ECov, NPts, RTarget,    ConSet, ...
> 
> Error in AverageEfficientFrontiers (line 36) [Risk, Return, Weights] =
> frontcon(AverageReturn, AverageCovariance, 10);"


function [] = AverageEfficientFrontiers( Years, Simulations )

AssetReturns = [0.006,0.01,0.014,0.018,0.022];
AssetStDev = [0.085,0.08,0.095,0.09,0.1];
CorrelationMatrix = [1,0.3,0.3,0.3,0.3; 
                     0.3,1,0.3,0.3,0.3;
                     0.3,0.3,1,0.3,0.3;
                     0.3,0.3,0.3,1,0.3;
                     0.3,0.3,0.3,0.3,1];
Months = Years*12;
CovarianceMatrix = corr2cov(AssetStDev,CorrelationMatrix);
% Preallocating avoids the need for MATLAB to copy the data from one array 
% to another inside the loop
TotalCumulativeReturn = zeros(Simulations,5);
PeriodCovariance = zeros(Simulations,5,5);

for i=1:Simulations
    MonthlyReturns = mvnrnd(AssetReturns,CovarianceMatrix,Months);
%   If A is a nonempty matrix, then prod(A) treats the columns of A as 
%   vectors and returns a row vector of the products of each column. 
%   A(i,:) is the ith row of A.
    TotalCumulativeReturn(i,:) = prod(1+MonthlyReturns)-1;
%   For matrix input X, where each row is an observation, and each column 
%   is a variable, cov(X) is the covariance matrix.
%   http://www.mathworks.co.uk/help/matlab/ref/cov.html
    PeriodCovariance(i,:,:) = cov(MonthlyReturns)*Months;
end
% If A is a nonempty, nonvector matrix, then mean(A) treats the columns of 
% A as vectors and returns a row vector whose elements are the mean of each 
% column.
AverageReturn = mean(TotalCumulativeReturn);
AverageCovariance = mean(PeriodCovariance);
% http://www.mathworks.co.uk/help/matlab/ref/reshape.html
AverageCovariance = reshape(AverageCovariance, [5,5]);
[Risk, Return, Weights] = frontcon(AverageReturn, AverageCovariance, 10);

plot(Risk, Return);
end

0 个答案:

没有答案