投资组合回测示例

投资组合回测是基于单策略回测的,其关键是每个策略都对应着各自的BacktestingEngine对象,下面介绍具体流程:

  • 创建回测函数run_backtesting(),这样每添加一个策略就创建其BacktestingEngine对象。
  1. from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
  2. from vnpy.app.cta_strategy.strategies.atr_rsi_strategy import AtrRsiStrategy
  3. from vnpy.app.cta_strategy.strategies.boll_channel_strategy import BollChannelStrategy
  4. from datetime import datetime
  5.  
  6. def run_backtesting(strategy_class, setting, vt_symbol, interval, start, end, rate, slippage, size, pricetick, capital):
  7. engine = BacktestingEngine()
  8. engine.set_parameters(
  9. vt_symbol=vt_symbol,
  10. interval=interval,
  11. start=start,
  12. end=end,
  13. rate=rate,
  14. slippage=slippage,
  15. size=size,
  16. pricetick=pricetick,
  17. capital=capital
  18. )
  19. engine.add_strategy(strategy_class, setting)
  20. engine.load_data()
  21. engine.run_backtesting()
  22. df = engine.calculate_result()
  23. return df
  • 分别进行单策略回测,得到各自的DataFrame,(该DataFrame包含交易时间、今仓、昨仓、手续费、滑点、当日净盈亏、累计净盈亏等基本信息,但是不包括最大回撤,夏普比率等统计信息),然后把DataFrame相加并且去除空值后即得到投资组合的DataFrame。
  1. df1 = run_backtesting(
  2. strategy_class=AtrRsiStrategy,
  3. setting={},
  4. vt_symbol="IF88.CFFEX",
  5. interval="1m",
  6. start=datetime(2019, 1, 1),
  7. end=datetime(2019, 4, 30),
  8. rate=0.3/10000,
  9. slippage=0.2,
  10. size=300,
  11. pricetick=0.2,
  12. capital=1_000_000,
  13. )
  14.  
  15. df2 = run_backtesting(
  16. strategy_class=BollChannelStrategy,
  17. setting={'fixed_size': 16},
  18. vt_symbol="RB88.SHFE",
  19. interval="1m",
  20. start=datetime(2019, 1, 1),
  21. end=datetime(2019, 4, 30),
  22. rate=1/10000,
  23. slippage=1,
  24. size=10,
  25. pricetick=1,
  26. capital=1_000_000,
  27. )
  28.  
  29. dfp = df1 + df2
  30. dfp =dfp.dropna()
  • 创建show_portafolio()函数,同样也是创建新的BacktestingEngine对象,对传入的DataFrame计算如夏普比率等统计指标,并且画图。故该函数不仅能显示单策略回测效果,也能展示投资组合回测效果。
  1. def show_portafolio(df):
  2. engine = BacktestingEngine()
  3. engine.calculate_statistics(df)
  4. engine.show_chart(df)
  5.  
  6. show_portafolio(dfp)