ApplicationsMultiobjective Optimization
Classic and Intelligent Portfolio Optimization in MATLAB
Explore portfolio optimization in MATLAB with mean-variance, MAD, and CVaR models, plus PSO, ICA, NSGA-II, and SPEA2 implementations.

On this page
This package applies portfolio optimization in MATLAB with both classic and intelligent methods. The goal is to decide how to split money between assets so that risk is low for a given return, in the spirit of the Markowitz model.
The Markowitz model
Harry Markowitz introduced mean-variance portfolio selection in 1952 (paper (opens in a new tab)). An investor holds assets with weights . If is the vector of mean asset returns and is their covariance matrix, the portfolio return is and its variance is . For a desired return , the model is:
The last constraints mean that the whole budget is invested and that short selling is not allowed.
The efficient frontier
For each feasible target return , the model seeks a minimum-variance portfolio meeting that target. Varying the target traces the minimum-variance boundary. Its efficient portion contains portfolios for which higher expected return requires higher risk. On this curve, no portfolio has both a lower risk and a higher return than another one. An investor chooses a point on the frontier according to how much risk is acceptable.
Seen as a problem with two objectives (low risk and high return), the efficient frontier is the Pareto front. Multi-objective algorithms such as NSGA-II and SPEA2 can approximate these trade-offs in one run.
Variance is not the only measure of risk. The package also uses:
- Semi-variance, which counts only the returns below the mean.
- Mean absolute deviation (MAD), the mean of (Konno and Yamazaki, 1991).
- Conditional value at risk (CVaR), the expected loss in the worst share of cases, for example the worst 5 percent when (Rockafellar and Uryasev, 2000).
What is in the package
The download has six folders:
- 01 Fetching Data: a script that downloads closing prices for IBM, GOOGL, MSFT, AAPL, YHOO and AMZN for January 2014 and computes the returns.
- 02 Portfolio Optimization using Classic Methods: four scripts (app1 to app4) that use MATLAB’s portfolio objects to compute the efficient frontier. They cover the mean-variance model, a version with its own moment estimate that can use semi-variance, a mean absolute deviation (MAD) model and a conditional value at risk (CVaR) model.
- 03 Portfolio Optimization using PSO: Particle Swarm Optimization.
- 04 Portfolio Optimization using ICA: the Imperialist Competitive Algorithm.
- 05 Portfolio Optimization using NSGA-II: the Non-dominated Sorting Genetic Algorithm II.
- 06 Portfolio Optimization using SPEA2: the Strength Pareto Evolutionary Algorithm 2.
Folders 02 to 06 each include the data file mydata.mat, so they can be used without downloading prices.
About the data
The data are historical. CreateData.m in folder 01 connects to Yahoo with MATLAB’s old yahoo data feed function and saves the daily closing prices from January 1 to February 1, 2014. The saved file holds 22 prices and 21 returns for each of the six symbols. The YHOO ticker no longer trades, because Yahoo’s operating business was sold in 2017, and the old Yahoo data connection may no longer work. So treat folder 01 as a record of how the data was made. The other folders all ship the same mydata.mat file. To use other assets, replace the return matrix R and the list of names Symbols in that file, with one column of R for each symbol.
The classic methods (folder 02)
app1.m: the mean-variance frontier with aPortfolioobject, which estimates the mean and covariance from the returns.app2.m: the same frontier, but the moments come fromEstimateReturnMoments.m. WithSemi=1, this function uses the semi-deviation of each asset instead of its standard deviation. The script setsSemi=0, so by default it gives the ordinary mean-variance frontier.app3.m: the MAD frontier with aPortfolioMADobject.app4.m: the CVaR frontier with aPortfolioCVaRobject and .
Each script computes 100 points of the frontier with estimateFrontier and plots the frontier together with the risk and return of each single asset.
How the intelligent methods work
The PSO and ICA folders solve a single-objective version of the problem. The cost is the portfolio risk, with a penalty when the portfolio return falls below a desired return. NSGA-II and SPEA2 treat risk and negative return as two objectives, so they search for the Pareto front directly.
In all four folders, a solution is a vector with values between 0 and 1. It is turned into valid weights by , so a nonzero, nonnegative vector produces weights that are nonnegative and sum to one. The risk and the return of are computed in CalculatePortfolioObjectives.m, with the same portfolio objects as in folder 02. The risk measure is set by model.method: 'mv' (mean-variance), 'msv' (mean semi-variance), 'mad' or 'cvar'. All four main scripts use 'cvar' with model.alpha=0.95. Change these two lines to use another risk measure.
For PSO and ICA, PortCost.m computes
The main script runs the algorithm 15 times, with values of evenly spaced between the lowest and the highest mean asset return. It then uses IsDominated.m to keep the non-dominated portfolios and draws them as the efficient frontier. PSO uses the constriction coefficients of Clerc and Kennedy.
Parameters in the code
| Folder | Main script | Iterations | Population | Other settings |
|---|---|---|---|---|
| 03 PSO | pso.m (calls RunPSO.m) |
100 | 40 | |
| 04 ICA | ica.m (calls RunICA.m) |
150 | 40 | 5 empires, beta=0.9, pRevolution=0.1 |
| 05 NSGA-II | nsga2.m |
100 | 50 | pCrossover=0.7, pMutation=0.4, mu=0.02 |
| 06 SPEA2 | spea2.m |
200 | 50 | archive size 100, pCrossover=0.7 |
For PSO and ICA, the iterations and the population apply to each of the 15 runs.
How to run the code
Open a folder in MATLAB and run its main script: app1.m to app4.m in folder 02, or pso.m, ica.m, nsga2.m or spea2.m in folders 03 to 06. Every script loads mydata.mat from its own folder. The classic scripts plot the frontier and the single assets. The PSO and ICA scripts print the progress of each run and then plot the 15 portfolios, with the efficient ones in red. The NSGA-II and SPEA2 scripts print the number of non-dominated solutions in each iteration and plot the current front as return against risk. SPEA2 also prints a short summary of both objectives at the end.
The portfolio objects (Portfolio, PortfolioMAD and PortfolioCVaR) are part of MATLAB’s Financial Toolbox, so all folders probably need it. Folder 01 probably also needs the Datafeed Toolbox for the yahoo connection.
Check the result
Check that the weights are finite, nonnegative, and sum to one. The normalization is undefined for an all-zero candidate, and the target-return penalty divides by , so zero or negative target returns need review. Compare portfolios using the same data and risk measure. The small historical sample illustrates the methods. Its fitted frontier does not establish future returns or out-of-sample risk. The legacy Yahoo connection and current MATLAB compatibility were not tested in this review.
Applications
Portfolio optimization is used to build investment portfolios of stocks, bonds and funds, in pension fund and asset management, and in risk management, where measures such as CVaR describe the losses in bad market conditions.
Related posts
Downloads
How to cite
If you use this code or tutorial in your work, articles or publications, please cite it.
Mostapha Kalami Heris, Classic and Intelligent Portfolio Optimization in MATLAB (YPAP112), Yarpiz, 2015. https://yarpiz.com/portfolio-optimization-ypap112@misc{yarpiz-ypap112,
author = {{Mostapha Kalami Heris}},
title = {{Classic and Intelligent Portfolio Optimization in MATLAB}},
howpublished = {Yarpiz},
year = {2015},
note = {Code YPAP112},
url = {https://yarpiz.com/portfolio-optimization-ypap112}
}Published Updated
Comments