Exemplo n.º 1
0
    def analyze_macd(self, historial_data, hot_thresh=None, cold_thresh=None):
        """Performs a macd analysis on the historical data

        Args:
            historial_data (list): A matrix of historical OHCLV data.
            hot_thresh (float, optional): Defaults to None. The threshold at which this might be good
                to purchase.
            cold_thresh (float, optional): Defaults to None. The threshold at which this might be good
                to sell.

        Returns:
            dict: A dictionary containing a tuple of indicator values and booleans for buy / sell
                indication.
        """

        dataframe = self.__convert_to_dataframe(historial_data)
        macd_value = abstract.MACD(dataframe).iloc[-1, 0]

        macd_data = {
            'values': (macd_value, ),
            'is_hot': False,
            'is_cold': False
        }

        return macd_data
Exemplo n.º 2
0
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        macd = ta.MACD(dataframe)

        dataframe['maShort'] = ta.MA(dataframe, timeperiod=50)
        dataframe['maMedium'] = ta.MA(dataframe, timeperiod=200)

        return dataframe
Exemplo n.º 3
0
    def evaluate_macd_cross_over(self,
                                 prefix="macd_crossover",
                                 impact_buy=2,
                                 impact_sell=2):
        """
            evaluates the MACD if we should buy or sale based on a crossover
        :param dataframe:
        :return:
        """

        self._weights(impact_buy, impact_sell)
        dataframe = self.dataframe
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        dataframe.loc[(
            crossed_above(dataframe['macdsignal'], dataframe['macd'])),
                      'sell_{}'.format(prefix)] = (1 * impact_sell)

        dataframe.loc[(
            crossed_above(dataframe['macd'], dataframe['macdsignal'])),
                      'buy_{}'.format(prefix)] = (1 * impact_buy)

        return dataframe
Exemplo n.º 4
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        dataframe['ema_high'] = ta.EMA(dataframe, timeperiod=5, price='high')
        dataframe['ema_close'] = ta.EMA(dataframe, timeperiod=5, price='close')
        dataframe['ema_low'] = ta.EMA(dataframe, timeperiod=5, price='low')
        stoch_fast = ta.STOCHF(dataframe, 5.0, 3.0, 0.0, 3.0, 0.0)
        dataframe['fastd'] = stoch_fast['fastd']
        dataframe['fastk'] = stoch_fast['fastk']
        dataframe['adx'] = ta.ADX(dataframe)
        dataframe['cci'] = ta.CCI(dataframe, timeperiod=20)
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['mfi'] = ta.MFI(dataframe)

        # required for graphing
        bollinger = qtpylib.bollinger_bands(dataframe['close'],
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe['bb_middleband'] = bollinger['mid']

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']
        dataframe['cci'] = ta.CCI(dataframe)

        return dataframe
Exemplo n.º 5
0
    def evaluate_macd_cross_over(self,
                                 prefix="macd_crossover",
                                 impact_buy=2,
                                 impact_sell=2):
        """
        evaluates the MACD if we should buy or sale based on a crossover
        :param dataframe:
        :param prefix:
        :return:
        """

        self._weights(impact_buy, impact_sell)
        dataframe = self.dataframe
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]
        dataframe["macdhist"] = macd["macdhist"]

        dataframe.loc[(
            crossed_above(dataframe["macdsignal"], dataframe["macd"])),
                      f"sell_{prefix}"] = (1 * impact_sell)

        dataframe.loc[(
            crossed_above(dataframe["macd"], dataframe["macdsignal"])),
                      f"buy_{prefix}"] = (1 * impact_buy)

        return dataframe
Exemplo n.º 6
0
    def evaluate_macd(self, prefix="macd", impact_buy=1, impact_sell=1):
        """
        evaluates the MACD if we should buy or sale
        :param dataframe:
        :param prefix:
        :return:
        """

        self._weights(impact_buy, impact_sell)
        dataframe = self.dataframe
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]
        dataframe["macdhist"] = macd["macdhist"]

        # macd < macds & macd < 0 == sell
        dataframe.loc[((dataframe["macd"] < dataframe["macdsignal"]) &
                       (dataframe["macd"] < 0)),
                      f"sell_{prefix}", ] = impact_sell

        # macd > macds & macd > 0 == buy
        dataframe.loc[((dataframe["macd"] > dataframe["macdsignal"]) &
                       (dataframe["macd"] > 0)),
                      f"buy_{prefix}", ] = impact_buy

        return dataframe
Exemplo n.º 7
0
    def analyze(self,
                historical_data,
                hot_thresh=None,
                cold_thresh=None,
                all_data=False):
        """Performs a macd analysis on the historical data

        Args:
            historical_data (list): A matrix of historical OHCLV data.
            hot_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to purchase.
            cold_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to sell.
            all_data (bool, optional): Defaults to False. If True, we return the MACD associated
                with each data point in our historical dataset. Otherwise just return the last one.

        Returns:
            dict: A dictionary containing a tuple of indicator values and booleans for buy / sell
                indication.
        """

        dataframe = self.convert_to_dataframe(historical_data)
        macd_values = abstract.MACD(dataframe).iloc[:, 0]

        analyzed_data = [(value, ) for value in macd_values]

        return self.analyze_results(analyzed_data,
                                    is_hot=lambda v: v > hot_thresh
                                    if hot_thresh else False,
                                    is_cold=lambda v: v < cold_thresh
                                    if cold_thresh else False,
                                    all_data=all_data)
Exemplo n.º 8
0
    def analyze(self,
                historical_data,
                signal=['macd'],
                hot_thresh=None,
                cold_thresh=None):
        """Performs a macd analysis on the historical data

        Args:
            historical_data (list): A matrix of historical OHCLV data.
            signal (list, optional): Defaults to macd. The indicator line to check hot/cold
                against.
            hot_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to purchase.
            cold_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to sell.

        Returns:
            pandas.DataFrame: A dataframe containing the indicators and hot/cold values.
        """

        dataframe = self.convert_to_dataframe(historical_data)
        macd_values = abstract.MACD(dataframe).iloc[:]
        macd_values.dropna(how='all', inplace=True)

        if macd_values[signal[0]].shape[0]:
            macd_values['is_hot'] = macd_values[signal[0]] > hot_thresh
            macd_values['is_cold'] = macd_values[signal[0]] < cold_thresh

        return macd_values
Exemplo n.º 9
0
    def evaluate_macd(self, prefix="macd", impact_buy=1, impact_sell=1):
        """
            evaluates the MACD if we should buy or sale
        :param dataframe:
        :return:
        """

        self._weights(impact_buy, impact_sell)
        dataframe = self.dataframe
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        # macd < macds & macd < 0 == sell
        dataframe.loc[((dataframe['macd'] < dataframe['macdsignal']) &
                       (dataframe['macd'] < 0)),
                      'sell_{}'.format(prefix)] = (1 * impact_sell)

        # macd > macds & macd > 0 == buy
        dataframe.loc[((dataframe['macd'] > dataframe['macdsignal']) &
                       (dataframe['macd'] > 0)),
                      'buy_{}'.format(prefix)] = (1 * impact_buy)

        return dataframe
Exemplo n.º 10
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        macd = ta.MACD(dataframe)

        dataframe['maShort'] = ta.EMA(dataframe, timeperiod=8)
        dataframe['maMedium'] = ta.EMA(dataframe, timeperiod=21)

        return dataframe
Exemplo n.º 11
0
def calculator_talib(data):
    ETF = {
        'open': data[OHLCV_columns[0]].dropna().astype(float),
        'high': data[OHLCV_columns[1]].dropna().astype(float),
        'low': data[OHLCV_columns[2]].dropna().astype(float),
        'close': data[OHLCV_columns[3]].dropna().astype(float),
        'volume': data[OHLCV_columns[4]].dropna().astype(float)
    }

    def talib2df(talib_output):
        if type(talib_output) == list:
            ret = pd.DataFrame(talib_output).transpose()
        else:
            ret = pd.Series(talib_output)
        ret.index = data['收盤價'].index
        return ret

    KD = talib2df(abstract.STOCH(ETF, fastk_period=9))
    #計算MACD#
    MACD = talib2df(abstract.MACD(ETF))
    #計算OBV#
    OBV = talib2df(abstract.OBV(ETF))
    #計算威廉指數#
    WILLR = talib2df(abstract.WILLR(ETF))
    #ATR 計算#
    ATR = talib2df(abstract.ATR(ETF))

    ETF = pd.DataFrame()
    ETF = pd.concat([data, KD, MACD, OBV, WILLR, ATR], axis=1)
    return ETF
Exemplo n.º 12
0
def populate_indicators(dataframe: DataFrame) -> DataFrame:
    """
    Adds several different TA indicators to the given DataFrame
    """
    dataframe['sar'] = ta.SAR(dataframe)
    dataframe['adx'] = ta.ADX(dataframe)
    stoch = ta.STOCHF(dataframe)
    dataframe['fastd'] = stoch['fastd']
    dataframe['fastk'] = stoch['fastk']
    dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2,
                                    nbdevdn=2)['lowerband']
    dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
    dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
    dataframe['mfi'] = ta.MFI(dataframe)
    dataframe['cci'] = ta.CCI(dataframe)
    dataframe['rsi'] = ta.RSI(dataframe)
    dataframe['mom'] = ta.MOM(dataframe)
    dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
    dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
    dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
    dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
    dataframe['ao'] = awesome_oscillator(dataframe)
    macd = ta.MACD(dataframe)
    dataframe['macd'] = macd['macd']
    dataframe['macdsignal'] = macd['macdsignal']
    dataframe['macdhist'] = macd['macdhist']
    return dataframe
Exemplo n.º 13
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Add several indicators needed for buy and sell strategies defined below.
        """
        # ADX
        dataframe['adx'] = ta.ADX(dataframe)
        # MACD
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        # MFI
        dataframe['mfi'] = ta.MFI(dataframe)
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)
        # Stochastic Fast
        stoch_fast = ta.STOCHF(dataframe)
        dataframe['fastd'] = stoch_fast['fastd']
        # Minus-DI
        dataframe['minus_di'] = ta.MINUS_DI(dataframe)
        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        # SAR
        dataframe['sar'] = ta.SAR(dataframe)

        return dataframe
    def do_populate_indicators(self, dataframe: DataFrame,
                               metadata: dict) -> DataFrame:
        """
        Adds multiple TA indicators to MoniGoMani's DataFrame per pair.
        Should be called with 'informative_pair' (1h candles) during backtesting/hyperopting with TimeFrame-Zoom!

        Performance Note: For the best performance be frugal on the number of indicators you are using.
        Only add in indicators that you are using in your weighted signal configuration for MoniGoMani,
        otherwise you will waste your memory and CPU usage.

        :param dataframe: (DataFrame) DataFrame with data from the exchange
        :param metadata: (dict) Additional information, like the currently traded pair
        :return DataFrame: DataFrame for MoniGoMani with all mandatory indicator data populated
        """

        # Momentum Indicators (timeperiod is expressed in candles)
        # -------------------

        # Parabolic SAR
        dataframe['sar'] = ta.SAR(dataframe)

        # Stochastic Slow
        stoch = ta.STOCH(dataframe)
        dataframe['slowk'] = stoch['slowk']

        # MACD - Moving Average Convergence Divergence
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd[
            'macd']  # MACD - Blue TradingView Line (Bullish if on top)
        dataframe['macdsignal'] = macd[
            'macdsignal']  # Signal - Orange TradingView Line (Bearish if on top)

        # MFI - Money Flow Index (Under bought / Over sold & Over bought / Under sold / volume Indicator)
        dataframe['mfi'] = ta.MFI(dataframe)

        # Overlap Studies
        # ---------------

        # Bollinger Bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_middleband'] = bollinger['mid']

        # SMA's & EMA's are trend following tools (Should not be used when line goes sideways)
        # SMA - Simple Moving Average (Moves slower compared to EMA, price trend over X periods)
        dataframe['sma9'] = ta.SMA(dataframe, timeperiod=9)
        dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50)
        dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)

        # TEMA - Triple Exponential Moving Average
        dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)

        # Volume Indicators
        # -----------------

        # Rolling VWAP - Volume Weighted Average Price
        dataframe['rolling_vwap'] = qtpylib.rolling_vwap(dataframe)

        return dataframe
Exemplo n.º 15
0
    def analyze_sl(self,
                   historical_data,
                   hot_thresh=None,
                   cold_thresh=None,
                   all_data=False):
        """Performs a macd analysis on the historical data using signal line for alerting

        Args:
            historical_data (list): A matrix of historical OHCLV data.
            hot_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to purchase.
            cold_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to sell.
            all_data (bool, optional): Defaults to False. If True, we return the MACD associated
                with each data point in our historical dataset. Otherwise just return the last one.

        Returns:
            dict: A dictionary containing a tuple of indicator values and booleans for buy / sell
                indication.
        """

        dataframe = self.convert_to_dataframe(historical_data)
        macd_values = abstract.MACD(dataframe).iloc[:]

        # List of 2-tuples containing the ema value and closing price respectively
        analyzed_data = [(r[1]['macdsignal'], r[1]['macd'])
                         for r in macd_values.iterrows()]

        return self.analyze_results(analyzed_data,
                                    is_hot=lambda s, v: s < v
                                    if hot_thresh else False,
                                    is_cold=lambda s, v: s > v
                                    if cold_thresh else False,
                                    all_data=all_data)
Exemplo n.º 16
0
    def normal_tf_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_middleband'] = bollinger['mid']
        dataframe['bb_upperband'] = bollinger['upper']

        dataframe['volume_mean_slow'] = dataframe['volume'].rolling(window=48).mean()

        # EMA
        dataframe['ema_200'] = ta.EMA(dataframe, timeperiod=200)

        dataframe['ema_26'] = ta.EMA(dataframe, timeperiod=26)
        dataframe['ema_12'] = ta.EMA(dataframe, timeperiod=12)

        # MACD 
        dataframe['macd'], dataframe['signal'], dataframe['hist'] = ta.MACD(dataframe['close'], fastperiod=12, slowperiod=26, signalperiod=9)

        # SMA
        dataframe['sma_5'] = ta.EMA(dataframe, timeperiod=5)

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        return dataframe
Exemplo n.º 17
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        ##################################################################################
        # buy and sell indicators

        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_middleband'] = bollinger['mid']
        dataframe['bb_upperband'] = bollinger['upper']

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        # dataframe['cci'] = ta.CCI(dataframe)
        # dataframe['mfi'] = ta.MFI(dataframe)
        # dataframe['rsi'] = ta.RSI(dataframe, timeperiod=7)

        # dataframe['canbuy'] = np.NaN
        # dataframe['canbuy2'] = np.NaN
        # dataframe.loc[dataframe.close.rolling(49).min() <= 1.1 * dataframe.close, 'canbuy'] == 1
        # dataframe.loc[dataframe.close.rolling(600).max() < 1.2 * dataframe.close, 'canbuy'] = 1
        # dataframe.loc[dataframe.close.rolling(600).max() * 0.8 >  dataframe.close, 'canbuy2'] = 1
        ##################################################################################
        # required for graphing
        bollinger = qtpylib.bollinger_bands(dataframe['close'],
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe['bb_middleband'] = bollinger['mid']

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

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        return dataframe
Exemplo n.º 19
0
    def cal_macd(self, fast=12, slow=26, signal=9):
        macd, macdsignal, macdhist = ta.MACD(self.close,
                                             fastperiod=fast,
                                             slowperiod=slow,
                                             signalperiod=signal)

        self.analysis_data['macd'] = macd
        self.analysis_data['macdsignal'] = macdsignal
        self.analysis_data['macdhist'] = macdhist
def generate_indicators(dataset,
                        timeperiod=5,
                        generate_target=True,
                        reset_index=False):

    # To avoid changes from original dataset
    df = pd.DataFrame(dataset).copy()

    # To prevent index from being Date
    if (reset_index):
        df = df.reset_index()

    df.columns = df.columns.str.lower()

    # check the given dataset has necessary_columns
    __check_columns(df)

    df = df[necessary_columns]

    # df_indicators has all columns except date, this is for talib to produces other indicators
    df_indicators = df.iloc[:, 1:]

    # Produce other indicators
    RSI = abstract.RSI(df_indicators.close, timeperiod)
    RSI = pd.DataFrame({'RSI': RSI})

    MOM = abstract.MOM(df_indicators.close, timeperiod)
    MOM = pd.DataFrame({'MOM': MOM})

    KD = abstract.STOCH(df_indicators)
    KD = pd.DataFrame(KD)  # KD has slowd and slowk

    MACD = abstract.MACD(df_indicators)
    MACD = pd.DataFrame(MACD)  # MACD has its own column names

    ADX = abstract.ADX(df_indicators)
    ADX = pd.DataFrame({'ADX': ADX})

    SMA = abstract.SMA(df_indicators.close)
    SMA = pd.DataFrame({'SMA': SMA})

    upper, middle, lower = talib.BBANDS(df_indicators.close, matype=MA_Type.T3)
    bb_df = pd.DataFrame({ \
        'upper_bb' : upper,
        'middel_bb' : middle,
        'lower_bb' : lower})

    # Combine all metrix
    frames = [df, RSI, MOM, KD, MACD, ADX, SMA, bb_df]
    combined = pd.concat(frames, axis=1)

    if (generate_target):
        target_name = 'next_' + str(timeperiod) + 'day_trend'
        combined[target_name] = np.where(
            combined.close.shift(-timeperiod) > combined.close, 1, 0)

    return combined
Exemplo n.º 21
0
def populate_indicators(dataframe: DataFrame) -> DataFrame:
    """
    Adds several different TA indicators to the given DataFrame
    """

    # Log the dataframe
    dataframe.to_csv("dataframe.csv", sep='\t')

    #Determine Trend
    dataframe = indicators.TREND(dataframe)

    #Exponential Moving Average
    dataframe['ema'] = ta.EMA(dataframe, timeperiod=33)

    #Parabolic SAR
    dataframe['sar'] = ta.SAR(dataframe, 0.02, 0.22)

    #Average Directional Movement Index
    dataframe['adx'] = ta.ADX(dataframe)

    #MACD
    macd = ta.MACD(dataframe)
    dataframe['macd'] = macd['macd']
    dataframe['macds'] = macd['macdsignal']
    dataframe['macdh'] = macd['macdhist']

    #Relative Strength Index
    dataframe['rsi'] = ta.RSI(dataframe, 14)
    dataframe = indicators.RSI(dataframe)

    #Absolute Price Oscillator
    dataframe['apo'] = ta.APO(dataframe,
                              fastperiod=12,
                              slowperiod=26,
                              matype=0)

    #Momentum
    dataframe['mom'] = ta.MOM(dataframe, 10)

    #Bollinger Bands
    dataframe = indicators.BBANDS(20, dataframe, 2)

    # Stochcastic
    dataframe['K'] = indicators.STOK(dataframe, 14)
    dataframe['D'] = indicators.STOD(dataframe, 14)
    dataframe = indicators.STOCH(dataframe)

    # if Counter.counter < 30:
    #     print(dataframe)
    #     print (macd)
    #     print (dataframe ['adx'])
    #     Counter.counter = Counter.counter + 1

    # else:
    #     exit()

    return dataframe
Exemplo n.º 22
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']
        dataframe['cci'] = ta.CCI(dataframe)

        return dataframe
Exemplo n.º 23
0
def apply_indicators(df: pd.DataFrame):

    # ADX
    df['adx'] = ta.ADX(df)

    # EMA
    df['ema_5'] = ta.EMA(df, 5)
    df['ema_10'] = ta.EMA(df, 10)
    df['ema_20'] = ta.EMA(df, 20)
    df['ema_50'] = ta.EMA(df, 50)
    df['ema_100'] = ta.EMA(df, 100)
    df['ema_200'] = ta.EMA(df, 200)

    # MACD
    macd = ta.MACD(df)
    df['macd'] = macd['macd']
    df['macdsignal'] = macd['macdsignal']
    df['macdhist'] = macd['macdhist']

    # inverse Fisher rsi/ RSI
    df['rsi'] = ta.RSI(df)
    rsi = 0.1 - (df['rsi'] - 50)
    df['i_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)

    # Stoch fast
    stoch_fast = ta.STOCHF(df)
    df['fastd'] = stoch_fast['fastd']
    df['fastk'] = stoch_fast['fastk']

    # Stock slow
    stoch_slow = ta.STOCH(df)
    df['slowd'] = stoch_slow['slowd']
    df['slowk'] = stoch_slow['slowk']

    # Bollinger bands
    bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(df),
                                        window=20,
                                        stds=2)
    df['bb_lowerband'] = bollinger['lower']
    df['bb_middleband'] = bollinger['mid']
    df['bb_upperband'] = bollinger['upper']

    # ROC
    df['roc'] = ta.ROC(df, 10)

    # CCI
    df['cci'] = ta.CCI(df, 14)

    # on balance volume
    df['obv'] = ta.OBV(df)

    # Average True Range
    df['atr'] = ta.ATR(df, 14)

    df = ichimoku(df)

    return df
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        dataframe['adx'] = ta.ADX(dataframe, timeperiod=14)
        dataframe['ao'] = qtpylib.awesome_oscillator(dataframe)

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

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

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)

        return dataframe
Exemplo n.º 26
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ema200'] = ta.EMA(dataframe, timeperiod=200)
        macd = ta.MACD(dataframe, fastperiod=24, slowperiod=56, signalperiod=6)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['sell-rsi'] = ta.RSI(dataframe, timeperiod=14)
        return dataframe
Exemplo n.º 27
0
def MACD(ohlcv, kw):
    """ :return Moving Average Convergence/Divergence (macd, macdsignal, macdhist =) """
    params = {'fastperiod': 12, 'slowperiod': 26, 'signalperiod': 9}
    fastperiod, slowperiod, signalperiod = _get_params(kw, params, ['fastperiod', 'slowperiod', 'signalperiod'])
    result = talib.MACD(ohlcv, fastperiod, slowperiod, signalperiod)
    return {
        'macd': result[0],
        'macdsignal': result[1],
        'macdhist': result[2]
    }
Exemplo n.º 28
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]

        for cciTime in cciTimeRange:
            cciName = "cci-" + str(cciTime)
            dataframe[cciName] = ta.CCI(dataframe, timeperiod=cciTime)

        return dataframe
Exemplo n.º 29
0
 def technical_index(self):
     df = self.max_min_price()
     df2 = self.institutional_investors()
     df['RSI'] = abstract.RSI(df) / 100
     df['CMO'] =(abstract.CMO(df)+100) / (2 *100)
     df['MACD'] =(abstract.MACD(df)['macd']+abstract.MACD(df)['macd'].max()) / (2 *abstract.MACD(df)['macd'].max())
     df['WILLR'] =(abstract.WILLR(df)+100) / (2 *100)
     df['WMA'] =abstract.WMA(df) / abstract.WMA(df).max()
     df['PPO'] =(abstract.PPO(df)+abstract.PPO(df).max()) / (2 *abstract.PPO(df).max())
     df['EMA'] =abstract.EMA(df) / abstract.EMA(df).max()
     df['ROC'] =(abstract.ROC(df)+abstract.ROC(df).max()) / (2 *abstract.ROC(df).max())
     df['SMA'] =abstract.SMA(df) / abstract.SMA(df).max()
     df['TEMA'] =abstract.TEMA(df) / abstract.TEMA(df).max()
     df['CCI'] =(abstract.CCI(df)+abstract.CCI(df).max()) / (2 *abstract.CCI(df).max())
     df['investment_trust'] = (df2['investment_trust'] + df2['investment_trust'].max()) / (2*df2['investment_trust'].max())
     df['foreign_investor'] = (df2['foreign_investor'] + df2['foreign_investor'].max()) / (2*df2['foreign_investor'].max())
     df = df.drop(columns=['volume', 'open', 'high', 'low', 'close', 'close_max', 'close_min'])
     df = df.dropna()
     return df
Exemplo n.º 30
0
    def __init__(self, ticker, start_day=None, length=730):
        self.ticker = ticker
        if (start_day == None):
            today = datetime.today()
            start_day = today - timedelta(days=length)
            start_str = str(start_day.strftime('%Y-%m-%d'))
            end_str = str(today.strftime('%Y-%m-%d'))
        else:
            start_str = start_day
            #start = time.strptime(start_day, "%Y-%m-%d")
            start = datetime.strptime(start_str, "%Y-%m-%d")
            end_day = start + timedelta(days=length)
            end_str = str(end_day.strftime('%Y-%m-%d'))

        i = y.get_historical_prices(ticker, start_str, end_str)

        #Lag Pandas DataFrame
        self.df = pd.DataFrame(i)

        #Snu Dataframe
        self.df = self.df.transpose()

        #endre datatype til float
        self.df = self.df.astype(float)
        self.df = self.df.rename(
            columns={
                'Close': 'close',
                'High': 'high',
                'Open': 'open',
                'Low': 'low',
                'Volume': 'volume'
            })

        stoch = abstract.STOCH(self.df, 14, 1, 3)
        macd = abstract.MACD(self.df)
        atr = abstract.ATR(self.df)
        obv = abstract.OBV(self.df)
        rsi = abstract.RSI(self.df)

        self.df['atr'] = pd.DataFrame(atr)
        self.df['obv'] = pd.DataFrame(obv)
        self.df['rsi'] = pd.DataFrame(rsi)

        #kombinerer to dataframes
        self.df = pd.merge(self.df,
                           pd.DataFrame(macd),
                           left_index=True,
                           right_index=True,
                           how='outer')
        self.df = pd.merge(self.df,
                           stoch,
                           left_index=True,
                           right_index=True,
                           how='outer')