可视化TALIB指标策略

策略分享
新手专区
标签: #<Tag:0x00007fcf804204f8> #<Tag:0x00007fcf804203b8>

(iQuant) #1
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"600006.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","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 today=data.current_dt.strftime('%Y-%m-%d')\n # 长期均线值要有意义,需要在50根k线之后\n k = context.instruments[0] # 标的为字符串格式\n sid = context.symbol(k) # 将标的转化为equity格式\n # 获取价格数据\n prices = data.history(sid, 'price', 100, '1d')\n # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd, signal 和 hist\n import talib\n macd, signal, hist = talib.MACD(np.array(prices), 12,26,9)\n \n # 计算现在portfolio中股票的仓位\n cur_position = context.portfolio.positions[sid].amount\n \n # 策略逻辑\n # 卖出逻辑 macd下穿signal\n if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0:\n # 进行清仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_value(sid, 0)\n\n # 买入逻辑 macd上穿signal\n if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0:\n # 买入股票\n if cur_position == 0 and data.can_trade(sid):\n context.order_target_percent(sid, 1)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n \n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":"1000001","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-81"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","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='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1074,124,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-81' Position='1056,304,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 [34]:
    # 本代码由可视化策略环境自动生成 2018年6月13日 14:03
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2015-01-01'),
        end_date=T.live_run_param('trading_date', '2017-01-01'),
        market='CN_STOCK_A',
        instrument_list='600006.SHA',
        max_count=0
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m2_handle_data_bigquant_run(context, data):
        today=data.current_dt.strftime('%Y-%m-%d')
        # 长期均线值要有意义,需要在50根k线之后
        k = context.instruments[0] # 标的为字符串格式
        sid = context.symbol(k) # 将标的转化为equity格式
        # 获取价格数据
        prices = data.history(sid, 'price', 100, '1d')
        # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd, signal 和 hist
        import talib
        macd, signal, hist = talib.MACD(np.array(prices), 12,26,9)
          
        # 计算现在portfolio中股票的仓位
        cur_position = context.portfolio.positions[sid].amount
        
        # 策略逻辑
        # 卖出逻辑 macd下穿signal
        if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0:
            # 进行清仓
            if cur_position > 0 and data.can_trade(sid):
                context.order_target_value(sid, 0)
    
        # 买入逻辑  macd上穿signal
        if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0:
            # 买入股票
            if cur_position == 0 and data.can_trade(sid):
                context.order_target_percent(sid, 1)
    # 回测引擎:准备数据,只执行一次
    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))
    
    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,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000001,
        benchmark='000300.SHA',
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        plot_charts=True,
        backtest_only=False,
        amount_integer=False
    )
    
    [2018-06-01 11:21:32.292824] INFO: bigquant: instruments.v2 开始运行..
    [2018-06-01 11:21:32.316112] INFO: bigquant: 命中缓存
    [2018-06-01 11:21:32.329843] INFO: bigquant: instruments.v2 运行完成[0.037023s].
    [2018-06-01 11:21:32.439486] INFO: bigquant: backtest.v7 开始运行..
    [2018-06-01 11:21:32.985957] INFO: algo: set price type:backward_adjusted
    [2018-06-01 11:21:45.715586] INFO: Performance: Simulated 488 trading days out of 488.
    [2018-06-01 11:21:45.718789] INFO: Performance: first open: 2015-01-05 01:30:00+00:00
    [2018-06-01 11:21:45.720188] INFO: Performance: last close: 2016-12-30 07:00:00+00:00
    
    • 收益率-31.5%
    • 年化收益率-17.75%
    • 基准收益率-6.33%
    • 阿尔法-0.17
    • 贝塔0.59
    • 夏普比率-0.46
    • 胜率0.2
    • 盈亏比3.018
    • 收益波动率46.41%
    • 信息比率-0.32
    • 最大回撤60.39%
    [2018-06-01 11:21:52.932024] INFO: bigquant: backtest.v7 运行完成[20.492981s].
    

    传统策略的可视化开发