Ejemplo n.º 1
0
    def toBuy(self, idx, data: _Data, ticker: str, kwargs: dict) -> bool:

        ma12 = kwargs['ma12']
        ma144 = kwargs['ma144']
        ma338 = kwargs['ma338']
        ma55 = kwargs['ma55']

        if crossover(ma12, ma338):
            print("Setting cross up at idx {} buy ".format(idx))
            self.lastCrossUp = 1
            self.lastCrossIdx = idx

        if crossover(ma338, ma12):
            print("Setting cross down at idx {} buy ".format(idx))
            self.lastCrossUp = -1
            self.lastCrossIdx = idx

        trendIdx = kwargs['trendIdx']

        if self.lastCrossUp == 1 and idx - self.lastCrossIdx < 48 and crossover(
                ma12, ma144):
            self.lastCrossUp = 0
            return True

        return False
Ejemplo n.º 2
0
    def next(self):

        if not self.position:

            # On upwards trend, if price closes above
            # "entry" MA, go long

            # Here, even though the operands are arrays, this
            # works by implicitly comparing the two last values
            if self.sma1 > self.sma2:
                if crossover(self.data.Close, self.sma_enter):
                    self.buy()

            # On downwards trend, if price closes below
            # "entry" MA, go short

            else:
                if crossover(self.sma_enter, self.data.Close):
                    self.sell()

        # But if we already hold a position and the price
        # closes back below (above) "exit" MA, close the position

        else:
            if (self.position.is_long
                    and crossover(self.sma_exit, self.data.Close)
                    or self.position.is_short
                    and crossover(self.data.Close, self.sma_exit)):

                self.position.close()
Ejemplo n.º 3
0
    def next(self):

        idx = self.close.shape[0]

        last_adx, last_atr, last_close, last_open = self.adx[-1], self.atr[-1], self.data.Close[-1],self.data.Open[-1]
        #self.printIfTrace(str(last_adx) + "," + str(last_atr))

        if self.adx[-1] > self.ADX_CUTOFF and not self.position and not self.orders:
            self.printIfTrace("return at: " + str(idx))
            return

        if self.adx[-1] > self.ADX_CUTOFF + 10 and (self.orders or self.position):
            self.printIfTrace("return at: " + str(idx))
            if not self.position and self.orders:
                self.orders.cancel()

            if self.position:
                self.position.close()
            return

        if self.adx[-1] < self.ADX_CUTOFF:

            ### close lower
            if crossover(self.ma12 - last_atr, self.close) and self.adx[-1] < self.adx[-2] and self.adx[-2] < self.adx[-3] and not self.position:
                price = self.data.Close[-1]#self.data.Low[-1] - self.ATR_RATIO * last_atr
                self.buy(price , sl =  price - self.PROFIT_RATIO * last_atr, tp= price + self.PROFIT_RATIO * last_atr)
                self.printIfTrace("Buy at index:" + str(idx))

            elif crossover(self.close, self.ma12 + last_atr) and self.adx[-1] < self.adx[-2] and self.adx[-2] < self.adx[-3] and not self.position:
                price = self.data.Close[-1] #self.data.High[-1] + self.ATR_RATIO * last_atr
                self.printIfTrace("Sell at index:" + str(idx))
                self.sell(price, sl =  price + self.PROFIT_RATIO * last_atr, tp= price - self.PROFIT_RATIO  * last_atr)
Ejemplo n.º 4
0
 def next(self):
     if crossover(self.data.Close, self.data.vwap):
         self.position.close()
         self.buy()
     elif crossover(self.data.vwap, self.data.Close):
         self.position.close()
         self.sell()
Ejemplo n.º 5
0
 def next(self):
     # If mal crosses above ma2 , buy the asset
     if crossover(self.ma1, self.ma2):
         self.buy()
     # Else , if mal crosses below ma2 , sell it
     elif crossover(self.ma2, self.ma1):
         self.sell()
Ejemplo n.º 6
0
    def next(self):
        # If sma1 crosses above sma2 buy the asset
        if crossover(self.sma1, self.sma2):
            self.buy()
# Else, if sma1 crosses below sma2 sell the asset
        elif crossover(self.sma2, self.sma1):
            self.position.close()
Ejemplo n.º 7
0
 def next(self):
     if crossover(self.sma1, self.sma2):
         self.position.close()
         self.buy()
     elif crossover(self.sma2, self.sma1):
         self.position.close()
         self.sell()
Ejemplo n.º 8
0
 def next(self):
     if self.buy_price == 0 and crossover(self.ma1, self.ma2):
         self.buy()
         self.buy_price = self.data.Close[-1]
     elif self.buy_price != 0 and crossover(self.ma2, self.ma1):
         self.position.close()
         self.buy_price = 0
Ejemplo n.º 9
0
    def next(self):
        if crossover(self.ma1, self.ma2) and self.orderPending is False:
            self.buy()
            self.orderPending = True

        if crossover(self.ma2, self.ma1) and self.orderPending is True:
            self.position.close()
            self.orderPending = False
Ejemplo n.º 10
0
    def next(self):
        # If sma1 crosses above sma2, buy the asset
        if crossover(self.sma1, self.sma2):
            self.buy()

        # Else, if sma1 crosses below sma2, sell it
        elif crossover(self.sma2, self.sma1):
            self.sell()
Ejemplo n.º 11
0
def iterate(broker, data):
    '''please note that broker, data and iterate are not related here,
    this objects are called by the stratmanager'''

    if crossover(data.sma_10, data.sma_20):
        broker.buy()
    elif crossover(data.sma_20, data.sma_10):
        broker.sell()
Ejemplo n.º 12
0
def iterate(broker, data):

    data.sma_10 = list(broker.prices.Close.rolling(10).mean())
    data.sma_20 = list(broker.prices.Close.rolling(20).mean())

    if crossover(data.sma_10, data.sma_20):
        broker.buy()
    elif crossover(data.sma_20, data.sma_10):
        broker.sell()
Ejemplo n.º 13
0
    def next(self):
        zero_l = self.data.Zero
        if crossover(self.ma1, zero_l) and self.orderPending is False:
            self.buy()
            self.orderPending = True

        if crossover(zero_l, self.ma1) and self.orderPending is True:
            self.position.close()
            self.orderPending = False
Ejemplo n.º 14
0
 def next(self):
     """
     ゴールデンクロスの時に買い、デッドクロスの時に売却する
     :return:
     """
     if crossover(self.sma1, self.sma2):
         self.buy()
     elif crossover(self.sma2, self.sma1):
         self.position.close()
Ejemplo n.º 15
0
    def next(self):

        stoploss_buy = 0.98*self.data.Close
        stoploss_sell = 0.02 * self.data.Close
        takeprofit_buy = 1.05*self.data.Close
        takeprofit_sell = 0.95 * self.data.Close

        #
        # First detect whether we are at a cross (UP or DOWN)
        #
        cross = 0
        # BULLISH SIGNAL
        if crossover(self.macd, self.macd_signal):
            cross = 1
        # BEARISH SIGNAL
        elif crossover(self.macd_signal, self.macd):
            cross = -1

        #print(f"current state={self.current_state} bar-cross={cross} MACD={self.macd[-1]} SIGNAL={self.macd_signal[-1]}")

        #
        # Weäre not looking and nothing happened, exit!
        #
        if self.current_state == 0 and cross == 0:
            return

        #
        # Are we currently LOOKING UP or DOWN?
        #
        if self.current_state == 0:
            # NO. Change to UP or DOWN.
            self.current_state = cross
        else:
            # YES. A cross will terminate that LOOKING state
            if cross != 0:
                self.current_state = 0



        if self.current_state != -1 and self.macd[-1] >= 0:
            #print(f"All is OK to take LONG position. Must check RSI though: {self.rsi[-1]}")
            self.position.close()
            #if self.rsi[-1] <= 30:
            #print(f"taking LONG position because of Signal {self.macd_signal[-2]} -> {self.macd_signal[-1]} MACD {self.macd[-2]} -> {self.macd[-1]} and  RSI({self.rsi[-1]})")
            self.buy(tp=takeprofit_buy)
            self.current_state = 0  # Not looking!
        else:
            if self.current_state != 1 and self.macd[-1] <= 0:
                #print(f"All is OK to take SHORT position. Must check RSI though: {self.rsi[-1]}")
                self.position.close()
                #if self.rsi[-1] >= 70:
                #print(
                #    f"taking SHORT position because of Signal {self.macd_signal[-2]} -> {self.macd_signal[-1]} MACD {self.macd[-2]} -> {self.macd[-1]} and  RSI({self.rsi[-1]})")
                self.sell(tp=takeprofit_sell)
                self.current_state = 0  # Not looking!

        #print("--- done with this bar ---")
Ejemplo n.º 16
0
 def next(self) -> int:
     if crossover(self.sma_A, self.sma_B) and crossover(
             self.sma_C, self.sma_D):
         return 1
     elif crossover(self.sma_B, self.sma_A) and crossover(
             self.sma_D, self.sma_C):
         return -1
     # Default value for transaction!
     return 0
Ejemplo n.º 17
0
 def next(self):
     if crossover(self.ma1, self.ma2):
         # if self.position.is_short:
         #     self.()
         self.buy()
     elif crossover(self.ma2, self.ma1):
         # if self.position.is_long:
         #     self.position.close()
         self.sell()
Ejemplo n.º 18
0
 def next(self):
     '''
     RSIが上限値を超えたら買われすぎと判断し売る
     RSIが下限値を下回ったら売られすぎと判断し買う
     '''
     if crossover(self.rsi_lower, self.rsi):
         self.buy()
     elif crossover(self.rsi, self.rsi_upper):
         self.sell()
Ejemplo n.º 19
0
 def next(self):
     # If mal crosses above ma2 , buy the asset
     if crossover(series1=self.ma1, series2=self.ma2):
         # Return True if series1 just crossed over series2.
         # https://kernc.github.io/backtesting.py/doc/backtesting/lib.html
         self.buy()
         # https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html
     # Else , if mal crosses below ma2 , sell it
     elif crossover(series1=self.ma2, series2=self.ma1):
         self.sell()
Ejemplo n.º 20
0
    def next(self):
        # If fast SMA crosses above slow SMA
        if crossover(self.fast_sma, self.slow_sma):
            if self.long_only == 0:
                self.position.close()
            self.buy()

        # Else, if fast SMA crosses below slow SMA
        elif crossover(self.slow_sma, self.fast_sma):
            self.position.close()
            if self.long_only == 0:
                self.sell()
Ejemplo n.º 21
0
    def next(self):
        # If sma1 crosses above sma2, close any existing
        # short trades, and buy the asset
        if crossover(self.sma1, self.sma2):
            self.position.close()
            self.buy()

        # Else, if sma1 crosses below sma2, close any existing
        # long trades, and sell the asset
        elif crossover(self.sma2, self.sma1):
            self.position.close()
            self.sell()
Ejemplo n.º 22
0
    def next(self):
        # If MACD crosses above signal line
        if crossover(self.macd, self.macdsignal):
            if self.long_only == 0:
                self.position.close()
            self.buy()

        # Else, if MACD crosses below signal line
        elif crossover(self.macdsignal, self.macd):
            self.position.close()
            if self.long_only == 0:
                self.sell()
Ejemplo n.º 23
0
 def next(self):
     macd = self.data.macd[self.index]
     macd_sig = self.data.macd_signal[self.index]
     sell_cross = crossover(self.data.vwap, self.data.Close)
     sell_macd_sig = macd < macd_sig
     volume_increasing = self.data.Volume[self.index] > self.data.Volume[
         self.index - 1]
     is_hollow = self.hollow[self.index]
     momentum_increasing = abs(self.differences[self.index]) < abs(self.differences[self.index-1]) \
                     and abs(self.differences[self.index-1]) < abs(self.differences[self.index-2]) \
                     and self.data.heikincloses[self.index] > self.data.heikinlows[self.index]
     check_top = (self.data.heikinopens[self.index] - self.data.heikinhighs[
         self.index]) / self.data.heikinhighs[self.index] < 0.05
     check_bottom = (self.data.heikinopens[self.index] -
                     self.data.heikinlows[self.index]
                     ) / self.data.heikinlows[self.index] < 0.05
     buy_heikin = is_hollow and momentum_increasing and not (
         self.hasStock) and check_bottom
     sell_heikin = not (is_hollow) and not (
         momentum_increasing) and self.hasStock and check_top
     if buy_heikin:
         self.buy()
         self.hasStock = True
     elif (sell_cross or sell_macd_sig or sell_heikin
           or not (volume_increasing)) and self.hasStock:
         self.sell()
         self.hasStock = False
     self.index += 1
Ejemplo n.º 24
0
    def next(self):
        # If sma1 crosses above sma2, buy the asset
        if crossover(self.sma1, self.sma2) and crossover(self.sma3, self.sma4):
            try:
                print("Is buying...")
                self.buy()
            except:
                log.error("Something went wrong in buy() function!")

        # Else, if sma1 crosses below sma2, sell it
        elif crossover(self.sma2, self.sma1) and crossover(
                self.sma4, self.sma3):
            try:
                self.sell()
            except:
                log.error("Something went wrong in sell() function!")
Ejemplo n.º 25
0
            def next(self, FIVE_DAYS=pd.Timedelta('3 days')):
                assert self.equity >= 0

                assert isinstance(self.sma, _Indicator)
                assert isinstance(self.remains_indicator, _Indicator)
                assert self.remains_indicator.name
                assert isinstance(self.remains_indicator._opts, dict)

                assert not np.isnan(self.data.Open[-1])
                assert not np.isnan(self.data.High[-1])
                assert not np.isnan(self.data.Low[-1])
                assert not np.isnan(self.data.Close[-1])
                assert not np.isnan(self.data.Volume[-1])
                assert not np.isnan(self.sma[-1])
                assert self.data.index[-1]

                self.orders.is_long
                self.orders.is_short
                self.orders.entry
                self.orders.sl
                self.orders.tp

                self.position
                self.position.size
                self.position.pl
                self.position.pl_pct
                self.position.open_price
                self.position.open_time
                self.position.is_long

                if crossover(self.sma, self.data.Close):
                    self.orders.cancel()
                    self.sell()
                    assert not self.orders.is_long
                    assert self.orders.is_short
                    assert self.orders.entry
                    assert not self.orders.sl
                    assert not self.orders.tp
                    price = self.data.Close[-1]
                    sl, tp = 1.05 * price, .9 * price
                    self.sell(price, sl=sl, tp=tp)
                    self.orders.set_entry(price)
                    self.orders.set_sl(sl)
                    self.orders.set_tp(tp)
                    assert self.orders.entry == price
                    assert self.orders.sl == sl
                    assert self.orders.tp == tp

                elif self.position:
                    assert not self.orders.entry
                    assert not self.position.is_long
                    assert not not self.position.is_short
                    assert self.position.open_price
                    assert self.position.pl
                    assert self.position.pl_pct
                    assert self.position.size < 0
                    if self.data.index[
                            -1] - self.position.open_time > FIVE_DAYS:
                        self.position.close()
Ejemplo n.º 26
0
    def next(self):
        if (self.l1 > self.l2) and crossover(self.k1, self.k2):
            self.buy()
            self.orders.set_tp(self.data.Close[-1]*(1 + (self.profit/1000)))
            self.orders.set_sl(self.data.Close[-1]*0.99)

        elif (self.l1 < self.l2) and crossover(self.k2, self.k1):
            self.sell()
            self.orders.set_tp(self.data.Close[-1]*(1 - (self.profit/1000)))
            self.orders.set_sl(self.data.High[-1]*1.01)

        if self.position and self.position.is_long and (
                crossover(self.k1, self.k2)):
            self.position.close()

        elif self.position and self.position.is_short and (
                crossover(self.k2, self.k1)):
            self.position.close()
Ejemplo n.º 27
0
 def toSell(self, idx, data: _Data, ticker: str, **kwargs) -> bool:
     ma12 = kwargs['ma12']
     ma55 = kwargs['ma55']
     ma169 = kwargs['ma169']
     trendIdx = kwargs['trendIdx']
     atr = kwargs['atr']
     return trendIdx[-1] < -atr[-1] * 1.5 and crossover(
         data.Close + atr[-1] * 0.5, ma12
     ) and ma55[-1] < ma169[
         -1]  #and ma169[-1] < ma55[-1] + 0.0060 and and np.diff(trendIdx[-5:]).mean() < np.diff(trendIdx[-10:-5]).mean()
Ejemplo n.º 28
0
 def next(self):
     prices = self.data.Close
     last_price = prices[-1]
     # if self.buy_price == 0 and crossover(self.ma1, self.ma2) and crossover(prices, self.ma3) and crossover(prices, self.ma4):
     if self.buy_price == 0 and crossover(self.ma1, self.ma2):
         self.buy()
         self.buy_price = last_price
     elif self.buy_price != 0 and (
             TakeProfit.takeProfit(5, last_price, self.buy_price) or
             CutLoss.shouldCutLossByPercent(8, last_price, self.buy_price)):
         self.position.close()
         self.buy_price = 0
Ejemplo n.º 29
0
    def toBuy(self, idx, data: _Data, ticker: str, **kwargs) -> bool:

        ma12 = kwargs['ma12']
        ma55 = kwargs['ma55']
        ma169 = kwargs['ma169']
        trendIdx = kwargs['trendIdx']
        atr = kwargs['atr']
        ### if strong trend exists and cross over ma169
        return trendIdx[-1] > atr[-1] * 1.5 and crossover(
            ma12, data.Close - atr[-1] * 0.5
        ) and ma55[-1] > ma169[
            -1]  #and ma55[-1] > ma169[-1] + 0.0060 and np.diff(trendIdx[-5:]).mean() > np.diff(trendIdx[-10:-5]).mean()
Ejemplo n.º 30
0
    def toSell(self, idx, data: _Data, ticker: str, kwargs: dict) -> bool:
        ma12 = kwargs['ma12']
        ma55 = kwargs['ma55']
        ma169 = kwargs['ma169']
        trendIdx = kwargs['trendIdx']
        atr = kwargs['atr']

        return crossover((ma55 + ma169) / 2, ma12) \
                   and data.Close[-1] < ma12[-1]  \
                   and data.Close[-2] < ma55[-2]\
                   and data.Close[-1] < ma55[-1] \
                   and ma55[-1] < (ma169[-1] + abs(trendIdx[-1] * 0.5)) \