Weightage for Multiple stocks

For 2 stocks we aare using this code


Create an empty dataframe

portfolio = pd.DataFrame()


Initialize the number of portfolios

num_of_portfolios = 500


Run the loop for each portfolio

for i in range(num_of_portfolios):

    # Generate a and b values randomly by using numpy random function.

    # The argument '1' ensures the values generated are between 0 and 1

    a = np.random.random(1)[0]

    b = 1-a

    portfolio.loc[i, 'hdfcbank_weight'] = a

    portfolio.loc[i, 'SBI_weight'] = b



    # Save the portfolio returns and portfolio standard deviation values along with its ratio

    portfolio.loc[i, 'returns'] = a * <br />
        annual_returns['hdfcbank'] + bannual_returns['SBI']



    portfolio.loc[i, 'std_dev'] = math.sqrt((a**2)
(annual_std_dev['hdfcbank']2) +

                                            (b
2)(annual_std_dev['SBI']**2)

                                            + 2
abcov_hdfcbank_SBI[0, 1])



    portfolio.loc[i, 'returns/std_dev'] = portfolio.loc[i, 'returns'] / <br />
                                      portfolio.loc[i, 'std_dev']



for multiple stocks how to write the coding.

Hi Perumal,



A similar query has already been answered here.



You should use matrix multiplication for multiple stock portfolio.


Create an empty dataframe

portfolio = pd.DataFrame()


Initialize the number of portfolios

num_of_portfolios = 500


Run the loop for each portfolio

for i in range(num_of_portfolios):

    # The below code generates random weights for 'n' stocks.

    weights = np.random.random(n)

    weights /= np.sum(weights)



    # Save the portfolio returns and portfolio standard deviation values along with its ratio

    portfolio.loc[i, 'returns'] = np.sum(np.dot(annual_returns, weights))



    portfolio.loc[i, 'std_dev'] =  np.sqrt(np.dot(weights.T, np.dot(covariance_matrix, weights))) * np.sqrt(252)



    portfolio.loc[i, 'returns/std_dev'] = portfolio.loc[i, 'returns'] / <br />
                                      portfolio.loc[i, 'std_dev']