布林带交易策略

来源:https://uqer.io/community/share/5673d440228e5bab38c97782

  1. from CAL.PyCAL import *
  2. from datetime import *
  3. import time
  4. import pandas as pd
  5. import numpy as np
  6. import math
  7. start = datetime(2014, 1, 1)
  8. end = datetime(2014, 6, 30)
  9. benchmark = 'HS300'
  10. universe = set_universe('HS300')
  11. capital_base = 100000
  12. refresh_rate = 1
  13. ##########################################
  14. t1 = 50 #MA周期
  15. t2 = 30 #ROC周期
  16. MaxBar = 0.75 #持仓周期最大时,首次卖出系数
  17. ##########################################
  18. T = pd.Series(data=[t1],index = universe)
  19. commission = Commission(buycost=0.0003, sellcost=0.0003)
  20. def initialize(account):
  21. pass
  22. def handle_data(account):
  23. #print account.current_date
  24. cal = Calendar('China.SSE')
  25. last_dayt1 = cal.advanceDate(account.current_date, str(-t1)+'B', BizDayConvention.Preceding).toDateTime() #计算出前t1个交易日
  26. buylist = []
  27. selllist = []
  28. #取出当前交易日至前t1交易日之间的收盘价格数据
  29. cp = DataAPI.MktEqudGet(secID=account.universe,ticker=u"",tradeDate=u"",beginDate=last_dayt1,endDate=account.current_date,field=[u"tradeDate",u"secID",u"closePrice"],pandas="1")
  30. #根据持仓周期,更新MA计算周期T,持仓周期增加1,MA计算周期就减少1,最小为10
  31. for stock in account.avail_secpos:
  32. T[stock] = T[stock] - 1
  33. if(T[stock] < 10):
  34. T[stock] = 10
  35. #计算t1周期MA
  36. cpg = cp['closePrice'].groupby(cp['secID'])
  37. ma = cpg.mean()
  38. std = cpg.std()
  39. #当股票当前价格突破布林线上轨,且ROC值大于0,买入
  40. for stock in account.universe:
  41. upband = ma[stock] + std[stock]
  42. if(len(cp[cp.secID == stock]) > t2):
  43. roc = (account.referencePrice[stock] - float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])) / float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])
  44. if account.referencePrice[stock] > upband and roc > 0:
  45. buylist.append(stock)
  46. #当股票当前价格突破布林线中轨,且ROC值小于0,卖出
  47. for stock in account.avail_secpos:
  48. #根据股票的持仓周期计算,MA周期
  49. MAT = np.mean(cp[cp.secID == stock][-T[stock]:]['closePrice'])
  50. stdT = np.std(cp[cp.secID == stock][-T[stock]:]['closePrice'])
  51. midband = MAT
  52. downband = MAT - stdT
  53. if(len(cp[cp.secID == stock]) > t2):
  54. roc = (account.referencePrice[stock] - float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])) / float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])
  55. if account.referencePrice[stock] < midband and roc < 0:
  56. selllist.append(stock)
  57. #买入策略,虚拟账户剩余金额按可买股票平均买入,0.95为成功成交系数
  58. for i in buylist:
  59. order(i, account.cash / len(buylist) / account.referencePrice[i] * 0.95)
  60. #卖出策略,按持仓周期逐步卖出,持仓周期越长,第一次卖出越多,最多为3/4仓位,以10天为单位递减
  61. for i in selllist:
  62. x = (account.avail_secpos[i] * MaxBar*math.pow(0.5,T[i] // 10 -1) // 100) * 100
  63. order(i,-x)
  64. if(x == 100):
  65. T[i] = t1

布林带交易策略 - 图1