Exemple #1
0
    def test_PLUS_DI(self):
        class MyPLUS_DI(OperatorPLUS_DI):
            def __init__(self, name, **kwargs):
                super(MyPLUS_DI, self).__init__(100, name, **kwargs)

        self.env.add_operator('minus_di', {
            'operator': MyPLUS_DI,
        })
        string = 'minus_di(14, high, low, close)'
        gene = self.env.parse_string(string)
        self.assertRaises(IndexError, gene.eval, self.env, self.dates[98],
                          self.dates[-1])
        df = gene.eval(self.env, self.dates[99], self.dates[100])
        ser0, ser1 = df.iloc[0], df.iloc[1]
        h = self.env.get_data_value('high').values
        l = self.env.get_data_value('low').values
        c = self.env.get_data_value('close').values
        res0, res1, res = [], [], []
        for i, val in ser0.iteritems():
            res0.append(
                talib.PLUS_DI(
                    h[:100, i], l[:100, i], c[:100,
                                              i], timeperiod=14)[-1] == val)
        for i, val in ser1.iteritems():
            res0.append(
                talib.PLUS_DI(h[1:100 + 1, i],
                              l[1:100 + 1, i],
                              c[1:100 + 1, i],
                              timeperiod=14)[-1] == val)
            res.append(
                talib.PLUS_DI(h[:100 + 1, i],
                              l[:100 + 1, i],
                              c[:100 + 1, i],
                              timeperiod=14)[-1] != val)
        self.assertTrue(all(res0) and all(res1) and any(res))
    def get(self, df):
        h, l, c = df['h'], df['l'], df['c']

        adx = talib.ADX(h, l, c, timeperiod=self.time_period)
        plus_di = talib.PLUS_DI(h, l, c, timeperiod=self.time_period)
        minus_di = talib.MINUS_DI(h, l, c, timeperiod=self.time_period)

        last_adx, last_plus_di, last_minus_di = adx.iloc[-1], plus_di.iloc[-1], minus_di.iloc[-1]

        material = dict(adx=adx, plus_di=plus_di, minus_di=minus_di)

        if last_adx > self.trend_threshold:
            if last_plus_di > last_minus_di:
                indicator_value = IndicatorValue(ADXIndicatorSign.TREND_PLUS.name, material=material)
            else:
                indicator_value = IndicatorValue(ADXIndicatorSign.TREND_MINUS.name, material=material)
        else:
            if last_plus_di > last_minus_di:
                indicator_value = IndicatorValue(ADXIndicatorSign.NO_TREND_PLUS.name, material=material)
            else:
                indicator_value = IndicatorValue(ADXIndicatorSign.NO_TREND_MINUS.name, material=material)

        if not self.is_test:
            logging.info('sign=>%s ADX=>%s +DI=>%s -DI=>%s', indicator_value.value, last_adx, last_plus_di,
                         last_minus_di)

        return indicator_value
Exemple #3
0
 def dmi(self):
     df = self.df
     MINUS_DI = talib.MINUS_DI(df.high, df.low, df.close, timeperiod=14)
     PLUS_DI = talib.PLUS_DI(df.high, df.low, df.close, timeperiod=14)
     ADX = talib.ADX(df.high, df.low, df.close, timeperiod=6)
     ADXR = talib.ADXR(df.high, df.low, df.close, timeperiod=6)
     return PLUS_DI.tolist(), MINUS_DI.tolist(), ADX.tolist(), ADXR.tolist()
def record_ADX(context, data):
    prices = data.history(context.stock, 'price', 252, '1d')
    market = data.history(context.market, 'price', 252, '1d')
    period = 14

    H = data.history(context.stock, 'high', 2 * period, '1d').dropna()
    L = data.history(context.stock, 'low', 2 * period, '1d').dropna()
    C = data.history(context.stock, 'price', 2 * period, '1d').dropna()

    ta_ADX = talib.ADX(H, L, C, period)
    ta_nDI = talib.MINUS_DI(H, L, C, period)
    ta_pDI = talib.PLUS_DI(H, L, C, period)

    ADX = ta_ADX[-1]
    nDI = ta_nDI[-1]
    pDI = ta_pDI[-1]

    beta = talib.BETA(prices, market, timeperiod=21)[-1:]

    if (ADX > 25) and (nDI > pDI):
        order_target_percent(context.stock, -1) and order_target_percent(
            context.market, beta)
    elif (ADX > 25) and (nDI < pDI):
        order_target_percent(context.stock, 1) and order_target_percent(
            context.market, -beta)

    record(ADX=ADX, nDI=nDI, pDI=pDI)
Exemple #5
0
def generate_feature(data):
    high = data.High.values
    low = data.Low.values
    close = data.Close.values

    feature_df = pd.DataFrame(index=data.index)
    feature_df["ADX"] = ADX = talib.ADX(high, low, close, timeperiod=14)
    feature_df["ADXR"] = ADXR = talib.ADXR(high, low, close, timeperiod=14)
    feature_df["APO"] = APO = talib.APO(close, fastperiod=12, slowperiod=26, matype=0)
    feature_df["AROONOSC"] = AROONOSC = talib.AROONOSC(high, low, timeperiod=14)
    feature_df["CCI"] = CCI = talib.CCI(high, low, close, timeperiod=14)
    feature_df["CMO"] = CMO = talib.CMO(close, timeperiod=14)
    feature_df["DX"] = DX = talib.DX(high, low, close, timeperiod=14)
    feature_df["MINUS_DI"] = MINUS_DI = talib.MINUS_DI(high, low, close, timeperiod=14)
    feature_df["MINUS_DM"] = MINUS_DM = talib.MINUS_DM(high, low, timeperiod=14)
    feature_df["MOM"] = MOM = talib.MOM(close, timeperiod=10)
    feature_df["PLUS_DI"] = PLUS_DI = talib.PLUS_DI(high, low, close, timeperiod=14)
    feature_df["PLUS_DM"] = PLUS_DM = talib.PLUS_DM(high, low, timeperiod=14)
    feature_df["PPO"] = PPO = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0)
    feature_df["ROC"] = ROC = talib.ROC(close, timeperiod=10)
    feature_df["ROCP"] = ROCP = talib.ROCP(close, timeperiod=10)
    feature_df["ROCR100"] = ROCR100 = talib.ROCR100(close, timeperiod=10)
    feature_df["RSI"] = RSI = talib.RSI(close, timeperiod=14)
    feature_df["ULTOSC"] = ULTOSC = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28)
    feature_df["WILLR"] = WILLR = talib.WILLR(high, low, close, timeperiod=14)
    feature_df = feature_df.fillna(0.0)

    matrix = np.stack((
        ADX, ADXR, APO, AROONOSC, CCI, CMO, DX, MINUS_DI, ROCR100, ROC,
        MINUS_DM, MOM, PLUS_DI, PLUS_DM, PPO, ROCP, WILLR, ULTOSC, RSI))
    matrix = np.nan_to_num(matrix)
    matrix = matrix.transpose()

    return feature_df, matrix
def adx(prices_df: pd.DataFrame,
        timeperiod=14) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    prices_arr = prices_df.to_numpy()
    adxs, plus_dis, minus_dis = \
        np.empty_like(prices_arr), np.empty_like(prices_arr), np.empty_like(prices_arr)
    for col in range(prices_arr.shape[1]):
        series = prices_arr[:, col]
        adxs[:, col] = talib.ADX(high=series,
                                 low=series,
                                 close=series,
                                 timeperiod=timeperiod)
        plus_dis[:, col] = talib.PLUS_DI(high=series,
                                         low=series,
                                         close=series,
                                         timeperiod=timeperiod)
        minus_dis[:, col] = talib.MINUS_DI(high=series,
                                           low=series,
                                           close=series,
                                           timeperiod=timeperiod)
    return (pd.DataFrame(adxs,
                         dtype=prices_arr.dtype,
                         index=prices_df.index,
                         columns=prices_df.columns),
            pd.DataFrame(plus_dis,
                         dtype=prices_arr.dtype,
                         index=prices_df.index,
                         columns=prices_df.columns),
            pd.DataFrame(minus_dis,
                         dtype=prices_arr.dtype,
                         index=prices_df.index,
                         columns=prices_df.columns))
Exemple #7
0
def plus_di(
    client,
    symbol,
    timeframe="6m",
    highcol="high",
    lowcol="low",
    closecol="close",
    period=14,
):
    """This will return a dataframe of
    Plus Directional Movement
    for the given symbol across the given timeframe

    Args:
        client (pyEX.Client): Client
        symbol (string): Ticker
        timeframe (string): timeframe to use, for pyEX.chart
        highcol (string): column to use to calculate
        lowcol (string): column to use to calculate
        closecol (string): column to use to calculate
        period (int): period to calculate across

    Returns:
        DataFrame: result
    """
    df = client.chartDF(symbol, timeframe)
    x = t.PLUS_DI(df[highcol].values, df[lowcol].values, df[closecol].values, period)
    return pd.DataFrame(
        {
            highcol: df[highcol].values,
            lowcol: df[lowcol].values,
            closecol: df[closecol].values,
            "plus_di": x,
        }
    )
Exemple #8
0
def checkOne(code_str):
    df = base.getOneStockData(code_str)
    df['MINUS_DM_' + str(adx_timeperiod)] = ta.MINUS_DM(
        np.array(df['high']), np.array(df['low']), timeperiod=adx_timeperiod)
    df['PLUS_DM_' + str(adx_timeperiod)] = ta.PLUS_DM(
        np.array(df['high']), np.array(df['low']), timeperiod=adx_timeperiod)
    df['TR_' + str(adx_timeperiod)] = ta.TRANGE(np.array(df['high']),
                                                np.array(df['low']),
                                                np.array(df['close']))
    df['MINUS_DI_' + str(adx_timeperiod)] = ta.MINUS_DI(
        np.array(df['high']),
        np.array(df['low']),
        np.array(df['close']),
        timeperiod=adx_timeperiod)
    df['PLUS_DI_' + str(adx_timeperiod)] = ta.PLUS_DI(
        np.array(df['high']),
        np.array(df['low']),
        np.array(df['close']),
        timeperiod=adx_timeperiod)
    df['ADX_' + str(adx_timeperiod)] = ta.ADX(np.array(df['high']),
                                              np.array(df['low']),
                                              np.array(df['close']),
                                              timeperiod=adx_timeperiod)
    df['ADXR_' + str(adx_timeperiod)] = ta.ADXR(np.array(df['high']),
                                                np.array(df['low']),
                                                np.array(df['close']),
                                                timeperiod=adx_timeperiod)

    df.to_csv(ADX_DIR + code_str + '.csv')
Exemple #9
0
 def compPLUSDI(self):
     pdi = talib.PLUS_DI(self.high,self.low,self.close,timeperiod=self.lookback)
     self.removeNullID(pdi)
     self.rawFeatures['PLUS_DI']=pdi 
     
     FEATURE_SIZE_DICT['PLUS_DI'] = 1
     return
Exemple #10
0
def di(candles: np.ndarray, period=14, sequential=False) -> DI:
    """
    DI - Directional Indicator

    :param candles: np.ndarray
    :param period: int - default=14
    :param sequential: bool - default=False

    :return: DI(plus, minus)
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    MINUS_DI = talib.MINUS_DI(candles[:, 3],
                              candles[:, 4],
                              candles[:, 2],
                              timeperiod=period)
    PLUS_DI = talib.PLUS_DI(candles[:, 3],
                            candles[:, 4],
                            candles[:, 2],
                            timeperiod=period)

    if sequential:
        return DI(PLUS_DI, MINUS_DI)
    else:
        return DI(PLUS_DI[-1], MINUS_DI[-1])
Exemple #11
0
def handle_data(context, data):
    security = g.security  
    # 获取股票的价格信息
    price = attribute_history(security, context.OBSERVATION, '1d', ('high','low','close'))

    ADX = talib.ADX(price['high'].values,price['low'].values,price['close'].values, context.ADXPERIOD)
    PDI = talib.PLUS_DI(price['high'].values,price['low'].values,price['close'].values, context.ADXPERIOD)
    NDI = talib.MINUS_DI(price['high'].values,price['low'].values,price['close'].values, context.ADXPERIOD)
    
    current_price = data[security].close
    current_position = context.portfolio.positions[security].closeable_amount
    cash = context.portfolio.cash
    
    print(security) 
    if current_price !=0:
        shares = cash/current_price
    
    record(ADX=ADX[-1])
    record(Plus_DI=PDI[-1])
    record(Minus_DI=NDI[-1])
    
    #ADX上行,+DI>-DI,当前空仓,则全仓买入标的
    if ADX[-1]>ADX[-2] and PDI[-1]>NDI[-1] and current_position <= 0:
        order_value(security,cash)
        log.info("Buying %s" % (security))#记录交易信息
    #ADX下行,+DI<-DI,则进行清仓
    if ADX[-1]<ADX[-2] and PDI[-1]<NDI[-1] and current_position > 0:
        order_target(security, 0)
        log.info("Selling %s" % (security))
Exemple #12
0
    def ADX5_AROON(self, df):
        adx5_exLevel = 95
        adx5_brLevel = 10

        df.drop(df.last_valid_index(), axis=0, inplace=True)

        df['PLUS_DI'] = talib.PLUS_DI(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=5)
        df['MINUS_DI'] = talib.MINUS_DI(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=5)
        df['ADX5'] = talib.ADX(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=5)
        df['ARDN'], df['ARUP'] = talib.AROON(df['High'].values, df['Low'].values, timeperiod=10)

        df['ADX5SHIFTED'] = df['ADX5'].shift(1)
        df['ARDNSHIFTED'] = df['ARDN'].shift(1)
        df['ARUPSHIFTED'] = df['ARUP'].shift(1)

        columns = ['PLUS_DI', 'MINUS_DI', 'ADX5', 'AROONDN', 'AROONUP', 'ADX5SHIFTED', 'ARDNSHIFTED', 'ARUPSHIFTED']

        def adx5_aroon_cond(row, columns):
            df1_adx5_cond = (row['ADX5'] > row['ADX5SHIFTED']) & (row['ADX5'] > adx5_brLevel) & (
                        row['ADX5'] < adx5_exLevel)
            arbuy = (row['ARUPSHIFTED'] < 5) & (row['ARUP'] > 85) & (row['ARUP'] > row['ARDN'])
            arsell = (row['ARDNSHIFTED'] < 5) & (row['ARDN'] > 85) & (row['ARUP'] < row['ARDN'])
            buy = (row['PLUS_DI'] > row['MINUS_DI']) & df1_adx5_cond & arbuy
            sell = (row['PLUS_DI'] < row['MINUS_DI']) & df1_adx5_cond & arsell
            return buy, sell

        df['BUY'], df['SELL'] = zip(*df.apply(lambda row: adx5_aroon_cond(row, columns), axis=1))

        df2 = df.tail(self.withinBars)
        df2['BUY'].any()
        df2['SELL'].any()

        #return [df['SELL'].iloc[-1], df['BUY'].iloc[-1], df['normal_time']]
        return [df2['SELL'].any(), df2['BUY'].any(), df['normal_time']]
def ADX(data, n=14):
    """
    data: original data with open,high,low,close,vol
    n: timeperiod
    """
    data['adx'] = ta.ADX(
        np.array(data.high), np.array(data.low), np.array(data.close),
        n)  #Average Directional Movement Index (Momentum Indicators)
    data['mdi'] = ta.MINUS_DI(np.array(data.high), np.array(data.low),
                              np.array(data.close), n)
    data['pdi'] = ta.PLUS_DI(np.array(data.high), np.array(data.low),
                             np.array(data.close), n)
    signal = pd.DataFrame(index=data.index)

    #strategy 1
    """
    当+DI上穿-DI,买入,信号为1
    当+DI下穿-DI,卖空,信号为-1
    """
    signal['1'] = ((data['pdi'] > data['mdi']) &
                   (data['pdi'].shift(1) < data['mdi'].shift(1))) * 1 + (
                       (data['pdi'] <= data['mdi']) &
                       (data['pdi'].shift(1) < data['mdi'].shift(1))) * (-1)
    signal['1'] = signal['1'][signal['1'].isin([1,
                                                -1])].reindex(data.index,
                                                              method='ffill')
    signal = signal.fillna(0)
    return signal
Exemple #14
0
def dmi(source, dmi_period, dmi_smooth):
	minus_name = "MINUS_DI_" + str(dmi_period) + "_" + str(dmi_smooth)
	plus_name = "PLUS_DI_" + str(dmi_period) + "_" + str(dmi_smooth)
	adx_name = "ADX_" + str(dmi_period) + "_" + str(dmi_smooth)

	source = source.join(
		pd.Series(talib.MINUS_DI(source['High'], source['Low'], source['Close'], timeperiod=dmi_period),
				  name=minus_name))
	source = source.join(pd.Series(talib.PLUS_DI(source['High'], source['Low'], source['Close'], timeperiod=dmi_period),
								   name=plus_name))
	source = source.join(pd.Series(talib.ADX(source['High'], source['Low'], source['Close'], timeperiod=dmi_smooth),
								   name=adx_name))

	# Trends
	source = do_uptrend(source, adx_name)
	source = do_uptrend(source, plus_name)
	source = do_uptrend(source, minus_name)

	# Overs
	source = do_over(source, adx_name, plus_name)
	source = do_over(source, adx_name, minus_name)
	source = do_over(source, plus_name, minus_name)

	# Aboves
	for level in range(5, 65, 5):
		source = do_above(source, adx_name, level)
		source = do_above(source, plus_name, level)
		source = do_above(source, minus_name, level)

	source = source.drop(columns=[adx_name, plus_name, minus_name])

	return source
Exemple #15
0
    def __calculate_indicator(self):
        # Create RSI Series
        self.rsi = talib.RSI(self.numpy_array["close"], timeperiod=14)

        # Create Bollinger Bands
        bollinger_upper, bollinger_middle, bollinger_lower = talib.BBANDS(
            self.numpy_array["close"], timeperiod=20)
        self.bollinger_bandwidth = (
            (bollinger_upper - bollinger_lower) / bollinger_middle) * 100

        # Calculate Directional Indicators.
        minus_dmi = talib.MINUS_DI(high=self.numpy_array["high"],
                                   low=self.numpy_array["low"],
                                   close=self.numpy_array["close"])
        plus_dmi = talib.PLUS_DI(high=self.numpy_array["high"],
                                 low=self.numpy_array["low"],
                                 close=self.numpy_array["close"])

        # If Directional Indicator gives Upward Direction.
        self.dmi_difference = plus_dmi - minus_dmi

        # Slope Calculation : Throws error if value is yet NaN
        try:
            self.rsi_slope_angle = self.__slope_to_degrees(
                talib.LINEARREG_SLOPE(self.rsi, timeperiod=5))
            self.bw_slope_angle = self.__slope_to_degrees(
                talib.LINEARREG_SLOPE(self.bollinger_bandwidth, timeperiod=5))
        except Exception:
            #logging.info("Value of RSI and Bollinger is null")
            raise StrategyNotReady(1, "Value of RSI and Bollinger is null")
        return None
Exemple #16
0
def get_strength_ADX(data):
    op = np.array(talib.ADX(data['High'], data['Low'], data['Close']))
    plus_DI = np.array(talib.PLUS_DI(data['High'], data['Low'], data['Close']))
    minus_DI = np.array(
        talib.MINUS_DI(data['High'], data['Low'], data['Close']))

    #plots
    list_traces = []
    list_traces.append(go.Scatter(x=data['Date'], y=op, name='ADX'))
    list_traces.append(go.Scatter(x=data['Date'], y=plus_DI, name='+DI'))
    list_traces.append(go.Scatter(x=data['Date'], y=minus_DI, name='-DI'))
    fig = go.Figure(data=list_traces)
    plot(fig)

    #score calculation
    score = 0
    if (op[-1] > 20):
        if (plus_DI[-1] > minus_DI[-1]):
            score = (op[-1] - 20) * 1.5
            if score > 10:
                score = 10
        else:
            score = (op[-1] - 20) * -1.5
            if score < -10:
                score = -10
    return score, fig
Exemple #17
0
def plus_di(df, periods=14):
    df, data = reset_index(df)
    df['DI+'] = ta.PLUS_DI(df['High'],
                           df['Low'],
                           df['Close'],
                           timeperiod=periods)
    return df
Exemple #18
0
def strategy_ema(candles, outperiod):
    # Define the decision period - in minutes
    decision_period=outperiod
    
    # Convert candles to decision period
    outcandles=convert_candle(candles,decision_period)
    
    # Calculate indicators - EMA, DMI
    short_ema=talib.EMA(outcandles[:,3], timeperiod=9)
    long_ema=talib.EMA(outcandles[:,3], timeperiod=20)
    ema_diff=short_ema-long_ema
    
    plus_di=talib.PLUS_DI(outcandles[:,4], outcandles[:,1], outcandles[:,3], timeperiod=14) # PLUS_DI(high, low, close, timeperiod=14)
    minus_di=talib.MINUS_DI(outcandles[:,4], outcandles[:,1], outcandles[:,3], timeperiod=14) #MINUS_DI(high, low, close, timeperiod=14)
    dm_diff=plus_di-minus_di
    
    # Iterate over the candles and determine buy/sell
    decision_table=[]
    for i in range(len(outcandles)):
        if math.isnan(ema_diff[i]) or math.isnan(dm_diff[i]):
            decision_table.append("") # do nothing
        else:
            decision_table.append("")
            if ema_diff[i]>0 and ema_diff[i-1]<0: # if crossed from below, buys
                #if dm_diff[i]>0: # confirm with directional movement
                decision_table[i]="buy"
            elif ema_diff[i]<0 and ema_diff[i-1]>0: #if cross from above, sells
                #if dm_diff[i]<0: # confirm with directional movement
                decision_table[i]="sell"
                
        # Check if it has crossed the ema_diff
        
    
    return decision_table
 def get_DI_positive(self, p=14):
     s = "DI_plus_{}".format(str(p))
     if s not in self.ti_df.columns:
         self.ti_df[s] = talib.PLUS_DI(self.history_df['High'],
                                       self.history_df['Low'],
                                       self.history_df['Close'], p)
     return self.ti_df[s]
Exemple #20
0
    def handle_bar(self, ctx):

        code = 'JCP'

        adx_period = 14
        short_ma_num = 5
        long_ma_num = 20
        data = ctx.data_provider.load_previous_quotes(
            code, end_date=ctx.current_date, previous_num=100)

        if len(data.date) == 0:
            return

        data_high = data.high[:-1]
        data_low = data.low[:-1]
        data_close = data.close[:-1]
        adx = talib.ADX(data_high, data_low, data_close, adx_period)
        plus_di = talib.PLUS_DI(data_high, data_low, data_close, adx_period)
        minus_di = talib.MINUS_DI(data_high, data_low, data_close, adx_period)
        short_ma = talib.SMA(data_close, short_ma_num)
        long_ma = talib.SMA(data_close, long_ma_num)

        current_price = data.close[-1]

        ma_up_cross = short_ma[-1] > long_ma[-1] and short_ma[-2] < long_ma[-2]
        ma_down_cross = short_ma[-1] < long_ma[-1] and short_ma[-2] > long_ma[
            -2]
        adx_up = adx[-1] > adx[-2]
        di_up = plus_di[-1] > minus_di[-1]

        if ma_up_cross and adx_up and di_up:
            ctx.order(code, 0.99, current_price)
        if ma_down_cross and not adx_up and not di_up:
            ctx.order(code, 0, current_price)
Exemple #21
0
def dmi(source, dmi_period, dmi_smooth):
    minus_name = "MINUS_DI_" + str(dmi_period) + "_" + str(dmi_smooth)
    plus_name = "PLUS_DI_" + str(dmi_period) + "_" + str(dmi_smooth)
    adx_name = "ADX_" + str(dmi_period) + "_" + str(dmi_smooth)

    source = source.join(
        pd.Series(talib.MINUS_DI(source['High'],
                                 source['Low'],
                                 source['Close'],
                                 timeperiod=dmi_period),
                  name=minus_name))
    source = source.join(
        pd.Series(talib.PLUS_DI(source['High'],
                                source['Low'],
                                source['Close'],
                                timeperiod=dmi_period),
                  name=plus_name))
    source = source.join(
        pd.Series(talib.ADX(source['High'],
                            source['Low'],
                            source['Close'],
                            timeperiod=dmi_smooth),
                  name=adx_name))

    return source
Exemple #22
0
def di(candles: np.ndarray, period: int = 14, sequential: bool = False) -> DI:
    """
    DI - Directional Indicator

    :param candles: np.ndarray
    :param period: int - default: 14
    :param sequential: bool - default: False

    :return: DI(plus, minus)
    """
    candles = slice_candles(candles, sequential)

    MINUS_DI = talib.MINUS_DI(candles[:, 3],
                              candles[:, 4],
                              candles[:, 2],
                              timeperiod=period)
    PLUS_DI = talib.PLUS_DI(candles[:, 3],
                            candles[:, 4],
                            candles[:, 2],
                            timeperiod=period)

    if sequential:
        return DI(PLUS_DI, MINUS_DI)
    else:
        return DI(PLUS_DI[-1], MINUS_DI[-1])
Exemple #23
0
def dmi(candles: np.ndarray, period=14, sequential=False) -> DMI:
    """
    DMI - Directional Movement Index

    :param candles: np.ndarray
    :param period: int - default=14
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    MINUS_DI = talib.MINUS_DI(candles[:, 3],
                              candles[:, 4],
                              candles[:, 2],
                              timeperiod=period)
    PLUS_DI = talib.PLUS_DI(candles[:, 3],
                            candles[:, 4],
                            candles[:, 2],
                            timeperiod=period)

    if sequential:
        return DMI(PLUS_DI, MINUS_DI)
    else:
        return DMI(PLUS_DI[-1], MINUS_DI[-1])
Exemple #24
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)
Exemple #25
0
def record_ADX(context, data):   

    period = 14
    
    H = data.history(context.aapl,'high', 2*period, '1d').dropna()
    L = data.history(context.aapl,'low', 2*period, '1d').dropna()   
    C = data.history(context.aapl,'price', 2*period, '1d').dropna()
    
    
    ta_ADX = talib.ADX(H, L, C, period)
    ta_nDI = talib.MINUS_DI(H, L, C, period)
    ta_pDI = talib.PLUS_DI(H, L, C, period)
    
    ADX = ta_ADX[-1]
    nDI = ta_nDI[-1]
    pDI = ta_pDI[-1]   

    record( ADX = ADX, nDI = nDI, pDI = pDI) 
    record(close_price = data.current(context.aapl,'close'))
    
    
    if nDI < pDI and ADX > 20 and data.can_trade(context.aapl):
        order_target_percent(context.aapl, 1)
    elif nDI > pDI and ADX > 20 and data.can_trade(context.aapl):
        order_target_percent(context.aapl, -1)

    
        
    

    print context.portfolio.positions[context.aapl].amount
Exemple #26
0
    def ADX_Overlap_old(self, args):
        adx5_exLevel = 70
        adx5_brLevel = 25
        adx14_exLevel = 45
        adx14_brLevel = 15

        df = args.df_current
        df.drop(df.last_valid_index(), axis=0, inplace=True)

        df['PLUS_DI'] = talib.PLUS_DI(df['High'].values,
                                      df['Low'].values,
                                      df['Close'].values,
                                      timeperiod=5)
        df['MINUS_DI'] = talib.MINUS_DI(df['High'].values,
                                        df['Low'].values,
                                        df['Close'].values,
                                        timeperiod=5)
        df['ADX5'] = talib.ADX(df['High'].values,
                               df['Low'].values,
                               df['Close'].values,
                               timeperiod=5)
        df['ADX14'] = talib.ADX(df['High'].values,
                                df['Low'].values,
                                df['Close'].values,
                                timeperiod=14)
        df['ADX5_Cond'] = (df.ADX5 > df.ADX5.shift(1)) & (
            df.ADX5 > adx5_brLevel) & (df.ADX5 < adx5_exLevel)
        df['ADX14_Cond'] = (df.ADX14 > df.ADX14.shift(1)) & (
            df.ADX14 > adx14_brLevel) & (df.ADX14 < adx14_exLevel)
        df['ADX5_14_OL'] = df['ADX5_Cond'] & df['ADX14_Cond']

        df['BUY'] = (df['PLUS_DI'] > df['MINUS_DI']) & df['ADX5_14_OL']
        df['SELL'] = (df['PLUS_DI'] < df['MINUS_DI']) & df['ADX5_14_OL']
        return [df['SELL'].iloc[-1], df['BUY'].iloc[-1]]
Exemple #27
0
 def plus_di(self, n, array=False):
     """
     PLUS_DI.
     """
     result = talib.PLUS_DI(self.high, self.low, self.close, n)
     if array:
         return result
     return result[-1]
Exemple #28
0
 def dmi(self, df, index):
     MINUS_DI = talib.MINUS_DI(df.high, df.low, df.close, timeperiod=14)
     #DX = talib.DX(df.high,df.low,df.close,timeperiod=14)
     PLUS_DI = talib.PLUS_DI(df.high, df.low, df.close, timeperiod=14)
     #PLUS_DM = talib.PLUS_DM(df.high,df.low, timeperiod=14)
     ADX = talib.ADX(df.high, df.low, df.close, timeperiod=6)
     ADXR = talib.ADXR(df.high, df.low, df.close, timeperiod=6)
     return MINUS_DI, PLUS_DI, ADX, ADXR
Exemple #29
0
 def plus_di(self, n: int, array: bool = False) -> Union[float, np.ndarray]:
     """
     PLUS_DI.
     """
     result = talib.PLUS_DI(self.high, self.low, self.close, n)
     if array:
         return result
     return result[-1]
Exemple #30
0
 def add_plusdi_ft(df, daily_count, count):
     for idx in range(1, count + 1):
         col_name = 'PLUSDI_' + str(idx)
         df[col_name] = talib.PLUS_DI(df.high,
                                      df.low,
                                      df.close,
                                      timeperiod=daily_count * idx)
     return df