10.矢量化回测

当然,函数中的某些数据你也可以灵活地修改为变量,这样你可以最大程度地自定义该函数以符合你自己的需要,比如这里我们将周期“252”修改为一个变量,在你调用该函数的时候作为参数进行赋值:

def BackTest(serie, auunualiazed_scalar=252):
  # Import the benchmark
  sp500 = yf.download('^GSPC', proxy="http://127.0.0.1:10809")['Adj Close'].pct_change(1)

  # Change the name
  sp500.name = 'SP500'

  # Concat the returns and the sp500
  val = pd.concat((serie, sp500), axis=1).dropna()

  # Compute the drawdown
  drawdown = drawdown_function(serie) * 100

  # Compute max drawdown
  max_drawdown = - np.min(drawdown)


  # Put a subplots
  fig, (cum, dra) = plt.subplots(1,2, figsize=(24, 8))

  # Put a Suptitle
  fig.suptitle('Backtesting', size=20)

  # Returns cumsum chart
  cum.plot(serie.cumsum() * 100, color='#39B3C7')

  # SP500 cumsum chart
  cum.plot(val['SP500'].cumsum() * 100, color='#B85A0F')

  # Put a legedn
  cum.legend(['Portfolio', 'SP500'])

  # Set individual title
  cum.set_title('Cumulative Return', size=13)
  cum.set_ylabel('Cumulative Return %', size=11)

  # Put the drawdown
  dra.fill_between(drawdown.index, 0, drawdown, color='#C73954', alpha=0.65)

  # Set individual title
  dra.set_title("Drawdown", size=13)
  dra.set_ylabel('drawdown in %', size=11)

  # Plot the graph
  plt.show()

  # Compute the sortino
  sortino = np.sqrt(auunualiazed_scalar) * serie.mean() / serie.loc[serie < 0].std()

  # Compute the beta
  beta = np.cov(val[['return', 'SP500']].values, rowvar=False)[0][1] / np.var(val['SP500'].values)

  # Compute the alpha
  alpha = auunualiazed_scalar * ( serie.mean() - beta * serie.mean())

  # Print the statistics
  print(f"Sortino: {np.round(sortino, 3)}")
  print(f"Beta: {np.round(beta, 3)}")
  print(f"Alpha: {np.round(alpha * 100, 3)} %")
  print(f"MaxDrawdown: {np.round(max_drawdown, 3)} %") 
BackTest(return_serie, 12)
10.矢量化回测

原创文章,作者:朋远方,如若转载,请注明出处:https://caovan.com/10-shilianghuahuice/.html

(0)
打赏 微信扫一扫 微信扫一扫
朋远方的头像朋远方
上一篇 2022年11月15日 下午10:14
下一篇 2022年12月9日 下午5:02

相关推荐

发表回复

登录后才能评论