Monte Carlo
Solution
I am going to do this solution in parts, there are other ways to do it like creating individual lists for each attribute, but I will instead create nested lists and turn it into a numpy array with an array representing each portoflio
portfolios = []
for _ in range(5001):
weights = np.random.dirichlet(np.ones(10))
r = portfolioReturn(weights,rets)
std = (portfolioVariance(weights,matrix))**.5
portfolios.append([weights,r,std])
print(portfolios[0])
print("")
portfolios = np.array(portfolios)
print(portfolios)
Remember, when we slice a numpy array, we can specify the outer first, then the inner, so to get the standard deviation of portfolio 10, we could do this.
print(portfolios[9,2])
And to get all the standard deviations….
print(portfolios[:,2])
So now, to plot…
import matplotlib.pyplot as plt
plt.plot(portfolios[:,2],portfolios[:,1],"bo")
plt.xlabel("Standard Deviation")
plt.ylabel("Expected Return")
plt.title("Portfolio Sets")
plt.show()
Who wants to look at boring blue though? Let’s turn it into a color map with the sharpe ratio! We can add a fourth attribute to our array, then from there we specify colors=portoflios[:,3] and cmap = coolwarm which gives us a cool warm color map. We will use .02 as the risk-free rate.
We will need to import the color map, and also switch to scatter plotting. I also used some limits on the x and y axis to clean it up.
from matplotlib.cm import coolwarm
portfolios = []
for _ in range(5001):
weights = np.random.dirichlet(np.ones(10))
r = portfolioReturn(weights,rets)
std = (portfolioVariance(weights,matrix))**.5
sharpe = (r-.02)/std
portfolios.append([weights,r,std,sharpe])
portfolios = np.array(portfolios)
plt.scatter(portfolios[:,2],portfolios[:,1],c=portfolios[:,3],cmap=coolwarm)
plt.xlim([.12,.3])
plt.ylim([.04,.075])
plt.xlabel("Standard Deviation")
plt.ylabel("Expected Return")
plt.title("Portfolio Sets")
plt.show()