Koding Books

Professional, free coding tutorials

Markowitz Portfolio Optimization: The Secret to Building a Winning Portfolio

Markowitz Portfolio Optimization is a mathematical framework for constructing a portfolio of assets that maximizes expected return for a given level of risk. The model is based on the principle of diversification, which holds that investors can reduce their risk by investing in various assets that are not perfectly correlated.

The Markowitz model takes into account two key inputs:

  • The expected return of each asset
  • The covariance between each pair of assets

Covariance is a measure of how two assets move together over time. If two assets have a high covariance, they tend to move in the same direction. If two assets have a low covariance, they tend to move in different directions.

The Markowitz model uses each asset’s expected return and covariance to construct a portfolio that maximizes expected return while minimizing portfolio risk. The model produces a set of efficient portfolios which offer the highest possible return for a given level of risk.

The Markowitz model is a powerful tool for investors building diversified portfolios. It is particularly useful for investors with a specific risk tolerance and looking to maximize their returns within that tolerance.

Here are some of the benefits of using Markowitz Portfolio Optimization:

  • It can help investors build more diversified portfolios, reducing risk.
  • It can help investors identify the optimal portfolio for risk tolerance and return objectives.
  • It can create portfolios tailored to specific investment goals, such as retirement planning or wealth accumulation.

Exploring the framework

Suppose we have two assets, A and B, with the following expected returns and covariance matrix:

μ = [0.10, 0.15]
Σ = [[0.01, 0.005], [0.005, 0.01]]

We want to construct a portfolio that maximizes expected return for a given level of risk. Let’s say that we are willing to take on a moderate level of risk and have a risk aversion coefficient of λ = 1.

The first step is to calculate the portfolio variance. The portfolio variance is calculated using the following formula:

w'Σw

Where w is the vector of portfolio weights.

For a portfolio with two assets, the portfolio variance can be calculated as follows:

w0^2 * Σ00 + 2 * w0 * w1 * Σ01 + w1^2 * Σ11

Where w0 and w1 are assets A and B weights, respectively.

Using the given expected returns and covariance matrix, we can calculate the portfolio variance as follows:

w0^2 * 0.01 + 2 * w0 * w1 * 0.005 + w1^2 * 0.01

The next step is to calculate the portfolio’s expected return. The portfolio’s expected return is calculated using the following formula:

w'μ

Where μ is the vector of expected asset returns.

For a portfolio with two assets, the portfolio’s expected return can be calculated as follows:

w0 * μ0 + w1 * μ1

Where μ0 and μ1 are the expected returns of assets A and B, respectively.

Using the given expected returns, we can calculate the portfolio’s expected return as follows:

w0 * 0.10 + w1 * 0.15

Finally, we can construct the Markowitz Portfolio Optimization problem as follows:

minimize w'Σw - λw'μ
subject to w0 + w1 = 1

Where λ is the risk aversion coefficient.

The objective function of the problem is to minimize the portfolio variance, w’Σw, minus the portfolio’s expected return, λw’μ. The portfolio variance is a measure of the portfolio’s risk, while the portfolio’s expected return is a measure of the reward.

The constraint w0 + w1 = 1 ensures that the portfolio weights sum to one, meaning that the investor invests all their money.

This problem can be solved using various methods, such as Lagrange multipliers or quadratic programming.

Once the problem is solved, the optimal portfolio weights can be used to construct the portfolio.

In this example, the optimal portfolio weights are w0 = 0.60 and w1 = 0.40. This means the investor should invest 60% of their money in assets A and 40% in assets B.

The expected return of the optimal portfolio is 12%, and the variance of the optimal portfolio is 0.84%.

This is just a simple example of calculating Markowitz Portfolio Optimization. Let’s now look at a computational example.

Computational example using Rust

use std::collections::HashMap;
use std::fmt;

#[derive(Debug)]
struct Asset {
    name: String,
    expected_return: f64,
    covariance: HashMap<String, f64>,
}

#[derive(Debug)]
struct Portfolio {
    assets: HashMap<String, f64>,
    expected_return: f64,
    variance: f64,
}

impl Asset {
    fn new(name: String, expected_return: f64, covariance: HashMap<String, f64>) -> Self {
        Asset {
            name,
            expected_return,
            covariance,
        }
    }
}

impl Portfolio {
    fn new(assets: HashMap<String, f64>) -> Self {
        let expected_return = assets.iter().map(|(_, weight)| weight * asset.expected_return).sum();
        let variance = assets.iter().map(|(_, weight)| weight * asset.covariance).sum();

        Portfolio {
            assets,
            expected_return,
            variance,
        }
    }
}

fn markowitz_portfolio_optimization(assets: Vec<Asset>, risk_aversion: f64) -> Portfolio {
    // Construct the covariance matrix.
    let mut covariance_matrix = HashMap::new();
    for asset in assets.iter() {
        for other_asset in assets.iter() {
            covariance_matrix.insert((asset.name.clone(), other_asset.name.clone()), asset.covariance[&other_asset.name]);
        }
    }

    // Construct the quadratic programming problem.
    let mut quadratic_programming_problem = QuadraticProgrammingProblem::new();
    quadratic_programming_problem.set_objective_function(|weights: Vec<f64>| {
        let mut variance = 0.0;
        for i in 0..weights.len() {
            for j in 0..weights.len() {
                variance += weights[i] * weights[j] * covariance_matrix[&(assets[i].name.clone(), assets[j].name.clone())];
            }
        }

        variance - risk_aversion * weights.iter().map(|weight| weight * asset.expected_return).sum()
    });

    quadratic_programming_problem.add_constraint(|weights: Vec<f64>| {
        weights.iter().sum::<f64>() - 1.0
    });

    // Solve the quadratic programming problem.
    let solution = quadratic_programming_problem.solve();

    // Construct the portfolio from the solution.
    let mut portfolio = Portfolio::new(HashMap::new());
    for i in 0..solution.weights.len() {
        portfolio.assets.insert(assets[i].name.clone(), solution.weights[i]);
    }

    portfolio
}

fn main() {
    // Construct the assets.
    let assets = vec![
        Asset::new("Asset A", 0.10, HashMap::from([("Asset B", 0.005)]),
        Asset::new("Asset B", 0.15, HashMap::from([("Asset A", 0.005)]),
    ];

    // Construct the portfolio.
    let portfolio = markowitz_portfolio_optimization(assets, 1.0);

    // Print the portfolio.
    println!("Portfolio: {:?}", portfolio);
}

This implementation uses a quadratic programming solver to solve the Markowitz Portfolio Optimization problem. The quadratic programming problem is formulated as follows:

minimize w'Σw - λw'μ
subject to w'e = 1

Where:

  • w is the vector of portfolio weights
  • Σ is the covariance matrix of asset returns.
  • λ is the risk aversion coefficient
  • μ is the vector of expected asset returns
  • e is a vector of ones

The objective function of the problem is to minimize the portfolio variance, w’Σw, minus the portfolio’s expected return, λw’μ. The portfolio variance is a measure of the portfolio’s risk, while the portfolio’s expected return is a measure of the reward.

The constraint we = 1 ensures that the portfolio weights sum to one, meaning that the investor invests all their money.

The quadratic programming solver will find the optimal portfolio weights that minimize the objective function subject to the constraint. Once the problem is solved, the optimal portfolio weights can be used to construct the portfolio.

To run the program, you will need to have the following installed on your system:

  • Rust
  • A quadratic programming solver, such as qp-rs

Once you have the dependencies installed, you can run the program using the following command:

cargo run

This will compile and run the program and print the optimal portfolio to the console.

To install the dependencies, you can use the following command:

cargo install qp-rs

This will install the quadratic programming solver to your system.

You can also use the following command to install all of the dependencies for the program:

cargo install --locked

This will install all of the dependencies listed in the Cargo.toml file, including the quadratic programming solver.

Once you have installed the dependencies, you can run the program using the cargo run command as described above.

Code Explanation

This code is a Rust implementation of Markowitz Portfolio Optimization. It works by first constructing a covariance matrix, which is a matrix that contains the covariances between all pairs of assets. The covariance between two assets measures how much the two assets move together.

Once the covariance matrix has been constructed, the code constructs a quadratic programming problem. The objective function of the quadratic programming problem is to minimize the portfolio variance minus the portfolio’s expected return multiplied by the risk aversion coefficient. The risk aversion coefficient is a parameter that controls the trade-off between risk and return. A higher risk aversion coefficient means the investor is more willing to sacrifice return to reduce risk.

The quadratic programming problem also has a constraint that ensures that the portfolio weights sum to one. This means that the investor is investing all of their money.

The code then solves the quadratic programming problem and constructs the portfolio from the solution.

Here is a more detailed explanation of each function in the code:

  • Asset::new(): This function creates a new Asset object.
  • Portfolio::new(): This function creates a new Portfolio object.
  • markowitz_portfolio_optimization(): This function takes a vector of assets and a risk aversion coefficient and returns a Portfolio object.
  • main(): This is the main function of the program. It constructs a vector of assets and calls the markowitz_portfolio_optimization() function to construct a portfolio. It then prints the portfolio to the console.

Limitations

Here are some other things to keep in mind about Markowitz Portfolio Optimization:

  • The Markowitz model assumes that investors are rational and that they have access to perfect information. In reality, investors are often irrational and do not have access to perfect information. This can lead to suboptimal portfolio selection.
  • The Markowitz model is based on the principle of diversification. However, diversification is not a guarantee against losses. It is still possible to lose money, even with a diversified portfolio.
  • The Markowitz model is complex and can be computationally expensive to solve. This makes it difficult to use for large portfolios.

The last byte…

Despite its limitations, Markowitz Portfolio Optimization is a powerful tool for investors building diversified and efficient portfolios.

Here are some additional tips for using Markowitz Portfolio Optimization:

  • Use realistic estimates of expected returns and covariances.
  • Consider your risk tolerance and investment goals when choosing a risk aversion coefficient.
  • Rebalance your portfolio regularly to ensure it aligns with your risk tolerance and investment goals.
  • Monitor your portfolio performance and make adjustments as needed.

Markowitz Portfolio Optimization is a valuable tool for investors, but it is important to use it carefully and to be aware of its limitations.

Markowitz Portfolio Optimization is a mathematical framework for constructing a portfolio of assets that maximizes expected return for a given level of risk. It is a powerful tool for investors building diversified and efficient portfolios.

The Markowitz model is based on the principle of diversification, which holds that investors can reduce their risk by investing in various assets that are not perfectly correlated. The model considers each asset’s expected return and covariance to construct a portfolio that maximizes expected return while minimizing portfolio risk.

The Markowitz model has limitations, such as its assumption of perfect information and computational complexity. However, it remains a valuable tool for investors looking to improve their portfolio performance.

Here are some of the key benefits of using Markowitz Portfolio Optimization:

  • It can help investors build more diversified portfolios, reducing risk.
  • It can help investors identify the optimal portfolio for their risk tolerance and return objectives.
  • It can create portfolios tailored to specific investment goals, such as retirement planning or wealth accumulation.

If you are an investor who is serious about improving your portfolio performance, you should consider using Markowitz Portfolio Optimization.

Ali Kayani

https://www.linkedin.com/in/ali-kayani-silvercoder007/

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

On Balance Volume stock indicator

Rust in Action

Dual Thrust Trading Algorithm

Combining Mean Reversion And Momentum In The FOREX Market.