首页 > 解决方案 > for 循环在 for 循环中给出关键错误我正在给出列表

问题描述

我正在尝试在 for 循环中回测我的算法交易环境的策略,它检查比较列表值并给出输出信号买入或卖出,然后将值存储在数据框中

尝试通过列表到数据框,但每次都会从熊猫中给出 keyerror



for i in range(len(merged_DF)):    

    if signal == "":
        stock_ret.append(0)
        if i > 0:
            if bar_num[i]>=2 and macd[i]>macd_sig[i] and macd_slope[i]>macd_sig_slope[i]:
                signal = "Buy"
            elif bar_num[i]<=-2 and macd[i]<macd_sig[i] and macd_slope[i]<macd_sig_slope[i]:
                signal = "Sell"

    elif signal == "Buy":
        stock_ret.append((merged_DF["close"][i]/merged_DF["close"][i-1])-1)
        if i > 0:
            if bar_num[i]<=-2 and macd[i]<macd_sig[i] and macd_slope[i]<macd_sig_slope[i]:
                signal = "Sell"
            elif macd[i]<macd_sig[i] and macd_slope[i]<macd_sig_slope[i]:
                signal = ""

    elif signal == "Sell":
        stock_ret.append((merged_DF["close"][i-1]/merged_DF["close"][i])-1)
        if i > 0:
            if bar_num[i]>=2 and macd[i]>macd_sig[i] and macd_slope[i]>macd_sig_slope[i]:
                signal = "Buy"
            elif macd[i]>macd_sig[i] and macd_slope[i]>macd_sig_slope[i]:
                signal = ""
Traceback (most recent call last):

  File "<ipython-input-26-b5a1f393f490>", line 12, in <module>
    stock_ret.append((merged_DF["close"][i]/merged_DF["close"][i-1])-1)

  File "c:\users\ramakrishnamekala\appdata\local\programs\python\python36\lib\site-packages\pandas\core\series.py", line 1071, in __getitem__
    result = self.index.get_value(self, key)

  File "c:\users\ramakrishnamekala\appdata\local\programs\python\python36\lib\site-packages\pandas\core\indexes\base.py", line 4730, in get_value
    return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))

  File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value

  File "pandas/_libs/index.pyx", line 88, in pandas._libs.index.IndexEngine.get_value

  File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 992, in pandas._libs.hashtable.Int64HashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 998, in pandas._libs.hashtable.Int64HashTable.get_item

KeyError: 2

信号 = 买入或卖出或无

标签: pythonalgorithmic-trading

解决方案


推荐阅读