随着时间的推移重新平衡投资组合

时间:2018-08-16 23:39:33

标签: python-3.x

我在实现rebalance portfolio函数方面遇到了很大的挑战。我对自己的目标不太清楚,并确认我的实现无法正常工作,并且正在寻找解决方案。

def rebalance_portfolio(returns, index_weights, shift_size, chunk_size):
    assert returns.index.equals(index_weights.index)
    assert returns.columns.equals(index_weights.columns)
    assert shift_size > 0
    assert chunk_size >= 0

    m = returns.values.shape[0]
    cov = get_covariance_returns(returns)
    x = cvx.Variable(m)
    portfolio_variance = cvx.quad_form(x, cov)
    print(portfolio_variance)    
    distance_to_index = cvx.norm(x - index_weights)
    objective = cvx.Minimize(portfolio_variance + shift_size * distance_to_index)
    x_values = get_optimal_weights(returns, index_weights, shift_size)

    return x_values

请注意:

returns is a DataFrame. Returns for each ticker and date.
index_weights is a DataFrame. Index weight for each ticker and date.
shift_size is an integer. The number of days between each rebalance.
chunk_size is an integer. The number of days to look in the past for rebalancing.

在我的实现中,我必须使用两个函数。首先,get_covariance_returns(returns: DataFrame) return 2 dimensional Ndarray The covariance of the returns。此函数返回DataFrame returns的协方差计算。其次,get_optimal_weights(covariance_returns:2 dimensional Ndarray, index_weights:Pandas Series, scale=2.0) return 1 dimensional Ndarray。此功能找到最佳权重。

1 个答案:

答案 0 :(得分:0)

我现在正在 Udacity 学习相同的课程,我在此链接中找到了针对您的问题“http://digtime.cn/articles/126/ai-for-tradingproject3smart-beta-and”的有效答案-portfolio-optimization-46"。

代码如下:

all_rebalance_weights = []

   for i in range(chunk_size, len(returns), shift_size):
       chunks = returns.iloc[i - chunk_size:i]
        
       cov_returns = get_covariance_returns(chunks)
      
       opt_weights = get_optimal_weights(cov_returns, index_weights.iloc[i-1])
        
       all_rebalance_weights.append(opt_weights)

   return all_rebalance_weights