简体   繁体   English

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

[英]portfolio rebalancing each period to get back initial weights

So I have 4 stocks and I would like to understand how to rebalance a portfolio.所以我有 4 只股票,我想了解如何重新平衡投资组合。 Let say each stock should keep a weight of 0.25 (1/4) and I only invest 1 dollar in total假设每只股票的权重应为 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}

So I first need to compute the returns of each stock:所以我首先需要计算每只股票的回报:

returns = stocks.pct_change()

and so the difference from the target weight and its return gives me the new allocation right since I invest only 1 dollar?所以目标权重和它的回报之间的差异给了我新的分配权,因为我只投资了 1 美元? But now, how do I rebalance the weights to get the target weights back and still have a total allocation of 1, and this for each period.但是现在,我如何重新平衡权重以获得目标权重并且仍然有 1 的总分配,并且每个时期都是如此。 I think the computations should be done in a for loop and at each iteration it starts back with the target weights but I don't know how I should handle that.我认为计算应该在 for 循环中完成,并且在每次迭代时它都从目标权重开始,但我不知道我应该如何处理它。

It's easier to do this in numpy than in pandas:在 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)

Result:结果:

   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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM