Rolling underwater results in: TypeError: cannot convert the series to <class 'float'>

Rolling underwater results in: TypeError: cannot convert the series to <class 'float'>

我正在尝试计算水下每年的滚动,它导致 TypeError: cannot convert the series to <class 'float'>。这是一个独立的玩具 MRE 示例:

import numpy as np
import pandas as pd

# generate random returns for two assets
dfr = pd.DataFrame(data=np.random.random_sample((10, 2)),
                   columns=['a', 'b'])
print(dfr)

# compute rolling underwater
dfu = dfr.rolling(5, axis=0).apply(lambda x: x / x.cummax() - 1.0)
print(dfu)

现在 pandas rolling.apply is possible return only scalar,如果添加一些聚合,例如max:

dfu = dfr.rolling(5, axis=0).apply(lambda x: (x / x.cummax() - 1.0).max())

经过一些研究,如果可能的话,使用 max - 聚合 return 标量,而不是在每次迭代中使用 cummax return 数组:

dfu = dfr.rolling(5, axis=0).max().sub(1.0).rdiv(dfr)
print(dfu)
          a         b
0       NaN       NaN
1       NaN       NaN
2       NaN       NaN
3       NaN       NaN
4  4.592909  2.918181
5  0.028935       inf
6       inf  0.280289
7  0.279465  0.233189
8  0.575998  1.178822
9  1.078521  0.429111

您可以使用此技巧测试您的解决方案如何工作:

def f(x):
    print (x / x.cummax() - 1.0)
    return x.sum()

dfu = dfr.rolling(5, axis=0).apply(f)

以及如何将输出转换为 DataFrame 的一种可能想法:

dfr =pd.concat( [(x / x.cummax() - 1.0) for x in dfr.rolling(5, axis=0)])