Example #1
0
 def macd(
     self,
     fast_period: int,
     slow_period: int,
     signal_period: int,
     islog: bool = False,
     array: bool = False
 ) -> Union[
     Tuple[np.ndarray, np.ndarray, np.ndarray],
     Tuple[float, float, float]
 ]:
     """
     MACD.
     """
     if islog:
         macd, signal, hist = talib.MACDEXT(
             np.log(self.close), fastperiod=fast_period, fastmatype=1, slowperiod=slow_period,slowmatype=1,
             signalperiod=signal_period, signalmatype=1
         )
     else:
         macd, signal, hist = talib.MACDEXT(
             self.close, fastperiod=fast_period, fastmatype=1, slowperiod=slow_period,slowmatype=1,
             signalperiod=signal_period, signalmatype=1
         )
     hist = hist * 2
     if array:
         return macd, signal, hist
     return macd[-1], signal[-1], hist[-1]
def macdext(close_ts, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0):
    import talib
    close_np = close_ts.cpu().detach().numpy()
    close_df = pd.DataFrame(close_np)
    DIF = close_df.apply(lambda x: talib.MACDEXT(x, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)[0])
    DEA = close_df.apply(lambda x: talib.MACDEXT(x, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)[1])
    MACD = close_df.apply(lambda x: talib.MACDEXT(x, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)[2])
    
    DIF_ts = torch.tensor(DIF.values, dtype=close_ts.dtype, device=close_ts.device)
    DEA_ts = torch.tensor(DEA.values, dtype=close_ts.dtype, device=close_ts.device)
    MACD_ts = torch.tensor(MACD.values, dtype=close_ts.dtype, device=close_ts.device)
    
    return DIF_ts, DEA_ts, MACD_ts
Example #3
0
def MACD(security_list, fastperiod=12, slowperiod=26, signalperiod=9):
    # 修复传入为单只股票的情况
    if isinstance(security_list, str):
        security_list = [security_list]
    # 计算 MACD
    security_data = history(slowperiod * 2,
                            '1d',
                            'close',
                            security_list,
                            df=False,
                            skip_paused=True)
    macd_DIF = {}
    macd_DEA = {}
    macd_HIST = {}
    for stock in security_list:
        macd_DIF[stock], macd_DEA[stock], macd = talib.MACDEXT(
            security_data[stock],
            fastperiod=fastperiod,
            fastmatype=1,
            slowperiod=slowperiod,
            slowmatype=1,
            signalperiod=signalperiod,
            signalmatype=1)
        macd_HIST[stock] = macd * 2
    return macd_DIF, macd_DEA, macd_HIST
Example #4
0
	def momentum(self):
		adx = talib.ADX(self.high,self.low,self.close,self.period)
		adxr = talib.ADXR(self.high,self.low,self.close,self.period)
		apo = talib.APO(self.high,self.low,self.close,self.period)
		aroondown, aroonup = talib.AROON(self.high, self.low, period)
		aroonosc = talib.AROONOSC(self.high,self.low,self.period)
		bop  = talib.BOP(self.opens,self.high,self.low,self.close)
		cci = talib.CCI(self.high,self.low,self.close,self.period)
		cmo = talib.CMO(self.close,self.period)
		dx = talib.DX(self.high,self.low,self.close,self.period)
		macd, macdsignal, macdhist = talib.MACD(self.close, fastperiod=period, slowperiod=period*5, signalperiod=period*2)
		macd1, macdsignal1, macdhist1 = talib.MACDEXT(self.close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
		macd2, macdsignal2, macdhist2 = talib.MACDFIX(self.close, signalperiod=9)
		mfi = talib.MFI(self.high, self.low, self.close, self.volume, timeperiod=14)
		minus_di = talib.MINUS_DI(self.high, self.low, self.close, timeperiod=14)
		minus_dm = talib.MINUS_DM(self.high, self.low, timeperiod=14)
		mom = talib.MOM(self.close, timeperiod=10)
		plus_di = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=14)
		plus_dm = talib.PLUS_DM(self.high, self.low, timeperiod=14)
		ppo  = talib.PPO(self.close, fastperiod=12, slowperiod=26, matype=0)
		roc  = talib.ROC(self.close, timeperiod=10)
		rocp = talib.ROCP(self.close, timeperiod=10)
		rocr = talib.ROCR(self.close, timeperiod=10)
		rocr100 = talib.ROCR100(self.close, timeperiod=10)
		rsi =  talib.RSI(self.close, timeperiod=14)
		slowk, slowd = talib.STOCH(self.high, self.low, self.close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
		fastk, fastd = talib.STOCHF(self.high, self.low, self.close, fastk_period=5, fastd_period=3, fastd_matype=0)
		fastk1, fastd1 = talib.STOCHRSI(self.close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
		trix = talib.TRIX(self.close, timeperiod=30)
		ultosc = talib.ULTOSC(self.high, self.low, self.close, timeperiod1=7, timeperiod2=14, timeperiod3=28)
		willr = talib.WILLR(self.high, self.low, self.close, timeperiod=14)
Example #5
0
    def fetch_hist_min_label_k_data(self, code, k_type, curr, total):
        sys.stdout.write('\r fetching %s hist %s k_data, %d - %d' % (code, k_type, curr, total))
        try:
            table_name = 'hist_' + k_type
            df = ts.get_k_data(code=code, autype='qfq', ktype=k_type, retry_count=20, pause=3)
            if len(df) < 80:
                return

            last_index = len(df) - 1
            if not if_times(df['date'][last_index], k_type):
                df = df.drop(last_index)

            macd_dif, macd_dea, macd_val = ta.MACDEXT(np.array(df['close']), fastperiod=12, fastmatype=1, slowperiod=26,
                                                      slowmatype=1, signalperiod=9, signalmatype=1)
            macd_val = macd_val * 2
            df['dif'] = pd.Series(macd_dif, index=df.index)
            df['dea'] = pd.Series(macd_dea, index=df.index)
            df['macd'] = pd.Series(macd_val, index=df.index)
            remain_count = 40;
            if k_type == '15':
                remain_count = 80
            df1 = df[(len(df) - remain_count):len(df)]
            df1.to_sql(table_name, self.__db.get_engine(), if_exists='append', index=False)
        except Exception as e:
            print(":", e.__repr__(), code)
    def get_technicals(self):
        import talib as ta

        stock_history = self.__get_history()

        # Get Bollinger bands
        stock_history['up_band'], \
            stock_history['mid_band'], \
            stock_history['low_band'] = ta.BBANDS(stock_history['Close'], timeperiod=20)

        # Get MACD
        stock_history['MACD'], \
            stock_history['MACD_signal'], \
            stock_history['MACD_hist'] = ta.MACDEXT(stock_history['Close'],
                                                         fastperiod=12, fastmatype=1,
                                                         slowperiod=26, slowmatype=1,
                                                         signalperiod=9, signalmatype=1)

        # Get OBV
        stock_history['OBV'] = ta.OBV(stock_history['Close'], stock_history['Volume'])

        # Get RSI
        stock_history['RSI'] = ta.RSI(stock_history['Close'], 14)

        if self.graph:
            self.__graph_technicals(stock_history)

        return stock_history
Example #7
0
def logic (ohlc, exchange="NSE"):
    inputs = {"open":np.array(ohlc.open.values),
          "high": np.array(ohlc.high.values),
          "low": np.array(ohlc.low.values),
          "close": np.array(ohlc.close.values),
          "volume": np.array(ohlc.volume.values).astype(float)}

    try:
        sma8 = talib.SMA(inputs["close"], 8)
        sma21 = talib.SMA(inputs["close"], 21)

        rsi = talib.RSI(inputs["close"], timeperiod=15)
        sma_rsi = talib.SMA(rsi,8)

        #natr = talib.NATR(inputs["high"],inputs["low"],inputs["close"], timeperiod=14)
        macd, macdsignal, macdhist = talib.MACDEXT(inputs["close"], fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
        ultosc = talib.ULTOSC(inputs["high"],inputs["low"],inputs["close"],timeperiod1=7, timeperiod2=14, timeperiod3=28)
        slowk, slowd = talib.STOCH(inputs["high"],inputs["low"],inputs["close"], 5, 3, 0, 3, 0)
        #obv = talib.OBV(inputs["close"], inputs["volume"])
        bop = talib.SMA(talib.BOP(inputs["open"], inputs["high"],inputs["low"],inputs["close"]),5)

        data = pd.DataFrame({ "sma_rsi":sma_rsi,"slowk": slowk, "slowd": slowd,"rsi":rsi, "ultosc": ultosc,
                              "macd": macd, "macdsignal": macdsignal,"macdhist":macdhist,# "obv":obv, "natr": natr,
                              "bop":bop, "sma8":sma8, "sma21":sma21,
                              })
    except Exception as e:
		    print(item + str(e) + " can't process")
    return data
Example #8
0
 def calculations(self):
     '''calculations'''
     self.df['rsi'] = ta.RSI(self.df['close'], timeperiod=5)
     self.df['apo'] = ta.APO(self.df['close'],
                             fastperiod=10,
                             slowperiod=5,
                             matype=0)
     self.df['upperband'], self.df['middleband'], self.df[
         'lowerband'] = ta.BBANDS(self.df['close'],
                                  timeperiod=5,
                                  nbdevup=2,
                                  nbdevdn=2,
                                  matype=0)
     self.df['ema'] = ta.EMA(self.df['close'], timeperiod=5)
     self.df['ma'] = ta.MA(self.df['close'], timeperiod=5, matype=0)
     self.df['sma'] = ta.MA(self.df['close'], timeperiod=5)
     self.df['t3'] = ta.T3(self.df['close'], timeperiod=5, vfactor=0)
     self.df['wma'] = ta.WMA(self.df['close'], timeperiod=5)
     self.df['aroonosc'] = ta.AROONOSC(self.df['high'],
                                       self.df['low'],
                                       timeperiod=5)
     self.df['cci'] = ta.CCI(self.df['high'],
                             self.df['low'],
                             self.df['close'],
                             timeperiod=5)
     self.df['cmo'] = ta.CMO(self.df['close'], timeperiod=14)
     self.df['macd'], self.df['macdsignal'], self.df[
         'macdhist'] = ta.MACDEXT(self.df['close'],
                                  fastperiod=12,
                                  fastmatype=0,
                                  slowperiod=26,
                                  slowmatype=0,
                                  signalperiod=9,
                                  signalmatype=0)
     self.df['slowk'], self.df['slowd'] = ta.STOCH(self.df['high'],
                                                   self.df['low'],
                                                   self.df['close'],
                                                   fastk_period=5,
                                                   slowk_period=3,
                                                   slowk_matype=0,
                                                   slowd_period=3,
                                                   slowd_matype=0)
     self.df['fastk'], self.df['fastd'] = ta.STOCHRSI(self.df['close'],
                                                      timeperiod=5,
                                                      fastk_period=5,
                                                      fastd_period=3,
                                                      fastd_matype=0)
     self.df['ultosc'] = ta.ULTOSC(self.df['high'],
                                   self.df['low'],
                                   self.df['close'],
                                   timeperiod1=7,
                                   timeperiod2=14,
                                   timeperiod3=28)
     self.df['adosc'] = ta.ADOSC(self.df['high'],
                                 self.df['low'],
                                 self.df['close'],
                                 self.df['volume'],
                                 fastperiod=3,
                                 slowperiod=10)
     return self.df
Example #9
0
 def macdext(self, fastPeriod, slowPeriod, signalPeriod, array=False):
     """MACD指标"""
     macd, signal, hist = talib.MACDEXT(self.close, fastPeriod, 1,
                                        slowPeriod, 1, signalPeriod, 1)
     if array:
         return macd, signal, hist * 2
     return macd[-1], signal[-1], hist[-1] * 2
    def indicator(self, period, proj_scores):

        # Relative position
        Relative_Position = []
        for i in range(period, len(proj_scores)):
            Relative_Position.append((proj_scores[i] - min(proj_scores[(i - period):i])) \
                                    /(max(proj_scores[(i - period):i]) - min(proj_scores[(i - period):i])))

        # Relative Strength Index
        RSI = talib.RSI(np.array(proj_scores), period)
        RSI = RSI[~np.isnan(RSI)]

        # Momentum
        MOM = (proj_scores / proj_scores.shift(period)).dropna() * 100

        # Moving Average Convergence-Divergence
        MACD_slow = period
        MACD_fast = int(floor(period * 0.5))
        MACD, MACD_signal, MACD_hist = talib.MACDEXT(np.array(proj_scores), fastperiod = MACD_fast, \
                                                     fastmatype = MA_Type.EMA, slowperiod = MACD_slow, \
                                                     slowmatype = MA_Type.EMA, signalperiod = 2, \
                                                     signalmatype = 0)
        MACD = MACD[~np.isnan(MACD)]

        # All Technical Indicators as Independent Variables for Prediction Models in DataFrame
        predictor_in_df = pd.DataFrame({'RP': Relative_Position, 'RSI': RSI, 'MOM': MOM, 'MACD': MACD}, \
                                        index = proj_scores.index[period:])

        return predictor_in_df
Example #11
0
def macd_cn(close, fast_period, slow_period, signal_period):
    # short_win = 12    # 短期EMA平滑天数
    # long_win  = 26    # 长期EMA平滑天数
    # macd_win  = 20     # DEA线平滑天数
    macd_dif, macd_dea, macd = tl.MACDEXT(close, fastperiod=fast_period, fastmatype=1, slowperiod=slow_period,
                                             slowmatype=1, signalperiod=signal_period, signalmatype=1)
    macd = macd * 2
    return macd_dif, macd_dea, macd
Example #12
0
 def getMacd(self, close):
     macdDIFF, macdDEA, macd = talib.MACDEXT(close,
                                             fastperiod=12,
                                             fastmatype=1,
                                             slowperiod=26,
                                             slowmatype=1,
                                             signalperiod=9,
                                             signalmatype=1)
     macd = macd * 2
     return macdDIFF, macdDEA, macd
Example #13
0
def macd_cn(close_arr, fastperiod, slowperiod, signalperiod):
    macdDIFF, macdDEA, macd = ta.MACDEXT(close_arr,
                                         fastperiod=fastperiod,
                                         fastmatype=1,
                                         slowperiod=slowperiod,
                                         slowmatype=1,
                                         signalperiod=signalperiod,
                                         signalmatype=1)
    macd = macd * 2
    return macdDIFF, macdDEA, macd
Example #14
0
def get_MACD(close, fastperiod, slowperiod, signalperiod):
    macdDIFF, macdDEA, macd = talib.MACDEXT(close,
                                            fastperiod=fastperiod,
                                            fastmatype=1,
                                            slowperiod=slowperiod,
                                            slowmatype=1,
                                            signalperiod=signalperiod,
                                            signalmatype=1)
    macd = macd * 2
    return macdDIFF, macdDEA, macd
Example #15
0
 def __init__(self, stock_data, fastperiod, slowperiod, signalperiod):
     close = stock_data['close']
     date = stock_data['date']
     self.dif, self.dea, self.macd = tl.MACDEXT(close, fastperiod=fastperiod, fastmatype=1, slowperiod=slowperiod, slowmatype=1, signalperiod=signalperiod, signalmatype=1)
     self.dif = pd.Series(self.dif).sort_index(ascending=False).dropna().reset_index(drop=True)
     self.dea = pd.Series(self.dea).sort_index(ascending=False).dropna().reset_index(drop=True)
     self.macd = pd.Series(self.macd).sort_index(ascending=False).dropna().reset_index(drop=True) * 2
     self.sz = len(self.dif)
     self.close = pd.Series(close).sort_index(ascending=False).reset_index(drop=True).head(self.sz)
     self.date = pd.Series(date).sort_index(ascending=False).reset_index(drop=True).head(self.sz)
Example #16
0
def TALIB_MACDEXT(close,
                  fastperiod=12,
                  fastmatype=talib.MA_Type.SMA,
                  slowperiod=26,
                  slowmatype=talib.MA_Type.SMA,
                  signalperiod=9,
                  signalmatype=talib.MA_Type.SMA):
    '''00354,7,3'''
    return talib.MACDEXT(close, fastperiod, fastmatype, slowperiod, slowmatype,
                         signalperiod, signalmatype)
Example #17
0
def get_macdext(df):
    df['DIFF'], df['DEA'], df['MACD'] = talib.MACDEXT(df['close'],
                                                      fastperiod=12,
                                                      fastmatype=1,
                                                      slowperiod=26,
                                                      slowmatype=1,
                                                      signalperiod=9,
                                                      signalmatype=1)
    df['MACD'] = df['MACD'] * 2
    return df
Example #18
0
def MACD_CN(close, fastperiod, slowperiod, signalperiod):
    macdDIFF, macdDEA, macd = tl.MACDEXT(close,
                                         fastperiod=fastperiod,
                                         fastmatype=1,
                                         slowperiod=slowperiod,
                                         slowmatype=1,
                                         signalperiod=signalperiod,
                                         signalmatype=1)
    macd = macd * 2
    return macdDIFF, macdDEA, macd
Example #19
0
def get_macdext(ohlc):
    # MACD (先行 12 日移動平均、遅行 26 日移動平均、 9 日シグナル線) を求める
    macdext, macdsignalext, macdhistext = ta.MACDEXT(ohlc['4_close'], fastperiod=12, fastmatype=0, slowperiod=26,
                                                     slowmatype=0, signalperiod=9, signalmatype=0)

    ohlc = ohlc.assign(
        macdext=macdext
        , macdsignalext=macdsignalext
        , macdhistext=macdhistext
    )
    return ohlc
Example #20
0
def add_MACDEXT(
    self,
    fastperiod=12,
    fastmatype=0,
    slowperiod=26,
    slowmatype=0,
    signalperiod=9,
    signalmatype=0,
    types=["line", "line", "histogram"],
    colors=["primary", "tertiary", "fill"],
    **kwargs
):
    """Moving Average Convergence Divergence with Controllable MA Type.

    Note that the first argument of types and colors refers to MACD,
    the second argument refers to MACD signal line and the third argument
    refers to MACD histogram.

    """
    if not self.has_close:
        raise Exception()

    utils.kwargs_check(kwargs, VALID_TA_KWARGS)
    if "kind" in kwargs:
        kwargs["type"] = kwargs["kind"]
    if "kinds" in kwargs:
        types = kwargs["type"]

    if "type" in kwargs:
        types = [kwargs["type"]] * 3
    if "color" in kwargs:
        colors = [kwargs["color"]] * 3

    name = "MACDEXT({},{},{})".format(
        str(fastperiod), str(slowperiod), str(signalperiod)
    )
    macd = name
    smacd = name + "[Sign]"
    hmacd = name + "[Hist]"
    self.sec[macd] = dict(type=types[0], color=colors[0])
    self.sec[smacd] = dict(type=types[1], color=colors[1], on=macd)
    self.sec[hmacd] = dict(type=types[2], color=colors[2], on=macd)
    (self.ind[macd], self.ind[smacd], self.ind[hmacd]) = talib.MACDEXT(
        self.df[self.cl].values,
        fastperiod,
        fastmatype,
        slowperiod,
        slowmatype,
        signalperiod,
        signalmatype,
    )
Example #21
0
def MACDEXT(Series,
            fastperiod=12,
            fastmatype=0,
            slowperiod=26,
            slowmatype=0,
            signalperiod=9,
            signalmatype=0):
    macd, macdsignal, macdhist = talib.MACDEXT(Series.values, fastperiod,
                                               fastmatype, slowperiod,
                                               slowmatype, signalperiod,
                                               signalmatype)
    return pd.Series(macd, index=Series.index), pd.Series(
        macdsignal, index=Series.index), pd.Series(macdhist,
                                                   index=Series.index)
Example #22
0
 def MACDEXT(Close,
             fastperiod=12,
             fastmatype=0,
             slowperiod=26,
             slowmatype=0,
             signalperiod=9,
             signalmatype=0):
     macd, macdsignal, macdhist = pd.DataFrame(), pd.DataFrame(
     ), pd.DataFrame()
     for i in Close.columns:
         macd[i], macdsignal[i], macdhist[i] = ta.MACDEXT(
             Close[i], fastperiod, fastmatype, slowperiod, slowmatype,
             signalperiod, signalmatype)
     return macd, macdsignal, macdhist
def MACDEXT(raw_df,
            fastperiod=12,
            fastmatype=0,
            slowperiod=26,
            slowmatype=0,
            signalperiod=9,
            signalmatype=0):
    # extract necessary data from raw dataframe (close)
    # returns 3 things
    macd, macdsignal, macdhist = ta.MACDEXT(raw_df.Close.values, fastperiod,
                                            fastmatype, slowperiod, slowmatype,
                                            signalperiod, signalmatype)
    singleMerged = np.stack((macd, macdsignal, macdhist), axis=-1)
    return singleMerged.tolist()
Example #24
0
def get_stocks_weekly_macd():
    result_list = []
    result_dict = {}
    df_stocks = get_stockbasket('', '')
    for stockcode in df_stocks['ts_code']:
        #获取前复权数据,默认为日期降序
        df_qfq = ts.pro_bar(ts_code=stockcode, freq='W', adj='qfq')
        if (df_qfq is None or len(df_qfq) < 2):
            continue
        else:
            #按照日期升序df
            df_qfq_asc = df_qfq.sort_values(by="trade_date", ascending=True)
            #重新设置索引
            df_qfq_asc.reset_index(drop=True, inplace=True)
            #初始化CDMA df
            df = pd.DataFrame()
            df['DIF'], df['DEA'], df['MACD'] = talib.MACDEXT(
                df_qfq_asc['close'],
                fastperiod=12,
                fastmatype=1,
                slowperiod=26,
                slowmatype=1,
                signalperiod=9,
                signalmatype=1)
            df['MACD'] = df['MACD'] * 2
            #按照index反序
            df = df.sort_index(ascending=False)
            #重新设置索引
            df.reset_index(drop=True, inplace=True)
            #赋值series给df_qfq
            df_qfq['DIF'] = df['DIF']
            df_qfq['DEA'] = df['DEA']
            df_qfq['MACD'] = df['MACD']
            DIF_1 = round(df_qfq['DIF'][1], 4)
            DEA_1 = round(df_qfq['DEA'][1], 4)
            DIF_0 = round(df_qfq['DIF'][0], 4)
            DEA_0 = round(df_qfq['DEA'][0], 4)
            #MACD_0 = round(df_qfq['MACD'][0],4)
            #MACD_1 = round(df_qfq['MACD'][1],4)
            #print (df_qfq['trade_date'][0],df_qfq['close'][0],DIF_0,DEA_0,MACD_0)
            if (DIF_1 < DEA_1 and DIF_0 > DEA_0):
                print(stockcode, df_qfq['trade_date'][0], df_qfq['close'][0],
                      DIF_1, DEA_1, DIF_0, DEA_0)
                result_list.append(stockcode)
                result_dict['ts_code'] = stockcode
                result_dict['trade_date'] = df_qfq['trade_date'][0]
                result_dict['close'] = df_qfq['close'][0]
                result_dict['reason'] = str(sys._getframe().f_code.co_name)
    print(len(result_list))
Example #25
0
def get_macd(df, fast, slow, signal):
    fast_d, slow_d, macd_d = talib.MACDEXT(df[config.close_key].values, fastperiod=fast, slowperiod=slow,
                                                       signalperiod=signal, fastmatype=1, slowmatype=1,
                                                       signalmatype=1)
    macd_d *= 2

    df['fast'], df['slow'], df['macd'] = fast_d, slow_d, macd_d
    # df.dropna(how='any')
    df[config.macd_positon_key] = ''
    macd_jincha = df.macd > 0

    df.loc[macd_jincha[np.logical_and(macd_jincha == True, macd_jincha.shift() == False)].index, config.macd_positon_key] = config.jincha
    df.loc[macd_jincha[np.logical_and(macd_jincha == False, macd_jincha.shift() == True)].index, config.macd_positon_key] = config.sicha

    return df
 def MACDEXT(self, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0):
     real_data = np.array([self.df.close], dtype='f8')
     # macd, macdsignal, macdhist = talib.MACDEXT(real_data[0], fastperiod=fastperiod, fastmatype=fastmatype,
     #                                            slowperiod=slowperiod,
     #                                            slowmatype=slowmatype, signalperiod=signalperiod,
     #                                            signalmatype=signalmatype)
     # return go.Scatter(
     #     x=self.df.index,
     #     y=macd,
     #     name='MACDEXT'
     # )
     return talib.MACDEXT(real_data[0], fastperiod=fastperiod, fastmatype=fastmatype,
                          slowperiod=slowperiod,
                          slowmatype=slowmatype, signalperiod=signalperiod,
                          signalmatype=signalmatype)
Example #27
0
def macd(security, fastperiod=12, slowperiod=26, signalperiod=9):
    closes = attribute_history(security, slowperiod * 5, '1d',
                               ('close'))['close'].values
    # 增加当日数据去计算
    cur_close = attribute_history(security, 1, '1m', ('close'))['close'].values
    closes = numpy.concatenate((closes, cur_close))
    #log.info('prices:', close)
    macdDIFF, macdDEA, macd = talib.MACDEXT(closes,
                                            fastperiod=fastperiod,
                                            fastmatype=1,
                                            slowperiod=slowperiod,
                                            slowmatype=1,
                                            signalperiod=signalperiod,
                                            signalmatype=1)
    macd = macd * 2
    #log.info("%s macd ==> DIFF=%s, DEA=%s, macd=%s", security, macdDIFF[-1], macdDEA[-1], macd[-1])
    return macdDIFF, macdDEA, macd
Example #28
0
def MACDEXT(close,
            fastperiod=12,
            fastmatype=0,
            slowperiod=26,
            slowmatype=0,
            signalperiod=9,
            signalmatype=0):
    ''' MACD with controllable MA type

    分组: Momentum Indicator 动量指标

    简介:

    macd, macdsignal, macdhist = MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
    '''
    return talib.MACDEXT(close, fastperiod, fastmatype, slowperiod, slowmatype,
                         signalperiod, signalmatype)
Example #29
0
def stc(candles: np.ndarray,
        fast_period: int = 23,
        fast_matype: int = 1,
        slow_period: int = 50,
        slow_matype: int = 1,
        k_period: int = 10,
        d_period: int = 3,
        source_type: str = "close",
        sequential: bool = False) -> Union[float, np.ndarray]:
    """
    STC - Schaff Trend Cycle (Oscillator)

    :param candles: np.ndarray
    :param fast_period: int - default: 23
    :param fastmatype: int - default: 1
    :param slow_period: int - default: 50
    :param slowmatype: int - default: 1
    :param k_period: int - default: 10
    :param d_period: int - default: 3
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    candles = slice_candles(candles, sequential)

    source = get_candle_source(candles, source_type=source_type)

    macd, macdsignal, macdhist = talib.MACDEXT(source,
                                               fastperiod=fast_period,
                                               fastmatype=fast_matype,
                                               slowperiod=slow_period,
                                               slowmatype=slow_matype)

    stok = (macd - talib.MIN(macd, k_period)) / (
        talib.MAX(macd, k_period) - talib.MIN(macd, k_period)) * 100

    d = talib.EMA(stok, d_period)

    kd = (d - talib.MIN(d, k_period)) / (talib.MAX(d, k_period) -
                                         talib.MIN(d, k_period)) * 100

    res = talib.EMA(kd, d_period)

    return res if sequential else res[-1]
Example #30
0
def get_macdext(df):
    df['DIF'], df['DEA'], df['MACD'] = talib.MACDEXT(df['close'],
                                                     fastperiod=12,
                                                     fastmatype=1,
                                                     slowperiod=26,
                                                     slowmatype=1,
                                                     signalperiod=9,
                                                     signalmatype=1)
    df['MACD'] = df['MACD'] * 2
    df['MACD'].dropna(inplace=True)
    df['MACD'] = df['MACD'].reset_index(drop=True)
    df['DIF'].dropna(inplace=True)
    df['DIF'] = df['DIF'].reset_index(drop=True)
    df['DEA'].dropna(inplace=True)
    df['DEA'] = df['DEA'].reset_index(drop=True)
    #交易日降序排列
    df = df.sort_values(by="trade_date", ascending=False)
    return df