-
Return and Variance 7
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
Lecture1.5
-
Lecture1.6
-
Lecture1.7
-
-
Solving Equations 5
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
Lecture2.4
-
Lecture2.5
-
-
Capital Allocation Line 6
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
Lecture3.5
-
Lecture3.6
-
-
Diversification 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
-
Investment Sets 3
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
-
Portfolios 7
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
Lecture6.4
-
Lecture6.5
-
Lecture6.6
-
Lecture6.7
-
-
Capital and Security Market Lines 3
-
Lecture7.1
-
Lecture7.2
-
Lecture7.3
-
-
Arbitrage 3
-
Lecture8.1
-
Lecture8.2
-
Lecture8.3
-
-
Dividend Discount Model 2
-
Lecture9.1
-
Lecture9.2
-
-
Fixed Income 4
-
Lecture10.1
-
Lecture10.2
-
Lecture10.3
-
Lecture10.4
-
-
Duration and Immunization 4
-
Lecture11.1
-
Lecture11.2
-
Lecture11.3
-
Lecture11.4
-
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()