Hands-On Python for Finance by Krish Naik

Hands-On Python for Finance by Krish Naik

Author:Krish Naik
Language: eng
Format: epub
Tags: COM051360 - COMPUTERS / Programming Languages / Python, COM018000 - COMPUTERS / Data Processing, COM062000 - COMPUTERS / Data Modeling and Design
Publisher: Packt Publishing
Published: 2019-03-29T17:45:31+00:00


portfolio_returns=[]

portfolio_volatilities=[]

for x in range(1000):

weights=np.random.random(num_assets)

weights/=np.sum(weights)

portfolio_returns.append(np.sum(weights*log_returns.mean())*250)

portfolio_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(log_returns.cov(),weights))))

portfolio_returns,portfolio_volatilities

The output generated is shown in the following screenshot:

In the loop, we are generating two weights, whose sums equal one. We need two weights, because, as we already mentioned, the portfolios are composed of two assets. As the number of assets increases, the number of weights also increases. We are using the append method, which will add each newly-generated portfolio return value to the list of portfolio returns. This operation will be repeated for each pass of the loop, 1,000 times until the portfolio returns list accumulates 1,000 observations. We repeat the same procedure for the portfolio volatilities. We will use the append method and apply the formula for standard deviation. The output of the preceding code is a list and is hard to manipulate, so we convert it into a NumPy array, as follows:

In[37]:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.