回测正常、首次模拟正常、定时模拟失败报错
由bq6nr2gp创建,最终由bq6nr2gp 被浏览 5 用户
# 问题描述
1,下面的策略代码,可以正常回测、可以正常模拟运行、但是到第二天模拟运行会报错
2,报错如下:
3,[2025-03-11 22:22:07.338366] ERROR: pypapertrading:moduleinvoker.py:38:_module_run run hit Exception, e "['instrument', 'date'] not in index"
Traceback (most recent call last):
File "dist/build/bigtrader/v30/core/pypapertrading/__init__.py", line 424, in v30.core.pypapertrading.BigQuantModule.run
File "dist/build/bigtrader/v30/core/pypapertrading/__init__.py", line 308, in v30.core.pypapertrading.BigQuantModule.create_account_data
File "dist/build/bigtrader/v30/core/pypapertrading/paper_test_helper.py", line 588, in v30.core.pypapertrading.paper_test_helper.PaperTestHelper.settle_account_data
File "dist/build/bigtrader/v30/core/pypapertrading/paper_test_helper.py", line 767, in v30.core.pypapertrading.paper_test_helper.PaperTestHelper.get_today_adjusts
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/frame.py", line 4096, in __getitem__
indexer = self.columns._get_indexer_strict(key, "columns")[1]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 6200, in _get_indexer_strict
self._raise_if_missing(keyarr, indexer, axis_name)
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 6252, in _raise_if_missing
raise KeyError(f"{not_found} not in index")
KeyError: "['instrument', 'date'] not in index"
2025-03-11 22:22:17 任务运行状态更新 state=failed event=20250311 1d6f6d1c-a98f-4896-a800-a55f3afa66fe
Traceback (most recent call last):
File "/var/app/enabled/aiflowtaskrun.py", line 199, in <module>
run(run_id=sys.argv[1], task_id=sys.argv[2], event_name=sys.argv[3], dry_run=sys.argv[4])
File "/var/app/enabled/aiflowtaskrun.py", line 194, in run
raise ex from ex
File "/var/app/enabled/aiflowtaskrun.py", line 181, in run
do_run(task_id, event_name)
File "/var/app/enabled/aiflowtaskrun.py", line 146, in do_run
pm.execute_notebook(
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/papermill/execute.py", line 134, in execute_notebook
raise_for_execution_errors(nb, output_path)
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/papermill/execute.py", line 241, in raise_for_execution_errors
raise error
papermill.exceptions.PapermillExecutionError:
---------------------------------------------------------------------------
Exception encountered at "In [1]":
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[1], line 110
96 context.order_target_percent(context.hedging_ins,1)
98 data = {
99 "start_date":'2019-03-01',
100 'end_date':'2025-03-01',
(...)
108 'instruments': list(etf_pool.keys())
109 }
--> 110 m3 = M.bigtrader.v30(
111 data=data,
112 initialize=initialize,
113 handle_data=handle_data,
114 capital_base=50000,
115 frequency="""daily""",
116 product_type="""基金""",
117 rebalance_period_type="""交易日""",
118 rebalance_period_days="""1""",
119
[2025-03-11 23:42:22] [info ] settle_account_data {'eefa260d-b80a-42ac-bba3-76809a3329cc': '0'} prev_trading_day=2025-03-10, trading_day=2025-03-11, first_trading_day=2025-03-10
[2025-03-11 23:42:22.900618] ERROR: pypapertrading:moduleinvoker.py:38:_module_run run hit Exception, e "['instrument', 'date'] not in index"
Traceback (most recent call last):
File "dist/build/bigtrader/v30/core/pypapertrading/__init__.py", line 424, in v30.core.pypapertrading.BigQuantModule.run
File "dist/build/bigtrader/v30/core/pypapertrading/__init__.py", line 308, in v30.core.pypapertrading.BigQuantModule.create_account_data
File "dist/build/bigtrader/v30/core/pypapertrading/paper_test_helper.py", line 588, in v30.core.pypapertrading.paper_test_helper.PaperTestHelper.settle_account_data
File "dist/build/bigtrader/v30/core/pypapertrading/paper_test_helper.py", line 767, in v30.core.pypapertrading.paper_test_helper.PaperTestHelper.get_today_adjusts
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/frame.py", line 4096, in __getitem__
indexer = self.columns._get_indexer_strict(key, "columns")[1]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 6200, in _get_indexer_strict
self._raise_if_missing(keyarr, indexer, axis_name)
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 6252, in _raise_if_missing
raise KeyError(f"{not_found} not in index")
KeyError: "['instrument', 'date'] not in index"
2025-03-11 23:42:25 任务运行状态更新 state=failed event=20250311 1d6f6d1c-a98f-4896-a800-a55f3afa66fe
Traceback (most recent call last):
File "/var/app/enabled/aiflowtaskrun.py", line 199, in <module>
run(run_id=sys.argv[1], task_id=sys.argv[2], event_name=sys.argv[3], dry_run=sys.argv[4])
File "/var/app/enabled/aiflowtaskrun.py", line 194, in run
raise ex from ex
File "/var/app/enabled/aiflowtaskrun.py", line 181, in run
do_run(task_id, event_name)
File "/var/app/enabled/aiflowtaskrun.py", line 146, in do_run
pm.execute_notebook(
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/papermill/execute.py", line 134, in execute_notebook
raise_for_execution_errors(nb, output_path)
File "/opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/papermill/execute.py", line 241, in raise_for_execution_errors
raise error
papermill.exceptions.PapermillExecutionError:
---------------------------------------------------------------------------
Exception encountered at "In [1]":
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[1], line 110
96 context.order_target_percent(context.hedging_ins,1)
98 data = {
99 "start_date":'2019-03-01',
100 'end_date':'2025-03-01',
(...)
108 'instruments': list(etf_pool.keys())
109 }
--> 110 m3 = M.bigtrader.v30(
111 data=data,
112 initialize=initialize,
113 handle_data=handle_data,
114 capital_base=50000,
115 frequency="""daily""",
116 product_type="""基金""",
117 rebalance_period_type="""交易日""",
118 rebalance_period_days="""1""",
119 rebalance_period_roll_forward=True,
120 backtest_engine_mode="""标准模式""",
121 before_start_days=120,
122 volume_limit=1,
123 order_price_field_buy="""open""",
124 order_price_field_sell="""open""",
125 benchmark="""512890.SH""",
126 # benchmark="""513100.SH""",
127 m_cached=False,
128 plot_charts=True
129 )
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/bigmodule/modules.py:28, in __call__(self, **kwargs)
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/bigmodule/moduleinvoker.py:203, in module_invoke(name, version, kwargs)
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/bigmodule/moduleinvoker.py:169, in _module_invoke(name, version, kwargs)
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/bigmodule/moduleinvoker.py:41, in _module_run(module, kwargs)
File dist/build/bigtrader/v30/__init__.py:386, in v30.run()
File dist/build/bigtrader/v30/__init__.py:215, in v30._run()
File dist/build/bigtrader/v30/core/pypapertrading/__init__.py:672, in v30.core.pypapertrading.BigQuantModule.run()
File dist/build/bigtrader/v30/core/pypapertrading/__init__.py:424, in v30.core.pypapertrading.BigQuantModule.run()
File dist/build/bigtrader/v30/core/pypapertrading/__init__.py:308, in v30.core.pypapertrading.BigQuantModule.create_account_data()
File dist/build/bigtrader/v30/core/pypapertrading/paper_test_helper.py:588, in v30.core.pypapertrading.paper_test_helper.PaperTestHelper.settle_account_data()
File dist/build/bigtrader/v30/core/pypapertrading/paper_test_helper.py:767, in v30.core.pypapertrading.paper_test_helper.PaperTestHelper.get_today_adjusts()
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/frame.py:4096, in DataFrame.__getitem__(self, key)
4094 if is_iterator(key):
4095 key = list(key)
-> 4096 indexer = self.columns._get_indexer_strict(key, "columns")[1]
4098 # take() does not accept boolean indexers
4099 if getattr(indexer, "dtype", None) == bool:
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/indexes/base.py:6200, in Index._get_indexer_strict(self, key, axis_name)
6197 else:
6198 keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr)
-> 6200 self._raise_if_missing(keyarr, indexer, axis_name)
6202 keyarr = self.take(indexer)
6203 if isinstance(key, Index):
6204 # GH 42790 - Preserve name from an Index
File /opt/pyenv/versions/3.11.8/lib/python3.11/site-packages/pandas/core/indexes/base.py:6252, in Index._raise_if_missing(self, key, indexer, axis_name)
6249 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
6251 not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())
-> 6252 raise KeyError(f"{not_found} not in index")
KeyError: "['instrument', 'date'] not in index"
©2025 BigQuant.com - 蜀ICP备16017083号-1
# 策略代码
"""
etf 的动量策略
"""
from bigmodule import M
import dai
import numpy as np
import pandas as pd
import math
from scipy.stats import linregress
etf_pool = {
'159957.SZ': '科技',
'159915.SZ': '创业 50',
'512890.SH': '红利',
'513050.SH':'中概'
}
# 交易引擎:初始化函数,只执行一次
def initialize(context):
from bigtrader.finance.commission import PerOrder
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0001, sell_cost=0.0001, min_cost=1))
context.ins = context.instruments
context.singe_ins = "512890.SH"
context.hedging_ins = "159915.SZ" # 创业50
context.momentum_days = 5
def get_instruments_score(context,instrument,data):
df = data.history(instrument, ["close", "volume"], context.momentum_days, '1d')
y = df['log'] = np.log(df.close)
x = df['num'] = np.arange(df.log.size)
slope, intercept = np.polyfit(x, y, 1)
annualized_returns = math.pow(math.exp(slope), 150) - 1
r_squared = 1 - (sum((y - (slope * x + intercept))**2) / ((len(y) - 1) * np.var(y, ddof=1)))
score = annualized_returns * r_squared
return score
def get_rank(context,d):
etf_pool_score = {}
for instrument in etf_pool:
if instrument == '512890.SH':
continue
score = get_instruments_score(context,instrument,d)
etf_pool_score [instrument] = score
df = pd.DataFrame(index=etf_pool, data={'score': etf_pool_score})
df = df.sort_values(by='score', ascending=False)
rank_list = list(df.index)
return rank_list[1]
# 交易引擎:数据处理函数,每个周期执行一次
def handle_data(context, data):
import pandas as pd
from datetime import datetime, timedelta
# print(data.current_dt.date())
import pandas as pd
# 获取512890的历史数据窗口
df = data.history(context.singe_ins, ['close'], 200, '1d')
# 计算200日均线
mean_200 = df['close'].mean()
# 计算当前价格
current_price = df['close'][-1]
current_hold_instruments = set(context.get_account_positions().keys())
if current_price < mean_200 * 1:
# 检查是否已经持仓
if context.singe_ins not in current_hold_instruments:
context.order_target_percent(context.hedging_ins,0)
context.order_target_percent(context.singe_ins, 1) # 买入仓位,调整比例
if context.singe_ins in current_hold_instruments and current_price > mean_200 * 1.10:
context.order_target_percent(context.singe_ins, 0)
context.hedging_ins = get_rank(context,data) # 卖出,清仓
context.order_target_percent(context.hedging_ins,1)
data = {
"start_date":'2019-03-01',
'end_date':'2025-03-01',
'market':'cn_stock',
# 'instruments':['518880.SH']
# '518880.SH', #黄金ETF(最佳避险大宗商品)
# '513100.SH', #纳指100(美股最优资产)
# '159915.SZ', #创业板100(成长股)
# '510300.SH', #沪深300(价值股,中大市值蓝筹股)
# '513050.SH', #中概互联
'instruments': list(etf_pool.keys())
}
m3 = M.bigtrader.v30(
data=data,
initialize=initialize,
handle_data=handle_data,
capital_base=50000,
frequency="""daily""",
product_type="""基金""",
rebalance_period_type="""交易日""",
rebalance_period_days="""1""",
rebalance_period_roll_forward=True,
backtest_engine_mode="""标准模式""",
before_start_days=120,
volume_limit=1,
order_price_field_buy="""open""",
order_price_field_sell="""open""",
benchmark="""512890.SH""",
# benchmark="""513100.SH""",
m_cached=False,
plot_charts=True
)
\