查找数据框的累积收益

时间:2018-08-18 12:42:43

标签: python pandas quantitative-finance

INPUT 返回:

                  TSYA         AYE        YYIT
2006-08-17         nan         nan         nan
2006-08-18  1.59904743  1.66397210  1.67345829
2006-08-19 -0.37065629 -0.36541822 -0.36015840
2006-08-20 -0.41055669  0.60004777  0.00536958

期望的输出以获取累计回报:

2006-08-17           nan
2006-08-18    5.93647782
2006-08-19   -0.57128454
2006-08-20   -0.68260542
dtype: float64


我的尝试:

def calculate_cumulative_returns(returns):

"""
Calculate cumulative returns.

Parameters
----------
returns : DataFrame
    Returns for each ticker and date

Returns
-------
cumulative_returns : Pandas Series
    Cumulative returns for each date
"""    
res=(1 + returns).cumprod()
return pd.Series(res,index=returns.index)

错误消息:

Output: ValueError: cannot copy sequence with size 3 to array axis with dimension 4

运行代码时,输​​出中出现上述值错误。

我正在使用python和pandas进行编码。请帮我解决这个错误。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我不确定您的数字背后的数学原理,但是您可以按照以下步骤添加代表行结果的列。

import numpy as np
import pandas as pd

Nums = np.array([[1,2,3],[4,3,2],[5,6,7]])
df = pd.DataFrame(data=Nums, columns=('a', 'b', 'c'))

df['product'] = df.prod(axis=1)
df

    a   b   c   product
0   1   2   3   6
1   4   3   2   24
2   5   6   7   210

我的理解是,函数cumprod对每一行或每一列进行累加积(取决于所选轴)。函数prod仅返回行或列中所有数字的乘积。我之所以这样说是因为我可以在您的代码中看到函数cumprod

但是,如果您确实想要一个总和,则只需将功能prod替换为sum

df['Sum'] = df.sum(axis=1)

    a   b   c   Sum
0   1   2   3   6
1   4   3   2   9
2   5   6   7   18