移动平均- 熊猫

2024-09-29 02:18:21 发布

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

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

来自Quandl的原始数据

Exchange=Quandl.get(“德国央行/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

计算移动平均值

移动平均值=pd.滚动平均值(交换,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

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


Tags: get原始数据dateexchangevalue时间序列nan
3条回答

滚动平均值返回一个Series您只需将其作为DataFrameMA)的新列添加,如下所述。

有关信息,pandas的较新版本不赞成使用rolling_mean函数。我在我的示例中使用了新方法,请参见下面熊猫的一段引文documentation

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

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

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

使用股价数据的示例:

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

如果要计算多个移动平均值:

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

那么你可以把所有的平均数加起来

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

相关问题 更多 >