【问题标题】:Moving Average Pandas移动平均熊猫
【发布时间】:2017-02-24 22:18:22
【问题描述】:

我想在我的交易时间序列中添加移动平均计算。

来自Quandl的原始数据

Exchange = Quandl.get("BUNDESBANK/BBEX3_D_SEK_USD_CA_AC_000",
                      authtoken="xxxxxxx")

#               Value
# Date               
# 1989-01-02  6.10500
# 1989-01-03  6.07500
# 1989-01-04  6.10750
# 1989-01-05  6.15250
# 1989-01-09  6.25500
# 1989-01-10  6.24250
# 1989-01-11  6.26250
# 1989-01-12  6.23250
# 1989-01-13  6.27750
# 1989-01-16  6.31250

# Calculating Moving Avarage
MovingAverage = pd.rolling_mean(Exchange,5)

#               Value
# Date          
# 1989-01-02      NaN
# 1989-01-03      NaN
# 1989-01-04      NaN
# 1989-01-05      NaN
# 1989-01-09  6.13900
# 1989-01-10  6.16650
# 1989-01-11  6.20400
# 1989-01-12  6.22900
# 1989-01-13  6.25400
# 1989-01-16  6.26550

我想使用相同的索引 (Date) 在 Value 之后将计算出的移动平均线作为一个新列添加到右侧。最好我还想将计算出的移动平均线重命名为MA

【问题讨论】:

    标签: python python-3.x pandas moving-average


    【解决方案1】:

    滚动平均值返回Series,您只需将其添加为DataFrame (MA) 的新列,如下所述。

    有关信息,rolling_mean 函数已在 pandas 较新版本中被弃用。我在示例中使用了新方法,请参阅下面来自 pandas documentation 的引用。

    警告 在 0.18.0 版之前,pd.rolling_*pd.expanding_*pd.ewm* 是模块级函数,现已弃用。这些由使用RollingExpandingEWM. 对象和相应的方法调用来替换。

    df['MA'] = df.rolling(window=5).mean()
    
    print(df)
    #             Value    MA
    # Date                   
    # 1989-01-02   6.11   NaN
    # 1989-01-03   6.08   NaN
    # 1989-01-04   6.11   NaN
    # 1989-01-05   6.15   NaN
    # 1989-01-09   6.25  6.14
    # 1989-01-10   6.24  6.17
    # 1989-01-11   6.26  6.20
    # 1989-01-12   6.23  6.23
    # 1989-01-13   6.28  6.25
    # 1989-01-16   6.31  6.27
    

    【讨论】:

    • 如果有多列,会“滚动”选择哪一列?
    • @dineshdileep none 实际上在这种情况下mean 将适用于所有列。如果你想明确选择一列,你可以这样做df.rolling(window=5)['MA'].mean()
    • 因提及 EWM 而受到支持。不知道这个,正是我要找的。谢谢!
    • 如果您不想在开头使用 NAN,请使用 min_periods=0(或较小的值)。
    【解决方案2】:

    要在 pandas 中获得移动平均线,我们可以使用 cum_sum 然后除以计数。

    以下是工作示例:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'id': range(5),
                       'value': range(100,600,100)})
    
    # some other similar statistics
    df['cum_sum'] = df['value'].cumsum()
    df['count'] = range(1,len(df['value'])+1)
    df['mov_avg'] = df['cum_sum'] / df['count']
    
    # other statistics
    df['rolling_mean2'] = df['value'].rolling(window=2).mean()
    
    print(df)
    

    输出

       id  value  cum_sum  count  mov_avg     rolling_mean2
    0   0    100      100      1    100.0           NaN
    1   1    200      300      2    150.0           150.0
    2   2    300      600      3    200.0           250.0
    3   3    400     1000      4    250.0           350.0
    4   4    500     1500      5    300.0           450.0
    

    【讨论】:

    • 你为什么要这样做而不是普通的滚动平均值?
    【解决方案3】:

    也可以使用以下代码直接在折线图中计算和可视化移动平均线:

    使用股票价格数据的示例:

    import pandas_datareader.data as web
    import matplotlib.pyplot as plt
    import datetime
    plt.style.use('ggplot')
    
    # Input variables
    start = datetime.datetime(2016, 1, 01)
    end = datetime.datetime(2018, 3, 29)
    stock = 'WFC'
    
    # Extrating data
    df = web.DataReader(stock,'morningstar', start, end)
    df = df['Close']
    
    print df 
    
    plt.plot(df['WFC'],label= 'Close')
    plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
    plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
    plt.legend(loc='best')
    plt.title('Wells Fargo\nClose and Moving Averages')
    plt.show()
    

    如何做到这一点的教程:https://youtu.be/XWAPpyF62Vg

    【讨论】:

    • 我的印象是 seaborn 或 matplotlib 能够计算移动平均线。我错了。
    【解决方案4】:

    如果您计算多个移动平均线:

    for i in range(2,10):
       df['MA{}'.format(i)] = df.rolling(window=i).mean()
    

    然后您可以对所有 MA 进行聚合平均

    df[[f for f in list(df) if "MA" in f]].mean(axis=1)
    

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 2020-07-24
      • 1970-01-01
      • 2019-02-13
      • 2021-08-26
      • 1970-01-01
      • 2020-06-12
      • 2021-10-23
      相关资源
      最近更新 更多