[关闭]
@Channelchan 2018-01-06T14:47:00.000000Z 字数 1235 阅读 125453

8. 完整策略

  1. import rqalpha
  2. import os
  3. from rqalpha.api import *
  4. import talib
  5. import pandas as pd
  6. def init(context):
  7. context.s1 = "000001.XSHE"
  8. context.SHORTPERIOD = 10
  9. context.LONGPERIOD = 30
  10. def handle_bar(context, bar_dict):
  11. prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')
  12. short_avg = talib.SMA(prices, context.SHORTPERIOD)
  13. long_avg = talib.SMA(prices, context.LONGPERIOD)
  14. # 计算现在portfolio中股票的仓位
  15. cur_position = context.portfolio.positions[context.s1].quantity
  16. avg_price = context.portfolio.positions[context.s1].avg_price
  17. capital = cur_position*avg_price
  18. # 计算现在portfolio中的现金可以购买多少股票
  19. shares = context.portfolio.cash/bar_dict[context.s1].close
  20. #图形显示当前占用资金
  21. plot('capital', capital)
  22. # 如果短均线从上往下跌破长均线,而上一个bar的短线平均值高于长线平均值
  23. if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:
  24. # 进行清仓
  25. order_target_value(context.s1, 0)
  26. # 如果短均线从下往上突破长均线,为入场信号
  27. if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:
  28. # 满仓入股
  29. order_shares(context.s1, shares)
  30. config = {
  31. "base": {
  32. "start_date": "2015-06-01",
  33. "end_date": "2017-12-30",
  34. "accounts": {'stock':1000000},
  35. "benchmark": "000001.XSHE",
  36. # "strategy_file_path": os.path.abspath(__file__)
  37. },
  38. "extra": {
  39. "log_level": "error",
  40. },
  41. "mod": {
  42. "sys_analyser": {
  43. "enabled": True,
  44. "plot": True
  45. }
  46. }
  47. }
  48. # 您可以指定您要传递的参数
  49. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_1_0.png-89.5kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注