技术指标--MACD

Python MACD 金叉 死叉

'''
   MACD 金叉,死叉
'''
import pandas as pd
import talib


class MACDBreak:
    def __init__(self, close):
        self.close = close

    def __get_macd(self, fastperiod, slowperiod, signalperiod):
        diff, dea, hist = talib.MACD(self.close, fastperiod=fastperiod, slowperiod=slowperiod,
                                     signalperiod=signalperiod)
        return pd.DataFrame({'diff': diff[~pd.isna(diff)], 'dea': dea[~pd.isna(dea)], 'macd': hist[~pd.isna(hist)] * 2},
                            columns=['diff', 'dea', 'macd'])

    def golden_cross(self, fastperiod=12, slowperiod=26, signalperiod=9):
        """
        金叉
        :return: [time,diff,dea,macd]
        """
        df = self.__get_macd(fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod)
        for i in range(int(df.shape[0]) - 1, 1, -1):
            if (df['diff'][i - 1] <= df['dea'][i - 1]) and (df['diff'][i] >= df['dea'][i]):
                return [df.index[i - 1], df['diff'][i - 1], df['dea'][i - 1], df['macd'][i - 1]]
        return []

    def dead_cross(self, fastperiod=12, slowperiod=26, signalperiod=9):
        """
        死叉
        :return: [time,diff,dea,macd]
        """
        df = self.__get_macd(fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod)
        for i in range(int(df.shape[0]) - 1, 1, -1):
            if (df['diff'][i - 1] >= df['dea'][i - 1]) and (df['diff'][i] <= df['dea'][i]):
                return [df.index[i - 1], df['diff'][i - 1], df['dea'][i - 1], df['macd'][i - 1]]
        return []

你可能感兴趣的:(技术指标--MACD)