布林带回调系统-日内

来源:https://uqer.io/community/share/566929a4f9f06c6c8a91b6e6

  1. import numpy as np
  2. import pandas as pd
  3. from pandas import DataFrame
  4. start = '2014-01-01' # 回测起始时间
  5. end = '2015-01-01' # 回测结束时间
  6. benchmark = 'HS300' # 策略参考标准
  7. universe = set_universe('HS300') # 证券池,支持股票和基金
  8. capital_base = 100000 # 起始资金
  9. freq = 'm' # 策略类型,'d'表示日间策略使用日线回测,'m'表示日内策略使用分钟线回测
  10. refresh_rate = 239 # 调仓频率,表示执行handle_data的时间间隔,若freq = 'd'时间间隔的单位为交易日,若freq = 'm'时间间隔为分钟
  11. period = 10
  12. multiple=1.5
  13. threshold=-0.1
  14. boll=pd.DataFrame(index=universe,columns = ['mean_cp','high_channel','low_channel'])
  15. def initialize(account): # 初始化虚拟账户状态
  16. pass
  17. def handle_data(account): # 每个交易日的买入卖出指令
  18. if(account.current_minute=='09:30'):
  19. close_prices = account.get_daily_attribute_history('closePrice', period)
  20. for s in account.universe:
  21. mean_cp = close_prices[s].mean()
  22. bias = multiple*np.std(close_prices[s])
  23. high_channel = mean_cp + bias
  24. low_channel = mean_cp - bias
  25. boll.at[s,'high_channel']=high_channel
  26. boll.at[s,'low_channel']=low_channel
  27. boll.at[s,'mean_cp']=mean_cp
  28. elif(account.current_minute=='14:50'):
  29. print account.current_date,",",account.valid_secpos
  30. else:
  31. for s in account.valid_secpos: #清仓
  32. if account.referencePrice[s]>=boll.at[s,'mean_cp'] :
  33. order_to(s, 0)
  34. buylist=[]
  35. c = account.referencePortfolioValue
  36. for s in account.universe:
  37. if ((account.referencePrice[s]-boll.at[s,'low_channel'])/boll.at[s,'low_channel'])<=threshold:
  38. buylist.append(s)
  39. if (len(buylist)==0):
  40. return
  41. else:
  42. w=min(0.2,1.0/len(buylist))# 最大仓位1/5
  43. for s in buylist:
  44. p=account.referencePrice[s]*1.01
  45. num=int(c * w / p)
  46. order(s, num)