本文介绍了如何计算 pandas 滚动窗口中的波动率(标准差)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个时间序列"Ser",我想用一个滚动窗口来计算波动率(标准差).我当前的代码以这种形式正确执行了此操作:

I have a time series "Ser" and I want to compute volatilities (standard deviations) with a rolling window. My current code correctly does it in this form:

w=10
for timestep in range(length):
    subSer=Ser[timestep:timestep+w]
    mean_i=np.mean(subSer)
    vol_i=(np.sum((subSer-mean_i)**2)/len(subSer))**0.5
    volList.append(w_i)

在我看来,这是非常低效的.熊猫是否具有内置功能可用于执行此类操作?

This seems to me very inefficient. Does Pandas have built-in functionality for doing something like this?

推荐答案

您似乎正在寻找 Series.rolling .您可以应用 std 计算到结果对象:

It looks like you are looking for Series.rolling. You can apply the std calculations to the resulting object:

roller = Ser.rolling(w)
volList = roller.std(ddof=0)

如果您不打算再次使用滚动窗口对象,则可以编写单行代码:

If you don't plan on using the rolling window object again, you can write a one-liner:

volList = Ser.rolling(w).std(ddof=0)

请记住,在这种情况下必须使用ddof=0,因为标准差的归一化是通过len(Ser)-ddof进行的,并且ddof在熊猫中默认为1.

Keep in mind that ddof=0 is necessary in this case because the normalization of the standard deviation is by len(Ser)-ddof, and that ddof defaults to 1 in pandas.

这篇关于如何计算 pandas 滚动窗口中的波动率(标准差)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 20:11