实盘信号发了10个股票,但是我只想让他发排名靠前的三个,并且每个股票仓位最大限制在33%,请问回测模拟模块怎么改?

新手专区
标签: #<Tag:0x00007f25afa37268>

(tkyz) #1

https://i.bigquant.com/user/tkyz/lab/share/%E5%8F%AF%E8%A7%86%E5%8C%96%E7%AD%96%E7%95%A5-%E7%A9%BA%E7%99%BD.ipynb?_t=1549004137171


(iQuant) #2
克隆策略

    {"Description":"实验创建于2019/2/1","Summary":"","Graph":{"EdgesInternal":[],"ModuleNodes":[{"Id":"-382","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n # 获取今日的日期\n today = data.current_dt.strftime('%Y-%m-%d') \n \n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表\n stock_hold_now = [equity.symbol for equity in context.portfolio.positions ] \n \n # 按日期过滤得到今日的预测数据,和买入备选股票列表\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 需要卖出的股票:已有持仓中不在买入列表的股票\n stock_to_sell = [ i for i in stock_hold_now if i not in stock_to_buy]\n \n # 可用现金\n cash_for_buy = context.portfolio.cash\n \n # 生成卖出订单:\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 持仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_percent(sid, 0) # 全部卖出 \n \n \n # 生成买入订单:买入每天两个策略前两名的股票\n if len(stock_to_buy)>0:\n weight = 1/3 # 每只股票的比重为等资金比例持有1/3仓位\n cash = cash_for_buy * weight # 每只股票的买入市值\n max_cash_per_instrument = 0.33 * context.portfolio.portfolio_value # 最大买入现金量\n for instrument in stock_to_buy[:3]:# 只买前3只\n sid = context.symbol(instrument) # 将标的转化为equity格式\n if data.can_trade(sid):\n context.order_target_value(sid, min(cash, max_cash_per_instrument)) # 买入金额控制为可用现金的1/3且不超过总资产的33% \n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0002, sell_cost=0.0012, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 3\n # 每只的股票等资金分配\n context.stock_weights = [1/stock_count for i in range(3)]\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":"150000","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"后复权","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-382"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-382"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-382"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-382"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-382"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-382","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='-382' Position='487,420,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":false}
    In [ ]:
    # 本代码由可视化策略环境自动生成 2019年2月1日 15:35
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m1_handle_data_bigquant_run(context, data):
    
        # 获取今日的日期
        today = data.current_dt.strftime('%Y-%m-%d')  
        
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
        stock_hold_now = [equity.symbol for equity in context.portfolio.positions ]      
        
        # 按日期过滤得到今日的预测数据,和买入备选股票列表
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        stock_to_buy = list(ranker_prediction.instrument)
        
        # 需要卖出的股票:已有持仓中不在买入列表的股票
        stock_to_sell = [ i for i in stock_hold_now if i not in stock_to_buy]
        
        # 可用现金
        cash_for_buy = context.portfolio.cash
        
        # 生成卖出订单:
        if len(stock_to_sell)>0:
            for instrument in stock_to_sell:
                sid = context.symbol(instrument) # 将标的转化为equity格式
                cur_position = context.portfolio.positions[sid].amount # 持仓
                if cur_position > 0 and data.can_trade(sid):
                    context.order_target_percent(sid, 0) # 全部卖出   
        
        
        # 生成买入订单:买入每天两个策略前两名的股票
        if len(stock_to_buy)>0:
            weight = 1/3 # 每只股票的比重为等资金比例持有1/3仓位
            cash = cash_for_buy * weight # 每只股票的买入市值
            max_cash_per_instrument = 0.33 * context.portfolio.portfolio_value # 最大买入现金量
            for instrument in stock_to_buy[:3]:# 只买前3只
                sid = context.symbol(instrument) # 将标的转化为equity格式
                if  data.can_trade(sid):
                    context.order_target_value(sid, min(cash, max_cash_per_instrument)) # 买入金额控制为可用现金的1/3且不超过总资产的33%        
    
    # 回测引擎:准备数据,只执行一次
    def m1_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m1_initialize_bigquant_run(context):
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0002, sell_cost=0.0012, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        stock_count = 3
        # 每只的股票等资金分配
        context.stock_weights = [1/stock_count for i in range(3)]
    
    
    m1 = M.trade.v4(
        start_date='',
        end_date='',
        handle_data=m1_handle_data_bigquant_run,
        prepare=m1_prepare_bigquant_run,
        initialize=m1_initialize_bigquant_run,
        volume_limit=0,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=150000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    

    (tkyz) #3

    好的,谢谢