Python 查找数据帧的累积返回
输入返回:Python 查找数据帧的累积返回,python,pandas,quantitative-finance,Python,Pandas,Quantitative Finance,输入返回: 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 累积收益的预期产
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进行编码。请帮我纠正这个错误。非常感谢您的帮助。我不确定您的数字背后的数学含义,但以下是您可以添加一列来表示行的乘积
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
一门课程的项目问题。。。违背了他们的荣誉准则