Visualizing the efficient frontier
Our optimization code generated the portfolio that is optimal for the specific risk-free rate of return. This is one type of? portfolio. To be able to plot all of the portfolios along the Markowitz bullet, we can change the optimization around a little bit.
The following function takes a weights vector, the returns, and a target return and calculates the variance of that portfolio with an extra penalty the further the mean is from the target return, so as to help push portfolios with weights further from the mean considering they are on the frontier:
In [27]: def objfun(W, R, target_ret): stock_mean = np.mean(R,axis=0) port_mean = np.dot(W,stock_mean) cov=np.cov(R.T) port_var = np.dot(np.dot(W,cov),W.T) penalty = 2000*abs(port_mean-target_ret) return np.sqrt(port_var) + penalty
We now create a function that will run through a set of desired return values, ranging from the lowest returning stock to the highest...