How it works...

In Steps 1 to 4, we followed the already established approach—imported the libraries, set up the parameters, downloaded stock prices of four US tech companies (Apple, IBM, Microsoft, and Twitter) over the years 2017-2018, and calculated simple returns, using the adjusted close prices.

In Step 5, we created a list of weights, each one equal to 1 / n_assets, where n_assets is the number of assets we want to have in our portfolio. Next, we calculated the portfolio returns as a matrix multiplication (also known as the dot product—np.dot) of the portfolio weights and a transposed matrix of asset returns. To transpose the matrix, we used the T method of a pandas DataFrame. Then, we stored the portfolio returns as a pandas Series ...

Get Python for Finance Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.