1. # coding=utf-8
      2. from __future__ import print_function, absolute_import, unicode_literals
      3. import numpy as np
      4. from gm.api import *
      5. from pandas import DataFrame
      6. '''
      7. 本策略以0.8为初始权重跟踪指数标的沪深300中权重大于0.35%的成份股.
      8. 个股所占的百分比为(0.8*成份股权重)*100%.然后根据个股是否:
      9. 1.连续上涨5天 2.连续下跌5天
      10. 来判定个股是否为强势股/弱势股,并对其把权重由0.8调至1.0或0.6
      11. 回测时间为:2017-07-01 08:50:00到2017-10-01 17:00:00
      12. '''
      13. def init(context):
      14. # 资产配置的初始权重,配比为0.6-0.8-1.0
      15. context.ratio = 0.8
      16. # 获取沪深300当时的成份股和相关数据
      17. stock300 = get_history_constituents(index='SHSE.000300', start_date='2017-06-30', end_date='2017-06-30')[0][
      18. 'constituents']
      19. stock300_symbol = []
      20. stock300_weight = []
      21. for key in stock300:
      22. # 保留权重大于0.35%的成份股
      23. if (stock300[key] / 100) > 0.0035:
      24. stock300_symbol.append(key)
      25. stock300_weight.append(stock300[key] / 100)
      26. context.stock300 = DataFrame([stock300_weight], columns=stock300_symbol, index=['weight']).T
      27. print('选择的成分股权重总和为: ', np.sum(stock300_weight))
      28. subscribe(symbols=stock300_symbol, frequency='1d', count=5, wait_group=True)
      29. def on_bar(context, bars):
      30. # 若没有仓位则按照初始权重开仓
      31. for bar in bars:
      32. symbol = bar['symbol']
      33. position = context.account().position(symbol=symbol, side=PositionSide_Long)
      34. if not position:
      35. buy_percent = context.stock300['weight'][symbol] * context.ratio
      36. order_target_percent(symbol=symbol, percent=buy_percent, order_type=OrderType_Market,
      37. position_side=PositionSide_Long)
      38. print(symbol, '以市价单开多仓至仓位:', buy_percent)
      39. else:
      40. # 获取过去5天的价格数据,若连续上涨则为强势股,权重+0.2;若连续下跌则为弱势股,权重-0.2
      41. recent_data = context.data(symbol=symbol, frequency='1d', count=5, fields='close')['close'].tolist()
      42. if all(np.diff(recent_data) > 0):
      43. buy_percent = context.stock300['weight'][symbol] * (context.ratio + 0.2)
      44. order_target_percent(symbol=symbol, percent=buy_percent, order_type=OrderType_Market,
      45. position_side=PositionSide_Long)
      46. print('强势股', symbol, '以市价单调多仓至仓位:', buy_percent)
      47. elif all(np.diff(recent_data) < 0):
      48. buy_percent = context.stock300['weight'][symbol] * (context.ratio - 0.2)
      49. order_target_percent(symbol=symbol, percent=buy_percent, order_type=OrderType_Market,
      50. position_side=PositionSide_Long)
      51. print('弱势股', symbol, '以市价单调多仓至仓位:', buy_percent)
      52. if __name__ == '__main__':
      53. '''
      54. strategy_id策略ID,由系统生成
      55. filename文件名,请与本文件名保持一致
      56. mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
      57. token绑定计算机的ID,可在系统设置-密钥管理中生成
      58. backtest_start_time回测开始时间
      59. backtest_end_time回测结束时间
      60. backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
      61. backtest_initial_cash回测初始资金
      62. backtest_commission_ratio回测佣金比例
      63. backtest_slippage_ratio回测滑点比例
      64. '''
      65. run(strategy_id='strategy_id',
      66. filename='main.py',
      67. mode=MODE_BACKTEST,
      68. token='token_id',
      69. backtest_start_time='2017-07-01 08:50:00',
      70. backtest_end_time='2017-10-01 17:00:00',
      71. backtest_adjust=ADJUST_PREV,
      72. backtest_initial_cash=10000000,
      73. backtest_commission_ratio=0.0001,
      74. backtest_slippage_ratio=0.0001)

    指数增强(股票)

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