TA-Lib / ta-lib-python

Python wrapper for TA-Lib (http://ta-lib.org/).
http://ta-lib.github.io/ta-lib-python
Other
9.23k stars 1.72k forks source link

Create a MACD strategy with the 1d interval #405

Open MrKim42 opened 3 years ago

MrKim42 commented 3 years ago

Hello everyone,

i've been hurting my head for the past days trying to make a very simple MACD strategy on the 1D interval. When MACD crosses Up --> Buy When MACD crosses down --> Sell.

So, I know that the strategy "MultiRSI" should have helped me solve this issue... But I tried to update the MultiRSI to make it a 1d MACD strategy, but I can't figure it out.

Can someone help me?

Here is the code below:


# --- Do not remove these libs ---
from freqtrade.strategy.interface import IStrategy
from pandas import DataFrame
# --------------------------------
import talib.abstract as ta
from technical.util import resample_to_interval, resampled_merge
from technical.indicators import accumulation_distribution

class MultiMACD(IStrategy):
    """

    author@: Gert Wohlgemuth

    based on work from Creslin

    """
    minimal_roi = {
        "0": 0.01
    }

    # Optimal stoploss designed for the strategy
    stoploss = -0.05

    # Optimal timeframe for the strategy
    timeframe = '4h'

    def get_ticker_indicator(self):
        return int(self.timeframe[:-1])

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

        # resample our dataframes

        dataframe_short = resample_to_interval(dataframe, 60)
        dataframe_long = resample_to_interval(dataframe,  1440)

        # compute our MACD's
        dataframe_short['macd'] = ta.macd(dataframe_short, fastperiod=12, slowperiod=26, signalperiod=7)
        dataframe_long['macd'] = ta.macd(dataframe_long, fastperiod=12, slowperiod=26, signalperiod=7)

        # merge dataframe back together
        dataframe = resampled_merge(dataframe, dataframe_short)
        dataframe = resampled_merge(dataframe, dataframe_long)

        dataframe_short['macd'] = macd['macd']
        dataframe_short['macdsignal'] = macd['macdsignal']

        dataframe_long['macd'] = macd['macd']
        dataframe_long['macdsignal'] = macd['macdsignal']
        dataframe.fillna(method='ffill', inplace=True)

        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                 dataframe_long['macd']  > dataframe_long['macdsignal']

            ),
            'buy'] = 1
        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
               dataframe_long['macd']  < dataframe_long['macdsignal']
            ),
            'sell'] = 1
        return dataframe

This is the error I get from the terminal:

Traceback (most recent call last):
  File "/Users/Radu/freqtrade/freqtrade/main.py", line 37, in main
    return_code = args['func'](args)
  File "/Users/Radu/freqtrade/freqtrade/commands/optimize_commands.py", line 50, in start_backtesting
    backtesting.start()
  File "/Users/Radu/freqtrade/freqtrade/optimize/backtesting.py", line 447, in start
    min_date, max_date = self.backtest_one_strategy(strat, data, timerange)
  File "/Users/Radu/freqtrade/freqtrade/optimize/backtesting.py", line 407, in backtest_one_strategy
    preprocessed = self.strategy.ohlcvdata_to_dataframe(data)
  File "/Users/Radu/freqtrade/freqtrade/strategy/interface.py", line 669, in ohlcvdata_to_dataframe
    for pair, pair_data in data.items()}
  File "/Users/Radu/freqtrade/freqtrade/strategy/interface.py", line 669, in <dictcomp>
    for pair, pair_data in data.items()}
  File "/Users/Radu/freqtrade/freqtrade/strategy/interface.py", line 685, in advise_indicators
    return self.populate_indicators(dataframe, metadata)
  File "/Users/Radu/user_data/strategies/MultiMACD2.py", line 38, in populate_indicators
    dataframe_short['macd'] = ta.macd(dataframe_short, fastperiod=12, slowperiod=26, signalperiod=7)
AttributeError: module 'talib.abstract' has no attribute 'macd'

As always, thanks in advance for your help !!

mrjbq7 commented 3 years ago

Try ta.MACD instead of ta.macd...

MrKim42 commented 3 years ago

Try ta.MACD instead of ta.macd...

Thanks, it indeed changed what I got from the terminal, now this is the issue I get:

Traceback (most recent call last):
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3080, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'macd'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/generic.py", line 3826, in _set_item
    loc = self._info_axis.get_loc(key)
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: 'macd'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Radu/freqtrade/freqtrade/main.py", line 37, in main
    return_code = args['func'](args)
  File "/Users/Radu/freqtrade/freqtrade/commands/optimize_commands.py", line 50, in start_backtesting
    backtesting.start()
  File "/Users/Radu/freqtrade/freqtrade/optimize/backtesting.py", line 447, in start
    min_date, max_date = self.backtest_one_strategy(strat, data, timerange)
  File "/Users/Radu/freqtrade/freqtrade/optimize/backtesting.py", line 407, in backtest_one_strategy
    preprocessed = self.strategy.ohlcvdata_to_dataframe(data)
  File "/Users/Radu/freqtrade/freqtrade/strategy/interface.py", line 669, in ohlcvdata_to_dataframe
    for pair, pair_data in data.items()}
  File "/Users/Radu/freqtrade/freqtrade/strategy/interface.py", line 669, in <dictcomp>
    for pair, pair_data in data.items()}
  File "/Users/Radu/freqtrade/freqtrade/strategy/interface.py", line 685, in advise_indicators
    return self.populate_indicators(dataframe, metadata)
  File "/Users/Radu/user_data/strategies/MultiMACD2.py", line 38, in populate_indicators
    dataframe_short['macd'] = ta.MACD(dataframe_short, fastperiod=12, slowperiod=26, signalperiod=7)
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/frame.py", line 3163, in __setitem__
    self._set_item(key, value)
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/frame.py", line 3243, in _set_item
    NDFrame._set_item(self, key, value)
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/generic.py", line 3829, in _set_item
    self._mgr.insert(len(self._info_axis), key, value)
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/internals/managers.py", line 1203, in insert
    block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/internals/blocks.py", line 2732, in make_block
    return klass(values, ndim=ndim, placement=placement)
  File "/Users/Radu/.env/lib/python3.7/site-packages/pandas/core/internals/blocks.py", line 143, in __init__
    f"Wrong number of items passed {len(self.values)}, "
ValueError: Wrong number of items passed 3, placement implies 1
mrjbq7 commented 3 years ago

Looks like your issues are pandas related and not TA-Lib...

ClayReyn commented 3 years ago

@MrKim42 The ValueError is telling you your pandas container can only receive 1 input, but you're passing it 3. You can easily fix this by creating more containers. so NOT >> df['MACD'] = TA.MACD(df) instead >> df[['MACD', 'MACD_Signal_Line']] = TA.MACD(df) @mrjbq7 is correct, it's more of a pandas issue than a TA-Lib issue, I recommend searching your error on StackOverflow if you want more information.