Python 的财务分析 - 返回值错误

Financial Analysis with Python - returning a value error

我希望使用 python 分析财务数据。我正在使用以下函数,但我继续 运行 进入值错误,到目前为止我很难解释为什么我 运行 会陷入这个问题。

此函数的预期结果是 df_1 包含 5000 个可能的投资组合,然后下一个函数将优化这些结果,然后我将绘制有效边界。

这就是有问题的函数...

#定义Return投资组合

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

*我继续收到此值错误。我不确定为什么。 *

    ---------------------------------------------------------------------------
    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)

您似乎正在尝试在两个矩阵之间执行点积。但是,一个具有 (11, 11) 的形状,另一个具有 (254, ) 的形状。您需要确保第一个矩阵的列数等于第二个矩阵的原始数