I'm looking to analyze financial data using python. I am using the below function but I continue to run into a value error and so far I'm having difficulty explaining why I'm running into this issue.
The expected result of this function was for df_1 to contain 5000 possible portfolios, the next function would then optimize those results and I would then plot the efficient frontier.
This is the function in question...
#Define Return Portfolios
def return_portfolios(expected_returns, cov_matrix):
port_returns = []
port_volatility = []
stock_weights = []
selected = (expected_returns.axes)[0]
num_assets = len(selected)
num_portfolios = 5000
for single_portfolio in range(num_portfolios):
weights = np.random.random(num_assets)
weights /= np.sum(weights)
returns = np.dot(weights, expected_returns)
volatility = np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights)))
port_returns.append(returns)
port_volatility.append(volatility)
stock_weights.append(weights)
portfolio = {'Returns': port_returns, 'Volatility': port_volatility}
for counter, symbol in enumerate(selected):
portfolio[symbol + 'Weight'] = [Weight [counter] for Weight in stock_weights]
df = pd.Dataframe(portfolio)
column_order = ['Returns', 'Volatility'] + [stock +' Weight' for stock in selected]
df = df[column_order]
return df
*I continue to get this value error. I'm not sure why. *
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-f1e87857141b> in <module>
1 #Plot Efficient Frontier
----> 2 df_1 = return_portfolios(daily_ER, covariance)
3
4 weights, returns, risks = optimal_portfolio(daily_ER[1:])
5
<ipython-input-3-d248522d6f87> in return_portfolios(expected_returns, cov_matrix)
14 weights /= np.sum(weights)
15 returns = np.dot(weights, expected_returns)
---> 16 volatility = np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights)))
17 port_returns.append(returns)
18 port_volatility.append(volatility)
<__array_function__ internals> in dot(*args, **kwargs)
ValueError: shapes (11,11) and (254,) not aligned: 11 (dim 1) != 254 (dim 0)
It looks like you are trying to perform dot product between two matrices. However, one has the shape of (11, 11), another has shape (254, ). You need to make sure that the number of columns of the first matrix equals the number of raws of second matrix