Exercise

# 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.

Instructions

**100 XP**

- 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) of`weights`

with the monthly returns for the current`date`

in the loop. - Use the
`.setdefault()`

method to add an empty list (`[]`

) to the`portfolio_weights`

dictionary for the current`date`

, then append`weights`

to the list.