绘制标准差与带宽平均值的比率

2024-06-01 01:12:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过计算给定带宽上的标准差与平均值的比值来揭示数据中难以看到的相关性。窗口将向右移动一个频率单元,然后再次计算比率,依此类推。我认为这是可能的准备功能从Matplotlib或scipy库?如果能给我看一下解决办法,我将不胜感激。你知道吗


Tags: 数据功能matplotlibscipy单元频率比率平均值
1条回答
网友
1楼 · 发布于 2024-06-01 01:12:56

你要计算的是相对标准偏差(RSD)的滚动版本,也就是变异系数(CV)。WikipediaInvestopedia。你知道吗

RSD=CV=SD/平均值。你知道吗

让我们先做一些时间序列数据。你知道吗

import pandas as pd
import numpy as np

# some sample data
ts = pd.Series(np.random.randn(1000), 
               index=pd.date_range('1/1/2000', 
                                   periods=1000)).cumsum()

解决方案

下面的代码将为您提供所需的内容。你知道吗

选项A

window = 60
rolling_rsd = ts.rolling(window=window).std()/ts.rolling(window=window).mean()

选项B

或者,您可以使用以下方便功能:

def rsd(ts, window = 60):
    """
    Returns the Relative Standard Deviation (RSD), 
    a.k.a Coefficient of Variation (CV) for a 
    given rolling window size on a time series data-column.

    ts = time series data
    window = window size to compute rolling mean, std, rsd
    Example:
       rolling_rsd, rolling_mean, rolling_std = rsd(ts, window = 60)
    """
    rolling_mean = ts.rolling(window=window).mean()
    rolling_std = ts.rolling(window=window).std()
    rolling_rsd = rolling_std/rolling_mean

    return (rolling_rsd, rolling_mean, rolling_std)

详细示例


import pandas as pd
import numpy as np

# some sample data
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)).cumsum()

#plot the time series
ts.plot(style='k ')

def rsd(ts, window = 60):
    """
    Returns the Relative Standard Deviation (RSD), 
    a.k.a Coefficient of Variation (CV) for a 
    given rolling window size on a time series data-column.

    ts = time series data
    window = window size to compute rolling mean, std, rsd
    Example:
       rolling_rsd, rolling_mean, rolling_std = rsd(ts, window = 60)
    """
    rolling_mean = ts.rolling(window=window).mean()
    rolling_std = ts.rolling(window=window).std()
    rolling_rsd = rolling_std/rolling_mean

    return (rolling_rsd, rolling_mean, rolling_std)

(rolling_rsd, rolling_mean, rolling_std) = rsd(ts, window = 60)

# calculate a 60 day rolling mean and plot
rolling_mean.plot(style='k')

# add the 20 day rolling standard deviation:
rolling_std.plot(style='b')

# add the 20 day rolling standard deviation:
rolling_rsd.plot(style='r')

注:

您也可以直接如下计算(如果您不想使用另一个函数)。你知道吗

# calculate a 60 day rolling standard deviation (rsd)

rolling_rsd = ts.rolling(window=60).std()/ts.rolling(window=60).mean()

相关解决方案/问题
1How can I simply calculate the rolling/moving variance of a time series in python?

相关问题 更多 >