gpt4 book ai didi

python - 移动平均线 Pandas

转载 作者:IT老高 更新时间:2023-10-28 22:17:32 25 4
gpt4 key购买 nike

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

来自 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

最佳答案

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

有关信息,rolling_mean 函数已在 pandas 较新版本中被弃用。我在示例中使用了新方法,请参阅下面来自 pandas 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

关于python - 移动平均线 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com