每个时期的投资组合重新平衡以恢复初始权重

问题描述 投票:0回答:2

我有 4 只股票,我想了解如何重新平衡投资组合。假设每只股票的权重应为 0.25 (1/4),而我总共只投资 1 美元

import pandas as pd
import numpy as np

stocks = pd.DataFrame([[52.38, 45.22, 12.01, 120.94],
                      [51.25, 42.35, 13.32, 123.90],
                      [53.40, 44.18, 15.11, 120.54],
                      [56.98, 47.89, 14.65, 118.98]], columns = ['w', 'x', 'y', 'z'])

target_weights = {'w':0.25, 'x':0.25, 'y':0.25, 'z':0.25}

所以我首先需要计算每只股票的回报:

returns = stocks.pct_change()

那么,由于我只投资 1 美元,目标权重及其回报的差异就为我提供了新的分配?但现在,我如何重新平衡权重以恢复目标权重,并且总分配仍然为 1,并且每个时期都是如此。我认为计算应该在 for 循环中完成,并且在每次迭代时它都会以目标权重开始,但我不知道应该如何处理。

python pandas finance
2个回答
2
投票

在 numpy 中比在 pandas 中更容易做到这一点:

# Price of w, x, y, z at the beginning of each period
price = np.array(
    [
        [52.38, 45.22, 12.01, 120.94],
        [51.25, 42.35, 13.32, 123.90],
        [53.40, 44.18, 15.11, 120.54],
        [56.98, 47.89, 14.65, 118.98],
    ]
)
# The number of shares for each security in the portfolio
# at the beginning of each period
quantity = np.zeros_like(price)

initial_investment = 1
target_weight = np.array([0.25, 0.25, 0.25, 0.25])

for i in range(price.shape[0]):
    if i == 0:
        quantity[i] = initial_investment * target_weight / price[i]
    else:
        portfolio_value = (quantity[i-1] * price[i]).sum()
        quantity[i] = portfolio_value * target_weight / price[i]

# Final assembly
columns = pd.MultiIndex.from_product([["price", "quantity"], list("wxyz")])
df = pd.DataFrame(np.hstack([price, quantity]), columns=columns)
df["portfolio_value"] = (df["price"] * df["quantity"]).sum(axis=1)

结果:

   price                        quantity                               portfolio_value
       w      x      y       z         w         x         y         z                
0  52.38  45.22  12.01  120.94  0.004773  0.005529  0.020816  0.002067        1.000000
1  51.25  42.35  13.32  123.90  0.004937  0.005975  0.018996  0.002042        1.012128
2  53.40  44.18  15.11  120.54  0.004966  0.006003  0.017552  0.002200        1.060818
3  56.98  47.89  14.65  118.98  0.004780  0.005687  0.018590  0.002289        1.089362

0
投票

我有一个与此非常相似的解决方案,但不知道如何摆脱 for 循环并用向量化函数替换。知道如何做到这一点吗?

© www.soinside.com 2019 - 2024. All rights reserved.