# Classic and Intelligent Portfolio Optimization in MATLAB

URL: https://yarpiz.com/portfolio-optimization-ypap112
Author: Mostapha Kalami Heris
Published: 2015-09-22
Updated: 2026-10-30
Topics: Applications, Multiobjective Optimization

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

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](https://doi.org/10.2307/2975974)). An investor holds $n$ assets with weights $w_1, \dots, w_n$. If $\mu$ is the vector of mean asset returns and $\Sigma$ is their covariance matrix, the portfolio return is $\mu^\top w$ and its variance is $w^\top \Sigma w$. For a desired return $R^*$, the model is:

$$
\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^*$, 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 - \bar{r}|$ (Konno and Yamazaki, 1991).
- **Conditional value at risk (CVaR)**, the expected loss in the worst $1 - \alpha$ share of cases, for example the worst 5 percent when $\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 $\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 $x$ with values between 0 and 1. It is turned into valid weights by $w = 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 $w$ 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 = \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^*$ 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 | $\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^*$, 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

- [Particle Swarm Optimization in MATLAB](https://yarpiz.com/particle-swarm-optimization-ypea102)
- [Imperialist Competitive Algorithm (ICA) in MATLAB](https://yarpiz.com/imperialist-competitive-algorithm-ypea118)
- [NSGA-II in MATLAB](https://yarpiz.com/nsga2-ypea120)
- [Strength Pareto Evolutionary Algorithm 2 (SPEA2) in MATLAB](https://yarpiz.com/spea2-ypea122)

## How to cite

Mostapha Kalami Heris, Classic and Intelligent Portfolio Optimization in MATLAB (YPAP112), Yarpiz, 2015. https://yarpiz.com/portfolio-optimization-ypap112
