python 每个季度如何再平衡?

c0vxltue  于 2023-01-29  发布在  Python
关注(0)|答案(1)|浏览(108)

我每个季度都在努力重新平衡这个投资组合。
我这里有下面的代码,我没有得到我想要的Shares_to_buy .也许我没有正确计算它在for循环?此外,它是给出奇怪的输出,如在Bonds键,它有所有0.0744在该列,我不明白为什么,考虑到在if语句中,我声明如果差值的绝对值小于0.01,那么答案应该是0,但是没有出现。

import numpy as np
import pandas as pd

prices = np.array(
    [
        [250.00, 250.00, 250.00, 250.00],
        [270.25, 251.35, 242.32, 260.90],
        [253.40, 244.18, 215.11, 270.54],
        [286.98, 247.89, 214.65, 318.98],
    ]
)

target_weights = np.array([0.25, 0.25, 0.25, 0.25])
startAUM = 1000
assets = list(['Equities','Bonds','Commodities','Real Estate'])
dates = pd.date_range('20220101', '20221231', freq='Q')

df = pd.DataFrame(data=prices,columns=assets,index=dates)
        
current_allocs = {}
total_value = df.sum(axis=1)
        
for stock,value in df.items():
    current_allocs[stock] = pd.DataFrame(value / total_value,columns=['Weight'])
for stock, weight, total in zip(df.items(),target_weights, total_value):
    print(stock[0])
    current_alloc = current_allocs.get(stock[0], 0)
    current_allocs[stock[0]]['diff'] = current_alloc - weight
    current_allocs[stock[0]]['Price'] = stock[1]
    current_allocs[stock[0]]['Shares_to_buy'] = 0
    shares = []
    for c,d in current_allocs[stock[0]].iterrows():
        if abs(d['diff']) > 0.01:
            shares_to_buy = (weight - d['Weight']) * total / d['Price']
            shares.append(shares_to_buy)
        else:
            current_allocs[stock[0]]['Shares_to_buy'] = 0
            shares.append(shares_to_buy)
    current_allocs[stock[0]]['Shares_to_buy'] = shares_to_buy
az31mfrm

az31mfrm1#

你在if和else中使用了相同的代码**-→shares.append(shares_to_buy)←-**
但是你没有在else部分定义→(shares_to_buy

↓可能的解决方案↓
待买股份=(权重- d [“权重”]) 合计/ d [“价格”]*

我使用这个代码没有条件,所以写这个代码上面如果条件,如果你想

决定在股票中添加shares_to_buy,条件是什么,或者两者都有,但是不要忘记定义shares_to_buy:)

相关问题