布林带交易策略
来源:https://uqer.io/community/share/5673d440228e5bab38c97782
from CAL.PyCAL import *
from datetime import *
import time
import pandas as pd
import numpy as np
import math
start = datetime(2014, 1, 1)
end = datetime(2014, 6, 30)
benchmark = 'HS300'
universe = set_universe('HS300')
capital_base = 100000
refresh_rate = 1
t1 = 50
t2 = 30
MaxBar = 0.75
T = pd.Series(data=[t1],index = universe)
commission = Commission(buycost=0.0003, sellcost=0.0003)
def initialize(account):
pass
def handle_data(account):
cal = Calendar('China.SSE')
last_dayt1 = cal.advanceDate(account.current_date, str(-t1)+'B', BizDayConvention.Preceding).toDateTime()
buylist = []
selllist = []
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")
for stock in account.avail_secpos:
T[stock] = T[stock] - 1
if(T[stock] < 10):
T[stock] = 10
cpg = cp['closePrice'].groupby(cp['secID'])
ma = cpg.mean()
std = cpg.std()
for stock in account.universe:
upband = ma[stock] + std[stock]
if(len(cp[cp.secID == stock]) > t2):
roc = (account.referencePrice[stock] - float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])) / float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])
if account.referencePrice[stock] > upband and roc > 0:
buylist.append(stock)
for stock in account.avail_secpos:
MAT = np.mean(cp[cp.secID == stock][-T[stock]:]['closePrice'])
stdT = np.std(cp[cp.secID == stock][-T[stock]:]['closePrice'])
midband = MAT
downband = MAT - stdT
if(len(cp[cp.secID == stock]) > t2):
roc = (account.referencePrice[stock] - float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])) / float(cp[cp.secID == stock][-t2:-t2+1]['closePrice'])
if account.referencePrice[stock] < midband and roc < 0:
selllist.append(stock)
for i in buylist:
order(i, account.cash / len(buylist) / account.referencePrice[i] * 0.95)
for i in selllist:
x = (account.avail_secpos[i] * MaxBar*math.pow(0.5,T[i] // 10 -1) // 100) * 100
order(i,-x)
if(x == 100):
T[i] = t1