*Using FREE stock price data, Python programming and Modern Portfolio Theory to determine risk and return weighted stock portfolios*
Welcome back to the blog! In this post I am going to show you something that some of you may find very interesting if you want to learn more about how basic stock portfolios are created and weighted in order to achieve desired levels of risk and return. This blog post is NOT about day trading volatility, looking for short duration trading opportunities or even technical analysis. This blog post WILL show you how you can get a selection of stocks and measure their individual performance and volatility and variance in order to find the perfect mix of stocks in order to achieve maximum return for your risk.
Before I continue I would like to say once more, THIS IS NOT FINANCIAL ADVICE and you should not create a stock portfolio with real money using only the information and code in this blog post. There is a lot more to it including investment selection, tax implications and counter-party risk.
What is Modern Portfolio Theory?
Modern portfolio theory (MPT) is a theory on how risk-averse investors can construct portfolios to maximise expected return based on a given level of market risk – From Investopedia.
Now, the basic idea is that an investor gets a list of investments they want to invest in (another challenge in itself but that is for another blog post) and by analysing both the expected returns of each investment and the expected risk, which is derived from the variance and correlations of each individual investment, you can calculate the required weights of each investment to achieve the maximum potential returns for your desired level for risk.
MPT assumes that investors are risk-averse, meaning they prefer a less risky portfolio to a riskier one for a given level of return. When completing the MPT simulation I will show you later in this blog, we can find both the optimum portfolio weighting to produce a portfolio with minimum risk but also the optimum portfolio weighting to produce maximum returns with minimum risk as defined by the Sharpe ratio.
The Sharpe ratio was developed by Nobel laureate William F. Sharpe and is used to help investors understand the return of an investment compared to its risk. The ratio is the average return earned in excess of the risk-free rate per unit of volatility or total risk. Volatility is a measure of the price fluctuations of an asset or portfolio.
As a performance metric, the greater the value of the Sharpe ratio, the more attractive the risk-adjusted return.
As explained earlier, I will be using the Sharpe Ratio in the following simulation to find the optimum weighting of investments in the portfolio to produce the maximum returns for least amount of risk. I will also show you how to find the weights of investments in the portfolio to produce the lowest risk. For the purpose of the Sharpe Ratio calculations in this blog post I will be using the 10 year US treasury rate which is 1.15% as at the time of writing.
Now let’s get in to the good stuff and look at some code and calculations!
Running a Modern Portfolio Theory simulation using Python programming.
First things first, I download the required price data for the investments in my portfolio. In the example I am going to show you, I have chosen 5 separate publicly traded stocks in various sectors. They are listed in the code below.
I use the Pandas DataReader tool to download the price data direct from the yahoo finance website. It is quick, easy, accurate and more importantly, free to use.
You will notice I have written comment lines within the code to explain each individual line of code to you and what it does. In the image above, you can see that I download the stock data, filter it to select only the adjusted close prices and then print the last 5 rows to visually check that the data download has worked.
We then calculate the covariance of stocks within the portfolio using percentage change in close price. Covariance is used to determine the relationship between the prices of each stock within the portfolio and that is why it creates a matrix where every stock within the portfolio can be compared to each other.
Another key metric we need to run the modern portfolio simulation is the correlation between each of the stocks in the portfolio. This is done using the percentage change in price and again, it is printed as a matrix which can be seen below.
You will remember in the previous section of this blog post I talked about how MPT uses variance as a measure of risk. This is going to be calculated next along with the annual returns of the stocks in the portfolio to determine performance.
I first start by assigning generic weights to each stock in the portfolio to determine the portfolio variance and annual returns of each stock. This effectively produces the performance of the portfolio of stocks assuming even weightings or almost even weightings.
The first 2 stocks have 20% weight and the remaining 4 stocks in the portfolio have 15% weight.
I then use the the individual returns of each stock in the portfolio and the assigned weights of each stock to produce the annual return for the entire portfolio. This is shown below.
At this stage, I am working with the weights that I have assigned to the stocks in the portfolio and this means the current performance and volatility of the portfolio is NOT yet optimised. In a few steps you will see how the optimisation process begins.
The final step before beginning the optimisation process is to obtain the volatility of each stock in the portfolio. This is calculated using the standard deviation of each stock and then annualising it by multiplying it by the square root to the power of 250. The number 250 represents the number of trading days in a year to get annual volatility. This is shown below.
I then print the annual returns and annual volatility of each stock in the portfolio based on their current (non-optimised) weights I assigned to them.
Now let’s make things even more interesting and look at the code used to find the optimum weights for stocks within the portfolio. The basic idea is that the program randomly generates 6 weightings that equal 1.0 (1.0 = 100% exposure to stocks across all 6 stocks in the portfolio) and applies them to the annual returns and annual volatility data we calculated in previous steps.
The program then repeats this step 10,000 times to produce 10,000 different randomly weighted portfolios. I then plot this information on a scatter plot and query the results of the 10,000 randomly weighted portfolio to find the optimum weightings of stocks depending on our goals. All of this is covered in more detail in the following steps.
The code above is used to create the random portfolios. Don’t worry about understanding it but for those that like to know more, I have provided comments on the key parts. The output is a table of 10,000 portfolios all containing the 6 stocks I have used earlier but with random weights assigned to them and this will naturally mean every portfolio has different performance and risk.
The image below shows the first 5 rows of the table of results. An interesting fact for those of you that don’t use Python… it counts from 0 (Row 0 = First row with data).
I then plot all 10,000 randomly generate portfolios on a scatter plot graph. This can be used to visualise how different weightings in stocks effect both returns and volatile of a portfolio but it can then also be used to generate an 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. If i was to draw the efficient frontier on the chart below it would be an upward sloping trendline across the left edge of the plots. 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.
Finally, I can begin to query the results of the 10,000 randomly generate portfolios and find the correct weightings of stocks required to create a portfolio that suits my goals. In reality there are 2 real goals, minimum risk and maximum returns (risk adjusted).
First up is the code I use to find the portfolio with the lowest volatility.
Out of the 10,000 randomly generate portfolios, the one with the lowest overall volatility is shown above. This produced annual returns of 14.5489% with maximum volatility of 16.4218%. To achieve this, the weights for each individual stock are listed in the same query.
Next up is the code I use to find the portfolio with the highest Sharpe ratio. This would then be considered the optimised portfolio. As explained earlier, this is the portfolio with the best risk adjusted returns and is a common metric used by investors.
Using a risk free rate of 1.15% as defined by 10 year treasuries, I query the 10,000 randomly generate portfolios and look for the one with the highest Sharpe ratio. This produced annual returns of 25.9927% with maximum volatility of 21.1167%. To achieve this, the weights for each individual stock are listed in the same query.
Compared to the portfolio with the lowest overall vitality, the optimal portfolio increases annual returns by 11.44% whilst only increasing volatility by 4.69%.
And finally, I finish by plotting both the optimal portfolio and the lowest volatility portfolio on the scatter plot of all 10,000 randomly generate portfolios. It would generally be considered that these are both on the efficient frontier.
For a copy of the full code in order to analyse your own stock picks and run portfolio simulations based on the Modern Portfolio Theory, please email me using the Contact Page on my blog.
Limitations of MPT.
The main limitation of modern portfolio theory is that the risk element is measured using variance and not actual downside risk. Two portfolios with the same variance and returns would be considered the same using MPT but in reality they could be very different.
Portfolio A could have a variance consisting of frequent small losses where as portfolio B could have the same variance that is created from 1 large loss. Most investors would prefer frequent small drawdowns in capital as opposed to less frequent large swings. This is often linked to discussions on tail risk which is the likely hood of larger price swings occurring vs likely hood of smaller price swings but both create variance which is used in MPT.
A popular alternative is to use Post-Modern Portfolio Theory (PMPT) for portfolio optimisation. PMPT uses the standard deviation of negative returns as the measure of risk, while modern portfolio theory uses the standard deviation of all returns as a measure of risk.
Links for more information on both Modern Portfolio Theory and Post-Modern Portfolio Theory can be found below.
Technically, you can use MPT and the code shown in this blog post to analyse any investment including buying and holding commodities, investment trusts, funds and even Cryptocurrencies. Sharpe ratio is a universal method of risk adjusted performance analysis.
Many individuals and retail traders can use the MPT to create more efficient portfolios with ETF’s and Investment Trusts. It is a simple way to potentially boost your returns whilst managing risk. However, as explained in the previous section of this blog post, there are limitations because in MPT, risk is variance and not actually downside risk. For those of you looking to take this further, I suggest starting with research on Modern Portfolio Theory and then Post-modern portfolio theory (PMPT) which is a portfolio optimisation methodology that uses the downside risk of returns instead of the mean variance of investment returns.
If you are interested in learning my personal trading strategies, please consider my Mastering The Markets – Retail Trading Course. Head over to my Financial Analysis Education page to check out all of my education packages and the deals available.
All my technical analysis is done using the TradingView platform. You can get access via the link below.
My preferred broker of choice is IC Markets. Low spreads and trading costs really help long term profitability. A link to their site is below.
FTMO Trader Funding Programme.
Thanks for reading and please don’t forget to LIKE, SHARE and FOLLOW my blog to stay up to date with the latest market analysis and trading education posts.
DISCLAIMER: None of the information posted on this site is to be considered investment/financial advice. Trading is high risk and you should only trade with money you can afford to lose.