✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🏦 Standard & Poor's chooses Dash Enterprise for ESG analysis. Learn why, sign up for the June 23 Webinar here!

Calculation issue about Markowitz Portfolio Optimization

Firstly, this tutorial is really good, both in finance, math, and python. I like it a lot.

I was reading the tutorial of Markowitz Portfolio Optimization (Markowitz Portfolio Optimization | Python/v3 | Plotly). There is an issue about calculation the optimal risk level.
in the optimal_portfolio function,

m1 = np.polyfit(returns, risks, 2)
x1 = np.sqrt(m1[2] / m1[0])

I think it should be : m1 = np.polyfit(risks, returns, 2), because risks is x, and returns is y

Best wishes

Hi Ken, I think the reason why they do it this way around is: When you plot x=risk and y=returns, you get a Markowitz bullet with an efficient frontier that sketches out a parabola that’s ‘lying on its side’. That is, the tapered end is to the left, and the ‘arms’ that extend out to infinity are to the right.

On the other hand a 2nd order polynomial either sketches out a parabola where the tapered end is at the bottom and the the ‘arms’ are at the top, or visa versa.

So in order to fit a second order polynomial as a line of best fit to the efficient frontier, we first need to switch the axis around (returns = x, risks = y), so that the parabola is correctly oriented.

I hope that helps!