FinRL中FeatureEngineer执行报错KeyError,求助解决方法
解决FinRL FeatureEngineer的KeyError问题
问题场景
使用FinRL的FeatureEngineer处理股票数据集时,出现错误:
KeyError: "None of [Index(['tic', 'date', 'macd'], dtype='object')] are in the [columns]"
数据集示例:
date open high low close volume tic day 0 2009-11-18 170.10 170.20 158.00 158.20 2730000.0 GRAE 2 1 2009-11-18 63.02 63.69 62.12 62.49 59540.0 SGBD 2 2 2009-11-18 50.23 50.81 50.05 50.47 3310000.0 SQPH 2 3 2009-11-19 158.10 167.90 152.00 164.00 1630000.0 GRAE 3 4 2009-11-19 62.21 63.47 61.89 62.09 69320.0 SGBD 3
使用的特征工程代码:
fe = FeatureEngineer( use_technical_indicator=True, tech_indicator_list = INDICATORS, use_vix=True, use_turbulence=True, user_defined_feature = False) processed = fe.preprocess_data(df)
解决方案
1. 验证基础数据列与格式
- 执行
print(df.columns)确认数据集确实包含tic、date列,无拼写错误(如大小写、空格) - 将
date列转换为datetime类型:import pandas as pd df['date'] = pd.to_datetime(df['date'])
2. 检查INDICATORS变量定义
- 确保
INDICATORS已正确定义为FinRL支持的技术指标列表,比如:INDICATORS = ['macd', 'boll_ub', 'boll_lb', 'rsi_30', 'cci_30', 'dx_30'] - 若报错提到的
macd不在你的INDICATORS中,检查是否代码逻辑默认添加了该指标,或修正INDICATORS的定义
3. 排查技术指标计算问题
- 先关闭vix和turbulence功能,单独测试技术指标生成:
fe = FeatureEngineer( use_technical_indicator=True, tech_indicator_list = INDICATORS, use_vix=False, use_turbulence=False, user_defined_feature = False) processed = fe.preprocess_data(df) - 若仍报错,单独调用技术指标添加函数定位问题:
from finrl.meta.preprocessor.preprocessors import add_technical_indicator df_with_tech = add_technical_indicator(df, INDICATORS) print(df_with_tech.columns)
4. 补充足够的历史数据
- 技术指标如
macd需要至少12+26+9个交易日的数据才能计算,你的示例数据仅2天,会导致指标无法生成,进而出现列缺失错误 - 补充对应股票的更多历史交易数据,或调整
INDICATORS为短周期可计算的指标(如rsi_14、sma_10等)
内容的提问来源于stack exchange,提问作者Rabeya Akter
相关产品推荐
相关产品推荐

