【问题标题】:Average True Range and Exponential Moving Average Functions on PandasDataSeries needed需要 Pandas 数据系列的平均真实范围和指数移动平均函数
【发布时间】:2017-03-31 22:14:01
【问题描述】:

我在计算系列的平均真实范围 [ATR] 时卡住了。 ATR 基本上是 TrueRange[TR] 的 Exp Movin Avg

 TR is nothing but MAX of -
       Method 1: Current High less the current Low
       Method 2: Current High less the previous Close (absolute value)
       Method 3: Current Low less the previous Close (absolute value)

在 Pandas 中,我们没有内置的 EMA 函数。相反,我们有 EWMA,它是加权移动平均线。

如果有人帮助计算 EMA,那也足够好了

      def ATR(df,n):
          df['H-L']=abs(df['High']-df['Low'])
          df['H-PC']=abs(df['High']-df['Close'].shift(1))
          df['L-PC']=abs(df['Low']-df['Close'].shift(1))
          df['TR']=df[['H-L','H-PC','L-PC']].max(axis=1)
          df['ATR_' + str(n)] =pd.ewma(df['TR'], span = n, min_periods = n)
          return df

上面的代码没有给出错误,但也没有给出正确的值。我将它与手动计算 Excel 中相同数据系列的 ATR 值进行了比较,结果不同

           ATR excel formula-
             Current ATR = [(Prior ATR x 13) + Current TR] / 14

             - Multiply the previous 14-day ATR by 13.
             - Add the most recent day's TR value.
             - Divide the total by 14

这是我用作样本的数据序列

           start='2016-1-1'
           end='2016-10-30'
           auro=web.DataReader('AUROPHARMA.NS','yahoo',start,end)

【问题讨论】:

标签: python pandas technical-indicator


【解决方案1】:

您确实需要使用 ewma 参见此处:指数移动平均线 (EMA) 是一种类似于简单移动平均线的移动平均线,只是对最新数据赋予了更大的权重。

阅读更多:指数移动平均线 (EMA) http://www.investopedia.com/terms/e/ema.asp#ixzz4ishZbOGx

我不认为你的 excel 公式是正确的......这是在 python 中计算 ema 的手动方法

def exponential_average(values, window):
    weights = np.exp(np.linspace(-1.,0.,window))
    weights /= weights.sum()

    a = np.convolve(values, weights) [:len(values)]
    a[:window]=a[window]
    return a

【讨论】:

    【解决方案2】:

    scipy.signal.lfilter 可以帮到你。

    scipy.signal.lfilter(b, a, x, axis=-1,zi=None)
    

    过滤器函数实现为直接II转置结构。这意味着过滤器实现:

    a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M]
                          - a[1]*y[n-1] - ... - a[N]*y[n-N]
    

    如果我们对上述公式进行归一化,我们得到以下公式:

    y[n] = b'[0]*x[n] + b'[1]*x[n-1] + ... + b'[M]*x[n-M]
                      - a'[1]*y[n-1] + ... + a'[N]*y[n-N]
    

    b'[i] = b[i]/a[0], i = 0,1,...,M; a'[j] = a[j]/a[0],j = 1,2,...,Na'[0] = 1

    指数移动平均线公式:

    y[n] = alpha*x[n] + (1-alpha)*y[n-1]
    

    所以要应用scipy.signal.lfilter,通过上面的公式我们可以设置a和b如下:

    a[0] = 1, a[1] = -(1-alpha)
    b[0] = alpha
    

    我的实现如下,希望对你有所帮助。

    def ema(values, window_size):
        alpha = 2./ (window_size + 1)
        a = np.array([1, alpha - 1.])
        b = np.array([alpha])
        zi = sig.lfilter_zi(b, a)
        y, _ = sig.lfilter(b, a, values, zi=zi)
        return y
    

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多