如何计算实时数据的移动平均值?

问题描述

我已经使用移动平均线构建了几种回测算法,但是我从未针对实时市场构建过一种算法。

这段代码的目的是,计算主while循环的每次迭代的移动平均值,但是以前我每天都在遍历数据帧,但是现在我需要更频繁地遍历,因此我希望更准确。

这是我尝试过的(失败)

emasUsed = [3,5,8,30,35,40]
    for x in emasUsed:
        ema = x
        start = dt.datetime.Now() - dt.timedelta(ema)
        etf_df = pdr.get_data_yahoo(etf,start,Now)
        etf_df["Ema_"+str(ema)]=round(etf_df.iloc[:,4].ewm(span=ema,adjust=False).mean(),2)
                                
    cmin = min(etf_df["Ema_3"],etf_df["Ema_5"],etf_df["Ema_8"])
    cmax = max(etf_df["Ema_30"],etf_df["Ema_35"],etf_df["Ema_40"])

这是计算移动平均值的原始方法(该方法有效,但仅用于回测!)

etf_df = pdr.get_data_yahoo(etf,Now)
    emasUsed = [3,10,12,15,40,45,50,60]
    close = etf_df["Adj Close"][i]
    for x in emasUsed:
        ema = x
        etf_df["Ema_"+str(ema)]=round(etf_df.iloc[:,2)
    cmin = min(etf_df["Ema_3"][i],etf_df["Ema_5"][i],etf_df["Ema_8"][i],etf_df["Ema_10"][i],etf_df["Ema_12"][i])
    cmax = max(etf_df["Ema_30"][i],etf_df["Ema_35"][i],etf_df["Ema_40"][i],etf_df["Ema_45"][i],etf_df["Ema_50"][i],etf_df["Ema_60"][i])

跟踪(最近一次通话最近一次):文件“ C:\ Python \ python37 \ lib \ site-packages \ pandas \ core \ indexes \ base.py”, 第2646行,位于get_loc中 返回self._engine.get_loc(key)文件“ pandas_libs \ index.pyx”,第111行,在pandas._libs.index.IndexEngine.get_loc文件中 第138行中的“ pandas_libs \ index.pyx” pandas._libs.index.IndexEngine.get_loc文件 “ pandas_libs \ hashtable_class_helper.pxi”,第1618行,在 pandas._libs.hashtable.PyObjectHashTable.get_item文件 “ pandas_libs \ hashtable_class_helper.pxi”,第1626行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError:'Ema_3'

在处理上述异常期间,发生了另一个异常:

回溯(最近通话最近):文件 “ C:\ Users \ btjto \ Desktop \ Trading Algorithm \ Paper Trading-ETF Rotation.py“,第82行,在 cmin = min(etf_df [“ Ema_3”],etf_df [“ Ema_5”],etf_df [“ Ema_8”])文件“ C:\ Python \ python37 \ lib \ site-packages \ pandas \ core \ frame.py”,行 2800,在获取中 indexer = self.columns.get_loc(key)文件“ C:\ Python \ python37 \ lib \ site-packages \ pandas \ core \ indexes \ base.py”, 第2648行,在get_loc中 返回self._engine.get_loc(self._maybe_cast_indexer(key))文件“ pandas_libs \ index.pyx”,行111,在 pandas._libs.index.IndexEngine.get_loc文件 第138行中的“ pandas_libs \ index.pyx” pandas._libs.index.IndexEngine.get_loc文件 “ pandas_libs \ hashtable_class_helper.pxi”,第1618行,在 pandas._libs.hashtable.PyObjectHashTable.get_item文件 “ pandas_libs \ hashtable_class_helper.pxi”,第1626行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError:'Ema_3'

对于错误的任何帮助,我们将不胜感激!

我会以错误的方式处理吗?

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)