Mean-Variance Portfolio Optimization using Python

Portfolio Management is one of the most traditional segments in terms of Data Science applications in the field of Finance. In this article our two members Florian Kollarczik and Florian Leodolter will share a beginner’s guide to perform simple, yet very insightful Portfolio Optimization using Python. We hope you find it as “stonks” as we do.

General Introduction

Portfolio Optimization is the procedure of creating the best possible portfolio for certain underlying assets given defined circumstances. Therefore, this article will serve as guidance in optimizing a portfolio using the Efficient Frontier in Python. As our reference portfolio, we are using the Austrian Traded Index (^ATX) currently consisting of 20 stocks.

In his 1952 published paper “Portfolio Selection”, Nobel Prize winner Harry M. Markowitz presented his Modern Portfolio Theory (MPT). [1] The theory describes how risk-averse investors are able to assemble portfolios with maximum expected returns given a certain level of market risk. Investment portfolios along with the Efficient Frontier yield the highest expected rate of return and are therefore most “efficient” for every designated volatility (standard deviation) rate.

The Sharpe ratio is a measure of excess portfolio return over the risk-free rate relative to its standard deviation. [2] Thus the ratio represents the reward per unit of variability. [3]

Formula 1: Sharpe Ratio

Sharpe Ratios less than 1.0 are considered to be deficient, whereas everything above 1.0 is perceived to be adequate. Investors review a ratio of at least 2.0 to be very good, while a value higher than 3.0 is appraised to be outstanding. [4] Our goal is to compose a portfolio which maximizes the Sharpe Ratio and compare its performance to other frequentely applied strategies.

As briefly mentioned above, this article should act as a step by step approach, which allows anyone to start performing stock analysis by themselves. So let’s dive in:

Import the relevant tickers for your desired default portfolio. You can chose whatever stocks you want to invest in, so there are no boundaries of what stocks can be chosen. Having said that, this particular model is designed to value stocks only and cannot deal with derivatives for example. As mentioned above, we will be using the ^ATX with its 20 current companies.

Austrian Traded Index (ATX) is a free float weighted price index made up of the most liquid stocks traded on Vienna Stock Exchange and listed in the „prime market“. The index is calculated in EUR and disseminated in real time. ATX is designed as a tradable index to be used as an underlying instrument for structured products and for standardized derivatives (futures & options).

Vienna Stock Exchange

For benchmarking, we are importing other indices, most importantly the ATX Total Return Index (^ATXTR). In comparison to the ATX the ATXTR includes dividend payments. To make transnational comparisons, we are importing international indices: the S&P500 (^GSPC), the German share index (^DAX) and the NASDAQ Composite (^IXIC).

To get a better understanding of the performance of these commonly used indices, we calculate their cumulative return over the past 10 years.

From Figure 1, we can see that the ATX Total Return Index performed worse than all the other benchmark indices. The index barely moved from its level 10 years ago.

Figure 1

Now that we have seen the poor performance of the Austrian Traded Index compared to our global reference indices, we want to shed light upon the performance of the individual stocks comprising the ATX Total Return.

The two best performing stocks over the last 10 years have been the two real-estate companies included in the ATX.

  • S Immo (SPI): +160.78%
  • CA Immo (CAI): +148.36%

The other end of the spectrum is dominated by both banks and insurance companies.

  • Erste Group Bank (EBS): -42.89%
  • Vienna Insurance Group (VIG): -51.57%
  • UNIQA Insurance Group (UQA): -64.09%
  • Raiffeisen Bank International (RBI): -65.70%
Figure 2

In order to identify any potentially surprising correlations between individual stocks within the portfolio we are turning to a Correlation Matrix (Figure 3). Here you are able to spot certain uncovered relations between various assets within your portfolio. This will help you decide whether your portfolio is diversified enough for your preferences, or whether you should reconsider choosing different, less correlated stocks.

In our case, since Bawag (BG) joined the ATX only recently, its correlation with the majority of the remaining stocks is comparatively high. This doesn’t necessarily imply anything inadequate, but is certainly something that we need to observe in the future.

Figure 3

a) Expected Returns and Covariance Matrix (Exponentially Weighted)

Portfolio variance is a measure of the dispersion of returns of a portfolio. It is the aggregate of the actual returns of a given portfolio over a set period of time. Portfolio variance is calculated using the standard deviation of each security in the portfolio and the correlation between securities in the portfolio. Modern portfolio theory (MPT) states that portfolio variance can be reduced by selecting securities with low or negative correlations in which to invest, such as stocks and bonds.

Investopedia

Formula 2: Portfolio variance of N assets

For our further portfolio optimization purposes we are importing additional relevant libraries.

b) 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.

Investopedia

Figure 4

c) Minimum Variance Portfolio (Exponentially Weighted)

The Minimum Variance Portfolio (MVP) is, as the name already suggests , a respective financial portfolio of given assets with the lowest possible risk while still being considered optimal with its assets. The MVP is located at the vertex of the Efficient Frontier’s parabola. This particular portfolio is highly popular by very risk-averse investors, as its returns are already quite decent with low amounts of risk.

Formula 3: Minimum Variance Portfolio

As you can see in Figure 5 below, we are not using all the stocks within our index, as their respective variance in comparison to others is too large for our Minimum Variance Portfolio. In this case

  • Austrian Post (POST): 20.95%
  • Mayr-Melnhof Karton (MMK): 15.52%
  • Telekom Austria (TKA): 11.27%

are weighted to be the most significant.

By using the function ef.portfolio_performance, we get the following results:

  • Expected annual return: 1.9%
  • Annual volatility: 9.2%
  • Sharpe Ratio: 0.11
Figure 5

d) Maximum Sharpe Portfolio (Exponentially Weighted)

The Maximum Sharpe Portfolio, also called The Tangency Portfolio is located on the cusp where the Efficient Frontier is tangent to the risk-free rate.

For a portfolio with a maximized Sharpe Ratio, our portfolio will only consist of seven out of the original 20 individual assets. The highest Sharpe Ratio and therefore the largest weight within our Maximum Sharpe Portfolio is Verbund (VER) with a staggering 70.04%. (Figure 6) Our portfolios remaining stocks are:

  • CA Immo (CAI): 6.87%
  • OMV (OMV): 6.26%
  • Do & Co (DOC): 5.31%
  • AT&S Austria Technologie & Systemtechnik (ATS): 4.87%
  • Erste Group Bank (EBS): 4.43%
  • S Immo (SPI): 2.23%

By using the function ef.portfolio_performance, we get the following results:

  • Expected annual return: 69.1%
  • Annual volatility: 22.1%
  • Sharpe Ratio: 3.08
Figure 6

To assess the performance of our portfolio and compare it to our benchmark index ATX Total Return, we backtest our portfolios, starting on Oktober 20th 2018 for two years. First, we calculate the cumulative performance of our portfolios and the ATX Total Return in the given timeframe.

To simplify plotting, we create a DataFrame and interpolate missing values.

We can see from Figure 7 below, that all both our optimized portfolios would have outperformed the benchmark index ATX Total Return in the past 2 years. While the ATX TR index would have yielded a return of about -28%, our portfolio maximizing Sharpe Ratio (with exponentially weighted returns and variances) would have yielded a return of 10.38%, and our Minimum Variance portfolio a return of roughly -16%.

Figure 7

Conclusion

Using only a few lines of code, we were able to create a mean-variance optimized portfolio thanks to the PyPortfolioOpt library. [5] All of our optimized portfolios were able to beat our benchmark index (ATX Total Return index) in terms of cumulative return over the past 2 years. However, it is necessary to be extremely cautious. Although our backtesting results look promising, there is absolutely no guarantee that those gains compared to the index would also keep on in the future. Therefore, this article should not be seen as investment advice, but should rather provide a framework for you to build your own optimized portfolios. These portfolios don’t have to be limited to the Austrian Traded Index or any of its underlying assets. For any adaptations regarding the portfolio optimization, make sure to adjust every respective detail to prevent any sorts of mistakes.

Having said that, we would like to thank you for reading this article and hope to have helped you understand the matter just a little bit more and perhaps even encouraged you to try it out yourself. Be sure to leave us a response or some claps if you enjoyed the article or have any other questions. If you are interested in further Data Science related articles of any sorts, be sure to follow us at Lumos Student Data Consulting. Stay safe and have a nice day!

Lumos is a student-led Enterprise with a sole focus on Data Science related services based in Vienna. | Feel free to contact us: https://lumos-consulting.at/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store