羊驼反转策略

来源:https://uqer.io/community/share/566982a4f9f06c6c8a91b7a2

  1. # 第一步:设置基本参数
  2. start = '2011-04-01' # 回测起始时间
  3. end = '2015-12-01' # 回测结束时间
  4. capital_base = 1000000 # 起始资金
  5. refresh_rate = 10 # 调仓频率
  6. benchmark = 'HS300' # 策略参考标准
  7. freq = 'd' # 策略类型,'d'表示日间策略使用日线回测
  8. # 第二步:选择主题,设置股票池
  9. universe = set_universe('HS300') # 股票池
  10. import numpy as np
  11. import pandas as pd
  12. data=DataAPI.MktStockFactorsOneDayGet(tradeDate='20110331',secID=universe,ticker=u"",field=['secID','REVS10'],pandas="1") #获取start前一日股票池中十日收益
  13. buylist=data.dropna().sort(columns='REVS10',ascending=False).tail(10)['secID'].values.tolist() #将十日收益最差的十只股票组成list
  14. def initialize(account): # 初始化虚拟账户状态
  15. account.stocks_num=10
  16. def handle_data(account): # 每个交易日的买入卖出指令
  17. if account.stocks_num==10: #第一天交易使用buylist
  18. global buylist
  19. account.universe=buylist
  20. hist_prices = account.get_attribute_history('closePrice', 1)
  21. for i in account.universe:
  22. order(i,100000/hist_prices[i][0])
  23. account.stocks_num=1 #之后为非第一天交易策略
  24. sellist=[]
  25. replacelist=[]
  26. sell=DataAPI.MktStockFactorsOneDayGet(tradeDate=account.current_date,secID=account.universe,ticker=u"",field=['secID','REVS10'],pandas="1") #获得十日以来账户中所有股票的收益
  27. sellist.append(sell.min()['secID']) #找出收益最差的股票加入sellist
  28. replace=DataAPI.MktStockFactorsOneDayGet(tradeDate=account.current_date,secID=universe,ticker=u"",field=['secID','REVS10'],pandas="1") #获得股票池中十日以来所有股票的收益
  29. replace=replace.set_index('secID').drop(buylist)
  30. replace=replace.dropna().sort(columns='REVS10',ascending=False).tail(1).reset_index()['secID'].values.tolist() #获得收益最差的股票作为账户中新的代替股票
  31. replacelist.append(replace)
  32. account.universe.remove(sell.min()['secID'])
  33. account.universe=account.universe+replacelist[0]
  34. hist_prices = account.get_attribute_history('closePrice', 1) #获取前一个交易日账户股票价格
  35. for stk in sellist:
  36. order_to(stk,0)
  37. for stk in account.universe:
  38. order(stk,account.cash/10/hist_prices[stk][0])

羊驼反转策略 - 图1