我需要对一个时间序列中每一天的累计价值进行分析



我有一个具有时间序列的DataFrame。我需要得到第一行,并像我的投资一样增加。下一行是另一天,我需要比较以获得值的差异,这将是我一天的累积值。

我的数据:

我的数据

翻译:数据=日期

Cota=配额

Patrimonio Liquido=净值

目前我的代码如下:

len_fundo = len(self.fundo)
investiment = self.fundo.iloc[0]
dict_accumulated = {}
for value in range(1, len_fundo):
next_line = self.fundo.iloc[value]
dict_accumulated['Data'] = next_line['Data']
dict_accumulated['Acumulado'] = next_line['PL'] - investiment['PL']
investiment = next_line
accumulated = pd.DataFrame(data=dict_accumulated, index=[value])
return accumulated

但结果只是最后一行。

Data         Acumulado
4 2019-12-06   942355.3

我知道这是因为python dict不接受重复的密钥;因此,它取代了密钥,但我如何解决这种情况?我需要为每天生成一个带有日期和累计值列的新DF。。。

结果将是一个新的DF,如下所示:

在此处输入图像描述

我认为你应该使用

df['gains'] = df['current'].shift(1) - df['current'] # difference per day
df['acumulado'] = df['gains'].cumsum() # for cumulative sum of gains

使用带有pandas的环路通常是不好的实践

您没有提供一个功能齐全的示例,所以我无法测试它是否按预期工作,但您不能只列出dict_accumulated['Data']dict_accumulated['Acumulado']列表,然后在每个循环中附加到它们吗?类似这样的东西:

len_fundo = len(self.fundo)
investiment = self.fundo.iloc[0]
dict_accumulated = {}
dict_accumulated['Data'] = []
dict_accumulated['Acumulado'] = []
for value in range(1, len_fundo):
next_line = self.fundo.iloc[value]
dict_accumulated['Data'].append(next_line['Data'])
dict_accumulated['Acumulado'].append(next_line['PL'] - investiment['PL'])
investiment = next_line
accumulated = pd.DataFrame(data=dict_accumulated, index=[value])
return accumulated

相关内容

最新更新