移动平均线 - 熊猫

Mar*_*598 31 python moving-average python-3.x pandas

我想在我的交换时间序列中添加移动平均线计算.

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
Run Code Online (Sandbox Code Playgroud)

计算移动平均值

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
Run Code Online (Sandbox Code Playgroud)

我想使用相同的索引(日期)将计算出的移动平均线作为新值添加到"值"之后的右侧.最好我还想将计算出的移动平均值重命名为"MA"

Rom*_*ain 51

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

有关信息,该rolling_mean函数已在pandas较新版本中弃用.我在我的示例中使用了新方法,请参阅下面pandas 文档中的引用

警告在此之前版本0.18.0, ,pd.rolling_*,pd.expanding_*pd.ewm*是模块级的功能,现在不建议使用.这些被替换为使用Rolling,ExpandingEWM.对象以及相应的方法调用.

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
Run Code Online (Sandbox Code Playgroud)

  • 实际上@dineshdileep none在这种情况下的`mean`将适用于所有列.如果你想明确地选择一列你可以这样做`df.rolling(window = 5)['MA'].mean()` (4认同)

Mar*_*598 12

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

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

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()
Run Code Online (Sandbox Code Playgroud)

有关如何执行此操作的教程:https : //youtu.be/XWAPPyF62Vg


Pou*_*del 8

为了获得 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)
Run Code Online (Sandbox Code Playgroud)

输出

   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
Run Code Online (Sandbox Code Playgroud)

  • 为什么要这样做而不是普通滚动平均值? (2认同)

chr*_*821 5

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

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

然后你可以做所有MA的总平均值

df[[f for f in list(df) if "MA" in f]].mean(axis=1)
Run Code Online (Sandbox Code Playgroud)