#917·rqalpha

本地自有数据回测使用benchmark报错

Author: zhangshougCreated Apr 7, 2025Updated Apr 9, 2025
Labelsbug

提 ISSUE 须知

1. RQAlpha的版本

5.5.0

2. Python的版本

Python 3.8.8

3. 是Windows/Linux/MacOS or others?

Windows

4. 您出现问题对应的源码/或者能复现问题的简易代码 以及对应的配置

在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。

def init(context): # 实时打印日志 logger.info("RunInfo: {}".format(context.run_info))

before_trading此函数会在每天策略交易开始前被调用,当天只会被调用一次

def before_trading(context): logger.info("盘前执行函数,当前时间:",context.now) bar=history_bars('002049.XSHE', 10, '1d', fields=None, skip_suspended=True, include_now=False) df = pd.DataFrame.from_dict(bar) if 'datetime' in df.columns : df['datetime'] = df['datetime'].map(lambda x: convert_int_to_datetime(x)) df.set_index('datetime', inplace=True) df.index.name = '' print("打印002049.XSHE日线数据:",df.tail())

你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新

def open_auction(context, bar_dict): logger.info("开盘集合竞价时执行函数,当前时间:",context.now)

def handle_bar(context, bar_dict): logger.info("一天过去了,当前时间:",context.now) bar=history_bars('002049.XSHE', 10, '1d', fields=None, skip_suspended=True, include_now=False) df = pd.DataFrame.from_dict(bar) if 'datetime' in df.columns : df['datetime'] = df['datetime'].map(lambda x: convert_int_to_datetime(x)) df.set_index('datetime', inplace=True) df.index.name = '' print("最新日线数据:",df.tail())

after_trading函数会在每天交易结束后被调用,当天只会被调用一次

def after_trading(context): logger.info("盘后执行函数,当前时间:",context.now)

5. 您出现的错误堆栈日志信息

rqalpha run -f test.py -s 2025-04-02 -e 2025-04-03 --frequency 1d 正常 rqalpha run -f test.py -s 2025-04-02 -e 2025-04-03 --frequency 1d --benchmark 000300.XSHG 报错: [2025-04-02 00:00:00.000000] ERROR: user_system_log: 策略运行产生异常 Traceback (most recent call last): File "d:\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc return self._engine.get_loc(casted_key) File "pandas_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 1

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "d:\anaconda3\lib\site-packages\rqalpha\main.py", line 197, in run env.event_bus.publish_event(Event(EVENT.BEFORE_STRATEGY_RUN)) File "d:\anaconda3\lib\site-packages\rqalpha\core\events.py", line 46, in publish_event if listener(event): File "d:\anaconda3\lib\site-packages\rqalpha\mod\rqalpha_mod_sys_analyser\mod.py", line 151, in generate_benchmark_daily_returns_and_portfolio if convert_int_to_date(bars[1]['datetime']).date() != s: File "d:\anaconda3\lib\site-packages\pandas\core\frame.py", line 3024, in getitem indexer = self.columns.get_loc(key) File "d:\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc raise KeyError(key) from err KeyError: 1 [2025-04-02 00:00:00.000000] ERROR: user_system_log: 1 rqalpha run -f test.py -s 2025-04-02 -e 2025-04-03 --frequency 1m 报错: [2025-04-07 13:34:51.507387] ERROR: system_log: tear down fail for sys_analyser Traceback (most recent call last): File "d:\anaconda3\lib\site-packages\rqalpha\mod_init.py", line 80, in tear_down ret = self._mod_dict[mod_name].tear_down(*args) File "d:\anaconda3\lib\site-packages\rqalpha\mod\rqalpha_mod_sys_analyser\mod.py", line 359, in tear_down risk = Risk( File "d:\anaconda3\lib\site-packages\rqrisk\risk.py", line 30, in init assert (len(daily_returns) == len(benchmark_daily_returns)) AssertionError └─$ cat config.yml base:

启动的策略文件路径

#strategy_file: .buy_and_hold.py

回测起始日期

start_date: 2025-04-01

回测结束日期(如果是实盘,则忽略该配置)

end_date: 2050-01-01

目前支持 1d (日线回测) 和 1m (分钟线回测),如果要进行分钟线,请注意是否拥有对应的数据源,目前开源版本是不提供对应的数据源的。

frequency: 1m

Benchmark,如果不设置,默认没有基准参照。

benchmark: ~ accounts: # 设置 股票为交易品种 初始资金为 100000 元 stock: 100000 extra:

开启日志输出

log_level: verbose mod: sys_analyser: enabled: true # 开启 plot 功能 plot: true 使用 没有基准参照 的配置运行回测不报错