这是我的问题:
我有一个每月投资的DataFrame:
df = pd.DataFrame({'Dates':['2018-07-31','2018-07-31','2018-07-31','2018-08-31','2018-08-31','2018-08-31',
'2018-09-30','2018-09-30','2018-09-30'],
"Name":["Apple",'Google','Facebook','JP Morgan','IBM','Netflix',"Apple","Tesla","Boeing"],
"Monthly Return":[-0.018988,-0.028009,0.111742,-0.034540,-0.025806,-0.043647,0.001045,
0.155379,0.011644],
"Total Weight":[0.7,0.2,0.1,0.5,0.3,0.2,0.6,0.2,0.2]})
我想计算累计投资额,但这样做有困难: 假设我们的初始投资为1000 $
如果我们考虑每个资产的月收益率和权重, 我们在2018-07-31有了这个:
Dates Name Return Weight Investment Pofit/loss
2018-07-31 Apple -0.018988 0.7 700 -13.29
2018-07-31 Google -0.028009 0.2 200 -5.60
2018-07-31 Facebook 0.111742 0.1 100 11.17
所以对于2018年7月,我以1000 $开始,到月底,我有992.28 $(1000-13.29-5.60 + 11.17) 该金额将在2018年8月重新投资,到本月底,我将:992.28美元+/- 2018年8月的总利润/亏损。
我的目标是通过考虑每个月的利润/亏损来确定最终金额,但我真的不知道该怎么做。
如果有人对此有任何想法,欢迎您! 如果您不太清楚,请告诉我
答案 0 :(得分:1)
这是一个解决方案,为清楚起见,分为几个步骤:
df = pd.DataFrame({'Dates':['2018-07-31','2018-07-31','2018-07-31','2018-08-31','2018-08-31','2018-08-31',
'2018-09-30','2018-09-30','2018-09-30'],
"Name":["Apple",'Google','Facebook','JP Morgan','IBM','Netflix',"Apple","Tesla","Boeing"],
"Monthly Return":[-0.018988,-0.028009,0.111742,-0.034540,-0.025806,-0.043647,0.001045,
0.155379,0.011644],
"Total Weight":[0.7,0.2,0.1,0.5,0.3,0.2,0.6,0.2,0.2]})
df["weighted_return"] = df["Monthly Return"] * df["Total Weight"]
# df.groupby("Dates", freq="1M")
df["Dates"] = pd.to_datetime(df.Dates)
df.set_index("Dates", inplace=True)
t = df.groupby(pd.Grouper(freq="M")).sum()
在这一点上,t
是:
Monthly Return Total Weight weighted_return eom_value
Dates
2018-07-31 0.064745 1.0 -0.007719 0.992281
2018-08-31 -0.103993 1.0 -0.033741 0.966259
2018-09-30 0.168068 1.0 0.034032 1.034032
现在,我们可以使用cumprod
来计算一段时间内的回报:
t["eom_value"] = 1 + t.weighted_return
t.eom_value.cumprod()
结果:
Dates
2018-07-31 0.992281
2018-08-31 0.958800
2018-09-30 0.991430