IPython 与 RQAlpha

加载 RQAlpha magic

  1. In [3]:
  1. %load_ext rqalpha
  1. The rqalpha extension is already loaded. To reload it, use:
  2. %reload_ext rqalpha

查看 RQAlpha magic 帮助

我们可以通过 %%rqalpha 直接在 cell 中运行回测代码。%%rqalpha 后面的参数等价于在 CLI 中后面的 rqalpha run 的参数

  1. In [2]:
  1. %%rqalpha -h
  2. ""
  1. Usage: ipykernel_launcher.py [OPTIONS]
  2.  
  3. Start to run a strategy
  4.  
  5. Options:
  6. -h, --help Show this message and exit.
  7. -d, --data-bundle-path PATH
  8. -f, --strategy-file PATH
  9. -s, --start-date DATE
  10. -e, --end-date DATE
  11. -bm, --benchmark TEXT
  12. -mm, --margin-multiplier FLOAT
  13. -a, --account TEXT... set account type with starting cash
  14. -fq, --frequency [1d|1m|tick]
  15. -rt, --run-type [b|p]
  16. --resume
  17. --source-code TEXT
  18. -l, --log-level [verbose|debug|info|error|none]
  19. --disable-user-system-log disable user system log stdout
  20. --disable-user-log disable user log stdout
  21. --locale [cn|en]
  22. --extra-vars TEXT override context vars
  23. --enable-profiler add line profiler to profile your strategy
  24. --config TEXT config file path
  25. -mc, --mod-config TEXT... mod extra config
  26. --stock-t1 / --no-stock-t1 [sys_accounts] enable/disable stock T+1
  27. --report PATH [sys_analyser] save report
  28. -o, --output-file PATH [sys_analyser] output result pickle file
  29. -p, --plot / --no-plot [sys_analyser] plot result
  30. --plot-save TEXT [sys_analyser] save plot to file
  31. --progress [sys_progress]show progress bar
  32. --no-short-stock / --short-stock
  33. [sys_risk] enable stock shorting
  34. --signal [sys_simulation] exclude match engine
  35. -sp, --slippage FLOAT [sys_simulation] set slippage
  36. -cm, --commission-multiplier FLOAT
  37. [sys_simulation] set commission multiplier
  38. -me, --match-engine [current_bar|next_bar|last|best_own|best_counterparty]
  39. [Deprecated][sys_simulation] set matching
  40. type
  41. -mt, --matching-type [current_bar|next_bar|last|best_own|best_counterparty]
  42. [sys_simulation] set matching type

使用 %%rqalpha 进行回测

  1. In [3]:
  1. %%rqalpha -s 20100101 -e 20170505 -p -bm 000001.XSHG --account stock 100000
  2.  
  3. def init(context):
  4. context.stocks = ['000300.XSHG', '000905.XSHG', '000012.XSHG']
  5.  
  6.  
  7. def handle_bar(context, bar_dict):
  8. [hs, zz, gz] = context.stocks
  9. hs_history20 = history_bars(hs, 20, '1d', 'close')
  10. zz_history20 = history_bars(zz, 20, '1d', 'close')
  11.  
  12. hsIncrease = hs_history20[-1] - hs_history20[0]
  13. zzIncrease = zz_history20[-1] - zz_history20[0]
  14.  
  15. positions = context.portfolio.positions
  16. [hsQuality, zzQuality, gzQuality] = [positions[hs].quantity, positions[zz].quantity, positions[gz].quantity]
  17. if hsIncrease < 0 and zzIncrease < 0:
  18. if hsQuality > 0: order_target_percent(hs, 0)
  19. if zzQuality > 0: order_target_percent(zz, 0)
  20. order_target_percent(gz, 1)
  21. elif hsIncrease < zzIncrease:
  22. if hsQuality > 0: order_target_percent(hs, 0)
  23. if gzQuality > 0: order_target_percent(gz, 0)
  24. order_target_percent(zz, 1)
  25. else:
  26. if zzQuality > 0: order_target_percent(zz, 0)
  27. if gzQuality > 0: order_target_percent(gz, 0)
  28. order_target_percent(hs, 1)
  29. #logger.info("positions hs300: " + str(hsQuality) + ", zz500: " + str(zzQuality) + ", gz: " + str(gzQuality))

../_images/notebooks_run-rqalpha-in-ipython_6_0.png

获取回测报告

运行完回测后,报告会自动存储到 report 变量中。可以直接通过report 变量获取当次回测的结果。

另外 rqalpha 的 mod 的输出会自动存储在 results 变量中。

  1. In [4]:
  1. results.keys()
  1. Out[4]:
  1. dict_keys(['sys_analyser'])
  1. In [5]:
  1. report.keys()
  1. Out[5]:
  1. dict_keys(['summary', 'trades', 'portfolio', 'benchmark_portfolio', 'stock_account', 'stock_positions'])
  1. In [6]:
  1. report.trades[:5]
  1. Out[6]:
commissionexec_idlast_pricelast_quantityorder_book_idorder_idposition_effectsidesymboltaxtrading_datetimetransaction_cost
datetime
2010-01-04 15:00:0079.9614241498453688122.34817000012.XSHG1498453672NoneBUY国债指数02010-01-04 15:00:0079.961424
2010-01-06 15:00:0079.9483521498453689122.32817000012.XSHG1498453673NoneSELL国债指数02010-01-06 15:00:0079.948352
2010-01-06 15:00:0076.44470414984536904550.2821000905.XSHG1498453674NoneBUY中证500(沪)02010-01-06 15:00:0076.444704
2010-01-07 15:00:0074.91388814984536914459.1621000905.XSHG1498453675NoneSELL中证500(沪)02010-01-07 15:00:0074.913888
2010-01-07 15:00:0078.1805521498453692122.31799000012.XSHG1498453676NoneBUY国债指数02010-01-07 15:00:0078.180552
  1. In [7]:
  1. report.portfolio[:5]
  1. Out[7]:
cashmarket_valuestatic_unit_net_valuetotal_valueunit_net_valueunits
date
2010-01-04-31.74199951.781.00099920.0390.999200100000.0
2010-01-05-31.74199902.760.99999871.0190.998710100000.0
2010-01-064191.42695555.880.99999747.3060.997473100000.0
2010-01-07-44.99997725.690.99797680.6910.976807100000.0
2010-01-08-44.99997733.680.97797688.6810.976887100000.0
  1. In [8]:
  1. report.stock_positions[:5]
  1. Out[8]:
avg_pricelast_pricemarket_valueorder_book_idquantitysymbol
date
2010-01-04122.34122.3499951.78000012.XSHG817国债指数
2010-01-05122.34122.2899902.76000012.XSHG817国债指数
2010-01-06122.34122.320.00000012.XSHG0国债指数
2010-01-064550.284550.2895555.88000905.XSHG21中证500(沪)
2010-01-074550.284459.160.00000905.XSHG0中证500(沪)

使用 run_func 运行回测

  1. In [9]:
  1. config = {
  2. "base": {
  3. "start_date": "2010-01-01",
  4. "end_date": "2017-05-05",
  5. "benchmark": "000001.XSHG",
  6. "accounts": {
  7. "stock": 100000
  8. }
  9. },
  10. "extra": {
  11. "log_level": "info",
  12. },
  13. "mod": {
  14. "sys_analyser": {
  15. "enabled": True,
  16. "plot": True,
  17. },
  18. }
  19. }
  20.  
  21.  
  22. from rqalpha.api import *
  23. from rqalpha import run_func
  24.  
  25.  
  26. def init(context):
  27. context.stocks = ['000300.XSHG', '000905.XSHG', '000012.XSHG']
  28.  
  29.  
  30. def handle_bar(context, bar_dict):
  31. [hs, zz, gz] = context.stocks
  32. hs_history20 = history_bars(hs, 20, '1d', 'close')
  33. zz_history20 = history_bars(zz, 20, '1d', 'close')
  34.  
  35. hsIncrease = hs_history20[-1] - hs_history20[0]
  36. zzIncrease = zz_history20[-1] - zz_history20[0]
  37.  
  38. positions = context.portfolio.positions
  39. [hsQuality, zzQuality, gzQuality] = [positions[hs].quantity, positions[zz].quantity, positions[gz].quantity]
  40. if hsIncrease < 0 and zzIncrease < 0:
  41. if hsQuality > 0: order_target_percent(hs, 0)
  42. if zzQuality > 0: order_target_percent(zz, 0)
  43. order_target_percent(gz, 1)
  44. elif hsIncrease < zzIncrease:
  45. if hsQuality > 0: order_target_percent(hs, 0)
  46. if gzQuality > 0: order_target_percent(gz, 0)
  47. order_target_percent(zz, 1)
  48. else:
  49. if zzQuality > 0: order_target_percent(zz, 0)
  50. if gzQuality > 0: order_target_percent(gz, 0)
  51. order_target_percent(hs, 1)
  52.  
  53.  
  54. results = run_func(init=init, handle_bar=handle_bar, config=config)

../_images/notebooks_run-rqalpha-in-ipython_14_0.png

  1. In [10]:
  1. report = results["sys_analyser"]
  1. In [11]:
  1. report["trades"][:5]
  1. Out[11]:
commissionexec_idlast_pricelast_quantityorder_book_idorder_idposition_effectsidesymboltaxtrading_datetimetransaction_cost
datetime
2010-01-04 15:00:0079.9614241498454089122.34817000012.XSHG1498454073NoneBUY国债指数02010-01-04 15:00:0079.961424
2010-01-06 15:00:0079.9483521498454090122.32817000012.XSHG1498454074NoneSELL国债指数02010-01-06 15:00:0079.948352
2010-01-06 15:00:0076.44470414984540914550.2821000905.XSHG1498454075NoneBUY中证500(沪)02010-01-06 15:00:0076.444704
2010-01-07 15:00:0074.91388814984540924459.1621000905.XSHG1498454076NoneSELL中证500(沪)02010-01-07 15:00:0074.913888
2010-01-07 15:00:0078.1805521498454093122.31799000012.XSHG1498454077NoneBUY国债指数02010-01-07 15:00:0078.180552
  1. In [ ]:
  1.