ApplicationsMultiobjective Optimization

Classic and Intelligent Portfolio Optimization in MATLAB

Get the code
Comments

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

Illustration for Classic and Intelligent Portfolio Optimization in MATLAB
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 nn assets with weights w1,…,wnw_1, \dots, w_n. If μ\mu is the vector of mean asset returns and Σ\Sigma is their covariance matrix, the portfolio return is μ⊤w\mu^\top w and its variance is w⊤Σww^\top \Sigma w. For a desired return R∗R^*, the model is:

min⁡ww⊤Σwsubject toμ⊤w≥R∗∑i=1nwi=1,wi≥0\begin{aligned} \min_{w} \quad & w^\top \Sigma w \\ \text{subject to} \quad & \mu^\top w \ge R^* \\ & \sum_{i=1}^{n} w_i = 1, \qquad w_i \ge 0 \end{aligned}

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 R∗R^*, 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 ∣r−rˉ∣|r - \bar{r}| (Konno and Yamazaki, 1991).
  • Conditional value at risk (CVaR), the expected loss in the worst 1−α1 - \alpha share of cases, for example the worst 5 percent when α=0.95\alpha = 0.95 (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 a Portfolio object, which estimates the mean and covariance from the returns.
  • app2.m: the same frontier, but the moments come from EstimateReturnMoments.m. With Semi=1, this function uses the semi-deviation of each asset instead of its standard deviation. The script sets Semi=0, so by default it gives the ordinary mean-variance frontier.
  • app3.m: the MAD frontier with a PortfolioMAD object.
  • app4.m: the CVaR frontier with a PortfolioCVaR object and α=0.95\alpha = 0.95.

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 xx with values between 0 and 1. It is turned into valid weights by w=x/∑ixiw = x / \sum_i x_i, so a nonzero, nonnegative vector produces weights that are nonnegative and sum to one. The risk and the return of ww 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

z=risk⋅(1+1000 v),v=max⁡(0,  1−returnR∗)z = \text{risk} \cdot \left( 1 + 1000 \, v \right), \qquad v = \max\left(0, \; 1 - \frac{\text{return}}{R^*}\right)

The main script runs the algorithm 15 times, with values of R∗R^* 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 ϕ1=ϕ2=2.05\phi_1 = \phi_2 = 2.05
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 R∗R^*, 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.

Downloads

How to cite

If you use this code or tutorial in your work, articles or publications, please cite it.

Plain text
Mostapha Kalami Heris, Classic and Intelligent Portfolio Optimization in MATLAB (YPAP112), Yarpiz, 2015. https://yarpiz.com/portfolio-optimization-ypap112
BibTeX
@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}
}

Comments

Sign in or create a free account to join the discussion. No password needed.