开发环境运行策略代码报错AttributeError: 'TradingEnvironment' object has no attribute 'options_data'
由bqkrmo6v创建,最终由small_q 被浏览 72 用户
比较怪的是,下午都能运行的代码,晚上就不可运行了,\n使用新账号,报同样的错,
使用新电脑,报同样的错,
这个是代码问题还是环境问题,如果是环境问题有没有办法重置当前账号环境(以我的测试,这个应该不是环境问题)
我也看了M.hftrade.v2的文档,的确是没有 options_data属性,但是options_data是图形操作系统自己生成的。
\
# 本代码由可视化策略环境自动生成 2023年8月8日 09:32
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
# 显式导入 BigQuant 相关 SDK 模块
from bigdatasource.api import DataSource
from biglearning.api import M
from biglearning.api import tools as T
from biglearning.module2.common.data import Outputs
import pandas as pd
import numpy as np
import math
import warnings
import datetime
from zipline.finance.commission import PerOrder
from zipline.api import get_open_orders
from zipline.api import symbol
from bigtrader.sdk import *
from bigtrader.utils.my_collections import NumPyDeque
from bigtrader.constant import OrderType
from bigtrader.constant import Direction
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m8_run_bigquant_run(input_1, input_2, input_3):
# 示例代码如下。在这里编写您的代码
df = input_1.read()
df['list_date'] = df['list_date'].astype(str)
df['delist_date'] = df['delist_date'].astype(str)
df = df.loc[:,['instrument','list_date','delist_date']]
data_1 = DataSource.write_df(df)
return Outputs(data_1=data_1, data_2=None, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m8_post_run_bigquant_run(outputs):
return outputs
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m9_run_bigquant_run(input_1, input_2, input_3):
# 示例代码如下。在这里编写您的代码
df = input_1.read()
df = df.loc[:,['date','instrument','close','bond_prem_ratio','double_low','remain_size']]
data_1 = DataSource.write_df(df)
return Outputs(data_1=data_1, data_2=None, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m9_post_run_bigquant_run(outputs):
print(outputs)
# 从数据输出端 data_1 中读取数据
df = outputs.data_1.read()
print(df)
# 对读取的数据进行处理,例如添加新的列
df['new_column'] = df['close'] * 2
df['double_low_custom'] = df['close'] + df['bond_prem_ratio']
# 将处理后的数据写入一个新的输出端 data_2 中
data_1 = DataSource.write_df(df)
# 返回新的 Outputs 对象
return Outputs(data_1=data_1)
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m10_run_bigquant_run(input_1, input_2, input_3):
# 示例代码如下。在这里编写您的代码
df = input_1.read()
df['date'] = pd.to_datetime(df['date'])
df['list_date'] = pd.to_datetime(df['list_date'])
df['delist_date'] = pd.to_datetime(df['delist_date'])
#买入规则:上市满30天才能买入
df['can_buy'] = df['date'] > (df['list_date'] + timedelta(days=30))
#卖出规则:离退市日期差6个月时清仓
df['to_clean'] = (df['date'] + timedelta(days=180)) > df['delist_date']
data_1 = DataSource.write_df(df)
return Outputs(data_1=data_1, data_2=None, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m10_post_run_bigquant_run(outputs):
return outputs
# 交易引擎:初始化函数,只执行一次
def m7_initialize_bigquant_run(context):
print("initializing")
# 加载股票指标数据,数据继承自m6模块
context.indicator_data = context.options['data'].read_df()
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# 设置股票数量
context.stock_num = 20
# 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次
context.rebalance_days = 22
# 如果策略运行中,需要将数据进行保存,可以借用extension这个对象,类型为dict
# 比如当前运行的k线的索引,比如个股持仓天数、买入均价
try:
print(f"check idx: {context.extension.idx}")
except AttributeError as e:
context.extension.idx = 0
# 交易引擎:每个单位时间开盘前调用一次。
def m7_before_trading_start_bigquant_run(context, data):
context.subscribe(context.instruments)
pass
# 交易引擎:tick数据处理函数,每个tick执行一次
def m7_handle_tick_bigquant_run(context, data):
pass
# 回测引擎:每日数据处理函数,每天执行一次
def m7_handle_data_bigquant_run(context, data):
context.extension.idx += 1
# 不在换仓日就return,相当于后面的代码只会一个月运行一次,买入的股票会持有1个月
if context.extension.idx % context.rebalance_days != 0:
return
# 当前的日期
date = data.current_dt.strftime('%Y-%m-%d')
cur_data = context.indicator_data[context.indicator_data['date'] == date]
print('cur_data')
print(cur_data)
#建仓条件判断:市场双低均值达到170可进行建仓
if cur_data['double_low'].mean() > 170:
print(date,':该调仓日市场双低均值为',cur_data['double_low'].mean(),",无需建仓")
return
# 设定股票池
# 条件1:上市超过1个月
stock_can_buy = cur_data[cur_data['can_buy'] == 1]
# 条件2:剩余期限小于180个自然日
stock_to_clean = cur_data[cur_data['to_clean'] == 1]
symbols = list(set(stock_can_buy['instrument'].values).difference(set(stock_to_clean['instrument'].values)))
cur_data = cur_data.set_index('instrument').loc[symbols,:].reset_index().sort_values('double_low')
stock_to_buy = list(cur_data.instrument[:context.stock_num])
# 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
stock_hold_now = [equity for equity in context.portfolio.positions]
# 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有
no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]
# 需要卖出的股票
stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]
# 卖出
for stock in stock_to_sell:
context.order_target_percent(stock, 0)
# 如果当天没有买入的股票,就返回
if len(stock_to_buy) == 0:
print(date,'当天没有买入的股票')
return
# 等权重买入
weight = 1 / len(stock_to_buy)
# 买入
for stock in stock_to_buy:
context.order_target_percent(stock, weight)
# 交易引擎:成交回报处理函数,每个成交发生时执行一次
def m7_handle_trade_bigquant_run(context, data):
pass
# 交易引擎:委托回报处理函数,每个委托变化时执行一次
def m7_handle_order_bigquant_run(context, data):
pass
# 交易引擎:盘后处理函数,每日盘后执行一次
def m7_after_trading_bigquant_run(context, data):
pass
m1 = M.use_datasource.v1(
datasource_id='market_performance_CN_CONBOND',
start_date='2020-01-01',
end_date='2023-05-31'
)
m6 = M.trade_data_generation.v1(
input=m1.data,
category='CN_STOCK',
m_cached=False
)
m2 = M.use_datasource.v1(
datasource_id='basic_info_CN_CONBOND',
start_date='2020-01-01',
end_date='2023-05-31'
)
m8 = M.cached.v3(
input_1=m2.data,
run=m8_run_bigquant_run,
post_run=m8_post_run_bigquant_run,
input_ports='',
params='{}',
output_ports=''
)
m4 = M.input_features.v1(
features="""
# #号开始的表示注释,注释需单独一行
# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
double_low = close + bond_prem_ratio
remain_size > 1.5
"""
)
m5 = M.derived_feature_extractor.v3(
input_data=m1.data,
features=m4.data,
date_col='date',
instrument_col='instrument',
drop_na=False,
remove_extra_columns=False,
user_functions={}
)
m9 = M.cached.v3(
input_1=m5.data,
run=m9_run_bigquant_run,
post_run=m9_post_run_bigquant_run,
input_ports='',
params='{}',
output_ports=''
)
m3 = M.join.v3(
data1=m9.data_1,
data2=m8.data_1,
on='instrument',
how='inner',
sort=False
)
m10 = M.cached.v3(
input_1=m3.data,
run=m10_run_bigquant_run,
post_run=m10_post_run_bigquant_run,
input_ports='',
params='{}',
output_ports=''
)
m7 = M.hftrade.v2(
instruments=m6.instrument_list,
options_data=m10.data_1,
start_date='2020-01-01',
end_date='2023-05-31',
initialize=m7_initialize_bigquant_run,
before_trading_start=m7_before_trading_start_bigquant_run,
handle_tick=m7_handle_tick_bigquant_run,
handle_data=m7_handle_data_bigquant_run,
handle_trade=m7_handle_trade_bigquant_run,
handle_order=m7_handle_order_bigquant_run,
after_trading=m7_after_trading_bigquant_run,
capital_base=1000001,
frequency='daily',
price_type='真实价格',
product_type='可转债',
before_start_days='0',
volume_limit=1,
order_price_field_buy='close',
order_price_field_sell='close',
benchmark='000300.HIX',
plot_charts=True,
disable_cache=False,
replay_bdb=False,
show_debug_info=False,
backtest_only=False
)
\
{'version': 'v3', 'data_1': DataSource(655cd94fe54d4e79940331959bef7651T), 'data_2': None, 'data_3': None} date instrument close bond_prem_ratio double_low \0 2020-01-02 110031.HCB 126.000000 18.393200 144.393204 1 2020-01-02 110033.HCB 116.800003 16.957600 133.757599 2 2020-01-02 110034.HCB 108.900002 42.707199 151.607208 3 2020-01-02 110038.HCB 109.000000 73.657204 182.657196 4 2020-01-02 110041.HCB 119.900002 21.189199 141.089203 ... ... ... ... ... ... 311491 2023-05-31 128143.ZCB 118.906998 38.032600 156.939606 311492 2023-05-31 128144.ZCB 113.714996 38.135300 151.850296 311493 2023-05-31 132018.HCB 141.746002 0.248600 141.994598 311494 2023-05-31 132020.HCB 110.274002 50.236301 160.510300 311495 2023-05-31 132026.HCB 109.319000 20.343100 129.662094 remain_size 0 23.989988 1 12.117621 2 14.992964 3 6.309111 4 18.730385 ... ... 311491 2.439604 311492 9.793798 311493 131.698441 311494 35.064827 311495 100.000000 [311496 rows x 6 columns][2023-08-08 09:44:42.720546] INFO join: /data, 行数=307808/996, 耗时=0.325205s[2023-08-08 09:44:42.782457] INFO join: 最终行数: 307808[2023-08-08 09:44:48.359183] INFO hfbacktest: biglearning V1.4.21[2023-08-08 09:44:48.362653] INFO hfbacktest: bigtrader v1.10.4 2023-07-24---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[2], line 256
239 m3 = M.join.v3(
240 data1=m9.data_1,
241 data2=m8.data_1,
(...)
244 sort=False
245 )
247 m10 = M.cached.v3(
248 input_1=m3.data,
249 run=m10_run_bigquant_run,
(...)
253 output_ports=''
254 )
--> 256 m7 = M.hftrade.v2(
257 instruments=m6.instrument_list,
258 options_data=m10.data_1,
259 start_date='2020-01-01',
260 end_date='2023-05-31',
261 initialize=m7_initialize_bigquant_run,
262 before_trading_start=m7_before_trading_start_bigquant_run,
263 handle_tick=m7_handle_tick_bigquant_run,
264 handle_data=m7_handle_data_bigquant_run,
265 handle_trade=m7_handle_trade_bigquant_run,
266 handle_order=m7_handle_order_bigquant_run,
267 after_trading=m7_after_trading_bigquant_run,
268 capital_base=1000001,
269 frequency='daily',
270 price_type='真实价格',
271 product_type='可转债',
272 before_start_days='0',
273 volume_limit=1,
274 order_price_field_buy='close',
275 order_price_field_sell='close',
276 benchmark='000300.HIX',
277 plot_charts=True,
278 disable_cache=False,
279 replay_bdb=False,
280 show_debug_info=False,
281 backtest_only=False
282 )
File module2/common/modulemanagerv2.py:88, in biglearning.module2.common.modulemanagerv2.BigQuantModuleVersion.__call__()
File module2/common/moduleinvoker.py:331, in biglearning.module2.common.moduleinvoker.module_invoke()
File module2/common/moduleinvoker.py:253, in biglearning.module2.common.moduleinvoker._invoke_with_cache()
File module2/common/moduleinvoker.py:214, in biglearning.module2.common.moduleinvoker._invoke_with_cache()
File module2/common/moduleinvoker.py:171, in biglearning.module2.common.moduleinvoker._module_run()
File module2/modules/hftrade/v2/__init__.py:351, in biglearning.module2.modules.hftrade.v2.__init__.bigquant_run()
File module2/modules/hftrade/v2/__init__.py:190, in biglearning.module2.modules.hftrade.v2.__init__.bigquant_run.do_backtest_run()
File module2/common/modulemanagerv2.py:88, in biglearning.module2.common.modulemanagerv2.BigQuantModuleVersion.__call__()
File module2/common/moduleinvoker.py:331, in biglearning.module2.common.moduleinvoker.module_invoke()
File module2/common/moduleinvoker.py:253, in biglearning.module2.common.moduleinvoker._invoke_with_cache()
File module2/common/moduleinvoker.py:214, in biglearning.module2.common.moduleinvoker._invoke_with_cache()
File module2/common/moduleinvoker.py:173, in biglearning.module2.common.moduleinvoker._module_run()
File module2/modules/hfbacktest/v1/__init__.py:568, in biglearning.module2.modules.hfbacktest.v1.__init__.BigQuantModule.run()
File module2/modules/hfbacktest/v1/__init__.py:504, in biglearning.module2.modules.hfbacktest.v1.__init__.BigQuantModule.run_algo()
File /var/app/enabled/bigtrader2/bigtrader/run_trading.py:750, in run_backtest(start_date, end_date, strategy, strategy_setting, capital_base, product_type, frequency, instruments, options_data, **kwargs)
747 if kwargs.get("capital") and capital_base == DEFAULT_CAPITAL:
748 capital_base = kwargs.pop("capital")
--> 750 rt = RunTrading(RunMode.BACKTEST,
751 acct_type=acct_type,
752 account_id=account_id,
753 password="",
754 strategy=strategy,
755 strategy_setting=strategy_setting,
756 start_date=start_date,
757 end_date=end_date,
758 capital_base=capital_base,
759 instruments=instruments,
760 product_type=product_type,
761 frequency=frequency,
762 options_data=options_data,
763 **kwargs)
764 return rt.run(**kwargs)
File /var/app/enabled/bigtrader2/bigtrader/run_trading.py:267, in RunTrading.__init__(self, run_mode, strategy, **kwargs)
265 options_data = kwargs.pop("options_data", None)
266 if options_data is not None:
--> 267 trading_env.options['data'] = trading_env.options_data
269 if "initial_positions" in kwargs:
270 trading_env.initial_positions = kwargs.pop("initial_positions")
AttributeError: 'TradingEnvironment' object has no attribute 'options_data'
\