python - 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
信号 = 买入或卖出或无
解决方案
推荐阅读
- javascript - 如何在发送到服务器之前将 mimetype (video/webm) 和编解码器 (vp9) 添加到 blob 对象
- php - 如何使用 laravel 注册验证器返回错误
- php - 在php中搜索带有条件的数组
- angular - 为什么 Chrome 在使用 Angular Service-Worker 时会显示重复的 HTTP 请求?
- elasticsearch - Elasticsearch - cologne 和 koelnerphonetik 编码器的区别
- java - 在 API Retrofit PUT 调用中将自定义对象数组作为参数传递
- angular - ngmodule 不是子类型 ngmoduletype
- linux - Git不使用user.name
- python - Gunicorn 工作人员在长时间 API 调用后自行重启
- asp.net-core - mvc和api授权中间件的区别