def isThreeBarReversal(self, first, second): """A three-bar reversal pattern shows a turning point. Compared to the other reversal patterns, the three-bar reversal pattern is the most conservative one as it extends over three bars, using the third bar to confirm that the market has changed its direction. Bullish pattern: 1 - A bearish bar 2 - A bar has a lower high and lower low 3 - A bullish bar with a higher low and closes above the high of the second bar Bearish pattern: 1 - A bullish bar 2 - A bar has a higher high and higher low 3 - A bearish bar with a lower high and closes below the low of the second bar """ if self.isUp == second.isUp: return False if first.isUp != second.isUp: return False if self.isUp: if first.low < second.low and first.high < second.high: if self.low > first.low and self.close > second.close: prGreen("ThreeBarReversal - 1", self) self._actionType = "three_bar_reversal" return True else: if first.low > second.low and first.high < second.high: if self.low < first.low and self.close < second.close: prGreen("ThreeBarReversal - 2", self) self._actionType = "three_bar_reversal" return True return False
def isTwoBarReversal(self, first, second, third, trend): """The two-bar reversal pattern is made up of two strong bars closing in opposite directions. """ # None of the previous bars have big volume if any([b.volume >= self.average_volume * 2 for b in [first, second, third]]): return False # None of the previous bars can be higher than current if any([self.height < b.height for b in [first, second, third]]): return False if trend != self.isUp: return False if (first.isTall() and self.isTall()) and (first.isUp != self.isUp): if self.isUp and self.open >= first.close and self.height >= first.height: if self.isBarSequenceDown([first, second, third]): prGreen("TwoBarReversal - 1", self) self._actionType = "two_bar_reversal" return True elif not self.isUp and self.open <= first.close and self.height >= first.height: if self.isBarSequenceUp([first, second, third]): prGreen("TwoBarReversal - 2", self) self._actionType = "two_bar_reversal" return True return False
def isExhaustion(self, first): """ A bullish exhaustion bar opens with a gap down. Then, it works its way up to close near its top. A bearish exhaustion bar opens with a gap up before moving down to close as a bearish bar. In both cases, the gap remains unfilled. Also, high volume should occur with the exhaustion bar. When to buy/sell: - Buy above a bullish exhaustion bar - Sell below a bearish exhaustion bar Args: first (Bar): Previous bar to compare. """ if not self.volume > self.average_volume * 3: return False if self.isUp == first.isUp: return False if not self.isGap(first): return False prGreen("Exhaustion", self, ["ISUP", self.height, first.isUp]) self._actionType = "exhaustion" return True
def isReversal(self, first, trend): """ A bullish reversal bar pattern goes below the low of the previous bar before closing higher. A bearish reversal bar pattern goes above the high of the last bar before closing lower. When to buy/sell: - Buy above the bullish reversal bar in an uptrend - Sell below the bearish reversal bar in a downtrend Args: first (Bar): Previous bar to compare. trend (bool): True if its going UP, False if DOWN. """ if self.isUp == first.isUp or first.height <= 0.01: return False if self.isUp and trend: if self.close > first.close and self.low < first.low: #if not self.isNumberSimilar(self.open, first.close): # return False #if self.low <= first.low: prGreen("Reversal - 1", self, [trend]) self._actionType = "reversal" return True elif not self.isUp and not trend: if self.close < first.close and self.high > first.high: #if not self.isNumberSimilar(self.close, first.open): # return False #if self.high >= first.high: prGreen("Reversal - 2", self, [trend]) self._actionType = "reversal" return True return False
def isThreeBarPullBack(self, first, second, third): if not self.isTall(): return False if any([not b.isShort(self) for b in [first, second, third]]): return False if self.isUp and all([not b.isUp for b in [first, second, third]]): # Los lows no pueden ser menores que self. if all([self.low < b.low for b in [first, second, third]]): prGreen("ThreePullback - 1", self) self._actionType = "three_reversal_pullback" return True if not self.isUp and all([b.isUp for b in [first, second, third]]): if all([self.high > b.high for b in [first, second, third]]): prGreen("ThreePullback - 2", self) self._actionType = "three_reversal_pullback" return True return False
def start(self): try: print('Now: ', datetime.now().strftime('%Y-%m-%d %H:%M:%S')) pathnames = getPathnames(self.lessonDir, '.json') pathnames = sorted(pathnames, reverse=True) num = len(pathnames) sequenceNum = -1 while sequenceNum < 0 or sequenceNum >= num: prGreen('Please select a lesson you want to study:') for index in range(num): pathname = pathnames[index] prLightPurple('{:3}\t{}'.format(index + 1, pathname)) prGreen( 'Please input the sequence number (default is {}):'.format( num)) sequenceNum = stdinReadline(20, isPrompt=False) try: if len(sequenceNum) > 0: sequenceNum = int(sequenceNum) - 1 else: sequenceNum = num - 1 except ValueError as e: sequenceNum = num - 1 contentFile = pathnames[sequenceNum] prYellow('"{}" is selected.'.format(contentFile)) prGreen( 'Do you like to study or do a test?:\n\t1, study\n\t2, test\nPlease input sequence number (default is 2):' ) sequenceNum = stdinReadline(20, isPrompt=False) if '1' == sequenceNum: procedure = StudyProcedure(self.dirname, contentFile) else: procedure = TestProcedure(self.dirname, contentFile) procedure.run() except KeyboardInterrupt: pass except Exception as e: print('Error occurs at', datetime.now().strftime('%Y-%m-%d %H:%M:%S')) traceback.print_exc(file=sys.stdout) finally: pass
def isPinochio(self, first, trend): """ For bullish pin bars, the lower tail takes up most of the bar. For bearish pin bars, it is the upper tail that dominates. """ # error # Pinocho tiene que ver que la bara anterior este tambien similar a la # actual. b_trend = trend if self.height == 0.0: return False if b_trend: # UP with resistance to go DOWN. if self.isUp and (self.low - self.open) > self.height * 2: if first.low < self.low and first.high >= self.high: prGreen("Pinochio - 1", self, [trend]) self._actionType = "pinochio" return True # elif not self.isUp and (self.low - self.close) > self.height * 2: # if first.low < self.low and first.high >= self.high: # prGreen("Pinochio - 2", self, [trend]) # self._actionType = "pinochio" # return True else: # UP with resistance to continue UP #if self.isUp and (self.high - self.close) > self.height * 2: # if first.high < self.high and first.low <= self.low: # prGreen("Pinochio - 3", self, [trend]) # self._actionType = "pinochio" # return True if not self.isUp and (self.high - self.open) > self.height * 2: if first.high < self.high and first.low <= self.low: prGreen("Pinochio - 4", self, [trend]) self._actionType = "pinochio" return True return False
def step(self, action): # Pseudo prune and get the corresponding statistics. The real pruning happens till the end of all pseudo pruning if self.visited[self.cur_ind]: action = self.strategy_dict[self.prunable_idx[self.cur_ind]][0] preserve_idx = self.index_buffer[self.cur_ind] else: action = self._action_wall(action) # percentage to preserve preserve_idx = None # prune and update action action, d_prime, preserve_idx = self.prune_kernel( self.prunable_idx[self.cur_ind], action, preserve_idx) if not self.visited[self.cur_ind]: for group in self.shared_idx: if self.cur_ind in group: # set the shared ones for g_idx in group: self.strategy_dict[ self.prunable_idx[g_idx]][0] = action self.strategy_dict[self.prunable_idx[g_idx - 1]][1] = action self.visited[g_idx] = True self.index_buffer[g_idx] = preserve_idx.copy() if self.export_model: # export checkpoint print('# Pruning {}: ratio: {}, d_prime: {}'.format( self.cur_ind, action, d_prime)) self.strategy.append(action) # save action to strategy self.d_prime_list.append(d_prime) self.strategy_dict[self.prunable_idx[self.cur_ind]][0] = action if self.cur_ind > 0: self.strategy_dict[self.prunable_idx[self.cur_ind - 1]][1] = action # all the actions are made if self._is_final_layer(): # ====================== 通道剪裁================================== assert len(self.strategy) == len(self.prunable_idx) current_flops = self._cur_flops() acc_t1 = time.time() acc, acc_ = self._validate(self.val_loader, self.model) acc_t2 = time.time() self.val_time = acc_t2 - acc_t1 compress_ratio = current_flops * 1. / self.org_flops info_set = { 'compress_ratio': compress_ratio, 'accuracy': acc, 'strategy': self.strategy.copy(), 'accuracy_': acc_ } reward = self.reward(self, acc, current_flops) if reward > self.best_reward: self.best_reward = reward self.best_strategy = self.strategy.copy() self.best_d_prime_list = self.d_prime_list.copy() prGreen( 'New best reward: {:.4f}, {}: {:.4f}, acc_another:{},compress: {:.4f}' .format(self.best_reward, self.args.acc_metric, acc, acc_, compress_ratio)) prGreen('New best policy: {}'.format(self.best_strategy)) prGreen('New best d primes: {}'.format(self.best_d_prime_list)) obs = self.layer_embedding[ self.cur_ind, :].copy() # actually the same as the last state done = True if self.export_model: # export state dict torch.save(self.model.state_dict(), self.export_path) return None, None, None, None return obs, reward, done, info_set info_set = None reward = 0 done = False self.visited[self.cur_ind] = True # set to visited self.cur_ind += 1 # the index of next layer # build next state (in-place modify) self.layer_embedding[self.cur_ind][-3] = self._cur_reduced( ) * 1. / self.org_flops # reduced self.layer_embedding[self.cur_ind][-2] = sum( self.flops_list[self.cur_ind + 1:]) * 1. / self.org_flops # rest self.layer_embedding[self.cur_ind][-1] = self.strategy[ -1] # last action obs = self.layer_embedding[self.cur_ind, :].copy() return obs, reward, done, info_set