Portfolio Optimization Using Python [Part 1/2]

I recently came across applications of analytics in the investment domain. I thought about collating information and code for these techniques and presenting a simple explanation of these, which may be helpful to others. This part deals with Modern Portfolio Theory [MPT] and its implementation in Python.

What is Modern Portfolio Theory?

Modern Portfolio Theory is Markowitz’s theory regarding maximizing the return investors could get in their investment portfolio considering the risk involved in the investments. MPT asks the investor to consider how much the risk of one investment can impact their entire portfolio.

Harry Max Markowitz, in a 1952 paper published by The Journal of Finance, first proposed the theory as a means to create and construct a portfolio of assets to maximize returns within a given level of risk, or to devise one with a desired, specified and expected level of return with the least amount of risk.

Markowitz theorized that investors could design a portfolio to maximize returns by accepting a quantifiable amount of risk. In other words, investors could reduce risk by diversifying their assets and asset allocation of their investments using a quantitative method. With a well-balanced and calculated portfolio, if some of the assets fall due to market conditions, others should rise an equal amount in compensation, according to MPT. Markowitz demonstrated that, by taking a portfolio as its whole, it was less volatile than the total sum of its parts.

The three main ideas that Modern-Portfolio-Theory talks about are:

1. A stock with better returns is a more convincing investment than a stock with inferior returns. [Mean expectation of returns]

2. A stock with wild swings is a less sure investment than a stock with more stable earnings growth. [Variance is bad]

3. Two stocks that are basically doing the same are not as different as two stocks with vastly different revenue models. [Correlation is bad]

4. A hidden fourth idea is that it’s always better if you have more people working for you. In that sense diversification between stocks is better since that way many companies are working to bring you returns.

Practical Implementation using Python

Here we will use this theory to find the optimum portfolio under five distinct cases:

Given the list of securities or assets to be evaluated -

1. An Investor wants the portfolio with the lowest level of risk.

2. An Investor wants the optimum portfolio giving the optimum combination of risk and returns.

3. An Investor wants a portfolio giving a return not less than the minimum acceptable return fixed by the investor.

4. A portfolio that maximizes the Investor’s utility.

Our goal is to determine the portfolio weights of the securities, or the proportion in which the budget has to be distributed among the securities. We will also compute the expected future return and volatility for our portfolio. We have selected the below-mentioned stocks for our analysis:

Let’s first import the necessary libraries.

We will need the Adjusted Daily Closing prices of the stocks. We will pull this information from Yahoo Finance. The data will be taken from 01–01–2008 to date.

Let’s see what we got here.

Looks Great! So, we have 3297 rows of daily closing prices for the six stocks. Let us now plot these on a line chart and see how the stocks have performed in the past. To compare them, we need to normalize them.

We see that Amazon has definitely performed better than the other stocks. The growth rate of Amazon stock price has picked up majorly after 2015. The stock with the lowest growth in stock prices is HSBC.

Before we start with the calculations, we will go through the process which we need to follow to get the portfolio weights and measures.

1. Assume random weights of the stocks ensuring that the sum of the weights is equal to 1.
2. Generate a number of portfolios with random weights as per the condition above and calculate
3. Calculate annualised Average/Mean returns and volatility assuming the number of trading days in a year as 252.
4. Calculate the Sharpe Ratio [Return- Risk-free Return]/Volatility.
5. Calculate the Covariance Matrix of the portfolios.
6. Iterate on the randomly created portfolios and their weights to get to the optimum portfolio.

Let us consider each case and define functions for our analysis.

Case 1: An Investor wants the portfolio with the lowest level of risk.
&
Case 2: An Investor wants the optimum portfolio giving the optimum combination of risk and returns.

We will first simulate the portfolio measures using a loop and then see if optimization improves our results. To optimize we will use Sequential Least-Squares Programming (SLSQP) — SLSQP minimizes a function of several variables with any combination of bounds, equality and inequality constraints.

Let us now define the variables needed for the functions.

The risk-free rate of return is the 10-year US Treasury Bond yield as on 04–02–2021 at 03:12 hours EST is 1.136%. This is the return that an investor can earn at almost no risk. We are considering 0.1 million portfolio weight combinations to arrive at our desired portfolio.

Simulating Portfolios based on Efficient Frontier

We get the following result:

The green star represents the portfolio which is the least volatile, i.e. the portfolio of Case 1. The red star is the optimum portfolio where the Sharpe ratio is the maximum (Case 2). From the plot of the randomly simulated portfolios, we can see it forms a shape of an arch line on the top of clustered blue dots. This line is called the efficient frontier.

The efficient frontier is the set of optimal portfolios that offer the highest expected return for a defined level of risk or the lowest risk for a given level of expected return. Portfolios that lie below the efficient frontier are sub-optimal because they do not provide enough return for the level of risk. Portfolios that cluster to the right of the efficient frontier are sub-optimal because they have a higher level of risk for the defined rate of return. The efficient frontier is curved because there is a diminishing marginal return to risk. Each unit of risk added to a portfolio results in a relatively smaller amount of additional returns.

Optimizing Portfolios based on Efficient Frontier

We see that calculating portfolio optimization lead to a percentage increase for the Case 1 portfolio and Case 2 portfolio.

Case 3: An Investor wants a portfolio giving a return not less than the minimum acceptable return fixed by the investor.

Here we will use Roy’ Safety First (SF) criterion to determine the optimal portfolio weights.

Roy’s safety-first criterion is a risk management technique used by investors to compare and choose a portfolio based on the criterion that the probability of a portfolio’s return dropping below a threshold level return is reduced.

In Roy’s safety-first criterion, the optimal portfolio is one that minimizes the probability of the portfolio’s return falling below a threshold return level. So, the portfolio with the highest SF ratio is the optimum portfolio.

Let’s define the function for Roy’s Safety First (SF) criterion. We will use a modified version of the ‘display_simulated_ef_with_random’ and ‘display_calculated_ef_with_random’ functions.
A thing to note here is that the ‘risk-free return’ is actually the threshold return and so the ‘Sharpe ratio’ becomes SF ratio.

Assuming a minimum acceptable return requirement of 20%, we will find the optimum portfolio using the SF ratio.

Simulating Portfolios based on Efficient Frontier

Optimizing Portfolios based on Efficient Frontier

Case 4: A portfolio that maximizes the Investor’s utility.

One of the approaches to finding the optimal point on the efficient frontier for a given investor is to maximize the investor's utility. In the field of economics, utility (u) is a measure of how much benefit consumers derive from certain goods or services. From a finance standpoint, it refers to how much benefit investors obtain from portfolio performance. Utility is a measure of relative satisfaction that an investor derives from different portfolios. We can generate a mathematical function to represent this utility that is a function of the portfolio expected return, the portfolio variance and a measure of risk aversion. Where U = utility, E(r) = portfolio expected return, A = risk aversion coefficient and σ² = portfolio variance

In determining the risk aversion (A), we measure the marginal reward an investor needs in order to take on more risk. A risk-averse investor will need a high margin reward for taking on more risk. The utility equation shows the following:

• Utility can be positive or negative — it is unbounded.
• High returns add to utility.
• High variance reduces utility.
• Utility does not measure satisfaction but can be used to rank portfolios.

The risk aversion coefficient, A, ranges between 0 and 10. Practically it ranges between 1 to 10. It is 1 for the aggressive investor(s), 4 for the moderate investor(s), and 10 for the risk-averse investor(s).

We will define a function to calculate the optimal portfolio based on Utility to Investor using the PyPortfolioOpt library.

We will find the optimal portfolios for the three types of Investor(s) we mentioned above.

Looks good!
Now that we have seen the practical demonstration of the MPT, let us now see the issues with this theory.

Issues With Modern Portfolio Theory

Critics contend MPT doesn’t deal with the real world, because all the measures used by MPT are based on projected values or mathematical statements about what is expected rather than real or existing. Investors have to use predictions based on historical measurements of asset returns and volatility in the equations, which means they are subject to be changed by variables currently not known or considered at the time of the equation.

Investors have to estimate from past market data because MPT tries to model risk in terms of the likelihood of losses, without a rationale for why those losses could occur. That makes the risk assessment probabilistic, but not structural.

In other words, the mathematical model of MPT makes investing appear orderly when its reality is far less so. As an example, contrary to what the theory predicts, a researcher in the late 1970s, Sanjay Basu, demonstrated that low price-to-earnings ratio (P/E) stocks outperformed high P/E stocks. And in the early 1980s, another researcher, Rolf Banz, demonstrated that small-capitalization stocks outperformed large-cap stocks.

The Bottom Line

The gist of MPT is that the market is hard to beat and that the people who beat the market are those who take on above-average risk. It is also implied that these risk-takers will get their comeuppance when markets turn down.

Then again, investors such as Warren Buffett remind us that portfolio theory is just that — theory. At the end of the day, a portfolio’s success rests on the investor’s skills and the time he or she devotes to it. Sometimes it is better to pick a small number of out-of-favour investments and wait for the market to turn in your favour than to rely on market averages alone.

In this article, I tried to collate the theory and practical implementation of the Modern Portfolio Theory. In the next part, we will go through the other portfolio optimization techniques.

A special mention for Ricky Kim, a data lover, whose work motivated me to explore this topic.