Calculate portfolios
We'll now generate portfolios to find each month's best one. numpy
's random.random()
generates random numbers from a uniform distribution, then we normalize them so they sum to 1 using the /=
operator. We use these weights to calculate returns and volatility. Returns are sums of weights times individual returns. Volatility is more complex, and involves the covariances of the different stocks.
Finally we'll store the values in dictionaries for later use, with months' dates as keys.
In this case, we will only generate 10 portfolios for each date so the code will run faster, but in a real-world use-case you'd want to use more like 1000 to 5000 randomly-generated portfolios for a few stocks.
Este ejercicio forma parte del curso
Machine Learning for Finance in Python
Instrucciones del ejercicio
- Generate 3 random numbers for the weights using
np.random.random()
. - Calculate
returns
by taking the dot product (np.dot()
; multiplies element-by-element and sums up two arrays) ofweights
with the monthly returns for the currentdate
in the loop. - Use the
.setdefault()
method to add an empty list ([]
) to theportfolio_weights
dictionary for the currentdate
, then appendweights
to the list.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
portfolio_returns, portfolio_volatility, portfolio_weights = {}, {}, {}
# Get portfolio performances at each month
for date in sorted(covariances.keys()):
cov = covariances[date]
for portfolio in range(10):
weights = np.random.random(____)
weights /= np.sum(weights) # /= divides weights by their sum to normalize
returns = np.dot(____, returns_monthly.loc[____])
volatility = np.sqrt(np.dot(weights.T, np.dot(cov, weights)))
portfolio_returns.setdefault(date, []).append(returns)
portfolio_volatility.setdefault(date, []).append(volatility)
portfolio_weights.setdefault(date, ____).append(____)
print(portfolio_weights[date][0])