%% Plot the Efficient Frontier for the Portfolio Object with BoundType and MaxNumAssets Constraints
% Create a Portfolio object for 12 stocks based on CAPMuniverse.mat.

load CAPMuniverse
p0 = Portfolio('AssetList',Assets(1:12));
p0 = estimateAssetMoments(p0, Data(:,1:12),'missingdata',true);
p0 = setDefaultConstraints(p0);

% Use setMinMaxNumAssets to define a maximum number of 3 assets.

pWithMaxNumAssets = setMinMaxNumAssets(p0, [], 3);

% Use setBounds to define a lower and upper bound and a BoundType of 'Conditional'.

pWithConditionalBound = setBounds(p0, 0.1, 0.5,'BoundType', 'Conditional');

% Use plotFrontier to compare the different portfolio objects.

figure;
plotFrontier(p0); hold on; 
plotFrontier(pWithMaxNumAssets); hold on; 
plotFrontier(pWithConditionalBound); hold off;
legend('p0', 'with Max 3 assets invested', ' with each asset weight 0 or [0.1, 0.5]', 'location', 'best');

% Define a target return and use estimateFrontierByReturn to compare the three portfolio objects.

targetRetn = 2.0e-3;
pwgt0 = estimateFrontierByReturn(p0, targetRetn);
pwgtWithMaxNumAssets = estimateFrontierByReturn(pWithMaxNumAssets, targetRetn);
pwgtConditionalBound = estimateFrontierByReturn(pWithConditionalBound, targetRetn);

% The following table shows the final allocation for specified target return among the three portfolio objects. You can see that the small positions in 'AAPL'and 'HPQ' are avoided in pwgtConditionalBound, and only three assets are invested in pwgtWithMaxNumAssets.

result = table(p0.AssetList',pwgt0,pwgtWithMaxNumAssets,pwgtConditionalBound)

% Copyright 2018 The MathWorks, Inc.