1. # coding=utf-8
      2. from __future__ import print_function, absolute_import
      3. from gm.api import *
      4. import talib
      5. import time
      6. '''
      7. 本策略以DCE.i1801为交易标的,根据其一分钟(即60s频度)bar数据建立双均线模型,
      8. 短周期为30,长周期为60,当短期均线由上向下穿越长期均线时做空,
      9. 当短期均线由下向上穿越长期均线时做多,每次开仓前先平掉所持仓位,再开仓。
      10. 回测数据为:DCE.i1801的60s频度bar数据
      11. 回测时间为:2017-09-01 09:00:00到2017-09-30 15:00:00
      12. '''
      13. def init(context):
      14. context.FAST = 30 # 短周期
      15. context.SLOW = 60 # 长周期
      16. context.symbol = 'DCE.i1801' # 订阅&交易标的
      17. context.period = context.SLOW + 1 # 订阅数据滑窗长度
      18. subscribe(context.symbol, '60s', count=context.period) # 订阅行情
      19. def on_bar(context, bars):
      20. print (bars[0].bob)
      21. # 获取数据
      22. prices = context.data('DCE.i1801', '60s', context.period, fields='close')
      23. # 计算长短周期均线
      24. fast_avg = talib.SMA(prices.values.reshape(context.period), context.FAST)
      25. slow_avg = talib.SMA(prices.values.reshape(context.period), context.SLOW)
      26. # 均线下穿,做空
      27. if slow_avg[-2] < fast_avg[-2] and slow_avg[-1] >= fast_avg[-1]:
      28. # 平多仓
      29. order_target_percent(symbol=context.symbol, percent=0, position_side=1, order_type=2)
      30. # 开空仓
      31. order_target_percent(symbol=context.symbol, percent=0.1, position_side=2, order_type=2)
      32. # 均线上穿,做多
      33. if fast_avg[-2] < slow_avg[-2] and fast_avg[-1] >= slow_avg[-1]:
      34. # 平空仓
      35. order_target_percent(symbol=context.symbol, percent=0, position_side=2,order_type=2)
      36. # 开多仓
      37. order_target_percent(symbol=context.symbol, percent=0.1, position_side=1,order_type=2)
      38. def on_execution_report(context, execrpt):
      39. # 打印委托执行回报
      40. print(execrpt)
      41. if __name__ == '__main__':
      42. '''
      43. strategy_id策略ID,由系统生成
      44. filename文件名,请与本文件名保持一致
      45. mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
      46. token绑定计算机的ID,可在系统设置-密钥管理中生成
      47. backtest_start_time回测开始时间
      48. backtest_end_time回测结束时间
      49. backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
      50. backtest_initial_cash回测初始资金
      51. backtest_commission_ratio回测佣金比例
      52. backtest_slippage_ratio回测滑点比例
      53. '''
      54. run(strategy_id='strategy_id',
      55. filename='main.py',
      56. mode=MODE_BACKTEST,
      57. token='token_id',
      58. backtest_start_time='2017-09-01 09:00:00',
      59. backtest_end_time='2017-09-30 15:00:00',
      60. backtest_adjust=ADJUST_NONE,
      61. backtest_initial_cash=10000000,
      62. backtest_commission_ratio=0.0001,
      63. backtest_slippage_ratio=0.0001)

    BacktestResult

    原文: https://www.myquant.cn/docs/python_strategyies/153