我的策略里, 不能买卖ETF基金吗??


(jh_ufo) #1
# 回测起始时间
start_date = '2012-01-01'
# 回测结束时间
end_date = '2017-07-01'
# 策略比较参考标准,以沪深300为例
benchmark = '000300.INDX'
# 证券池 
instruments = ['510050.SHA']

我用510050 作为股票标的,回测显示没有任何成交记录,难道不能买卖ETF基金吗

(iQuant) #2

支持基金回测哈。

克隆策略

基金与股票,代码后缀不一样。

In [6]:
D.history_data(['510050.OFA'],'2018-01-25','2018-01-25',['name'])
Out[6]:
date instrument name
0 2018-01-25 510050.OFA 华夏上证50ETF

可见华夏上证50ETF的名称后缀为OFA

简单的基金策略demo

    {"Description":"实验创建于2018/1/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-21:instruments","SourceOutputPortId":"-12:data"}],"ModuleNodes":[{"Id":"-12","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2013-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2017-12-12","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510050.OFA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-12"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-12","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-21","ModuleId":"BigQuantSpace.trade.trade-v3","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 # 长期均线值要有意义,需要在50根k线之后\n if context.trading_day_index < context.long_period: \n return\n instruments =m1.data.read_pickle()['instruments'] # m1即为证券代码列表模块名称\n k = instruments[0] # 标的为字符串格式\n sid = context.symbol(k) # 将标的转化为equity格式\n price = data.current(sid, 'price') # 最新价格\n \n short_mavg = data.history(sid, 'price',context.short_period, '1d').mean() # 短期均线值\n long_mavg = data.history(sid, 'price',context.long_period, '1d').mean() # 长期均线值\n\n cash = context.portfolio.cash # 现金\n cur_position = context.portfolio.positions[sid].amount # 持仓\n \n # 交易逻辑\n # 如果短期均线大于长期均线形成金叉,并且没有持仓,并且该股票可以交易\n if short_mavg > long_mavg and cur_position == 0 and data.can_trade(sid): \n context.order(sid, int(cash/price/100)*100) # 买入\n # 如果短期均线小于长期均线形成死叉,并且有持仓,并且该股票可以交易\n elif short_mavg < long_mavg and cur_position > 0 and data.can_trade(sid): \n context.order_target_percent(sid, 0) # 全部卖出","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 context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) # 设置手续费,买入成本为万分之三,卖出为千分之1.3\n context.short_period = 5 # 短期均线\n context.long_period = 50 # 长期均线 \n \n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","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":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"amount_integer","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-21"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-21"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-21","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"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='-12' Position='580.3411865234375,-183.15665817260742,200,200'/><NodePosition Node='-21' Position='636.1523742675781,132.10943603515625,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":true}
    In [7]:
    # 本代码由可视化策略环境自动生成 2018年1月26日 13:31
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2013-01-01',
        end_date='2017-12-12',
        market='CN_STOCK_A',
        instrument_list='510050.OFA',
        max_count=0
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m2_handle_data_bigquant_run(context, data):
          # 长期均线值要有意义,需要在50根k线之后
        if context.trading_day_index <  context.long_period:   
            return
        instruments =m1.data.read_pickle()['instruments'] # m1即为证券代码列表模块名称
        k = instruments[0] # 标的为字符串格式
        sid = context.symbol(k) # 将标的转化为equity格式
        price = data.current(sid, 'price') # 最新价格
     
        short_mavg = data.history(sid, 'price',context.short_period, '1d').mean() # 短期均线值
        long_mavg = data.history(sid, 'price',context.long_period, '1d').mean() # 长期均线值
    
        cash = context.portfolio.cash  # 现金
        cur_position = context.portfolio.positions[sid].amount # 持仓
        
        # 交易逻辑
        # 如果短期均线大于长期均线形成金叉,并且没有持仓,并且该股票可以交易
        if short_mavg > long_mavg and cur_position == 0 and data.can_trade(sid):  
            context.order(sid, int(cash/price/100)*100) # 买入
        # 如果短期均线小于长期均线形成死叉,并且有持仓,并且该股票可以交易
        elif short_mavg < long_mavg and cur_position > 0 and data.can_trade(sid):  
            context.order_target_percent(sid, 0) # 全部卖出
    # 回测引擎:准备数据,只执行一次
    def m2_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m2_initialize_bigquant_run(context):
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) # 设置手续费,买入成本为万分之三,卖出为千分之1.3
        context.short_period = 5 # 短期均线
        context.long_period = 50 # 长期均线 
        
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m2_before_trading_start_bigquant_run(context, data):
        pass
    
    m2 = M.trade.v3(
        instruments=m1.data,
        start_date='',
        end_date='',
        handle_data=m2_handle_data_bigquant_run,
        prepare=m2_prepare_bigquant_run,
        initialize=m2_initialize_bigquant_run,
        before_trading_start=m2_before_trading_start_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=1000000,
        benchmark='000300.SHA',
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        plot_charts=True,
        backtest_only=False,
        amount_integer=False
    )
    
    [2018-01-26 13:29:59.222232] INFO: bigquant: instruments.v2 开始运行..
    [2018-01-26 13:29:59.227437] INFO: bigquant: 命中缓存
    [2018-01-26 13:29:59.228769] INFO: bigquant: instruments.v2 运行完成[0.006607s].
    [2018-01-26 13:29:59.258044] INFO: bigquant: backtest.v7 开始运行..
    [2018-01-26 13:29:59.362371] INFO: algo: set price type:backward_adjusted
    [2018-01-26 13:30:14.124650] INFO: Performance: Simulated 1202 trading days out of 1202.
    [2018-01-26 13:30:14.126468] INFO: Performance: first open: 2013-01-04 01:30:00+00:00
    [2018-01-26 13:30:14.128133] INFO: Performance: last close: 2017-12-12 07:00:00+00:00
    
    • 收益率71.86%
    • 年化收益率12.02%
    • 基准收益率59.18%
    • 阿尔法0.05
    • 贝塔0.42
    • 夏普比率0.43
    • 胜率0.381
    • 盈亏比3.891
    • 收益波动率17.47%
    • 信息比率0.09
    • 最大回撤20.63%
    [2018-01-26 13:30:18.775819] INFO: bigquant: backtest.v7 运行完成[19.517739s].