问答交流

求问,提交模拟交易之后报错AttributeError: 'DataFrame' object has no attribute 'instrument'

由bql6wtb2创建,最终由small_q 被浏览 31 用户

新手课程里面的源码,运行回测是好的,但是提交模拟之后就会报错。错误和源码附上,求助大神帮我解答一下,谢谢

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-b2f5bb4c55e4> in <module>
    191 
    192 # @module(position="241,670", comment='', comment_collapsed=True)
--> 193 m6 = M.hftrade.v2(
    194     instruments=m1.data,
    195     options_data=m5.data,

/var/app/enabled/biglearning/module2/common/modulemanagerv2.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.modulemanagerv2.BigQuantModuleVersion.__call__()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker.module_invoke()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker._invoke_with_cache()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker._invoke_with_cache()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker._module_run()

/var/app/enabled/biglearning/module2/modules/hftrade/v2/__init__.cpython-38-x86_64-linux-gnu.so in biglearning.module2.modules.hftrade.v2.__init__.bigquant_run()

/var/app/enabled/biglearning/module2/modules/hftrade/v2/__init__.cpython-38-x86_64-linux-gnu.so in biglearning.module2.modules.hftrade.v2.__init__.bigquant_run.do_paper_run()

/var/app/enabled/biglearning/module2/common/modulemanagerv2.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.modulemanagerv2.BigQuantModuleVersion.__call__()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker.module_invoke()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker._invoke_with_cache()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker._invoke_with_cache()

/var/app/enabled/biglearning/module2/common/moduleinvoker.cpython-38-x86_64-linux-gnu.so in biglearning.module2.common.moduleinvoker._module_run()

/var/app/enabled/biglearning/module2/modules/hfpapertrading/v1/__init__.cpython-38-x86_64-linux-gnu.so in biglearning.module2.modules.hfpapertrading.v1.__init__.BigQuantModule.run()

/var/app/enabled/biglearning/module2/modules/hfpapertrading/v1/__init__.cpython-38-x86_64-linux-gnu.so in biglearning.module2.modules.hfpapertrading.v1.__init__.BigQuantModule.run()

/var/app/enabled/biglearning/module2/modules/hfpapertrading/v1/paper_test_helper.cpython-38-x86_64-linux-gnu.so in biglearning.module2.modules.hfpapertrading.v1.paper_test_helper.PaperTestHelper.get_orders()

/usr/local/python3/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5460             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5461                 return self[name]
-> 5462             return object.__getattribute__(self, name)
   5463 
   5464     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'instrument'

源码如下,有没有大神帮我解答一下,谢谢


 
# 显式导入 BigQuant 相关 SDK 模块
from bigdatasource.api import DataSource
from bigdata.api.datareader import D
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

# <aistudiograph>

# @param(id="m6", name="initialize")
# 交易引擎:初始化函数,只执行一次
def m6_initialize_bigquant_run(context):
    #读取数据
    context.ranker_prediction = context.options['data'].read_df()
    context.ranker_prediction.set_index('date',inplace=True)
    
    #print(context.ranker_prediction)
    

# @param(id="m6", name="before_trading_start")
# 交易引擎:每个单位时间开盘前调用一次。
def m6_before_trading_start_bigquant_run(context, data):
    # 盘前处理,订阅行情等
    pass

# @param(id="m6", name="handle_tick")
# 交易引擎:tick数据处理函数,每个tick执行一次
def m6_handle_tick_bigquant_run(context, tick):
    pass

# @param(id="m6", name="handle_data")
# 交易引擎:bar数据处理函数,每个时间单位执行一次
def m6_handle_data_bigquant_run(context, data):
    
    
    #context = 回测引擎
    #context内部 会有一些功能~ 是通过 context.xxx 来使用的
    #data
    
    #调仓期的控制
    remainder = context.trading_day_index % 5
    #如果没到调仓期直接结束运行
    if remainder !=0:
        
        return


    import datetime
    #初始化
    buy_list = []  #买入列表
    sell_list = [] #卖出列表
    
    #==================== 数据准备
    today = data.current_dt.strftime('%Y-%m-%d')   #读取当天日期
    time = data.current_dt

    account_pos = context.get_account_positions()
    holding_list = list({key: value for key, value in account_pos.items() if value.avail_qty > 0}.keys())
    holding_num = len(holding_list)

    #读取当日数据
    try:
        today_data  = context.ranker_prediction.loc[today,:]
        today_data.reset_index(inplace=True)
    except:
        return
    
    #策略
    today_data=today_data[today_data['上市时间'] >= 365] #上市时间的过滤
    today_data=today_data[today_data['市盈率ttm'] >= 0]  #财务数据过滤
    today_data=today_data[today_data['换手排名'] <= 0.4] 
    today_data.sort_values(by='市值',ascending=True,inplace=True)  #市值排序
 

    
    #构建目标列表
    target_list = today_data.instrument.to_list()[:40]


    #构建卖出列表
    for ins in holding_list:
        if ins not in target_list:
            sell_list.append(ins)

    #构建买入列表
    for ins in target_list:
        if ins not in holding_list:
            buy_list.append(ins)
    
    #先卖
    for ins in sell_list:
        context.order_target(ins,0)

    #等权买
    for ins in buy_list:
        context.order_target_percent(ins,0.025)

# @param(id="m6", name="handle_trade")
# 交易引擎:成交回报处理函数,每个成交发生时执行一次
def m6_handle_trade_bigquant_run(context, trade):
    pass

# @param(id="m6", name="handle_order")
# 交易引擎:委托回报处理函数,每个委托变化时执行一次
def m6_handle_order_bigquant_run(context, order):
    pass

# @param(id="m6", name="after_trading")
# 交易引擎:盘后处理函数,每日盘后执行一次
def m6_after_trading_bigquant_run(context, data):
    pass


# @module(position="-61,137", comment='', comment_collapsed=True)
m1 = M.instruments.v2(
    start_date=T.live_run_param('trading_date', '2022-01-01'),
    end_date=T.live_run_param('trading_date', '2022-12-31'),
    market='CN_STOCK_A',
    instrument_list='',
    max_count=0
)

# @module(position="658,76", comment='', comment_collapsed=True)
m2 = M.input_features.v1(
    features="""




#构建一个因子。 open-close的绝对值


市值=market_cap_0

市盈率ttm=pe_ttm_0

上市时间=list_days_0

换手排名=rank_turn_0
"""
)

# @module(position="291,266", comment='', comment_collapsed=True)
m3 = M.general_feature_extractor.v7(
    instruments=m1.data,
    features=m2.data,
    start_date='',
    end_date='',
    before_start_days=90
)

# @module(position="386,411", comment='', comment_collapsed=True)
m4 = M.derived_feature_extractor.v3(
    input_data=m3.data,
    features=m2.data,
    date_col='date',
    instrument_col='instrument',
    drop_na=True,
    remove_extra_columns=True,
    user_functions={}
)

# @module(position="366,501", comment='', comment_collapsed=True)
m5 = M.chinaa_stock_filter.v1(
    input_data=m4.data,
    index_constituent_cond=['全部'],
    board_cond=['上证主板', '深证主板', '创业板'],
    industry_cond=['全部'],
    st_cond=['正常'],
    delist_cond=['非退市'],
    output_left_data=False
)

# @module(position="241,670", comment='', comment_collapsed=True)
m6 = M.hftrade.v2(
    instruments=m1.data,
    options_data=m5.data,
    start_date='',
    end_date='',
    initialize=m6_initialize_bigquant_run,
    before_trading_start=m6_before_trading_start_bigquant_run,
    handle_tick=m6_handle_tick_bigquant_run,
    handle_data=m6_handle_data_bigquant_run,
    handle_trade=m6_handle_trade_bigquant_run,
    handle_order=m6_handle_order_bigquant_run,
    after_trading=m6_after_trading_bigquant_run,
    capital_base=1000000,
    frequency='daily',
    price_type='真实价格',
    product_type='股票',
    before_start_days='0',
    volume_limit=1,
    order_price_field_buy='close',
    order_price_field_sell='open',
    benchmark='000300.HIX',
    plot_charts=True,
    disable_cache=False,
    replay_bdb=False,
    show_debug_info=False,
    backtest_only=False
)
# </aistudiograph>

\

标签

金融交易模拟交易AttributeError回测data
评论
  • 只需要结束日期绑定实盘参数即可
  • undefined
  • https://bigquant.com/codeshare/11bc7269-9fcb-45d3-abda-c8ea971c6311
{link}