Exemplo n.º 1
0
def test_hyperopt_parameters():
    from skopt.space import Categorical, Integer, Real
    with pytest.raises(OperationalException, match=r"Name is determined.*"):
        IntParameter(low=0, high=5, default=1, name='hello')

    with pytest.raises(OperationalException,
                       match=r"IntParameter space must be.*"):
        IntParameter(low=0, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"RealParameter space must be.*"):
        RealParameter(low=0, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"DecimalParameter space must be.*"):
        DecimalParameter(low=0, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"IntParameter space invalid\."):
        IntParameter([0, 10], high=7, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"RealParameter space invalid\."):
        RealParameter([0, 10], high=7, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"DecimalParameter space invalid\."):
        DecimalParameter([0, 10], high=7, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"CategoricalParameter space must.*"):
        CategoricalParameter(['aa'], default='aa', space='buy')

    with pytest.raises(TypeError):
        BaseParameter(opt_range=[0, 1], default=1, space='buy')

    intpar = IntParameter(low=0, high=5, default=1, space='buy')
    assert intpar.value == 1
    assert isinstance(intpar.get_space(''), Integer)

    fltpar = RealParameter(low=0.0, high=5.5, default=1.0, space='buy')
    assert isinstance(fltpar.get_space(''), Real)
    assert fltpar.value == 1

    fltpar = DecimalParameter(low=0.0,
                              high=5.5,
                              default=1.0004,
                              decimals=3,
                              space='buy')
    assert isinstance(fltpar.get_space(''), Integer)
    assert fltpar.value == 1
    fltpar._set_value(2222)
    assert fltpar.value == 2.222

    catpar = CategoricalParameter(['buy_rsi', 'buy_macd', 'buy_none'],
                                  default='buy_macd',
                                  space='buy')
    assert isinstance(catpar.get_space(''), Categorical)
    assert catpar.value == 'buy_macd'
Exemplo n.º 2
0
def test_hyperopt_parameters():
    from skopt.space import Categorical, Integer, Real
    with pytest.raises(OperationalException, match=r"Name is determined.*"):
        IntParameter(low=0, high=5, default=1, name='hello')

    with pytest.raises(OperationalException,
                       match=r"IntParameter space must be.*"):
        IntParameter(low=0, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"RealParameter space must be.*"):
        RealParameter(low=0, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"DecimalParameter space must be.*"):
        DecimalParameter(low=0, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"IntParameter space invalid\."):
        IntParameter([0, 10], high=7, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"RealParameter space invalid\."):
        RealParameter([0, 10], high=7, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"DecimalParameter space invalid\."):
        DecimalParameter([0, 10], high=7, default=5, space='buy')

    with pytest.raises(OperationalException,
                       match=r"CategoricalParameter space must.*"):
        CategoricalParameter(['aa'], default='aa', space='buy')

    with pytest.raises(TypeError):
        BaseParameter(opt_range=[0, 1], default=1, space='buy')

    intpar = IntParameter(low=0, high=5, default=1, space='buy')
    assert intpar.value == 1
    assert isinstance(intpar.get_space(''), Integer)
    assert isinstance(intpar.range, range)
    assert len(list(intpar.range)) == 1
    # Range contains ONLY the default / value.
    assert list(intpar.range) == [intpar.value]
    intpar.in_space = True

    assert len(list(intpar.range)) == 6
    assert list(intpar.range) == [0, 1, 2, 3, 4, 5]

    fltpar = RealParameter(low=0.0, high=5.5, default=1.0, space='buy')
    assert isinstance(fltpar.get_space(''), Real)
    assert fltpar.value == 1

    fltpar = DecimalParameter(low=0.0,
                              high=5.5,
                              default=1.0004,
                              decimals=3,
                              space='buy')
    assert isinstance(fltpar.get_space(''), Integer)
    assert fltpar.value == 1

    catpar = CategoricalParameter(['buy_rsi', 'buy_macd', 'buy_none'],
                                  default='buy_macd',
                                  space='buy')
    assert isinstance(catpar.get_space(''), Categorical)
    assert catpar.value == 'buy_macd'
Exemplo n.º 3
0
class mabStra(IStrategy):

    # #################### RESULTS PASTE PLACE ####################
    # ROI table:
    minimal_roi = {"0": 0.598, "644": 0.166, "3269": 0.115, "7289": 0}

    # Stoploss:
    stoploss = -0.128
    # Buy hypers
    timeframe = '4h'

    # #################### END OF RESULT PLACE ####################

    # buy params
    buy_mojo_ma_timeframe = IntParameter(2, 100, default=7, space='buy')
    buy_fast_ma_timeframe = IntParameter(2, 100, default=14, space='buy')
    buy_slow_ma_timeframe = IntParameter(2, 100, default=28, space='buy')
    buy_div_max = DecimalParameter(0,
                                   2,
                                   decimals=4,
                                   default=2.25446,
                                   space='buy')
    buy_div_min = DecimalParameter(0,
                                   2,
                                   decimals=4,
                                   default=0.29497,
                                   space='buy')
    # sell params
    sell_mojo_ma_timeframe = IntParameter(2, 100, default=7, space='sell')
    sell_fast_ma_timeframe = IntParameter(2, 100, default=14, space='sell')
    sell_slow_ma_timeframe = IntParameter(2, 100, default=28, space='sell')
    sell_div_max = DecimalParameter(0,
                                    2,
                                    decimals=4,
                                    default=1.54593,
                                    space='sell')
    sell_div_min = DecimalParameter(0,
                                    2,
                                    decimals=4,
                                    default=2.81436,
                                    space='sell')

    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # SMA - ex Moving Average
        dataframe['buy-mojoMA'] = ta.SMA(
            dataframe, timeperiod=self.buy_mojo_ma_timeframe.value)
        dataframe['buy-fastMA'] = ta.SMA(
            dataframe, timeperiod=self.buy_fast_ma_timeframe.value)
        dataframe['buy-slowMA'] = ta.SMA(
            dataframe, timeperiod=self.buy_slow_ma_timeframe.value)
        dataframe['sell-mojoMA'] = ta.SMA(
            dataframe, timeperiod=self.sell_mojo_ma_timeframe.value)
        dataframe['sell-fastMA'] = ta.SMA(
            dataframe, timeperiod=self.sell_fast_ma_timeframe.value)
        dataframe['sell-slowMA'] = ta.SMA(
            dataframe, timeperiod=self.sell_slow_ma_timeframe.value)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame,
                           metadata: dict) -> DataFrame:

        dataframe.loc[(
            (dataframe['buy-mojoMA'].div(dataframe['buy-fastMA']) > self.
             buy_div_min.value) &
            (dataframe['buy-mojoMA'].div(dataframe['buy-fastMA']) < self.
             buy_div_max.value) &
            (dataframe['buy-fastMA'].div(dataframe['buy-slowMA']) > self.
             buy_div_min.value) &
            (dataframe['buy-fastMA'].div(dataframe['buy-slowMA']) < self.
             buy_div_max.value)), 'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe.loc[(
            (dataframe['sell-fastMA'].div(dataframe['sell-mojoMA']) > self.
             sell_div_min.value) &
            (dataframe['sell-fastMA'].div(dataframe['sell-mojoMA']) < self.
             sell_div_max.value) &
            (dataframe['sell-slowMA'].div(dataframe['sell-fastMA']) > self.
             sell_div_min.value) &
            (dataframe['sell-slowMA'].div(dataframe['sell-fastMA']) < self.
             sell_div_max.value)), 'sell'] = 1
        return dataframe
Exemplo n.º 4
0
class Heracles(IStrategy):
    ########################################## RESULT PASTE PLACE ##########################################
    # 10/100:     25 trades. 18/4/3 Wins/Draws/Losses. Avg profit   5.92%. Median profit   6.33%. Total profit  0.04888306 BTC (  48.88Σ%). Avg duration 4 days, 6:24:00 min. Objective: -11.42103

    # Buy hyperspace params:
    buy_params = {
        "buy_crossed_indicator_shift": 9,
        "buy_div_max": 0.75,
        "buy_div_min": 0.16,
        "buy_indicator_shift": 15,
    }

    # Sell hyperspace params:
    sell_params = {}

    # ROI table:
    minimal_roi = {"0": 0.598, "644": 0.166, "3269": 0.115, "7289": 0}

    # Stoploss:
    stoploss = -0.256

    # Optimal timeframe use it in your config
    timeframe = '4h'

    ########################################## END RESULT PASTE PLACE ######################################

    # buy params
    buy_div_min = DecimalParameter(0, 1, default=0.16, decimals=2, space='buy')
    buy_div_max = DecimalParameter(0, 1, default=0.75, decimals=2, space='buy')
    buy_indicator_shift = IntParameter(0, 20, default=16, space='buy')
    buy_crossed_indicator_shift = IntParameter(0, 20, default=9, space='buy')

    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe = dropna(dataframe)

        dataframe['volatility_kcw'] = ta.volatility.keltner_channel_wband(
            dataframe['high'],
            dataframe['low'],
            dataframe['close'],
            window=20,
            window_atr=10,
            fillna=False,
            original_version=True)

        dataframe['volatility_dcp'] = ta.volatility.donchian_channel_pband(
            dataframe['high'],
            dataframe['low'],
            dataframe['close'],
            window=10,
            offset=0,
            fillna=False)

        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame,
                           metadata: dict) -> DataFrame:
        """
        Buy strategy Hyperopt will build and use.
        """
        conditions = []

        IND = 'volatility_dcp'
        CRS = 'volatility_kcw'
        DFIND = dataframe[IND]
        DFCRS = dataframe[CRS]

        d = DFIND.shift(self.buy_indicator_shift.value).div(
            DFCRS.shift(self.buy_crossed_indicator_shift.value))

        # print(d.min(), "\t", d.max())
        conditions.append(
            d.between(self.buy_div_min.value, self.buy_div_max.value))

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        """
        Sell strategy Hyperopt will build and use.
        """
        dataframe.loc[:, 'sell'] = 0
        return dataframe
Exemplo n.º 5
0
class Zeus(IStrategy):

    # *    1/43:     86 trades. 72/6/8 Wins/Draws/Losses. Avg profit  12.66%. Median profit  11.99%. Total profit  0.10894395 BTC ( 108.94Σ%). Avg duration 3 days, 0:31:00 min. Objective: -48.48793
    # "max_open_trades": 10,
    # "stake_currency": "BTC",
    # "stake_amount": 0.01,
    # "tradable_balance_ratio": 0.99,
    # "timeframe": "4h",
    # "dry_run_wallet": 0.1,

    # Buy hyperspace params:
    buy_params = {
        "buy_cat": "<R",
        "buy_real": 0.0128,
    }

    # Sell hyperspace params:
    sell_params = {
        "sell_cat": "=R",
        "sell_real": 0.9455,
    }

    # ROI table:
    minimal_roi = {"0": 0.564, "567": 0.273, "2814": 0.12, "7675": 0}

    # Stoploss:
    stoploss = -0.256

    buy_real = DecimalParameter(0.001,
                                0.999,
                                decimals=4,
                                default=0.11908,
                                space='buy')
    buy_cat = CategoricalParameter([">R", "=R", "<R"],
                                   default='<R',
                                   space='buy')
    sell_real = DecimalParameter(0.001,
                                 0.999,
                                 decimals=4,
                                 default=0.59608,
                                 space='sell')
    sell_cat = CategoricalParameter([">R", "=R", "<R"],
                                    default='>R',
                                    space='sell')

    # Buy hypers
    timeframe = '4h'

    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # Add all ta features

        dataframe['trend_ichimoku_base'] = ta.trend.ichimoku_base_line(
            dataframe['high'],
            dataframe['low'],
            window1=9,
            window2=26,
            visual=False,
            fillna=False)
        KST = ta.trend.KSTIndicator(close=dataframe['close'],
                                    roc1=10,
                                    roc2=15,
                                    roc3=20,
                                    roc4=30,
                                    window1=10,
                                    window2=10,
                                    window3=10,
                                    window4=15,
                                    nsig=9,
                                    fillna=False)

        dataframe['trend_kst_diff'] = KST.kst_diff()

        # Normalization
        tib = dataframe['trend_ichimoku_base']
        dataframe['trend_ichimoku_base'] = (tib - tib.min()) / (tib.max() -
                                                                tib.min())
        tkd = dataframe['trend_kst_diff']
        dataframe['trend_kst_diff'] = (tkd - tkd.min()) / (tkd.max() -
                                                           tkd.min())
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame,
                           metadata: dict) -> DataFrame:
        conditions = []
        IND = 'trend_ichimoku_base'
        REAL = self.buy_real.value
        OPR = self.buy_cat.value
        DFIND = dataframe[IND]
        # print(DFIND.mean())
        if OPR == ">R":
            conditions.append(DFIND > REAL)
        elif OPR == "=R":
            conditions.append(np.isclose(DFIND, REAL))
        elif OPR == "<R":
            conditions.append(DFIND < REAL)

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        conditions = []
        IND = 'trend_kst_diff'
        REAL = self.sell_real.value
        OPR = self.sell_cat.value
        DFIND = dataframe[IND]
        # print(DFIND.mean())

        if OPR == ">R":
            conditions.append(DFIND > REAL)
        elif OPR == "=R":
            conditions.append(np.isclose(DFIND, REAL))
        elif OPR == "<R":
            conditions.append(DFIND < REAL)

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1

        return dataframe
Exemplo n.º 6
0
class GodStraNew(IStrategy):
    # #################### RESULTS PASTE PLACE ####################

    # #################### END OF RESULT PLACE ####################

    # TODO: Its not dry code!
    # Buy Hyperoptable Parameters/Spaces.
    buy_crossed_indicator0 = CategoricalParameter(god_genes_with_timeperiod,
                                                  default="ADD-20",
                                                  space='buy')
    buy_crossed_indicator1 = CategoricalParameter(god_genes_with_timeperiod,
                                                  default="ASIN-6",
                                                  space='buy')
    buy_crossed_indicator2 = CategoricalParameter(god_genes_with_timeperiod,
                                                  default="CDLEVENINGSTAR-50",
                                                  space='buy')

    buy_indicator0 = CategoricalParameter(god_genes_with_timeperiod,
                                          default="SMA-100",
                                          space='buy')
    buy_indicator1 = CategoricalParameter(god_genes_with_timeperiod,
                                          default="WILLR-50",
                                          space='buy')
    buy_indicator2 = CategoricalParameter(god_genes_with_timeperiod,
                                          default="CDLHANGINGMAN-20",
                                          space='buy')

    buy_operator0 = CategoricalParameter(operators, default="/<R", space='buy')
    buy_operator1 = CategoricalParameter(operators, default="<R", space='buy')
    buy_operator2 = CategoricalParameter(operators, default="CB", space='buy')

    buy_real_num0 = DecimalParameter(0,
                                     1,
                                     decimals=DECIMALS,
                                     default=0.89009,
                                     space='buy')
    buy_real_num1 = DecimalParameter(0,
                                     1,
                                     decimals=DECIMALS,
                                     default=0.56953,
                                     space='buy')
    buy_real_num2 = DecimalParameter(0,
                                     1,
                                     decimals=DECIMALS,
                                     default=0.38365,
                                     space='buy')

    # Sell Hyperoptable Parameters/Spaces.
    sell_crossed_indicator0 = CategoricalParameter(
        god_genes_with_timeperiod, default="CDLSHOOTINGSTAR-150", space='sell')
    sell_crossed_indicator1 = CategoricalParameter(god_genes_with_timeperiod,
                                                   default="MAMA-1-100",
                                                   space='sell')
    sell_crossed_indicator2 = CategoricalParameter(god_genes_with_timeperiod,
                                                   default="CDLMATHOLD-6",
                                                   space='sell')

    sell_indicator0 = CategoricalParameter(god_genes_with_timeperiod,
                                           default="CDLUPSIDEGAP2CROWS-5",
                                           space='sell')
    sell_indicator1 = CategoricalParameter(god_genes_with_timeperiod,
                                           default="CDLHARAMICROSS-150",
                                           space='sell')
    sell_indicator2 = CategoricalParameter(god_genes_with_timeperiod,
                                           default="CDL2CROWS-5",
                                           space='sell')

    sell_operator0 = CategoricalParameter(operators,
                                          default="<R",
                                          space='sell')
    sell_operator1 = CategoricalParameter(operators, default="D", space='sell')
    sell_operator2 = CategoricalParameter(operators,
                                          default="/>R",
                                          space='sell')

    sell_real_num0 = DecimalParameter(0,
                                      1,
                                      decimals=DECIMALS,
                                      default=0.09731,
                                      space='sell')
    sell_real_num1 = DecimalParameter(0,
                                      1,
                                      decimals=DECIMALS,
                                      default=0.81657,
                                      space='sell')
    sell_real_num2 = DecimalParameter(0,
                                      1,
                                      decimals=DECIMALS,
                                      default=0.87267,
                                      space='sell')

    # Stoploss:
    stoploss = -1
    # Buy hypers
    timeframe = '4h'

    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        '''
        It's good to calculate all indicators in all time periods here and so optimize the strategy.
        But this strategy can take much time to generate anything that may not use in his optimization.
        I just calculate the specific indicators in specific time period inside buy and sell strategy populator methods if needed.
        Also, this method (populate_indicators) just calculates default value of hyperoptable params
        so using this method have not big benefits instade of calculating useable things inside buy and sell trand populators
        '''
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame,
                           metadata: dict) -> DataFrame:

        conditions = list()

        # TODO: Its not dry code!
        buy_indicator = self.buy_indicator0.value
        buy_crossed_indicator = self.buy_crossed_indicator0.value
        buy_operator = self.buy_operator0.value
        buy_real_num = self.buy_real_num0.value
        condition, dataframe = condition_generator(dataframe, buy_operator,
                                                   buy_indicator,
                                                   buy_crossed_indicator,
                                                   buy_real_num)
        conditions.append(condition)
        # backup
        buy_indicator = self.buy_indicator1.value
        buy_crossed_indicator = self.buy_crossed_indicator1.value
        buy_operator = self.buy_operator1.value
        buy_real_num = self.buy_real_num1.value

        condition, dataframe = condition_generator(dataframe, buy_operator,
                                                   buy_indicator,
                                                   buy_crossed_indicator,
                                                   buy_real_num)
        conditions.append(condition)

        buy_indicator = self.buy_indicator2.value
        buy_crossed_indicator = self.buy_crossed_indicator2.value
        buy_operator = self.buy_operator2.value
        buy_real_num = self.buy_real_num2.value
        condition, dataframe = condition_generator(dataframe, buy_operator,
                                                   buy_indicator,
                                                   buy_crossed_indicator,
                                                   buy_real_num)
        conditions.append(condition)

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1

        # print(len(dataframe.keys()))

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        conditions = list()
        # TODO: Its not dry code!
        sell_indicator = self.sell_indicator0.value
        sell_crossed_indicator = self.sell_crossed_indicator0.value
        sell_operator = self.sell_operator0.value
        sell_real_num = self.sell_real_num0.value
        condition, dataframe = condition_generator(dataframe, sell_operator,
                                                   sell_indicator,
                                                   sell_crossed_indicator,
                                                   sell_real_num)
        conditions.append(condition)

        sell_indicator = self.sell_indicator1.value
        sell_crossed_indicator = self.sell_crossed_indicator1.value
        sell_operator = self.sell_operator1.value
        sell_real_num = self.sell_real_num1.value
        condition, dataframe = condition_generator(dataframe, sell_operator,
                                                   sell_indicator,
                                                   sell_crossed_indicator,
                                                   sell_real_num)
        conditions.append(condition)

        sell_indicator = self.sell_indicator2.value
        sell_crossed_indicator = self.sell_crossed_indicator2.value
        sell_operator = self.sell_operator2.value
        sell_real_num = self.sell_real_num2.value
        condition, dataframe = condition_generator(dataframe, sell_operator,
                                                   sell_indicator,
                                                   sell_crossed_indicator,
                                                   sell_real_num)
        conditions.append(condition)

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1
        return dataframe
Exemplo n.º 7
0
class mabStra(IStrategy):
    # buy params
    buy_mojo_ma_timeframe = IntParameter(2, 100, default=7, space='buy')
    buy_fast_ma_timeframe = IntParameter(2, 100, default=14, space='buy')
    buy_slow_ma_timeframe = IntParameter(2, 100, default=28, space='buy')
    buy_div_max = DecimalParameter(0, 2, decimals=4, default=2.25446, space='buy')
    buy_div_min = DecimalParameter(0, 2, decimals=4, default=0.29497, space='buy')
    # sell params
    sell_mojo_ma_timeframe = IntParameter(2, 100, default=7, space='sell')
    sell_fast_ma_timeframe = IntParameter(2, 100, default=14, space='sell')
    sell_slow_ma_timeframe = IntParameter(2, 100, default=28, space='sell')
    sell_div_max = DecimalParameter(0, 2, decimals=4, default=1.54593, space='sell')
    sell_div_min = DecimalParameter(0, 2, decimals=4, default=2.81436, space='sell')

    stoploss = -0.1

    # Optimal timeframe use it in your config
    timeframe = '4h'

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # SMA - ex Moving Average
        dataframe['buy-mojoMA'] = ta.SMA(dataframe,
                                         timeperiod=self.buy_mojo_ma_timeframe.value)
        dataframe['buy-fastMA'] = ta.SMA(dataframe,
                                         timeperiod=self.buy_fast_ma_timeframe.value)
        dataframe['buy-slowMA'] = ta.SMA(dataframe,
                                         timeperiod=self.buy_slow_ma_timeframe.value)
        dataframe['sell-mojoMA'] = ta.SMA(dataframe,
                                          timeperiod=self.sell_mojo_ma_timeframe.value)
        dataframe['sell-fastMA'] = ta.SMA(dataframe,
                                          timeperiod=self.sell_fast_ma_timeframe.value)
        dataframe['sell-slowMA'] = ta.SMA(dataframe,
                                          timeperiod=self.sell_slow_ma_timeframe.value)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        dataframe.loc[
            (
                (dataframe['buy-mojoMA'].div(dataframe['buy-fastMA'])
                    > self.buy_div_min.value) &
                (dataframe['buy-mojoMA'].div(dataframe['buy-fastMA'])
                    < self.buy_div_max.value) &
                (dataframe['buy-fastMA'].div(dataframe['buy-slowMA'])
                    > self.buy_div_min.value) &
                (dataframe['buy-fastMA'].div(dataframe['buy-slowMA'])
                    < self.buy_div_max.value)
            ),
            'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['sell-fastMA'].div(dataframe['sell-mojoMA'])
                    > self.sell_div_min.value) &
                (dataframe['sell-fastMA'].div(dataframe['sell-mojoMA'])
                    < self.sell_div_max.value) &
                (dataframe['sell-slowMA'].div(dataframe['sell-fastMA'])
                    > self.sell_div_min.value) &
                (dataframe['sell-slowMA'].div(dataframe['sell-fastMA'])
                    < self.sell_div_max.value)
            ),
            'sell'] = 1
        return dataframe
Exemplo n.º 8
0
class Diamond(IStrategy):
    # ###################### RESULT PLACE ######################
    #    Config: 5 x UNLIMITED STOCK costume pair list,
    #    hyperopt : 5000 x SortinoHyperOptLossDaily,
    #    34/5000: 297 trades. 136/156/5 Wins/Draws/Losses. Avg profit   0.49%. Median profit   0.00%. Total profit  45.84477237 USDT (  33.96Σ%). Avg duration 11:54:00 min. Objective: -46.50379

    # Buy hyperspace params:
    buy_params = {
        "buy_fast_key": "high",
        "buy_horizontal_push": 7,
        "buy_slow_key": "volume",
        "buy_vertical_push": 0.942,
    }

    # Sell hyperspace params:
    sell_params = {
        "sell_fast_key": "high",
        "sell_horizontal_push": 10,
        "sell_slow_key": "low",
        "sell_vertical_push": 1.184,
    }

    # ROI table:
    minimal_roi = {"0": 0.242, "13": 0.044, "51": 0.02, "170": 0}

    # Stoploss:
    stoploss = -0.271

    # Trailing stop:
    trailing_stop = True
    trailing_stop_positive = 0.011
    trailing_stop_positive_offset = 0.054
    trailing_only_offset_is_reached = False
    # timeframe
    timeframe = '5m'
    # #################### END OF RESULT PLACE ####################

    buy_vertical_push = DecimalParameter(0.5,
                                         1.5,
                                         decimals=3,
                                         default=1,
                                         space='buy')
    buy_horizontal_push = IntParameter(0, 10, default=0, space='buy')
    buy_fast_key = CategoricalParameter(
        [
            'open',
            'high',
            'low',
            'close',
            'volume',
            #  you can not enable this lines befour you
            #  populate an indicator for them and set
            #  the same key name for it
            #  'ma_fast', 'ma_slow', {...}
        ],
        default='ma_fast',
        space='buy')
    buy_slow_key = CategoricalParameter(
        [
            'open',
            'high',
            'low',
            'close',
            'volume',
            #  'ma_fast', 'ma_slow', {...}
        ],
        default='ma_slow',
        space='buy')

    sell_vertical_push = DecimalParameter(0.5,
                                          1.5,
                                          decimals=3,
                                          default=1,
                                          space='sell')
    sell_horizontal_push = IntParameter(0, 10, default=0, space='sell')
    sell_fast_key = CategoricalParameter(
        [
            'open',
            'high',
            'low',
            'close',
            'volume',
            #  'ma_fast', 'ma_slow', {...}
        ],
        default='ma_fast',
        space='sell')
    sell_slow_key = CategoricalParameter(
        [
            'open',
            'high',
            'low',
            'close',
            'volume',
            #  'ma_fast', 'ma_slow', {...}
        ],
        default='ma_slow',
        space='sell')

    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # you can add new indicators and enable them inside
        # hyperoptable categorical params on the top
        # dataframe['ma_fast'] = ta.SMA(dataframe, timeperiod=9)
        # dataframe['ma_slow'] = ta.SMA(dataframe, timeperiod=18)
        # dataframe['{...}'] = ta.{...}(dataframe, timeperiod={...})
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame,
                           metadata: dict) -> DataFrame:
        conditions = []
        conditions.append(
            qtpylib.crossed_above(
                dataframe[self.buy_fast_key.value].shift(
                    self.buy_horizontal_push.value),
                dataframe[self.buy_slow_key.value] *
                self.buy_vertical_push.value))

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        conditions = []
        conditions.append(
            qtpylib.crossed_below(
                dataframe[self.sell_fast_key.value].shift(
                    self.sell_horizontal_push.value),
                dataframe[self.sell_slow_key.value] *
                self.sell_vertical_push.value))
        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1
        return dataframe
Exemplo n.º 9
0
class Zeus(IStrategy):

    # 53/167:    167 trades. 96/66/5 Wins/Draws/Losses. Avg profit   3.00%. Median profit   2.70%. Total profit  0.16479843 BTC ( 164.80Σ%). Avg duration 22:04:00 min. Objective: -63.49577

    # Buy hyperspace params:
    buy_params = {
        "buy_cat": "<R",
        "buy_real": 0.0889,
    }

    # Sell hyperspace params:
    sell_params = {
        "sell_cat": "=R",
        "sell_real": 0.979,
    }

    # ROI table:
    minimal_roi = {"0": 0.336, "134": 0.113, "759": 0.027, "1049": 0}

    # Stoploss:
    stoploss = -0.245

    # Trailing stop:
    trailing_stop = True
    trailing_stop_positive = 0.35
    trailing_stop_positive_offset = 0.375
    trailing_only_offset_is_reached = False

    buy_real = DecimalParameter(0.001,
                                0.999,
                                decimals=4,
                                default=0.11908,
                                space='buy')
    buy_cat = CategoricalParameter([">R", "=R", "<R"],
                                   default='<R',
                                   space='buy')
    sell_real = DecimalParameter(0.001,
                                 0.999,
                                 decimals=4,
                                 default=0.59608,
                                 space='sell')
    sell_cat = CategoricalParameter([">R", "=R", "<R"],
                                    default='>R',
                                    space='sell')

    # Buy hypers
    timeframe = '4h'

    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # Add all ta features
        # Clean NaN values
        dataframe = dropna(dataframe)

        dataframe['trend_ichimoku_base'] = ta.trend.ichimoku_base_line(
            dataframe['high'],
            dataframe['low'],
            window1=9,
            window2=26,
            visual=False,
            fillna=False)
        KST = ta.trend.KSTIndicator(close=dataframe['close'],
                                    roc1=10,
                                    roc2=15,
                                    roc3=20,
                                    roc4=30,
                                    window1=10,
                                    window2=10,
                                    window3=10,
                                    window4=15,
                                    nsig=9,
                                    fillna=False)

        dataframe['trend_kst_diff'] = KST.kst_diff()

        # Normalization
        tib = dataframe['trend_ichimoku_base']
        dataframe['trend_ichimoku_base'] = (tib - tib.min()) / (tib.max() -
                                                                tib.min())
        tkd = dataframe['trend_kst_diff']
        dataframe['trend_kst_diff'] = (tkd - tkd.min()) / (tkd.max() -
                                                           tkd.min())
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame,
                           metadata: dict) -> DataFrame:
        conditions = []
        IND = 'trend_ichimoku_base'
        REAL = self.buy_real.value
        OPR = self.buy_cat.value
        DFIND = dataframe[IND]
        # print(DFIND.mean())
        if OPR == ">R":
            conditions.append(DFIND > REAL)
        elif OPR == "=R":
            conditions.append(np.isclose(DFIND, REAL))
        elif OPR == "<R":
            conditions.append(DFIND < REAL)

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        conditions = []
        IND = 'trend_kst_diff'
        REAL = self.sell_real.value
        OPR = self.sell_cat.value
        DFIND = dataframe[IND]
        # print(DFIND.mean())

        if OPR == ">R":
            conditions.append(DFIND > REAL)
        elif OPR == "=R":
            conditions.append(np.isclose(DFIND, REAL))
        elif OPR == "<R":
            conditions.append(DFIND < REAL)

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1

        return dataframe