羊驼反转策略(修改版)

来源:https://uqer.io/community/share/566c0e3cf9f06c6c8a91ceec

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

羊驼反转策略(修改版) - 图1