9.2 GMVP · Global Minimum Variance Portfolio (GMVP)

来源:https://uqer.io/community/share/55461734f9f06c1c3d688030

  1. import pandas as pd
  2. import numpy as np
  3. start = '2011-07-01' # 回测起始时间
  4. end = '2014-08-01' # 回测结束时间
  5. benchmark = 'SH50' # 策略参考标准
  6. universe = ['601398.XSHG','600028.XSHG', '601988.XSHG', '600036.XSHG','600030.XSHG','601318.XSHG', '600000.XSHG', '600019.XSHG', '600519.XSHG', '601166.XSHG']
  7. capital_base = 100000 # 起始资金
  8. longest_history = 40 # handle_data 函数中可以使用的历史数据最长窗口长度
  9. refresh_rate = 10 # 调仓频率,即每 refresh_rate 个交易日执行一次 handle_data() 函数
  10. def initialize(account): # 初始化虚拟账户状态
  11. pass
  12. def handle_data(account): # 每个交易日的买入卖出指令
  13. history_data = account.get_attribute_history('closePrice',40)
  14. retmatrix = []
  15. for s in account.universe:
  16. retmatrix.append([history_data[s][i]/ history_data[s][i - 1] for i in range(1,40) ])
  17. retmatrix = np.array(retmatrix)
  18. covmatrix = np.cov(retmatrix, y=None, rowvar=1, bias=0, ddof=None)
  19. covmatrix = np.matrix(covmatrix) # 不加这句执行矩阵求逆报错
  20. covinv = np.linalg.inv(covmatrix)
  21. one_row = np.matrix(np.ones(len(account.universe)))
  22. one_vector = np.matrix(np.ones(len(account.universe))).transpose()
  23. up = np.dot(covinv, one_vector)
  24. down = np.dot(np.dot(one_row, covinv), one_vector)
  25. weights = up/down
  26. weightsum = 0
  27. for a in weights:
  28. weightsum += a
  29. index= 0
  30. for s in account.universe:
  31. weigh = weights[index]/weightsum
  32. index = index + 1
  33. amount = account.cash * weigh / account.referencePrice[s]
  34. order_to(s,amount)

9.2 GMVP · Global Minimum Variance Portfolio (GMVP) - 图1

just implement the examples in the API doc