便宜就是 alpha

来源:https://uqer.io/community/share/5609169cf9f06c597565ef13

参考社区的策略,练手一个简单的调仓逻辑

策略思路

  • 一星期或者一个月一换仓
  • 每次换仓时,取股价最低的15只等权重买入
  1. import numpy as np
  2. from heapq import nlargest, nsmallest
  3. from CAL.PyCAL import *
  4. start = datetime(2012, 1, 1)
  5. end = datetime(2015, 8, 31)
  6. benchmark = 'HS300' # 策略参考标准
  7. universe = set_universe('ZZ500') + set_universe('HS300')
  8. capital_base = 1000000
  9. stk_num = 15 # 持仓股票数量
  10. refresh_rate = 5
  11. def initialize(account):
  12. pass
  13. def handle_data(account):
  14. cal = Calendar('China.SSE')
  15. # ----------------- 清洗universe --------------------------------
  16. date = account.current_date
  17. yesterday = cal.advanceDate(date, '-1B', BizDayConvention.Following)
  18. yesterday = datetime(yesterday.year(), yesterday.month(), yesterday.dayOfMonth()).strftime('%Y%m%d'),
  19. # 去除ST股
  20. try:
  21. STlist = DataAPI.SecSTGet(secID=account.universe, beginDate=yesterday, endDate=yesterday, field=['secID']).tolist()
  22. account.universe = [s for s in account.universe if s not in STlist]
  23. except:
  24. pass
  25. # 去除流动性差的股票
  26. tv = account.get_attribute_history('turnoverValue', 20)
  27. mtv = {sec: sum(tvs)/20. for sec,tvs in tv.items()}
  28. account.universe = [s for s in account.universe if mtv.get(s, 0) >= 10**7]
  29. # 去除新上市或复牌的股票
  30. opn = account.get_attribute_history('openPrice', 1)
  31. account.universe = [s for s in account.universe if not (np.isnan(opn.get(s, 0)[0]) or opn.get(s, 0)[0] == 0)]
  32. # ----------------- 调仓逻辑 --------------------------------
  33. bucket = {}
  34. for stk in account.universe:
  35. bucket[stk] = account.referencePrice[stk]
  36. # 以前面计算得到的turnover_delta对股票池中股票排序,并取前stk_num只,力图满足比赛要求
  37. # 注意:
  38. # 这里我们其实取了股价最低的 stk_num*2 只,原因在于:为了满足参赛要求,调仓时候我们必须
  39. # 达到一定仓位,如果取stk_num只,那么一旦遇到涨停停牌等买不进的情况,就跪了;所以我们拿
  40. # stk_num*2 数量的股票,但是却将仓位分成stk_num份,每份买进一只,这样有一只买不进,就
  41. # 买后面的,参赛调仓是不是保险了许多啊
  42. buy_list = nsmallest(stk_num*2, bucket, key=bucket.get)
  43. # 目前持仓中不在buy_list中的股票,清仓
  44. for stk, amount in account.valid_secpos.items():
  45. if stk not in buy_list:
  46. order_to(stk, 0)
  47. # buy_list中的股票,等权重买入
  48. position_per_stk = account.referencePortfolioValue/stk_num # 将仓位分成stk_num份
  49. for stk in buy_list:
  50. if account.referencePrice[stk] > 0:
  51. amount = int(position_per_stk/account.referencePrice[stk]/100.0) * 100
  52. order_to(stk, amount)
  53. return

便宜就是 alpha - 图1