一个期货策略

策略分享
标签: #<Tag:0x00007f25967e0078>

(summercs4) #1
克隆策略
In [2]:
# 1. 策略基本参数

# 回测起始时间
start_date = '2018-01-04'
# 回测结束时间
end_date = '2018-06-01'

# 策略比较参考标准,以沪深300为例
benchmark = '000300.SHA'

# 交易标的
instruments = ['CF1809.CZC']
# 起始资金
capital_base = 1000000

# 2. 策略主体函数
# 初始化虚拟账户状态,只在第一个交易日运行
def initialize(context):
    # 设置是否是结算模式
    context.set_need_settle(False)

    # 设置手续费,PerContract 说明手续费按手数/按金额是多少,分别是(开仓,平仓,平今)
    context.set_commission(equities_commission=None, futures_commission=PerContract(cost={'CF':(1, 1, 1)}))

    # 自定义一个属性来记录交易信号状态
    context.signal  =  ''

# 策略交易逻辑,每个交易日运行一次
def handle_data(context, data):
    today = data.current_dt.strftime('%Y-%m-%d')               # 当前交易日期
    sid = context.future_symbol(instruments[0])                # 交易标的
    position = context.portfolio.positions[sid]                # 持仓
    curr_position = position.amount                            # 净持仓数量

    price = data.current(sid, 'price')                         # 当前价格
    high_point = data.history(sid, 'price', 30, '1d').max()    # 30日高点
    low_point = data.history(sid, 'price', 30, '1d').min()     # 30日低点

    # 当前价格是30日高点并且交易信号状态不是long
    if price >= high_point and data.can_trade(sid)  and context.signal != 'long':
        order_target(sid,  10)
        # 重置交易状态为long
        context.signal = 'long'
        print(today, '买开')

    # 当前价格是30日低点并且交易信号状态不是short
    elif price <= low_point and data.can_trade(sid) and context.signal != 'short':
        order_target(sid,  -10)
        # 重置交易状态为short
        context.signal = 'short'
        print(today, '卖开')

# 3. 启动回测
# 策略回测接口: https://bigquant.com/docs/module_trade.html
m = M.trade.v4(
    instruments=instruments,
    start_date=start_date,
    end_date=end_date,
    initialize=initialize,
    before_trading_start=None,
    handle_data=handle_data,
    # 买入订单以开盘价成交
    order_price_field_buy='open',
    # 卖出订单以开盘价成交
    order_price_field_sell='open',
    capital_base=capital_base,
    benchmark=benchmark,
    volume_limit=0.25,
    product_type='future',
    m_deps=np.random.rand()
)
[2019-02-15 15:31:55.218142] INFO: algo: TradingAlgorithm V1.4.6
[2019-02-15 15:31:55.286941] INFO: algo: trading transform...
2018-01-12 买开
2018-03-28 卖开
2018-05-04 买开
[2019-02-15 15:31:56.086374] INFO: Performance: Simulated 98 trading days out of 98.
[2019-02-15 15:31:56.087614] INFO: Performance: first open: 2018-01-03 21:00:00+00:00
[2019-02-15 15:31:56.088430] INFO: Performance: last close: 2018-06-01 15:00:00+00:00
  • 收益率8.14%
  • 年化收益率22.31%
  • 基准收益率-8.29%
  • 阿尔法0.2
  • 贝塔0.1
  • 夏普比率1.51
  • 胜率0.0
  • 盈亏比0.0
  • 收益波动率11.87%
  • 信息比率0.13
  • 最大回撤4.86%