def OnFirstRun(self): """回测调用函数, 在第一个bar时调用, 先建立底仓""" assert (self.is_backtesting) code = self.data.get_code() df_hisdat = self.data.get_hisdat(code) #这里取不到开盘价, 用昨收盘代替 price = float(df_hisdat.iloc[-1]['c']) account = self._getAccount() account_mgr = ac.AccountMgr(account, price, code) num = ac.ShouShu(account_mgr.total_money() * self.lowerhold / price)
def Run(self): """ """ #self._log('Strategy_Boll_Pre') #以下为交易测试 code = self.data.get_code() #当前策略处理的股票 self.code = code if not self.is_backtesting and not self.AllowCode(code): return df_hisdat = self.data.get_hisdat(code) #日k线 df_five_hisdat = self.data.get_hisdat(code, dtype='5min') #5分钟k线 df_fenshi = self.data.get_fenshi(code) #日分时 if len(df_fenshi) == 0: self.data.log(code + u"未取到分时数据") return account = self._getAccount() #获取交易账户 price = float(df_fenshi.tail(1)['p']) #当前股价 closes = df_hisdat['c'] yestoday_close = closes[-2] #昨日收盘价 zhangfu = stock.ZhangFu(price, yestoday_close) self._log( 'price=%.2f %s %s' % (price, str(df_fenshi.index[-1]), str(df_five_hisdat.iloc[-1]))) account_mgr = ac.AccountMgr(account, price, code) trade_num = ac.ShouShu(account_mgr.init_money() * self.trade_num_use_money_percent / price) trade_num = max(100, trade_num) # 信号计算 four = stock.FOUR(closes) four = four[-1] upper, middle, lower = stock.TDX_BOLL(df_five_hisdat['c']) highs, lows, closes = df_five_hisdat['h'], df_five_hisdat[ 'l'], df_five_hisdat['c'] adx = stock.TDX_ADX(highs, lows, closes) self._log('boll : %.2f,%.2f,%.2f' % (upper[-1], middle[-1], lower[-1])) boll_w = abs(upper[-1] - lower[-1]) / middle[-1] * 100 #50个周期内最高值 is_high = abs(price - max(df_five_hisdat[-1000:]['h'])) / price < 0.005 boll_poss = [ upper[-1], (upper[-1] - middle[-1]) / 2 + middle[-1], middle[-1], (middle[-1] - lower[-1]) / 2 + lower[-1], lower[-1], ] self._log('boll_poss: %.2f, %.2f boll_w=%.2f adx=%.2f' % (boll_poss[0], boll_poss[1], boll_w, adx[-1])) #上一个成交的价位 pre_price = account_mgr.last_chengjiao_price() pre_pre_price = account_mgr.last_chengjiao_price(index=-2) sell_count = account_mgr.queryTradeCount(1) buy_count = account_mgr.queryTradeCount(0) #买入均价 adx = adx[-1] boll_up_ratio = 0.02 #信号判断 num = 0 if so.assemble( price > boll_poss[1], price > pre_price * (1 + self.trade_ratio), #price > boll_poss[2], #price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3.5, #adx > 60, #sell_count < 2, #pr.horizontal(df_five_hisdat), 0, ): num = -trade_num self.trade_status = self.enum.boll_up_mid #if self.order(1, code, price, num): #self._log(agl.utf8_to_ascii('一档卖出%s, %.2f, %d'%(code, price, num))) if so.assemble( price > boll_poss[0], price > pre_price * (1 + self.trade_ratio), #price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3, adx > 60, is_high, #four > self.trade_four[1], #sell_count < 2, #self.trade_status == self.enum.nothing, #0, ): num = -trade_num * 3 self.trade_status = self.enum.boll_up #if self.order(1, code, price, num): #self._log(agl.utf8_to_ascii('二档卖出%s, %.2f, %d'%(code, price, num))) if so.assemble( price < boll_poss[-2] * (1 + boll_up_ratio), price < pre_price * (1 - self.trade_ratio), #price < boll_poss[2], #price < self.min_sell_price*(1-0.03), #boll_w > 3.5, #adx>60, #buy_count < 2, #pr.horizontal(df_five_hisdat), 0, ): num = trade_num self.trade_status = self.enum.boll_down_mid #if boll_w > 6: #num *= self.trade_num_ratio #if self.order(0, code, price, num): #self._log(agl.utf8_to_ascii('一档买入%s, %.2f, %d'%(code, price, num))) if so.assemble( price < boll_poss[-1], price < pre_price * (1 - self.trade_ratio), #price < self.min_sell_price*(1-0.03), #boll_w > 3, #buy_count < 2, #self.trade_status == self.enum.nothing, #adx>70, #four < self.trade_four[0], #0, ): num = trade_num * 3 #num = account_mgr.last_chengjiao_num() self.trade_status = self.enum.boll_down #if self.order(0, code, price, num): #self._log(agl.utf8_to_ascii('二档买入%s, %.2f, %d'%(code, price, num))) #成本区间 if so.assemble( price < pre_price * (1 - 0.05), four < -0.1, self.trade_status == self.enum.boll_up, 0, ): num = trade_num * self.trade_num_ratio self.trade_status = self.enum.nothing if so.assemble( price > pre_price * (1 + 0.05), four > 0.1, self.trade_status == self.enum.boll_down, 0, ): num = -trade_num * self.trade_num_ratio self.trade_status = self.enum.nothing #zz顶抛出后回补 if so.assemble( price < pre_price * (1 - 0.02), #sell_count >= 2, self.trade_status == self.enum.zz_up, 0, ): #上次zz卖出的数量 num = account_mgr.last_chengjiao_num() self.trade_status = self.enum.zz_hui_bu if so.assemble( price > pre_price * (1 + 0.02), #sell_count >= 2, self.trade_status == self.enum.zz_down, 0, ): #上次zz卖出的数量 num = account_mgr.last_chengjiao_num() self.trade_status = self.enum.zz_hui_bu #计算分时zz zz_sign = 0 closes = df_five_hisdat['c'][-200:].values zz = stock.ZigZag(closes) if len(zz) > 2: zz_result = stock.analyzeZZ(zz) zz_line_ratio = zz_result[1] / zz_result[0] #线段比率 #扑捉大涨回头的信号 if abs(zz_result[0]) > 0.05 and abs(zz_line_ratio) > 0.05 and abs( zz_line_ratio) < 0.2 and abs(zz_result[0]) > 0.04: zz_sign = agl.where(zz_result[1] > 0, 1, -1) if num != 0: bSell = agl.where(num > 0, 0, 1) num = abs(num) #if bSell: #num = self._compensate(num, bSell, code) #基本上每天的振幅都在1个点以上 if abs(stock.ZhangFu(price, yestoday_close)) > 0.01: self.order(bSell, code, price, num) zz_pre_price = myredis.createRedisVal('policy_basesign_zz_pre_price', price) if so.assemble( zz_sign != 0, 0, ): #print self.price, getZZPrePrice(self.price),abs(self.price-getZZPrePrice(self.price))/self.price num = trade_num * 12 bSell = agl.where(zz_sign > 0, 0, 1) num = self._compensate(num, bSell, code) bCanOrder = False if so.assemble( bSell, price > zz_pre_price.get() * (1 + 0.03), #price > pre_price*(1+self.trade_ratio), ): bCanOrder = True self.trade_status = self.enum.zz_up if so.assemble( (not bSell), price < zz_pre_price.get() * (1 - 0.03), #price < pre_price*(1-self.trade_ratio) ): bCanOrder = True self.trade_status = self.enum.zz_down if bCanOrder: self._getAccount().Order(bSell, code, price, num) zz_pre_price.set(price) #信号发生时语音播报, 并通知界面回显 if not self.is_backtesting and (price > boll_poss[1] or price < boll_poss[-2]): codename = stock.GetCodeName(code) s = '%s, %.2f' % (codename, price) self.data.show(codename) #通知界面显示 self.data.speak2(s) #语音播报 #tick report if self.is_backtesting and self.is_tick_report: self._getAccount().TickReport(df_five_hisdat, 'win') return
def Run(self): """ """ #self._log('Strategy_Boll_Pre') #以下为交易测试 code = self.data.get_code() #当前策略处理的股票 self.code = code if not self.is_backtesting and not self.AllowCode(code): return self._log(self.getCurTime()) df_hisdat = self.data.get_hisdat(code) #日k线 df_five_hisdat = self.data.get_hisdat(code, dtype='5min') #5分钟k线 if len(df_five_hisdat) <= 30: return account = self._getAccount() #获取交易账户 price = float(df_five_hisdat.iloc[-1]['c']) #当前股价 closes = df_hisdat['c'] yestoday_close = closes[-2] #昨日收盘价 account_mgr = ac.AccountMgr(account, price, code) trade_num = ac.ShouShu(account_mgr.init_money() * self.trade_num[0] / price) # 指标计算 index = len(df_five_hisdat) four = self.getCalcTech('four', index) upper, middle, lower = self.getCalcTech('boll', index) df_five_hisdat.is_copy = False df_five_hisdat['boll_up'] = upper df_five_hisdat['boll_mid'] = middle df_five_hisdat['boll_lower'] = lower adx = self.getCalcTech('adx', index) self._log('boll : %.2f,%.2f,%.2f' % (upper[-1], middle[-1], lower[-1])) boll_w = abs(upper[-1] - lower[-1]) / middle[-1] * 100 #zz_up = stock.ZigZag(upper[-60:], percent=.1) #zz_low = stock.ZigZag(lower[-60:], percent=0.1) boll_poss = [ upper[-1], (upper[-1] - middle[-1]) / 2 + middle[-1], middle[-1], (middle[-1] - lower[-1]) / 2 + lower[-1], lower[-1], ] self.tech = np.array(df_five_hisdat['c']), four, adx four = four[-1] adx = adx[-1] self._log('boll_poss: %.2f, %.2f boll_w=%.2f adx=%.2f' % (boll_poss[0], boll_poss[1], boll_w, adx)) if np.isnan(four): return #形态识别 #shape_is_matched = True shape_is_matched = False if price > boll_poss[2]: base_boll_up = pr.get_boll_up_base() recognizer = pr.Recognize_boll(base_boll_up, df_five_hisdat) shape_is_matched = recognizer.is_matched() else: base_boll_lower = pr.get_boll_lower_base() recognizer = pr.Recognize_boll(base_boll_lower, df_five_hisdat) shape_is_matched = recognizer.is_matched() #帐户信息 pre_price = account_mgr.last_chengjiao_price(is_sell=-1) #上一个成交的价位 pre_buy_price = account_mgr.last_chengjiao_price(is_sell=0) if np.isnan(pre_buy_price): pre_buy_price = pre_price pre_sell_num = account_mgr.last_chengjiao_num() #上次的成交数量 pre_pre_price = account_mgr.last_chengjiao_price(index=-2) sell_count = account_mgr.queryTradeCount(1) buy_count = account_mgr.queryTradeCount(0) chen_ben = account_mgr.get_BuyAvgPrice() #买入成本 yin_kui = account_mgr.yin_kui() #盈亏成本 canwei = account_mgr.getCurCanWei() #信号判断 num = 0 #卖 if so.assemble( #price > boll_poss[1]*1.001, price > pre_price * (1 + self.trade_ratio), #price > boll_poss[2], #price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3.5, #adx > self.trade_adx, #four > self.trade_four[1], #sell_count < 2, #pr.horizontal(df_five_hisdat), shape_is_matched, #0, ): num = -trade_num #if so.assemble(price > boll_poss[0] , #price > pre_price*(1+self.trade_ratio), ##price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3.5,∂ ##adx>60, ##four > self.trade_four[1], ##sell_count < 2, ##self.trade_status == self.enum.nothing, ##0, #): #if pre_sell_num>0: #num = (pre_sell_num * self.trade_num_ratio) #else: #num = ac.ShouShu(account_mgr.getCurCanWei() * 0.5) #order = 1 #买 if so.assemble( #price < boll_poss[-2]*0.999, price < pre_price * (1 - self.trade_ratio), #price < boll_poss[2], #price < self.min_sell_price*(1-0.03), #boll_w > 3.5, four < self.trade_four[0], #adx>self.trade_adx, #buy_count < 2, #pr.horizontal(df_five_hisdat), shape_is_matched, #0, ): num = trade_num #if so.assemble( #price < pre_buy_price*(1-self.trade_ratio), ##price < self.min_sell_price*(1-0.03), ##boll_w > 3.5, ##buy_count < 2, ##self.trade_status == self.enum.nothing, ##adx>70, #four < self.trade_four[0]-0.02, ##0, #): ###加仓买入 #num = self._compensate(trade_num, 0, code) ##order = 0 if abs(num) > 0: order = num < 0 and 1 or 0 self.order(order, code, price, abs(num)) #tick report if self.is_backtesting and self.is_tick_report: self._getAccount().TickReport(df_five_hisdat, 'win') return
def Run(self): account = self._getAccount() code = self.data.get_code() hisdat = self.data.get_hisdat(code) closes = hisdat['c'].dropna() if len(closes)<60: return #计算技术指标 four = stock.FOUR(closes) boll_up, boll_mid, boll_low ,boll_w= stock.TDX_BOLL2(closes) adx = stock.TDX_ADX(hisdat['h'], hisdat['l'], closes) #收集使用过的技术指标,为了报告使用 self.tech = closes, four, boll_up, boll_mid, boll_low ,boll_w, adx four = four[-1] price = hisdat.iloc[-1]['c'] #print self.getCurTime(), four, price, boll_low[-1], boll_w[-1] #基于价值回归及成本控制,加上技术指标择时 #缺点, 资金利用率低, 选股必须选好, 否则碰到一直下跌的情况就会造成亏损 #优点, 成本在相对安全区域 #当成本亏base_ratio%时加倍买入 df_stock_list = account.StockList() df_stock_list = df_stock_list[df_stock_list['证券代码'] == code] #第一次买 if so.assemble(four<self.base_four[0] ,len(df_stock_list) == 0 , adx[-1] > 60, #price<boll_low[-1] , #boll_w[-1]>2 ): if hasattr(self, 'base_num_ratio'): total_money = ac.AccountMgr(self._getAccount(), price, code).init_money() self.base_num = ac.ShouShu(total_money*self.base_num_ratio/price) self._getAccount().Order(0, code, price, self.base_num) if len(df_stock_list) > 0: chengben = float(df_stock_list['参考盈亏成本价'].loc[0]) changwei = int(df_stock_list['库存数量'].loc[0]) yinkui = calcYinKui(price, chengben) #agl.Print( '盈亏:', chengben, yinkui, changwei, '频繁') if price < chengben*(1-self.base_ratio): #如果仓位大于总资金的70%, 那么仓位为剩余资金的一半 df_zhijing = account.ZhiJing() canuse_money = float(df_zhijing['可用'][-1]) total_money = canuse_money + changwei*price if canuse_money/total_money<self.base_rhombus_mid_ratio: num = ac.ShouShu(canuse_money/2/price) #这里开始就按上次交易的价格来作为判断, 最后一个买入 df_chengjiao = account.ChengJiao() df_chengjiao = df_chengjiao[df_chengjiao['买0卖1'] == '0'] last_buy_price = float(df_chengjiao['成交价格'][-1]) if price > last_buy_price*(1-self.base_ratio): num = 0 else: num = changwei*self.base_pramid_ratio if num>0: account.Order(0, code, price, num) #当赚base_ratio%时加倍卖出 chengben = float(df_stock_list['买入均价'].loc[0]) sell_avg_price = myredis.createRedisVal(self.key_sell_avg_price, chengben) sell_num = myredis.createRedisVal(self.key_sell_num, 0) if price>chengben*(1+self.base_ratio) and four>self.base_four[1]: #第一次卖 if sell_num.get() == 0: account.Order(1, code, price, self.base_num) sell_avg_price.set(price) sell_num.set(self.base_num) #print '--',chengben, sell_avg_price.get()*(1+self.base_ratio) if price > sell_avg_price.get()*(1+self.base_ratio): num = int(df_stock_list['可卖数量'].loc[0]) num = min(sell_num.get() * self.base_pramid_ratio, num) num = ac.ShouShu(num) if num > 0: account.Order(1, code, price, num) #更新卖出均价 new_sell_avg_price = (sell_avg_price.get() * sell_num.get()+price*num)/(sell_num.get()+num) sell_avg_price.set(new_sell_avg_price) sell_num.set(sell_num.get()+num)
def Run(self): account = self._getAccount() code = self.data.get_code() hisdat = self.data.get_hisdat(code) #hisdat = hisdat.dropna() #closes = hisdat['c'].dropna() closes = hisdat['c'] if len(closes)<60: return index = len(closes) #计算技术指标 #four = stock.FOUR(closes) four = self.getCalcTech('four', index) #boll_up, boll_mid, boll_low ,boll_w= stock.TDX_BOLL2(closes) boll_up, boll_mid, boll_low ,boll_w = self.getCalcTech('boll', index) #assert(agl.array_equal(boll_up, boll_up2)) #adx = stock.TDX_ADX(hisdat['h'], hisdat['l'], closes) adx = self.getCalcTech('adx', index) #assert(agl.array_equal(adx, adx2)) #收集使用过的技术指标,为了报告使用 self.tech = closes, four, boll_up, boll_mid, boll_low ,boll_w, adx four = four[-1] price = hisdat.iloc[-1]['c'] #print self.getCurTime(), four, price, boll_low[-1], boll_w[-1] #基于价值回归及成本控制,加上技术指标择时 #缺点, 资金利用率低, 选股必须选好, 否则碰到一直下跌的情况就会造成亏损 #优点, 成本在相对安全区域 #当成本亏base_ratio%时加倍买入 df_stock_list = account.StockList() df_stock_list = df_stock_list[df_stock_list['证券代码'] == code] #第一次买 if so.assemble(four<self.base_four[0] , len(df_stock_list) == 0 , #self.first_price == 0, #adx[-1] > 60, #price<boll_low[-1] , #boll_w[-1]>2, #syl < 50, ): if hasattr(self, 'base_num_ratio'): total_money = ac.AccountMgr(self._getAccount(), price, code).init_money() self.base_num = ac.ShouShu(total_money*self.base_num_ratio/price) self._getAccount().Order(0, code, price, self.base_num) if self.first_price == 0: self.first_price = price if len(df_stock_list) > 0: chengben = float(df_stock_list['参考盈亏成本价'].loc[0]) changwei = int(df_stock_list['库存数量'].loc[0]) yinkui = calcYinKui(price, self.first_price) #agl.Print( '盈亏:', chengben, yinkui, changwei, '频繁') buchagn_ratio = self._Fire(yinkui) if buchagn_ratio != 0:#补仓 df_zhijing = account.ZhiJing() canuse_money = float(df_zhijing['可用'][-1]) total_money = canuse_money + changwei*price use_money = total_money*buchagn_ratio num = ac.ShouShu(use_money/price) if num>0: account.Order(0, code, price, num) #当赚base_ratio%时加倍卖出 chengben = float(df_stock_list['买入均价'].loc[0]) if four>self.base_four[1]: #第一次卖 account.Order(1, code, price, self.base_num) #print '--',chengben, sell_avg_price.get()*(1+self.base_ratio) if price > self.first_price * (1+abs(yinkui)): num = int(df_stock_list['可卖数量'].loc[0]) num = num*0.1 num = ac.ShouShu(num) if num > 0: account.Order(1, code, price, num)
def Run(self): """ """ #self._log('Strategy_Boll_Pre') #以下为交易测试 code = self.data.get_code() #当前策略处理的股票 self.code = code if not self.is_backtesting and not self.AllowCode(code): return self._log(self.getCurTime()) df_hisdat = self.data.get_hisdat(code) #日k线 df_five_hisdat = self.data.get_hisdat(code, dtype='5min') #5分钟k线 account = self._getAccount() #获取交易账户 price = float(df_five_hisdat.tail(1)['c']) #当前股价 closes = df_hisdat['c'] yestoday_close = closes[-2] #昨日收盘价 account_mgr = ac.AccountMgr(account, price, code) trade_num = ac.ShouShu(account_mgr.init_money() * self.trade_num_use_money_percent / price) # 信号计算 four = stock.FOUR(df_hisdat['c'])[-1] upper, middle, lower = stock.TDX_BOLL(df_five_hisdat['c']) highs, lows, closes = df_five_hisdat['h'], df_five_hisdat[ 'l'], df_five_hisdat['c'] adx = stock.TDX_ADX(highs, lows, closes) adx = adx[-1] self._log('boll : %.2f,%.2f,%.2f' % (upper[-1], middle[-1], lower[-1])) boll_w = abs(upper[-1] - lower[-1]) / middle[-1] * 100 boll_poss = [ upper[-1], (upper[-1] - middle[-1]) / 2 + middle[-1], middle[-1], (middle[-1] - lower[-1]) / 2 + lower[-1], lower[-1], ] self._log('boll_poss: %.2f, %.2f boll_w=%.2f adx=%.2f' % (boll_poss[0], boll_poss[1], boll_w, adx)) pre_price = account_mgr.last_chengjiao_price(is_sell=-1) #上一个成交的价位 pre_buy_price = account_mgr.last_chengjiao_price(is_sell=0) if np.isnan(pre_buy_price): pre_buy_price = pre_price pre_sell_num = account_mgr.last_chengjiao_num() #上次的成交数量 pre_pre_price = account_mgr.last_chengjiao_price(index=-2) sell_count = account_mgr.queryTradeCount(1) buy_count = account_mgr.queryTradeCount(0) chen_ben = account_mgr.get_BuyAvgPrice() #买入成本 yin_kui = account_mgr.yin_kui() #盈亏成本 canwei = account_mgr.getCurCanWei() #信号判断 num = 0 if so.assemble( price > boll_poss[1] * 1.001, price > pre_price * (1 + self.trade_ratio), #price > boll_poss[2], #price > self.max_buy_price*(1+self.trade_ratio), #boll_w < 2.5, #adx > 45, #sell_count < 2, #pr.horizontal(df_five_hisdat), #0, ): num = trade_num #account.Order(1, code, price, num) if so.assemble( price > boll_poss[0], price > pre_price * (1 + self.trade_ratio), #price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3, #adx>60, four > self.trade_four[1], #sell_count < 2, #self.trade_status == self.enum.nothing, #0, ): if pre_sell_num > 0: num = (pre_sell_num * self.trade_num_ratio) else: num = ac.ShouShu(account_mgr.getCurCanWei() * 0.5) #self.trade_status = self.enum.boll_up if num > 0 and self.order(1, code, price, num): self._log( agl.utf8_to_ascii('二档卖出%s, %.2f, %d' % (code, price, num))) if so.assemble( price < boll_poss[-2] * 0.999, price < pre_price * (1 - self.trade_ratio), #price < boll_poss[2], #price < self.min_sell_price*(1-0.03), #boll_w > 2.5, #adx>45, #buy_count < 2, #pr.horizontal(df_five_hisdat), #0, ): num = trade_num #account.Order(0, code, price, num) if so.assemble( price < boll_poss[-1], price < pre_buy_price * (1 - self.trade_ratio), #price < self.min_sell_price*(1-0.03), #boll_w > 3, #buy_count < 2, #self.trade_status == self.enum.nothing, #adx>60, four < self.trade_four[0], #0, ): #加仓买入 num = account_mgr.getCurCanWei() * self.trade_num_ratio #self.trade_status = self.enum.boll_down if num > 0 and self.order(0, code, price, num): self._log( agl.utf8_to_ascii('二档买入%s, %.2f, %d' % (code, price, num))) #建首仓 if so.assemble( four < self.trade_four[0], canwei == 0, ): num = ac.ShouShu(account_mgr.total_money() * self.lowerhold / price) bSell = 0 self.order(bSell, code, price, num) #tick report if self.is_backtesting and self.is_tick_report: self._getAccount().TickReport(df_five_hisdat, 'win') return