我想计算净值曲线的滚动波动率。
# demo
import pandas as pd
def get_rolling_vol(s: pd.Series) -> float:
return s.pct_change().iloc[1:].std()
s = pd.Series([1, 1.2, 1.15, 1.19, 1.23, 1.3])
rolling = s.rolling(window=2)
stds = rolling.apply(lambda s: get_rolling_vol(s))
抛出错误:
FutureWarning: Currently, 'apply' passes the values as ndarrays to the applied function. In the future, this will change to passing it as Series objects. You need to specify 'raw=True' to keep the current behaviour, and you can pass 'raw=False' to silence this warning
stds = rolling.apply(lambda s: get_rolling_vol(s))
... (omits intermediate tracebacks)
AttributeError: 'numpy.ndarray' object has no attribute 'pct_change'
是否有任何方法可以使参数作为Series
而不是ndarrays
中的apply
传递? FutureWarning
说将来会这样,如果我现在想要的话该怎么办? (不想修改get_rolling_vol
函数,因为还有许多其他函数也假定参数为Series
,而修改所有这些函数将很繁琐。)谢谢。
答案 0 :(得分:1)
是的,这是可能的,如警告消息中所述:在raw=False
中使用rolling.apply
作为参数
这至少在熊猫0.24.1中有效