Ejemplo n.º 1
0
def myHMACalc(ohlc, period):
    half_length = int(round((period / 2), 0))
    sqrt_length = int(round(math.sqrt(period), 0))
    # ohlc = df['close'].values
    wmaf = WMA(ohlc, timeperiod=half_length)
    wmas = WMA(ohlc, timeperiod=period)
    deltawma = 2 * wmaf - wmas
    # deltawma = ohlc['deltawma'].values
    hma = WMA(deltawma, timeperiod=sqrt_length)
    return pd.Series(hma, name="{0} period HMA.".format(period))
Ejemplo n.º 2
0
def ASH(close, timerperiod = 9, smooth = 2):
    from talib import WMA 
    bull = np.full(len(close), np.nan)
    bear = np.full(len(close), np.nan)
    bull[1:] = 0.5*(abs(close[1:]-close[:-1])+(close[1:]-close[:-1]))
    bear[1:] = 0.5*(abs(close[1:]-close[:-1])-(close[1:]-close[:-1]))
    
    avgBull = WMA(bull, timerperiod)
    avgBear = WMA(bear, timerperiod)
    
    smoothBull = WMA(avgBull, smooth)
    smoothBear = WMA(avgBear, smooth)
    
    return smoothBull, smoothBear
Ejemplo n.º 3
0
def WADDAH_ATTAR_EXPLOSION(close, high, low, sensitive = 150, fast_period=20, slow_period = 40, channel_period = 20, channel_mult = 2, dead_zone=30):
    
    from talib import MACD 
    from talib import BBANDS 
    from talib import ATR 
    from talib import WMA 
    macd, macdsignal, macdhist = MACD(close, fastperiod=fast_period, slowperiod=slow_period, signalperiod=9)
    upperband, middleband, lowerband = BBANDS(close, timeperiod=channel_period, nbdevup=channel_mult, nbdevdn=channel_mult, matype=0)

    ind_trend1 = np.full(len(close), np.nan)
    ind_itrend1 = np.full(len(close), np.nan)
    ind_explo1 = np.full(len(close), np.nan)
    tr = WMA(ATR(high, low, close, 20),3)
    ind_dead = tr*dead_zone / 10
    for i in range(0,len(close)):
        if(i<2):
            continue
        trend1 = (macd[i] - macd[i-1]) * sensitive;
        trend2 = (macd[i-1] - macd[i-2]) * sensitive;
        explo1 = (upperband[i] - lowerband[i])
        #explo2 = (upperband[i-1] - lowerband[i-1])
        
        if(trend1>=0):
            ind_trend1[i]=trend1
            ind_itrend1[i]=0
        if(trend1<0):
            ind_trend1[i]=0
            ind_itrend1[i]=(trend1*-1)
        ind_explo1[i] = explo1
        #print(str(i)+"\t "+str(close[i])+"\t "+str(close[i])+"\t "+str(ind_trend1[i])+"\t"+str(ind_itrend1[i]))
    return ind_trend1, ind_itrend1, ind_explo1, ind_dead
Ejemplo n.º 4
0
def wma(close, length=None, asc=None, talib=None, offset=None, **kwargs):
    """Indicator: Weighted Moving Average (WMA)"""
    # Validate Arguments
    length = int(length) if length and length > 0 else 10
    asc = asc if asc else True
    close = verify_series(close, length)
    offset = get_offset(offset)
    mode_tal = bool(talib) if isinstance(talib, bool) else True

    if close is None: return

    # Calculate Result
    if Imports["talib"] and mode_tal:
        from talib import WMA
        wma = WMA(close, length)
    else:
        from numpy import arange as npArange
        from numpy import dot as npDot

        total_weight = 0.5 * length * (length + 1)
        weights_ = Series(npArange(1, length + 1))
        weights = weights_ if asc else weights_[::-1]

        def linear(w):
            def _compute(x):
                return npDot(x, w) / total_weight

            return _compute

        close_ = close.rolling(length, min_periods=length)
        wma = close_.apply(linear(weights), raw=True)

    # Offset
    if offset != 0:
        wma = wma.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        wma.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        wma.fillna(method=kwargs["fill_method"], inplace=True)

    # Name & Category
    wma.name = f"WMA_{length}"
    wma.category = "overlap"

    return wma
Ejemplo n.º 5
0
    def binaryClassificationInThirtyMinutes(self, df):
        '''
        Predict the price of bitcoin in the next 30 minutes by a given df (dataframe)

        Example: 
            binaryClassificationInThirtyMinutes(df) = 0

        Parameters:
            df: a dataframe with df.columns = ['open', 'high', 'low', 'close', 'volume']
        Returns:
            prediction: int = a prediction by the model, 0 for down, 1 for same or up
        '''

        # if len(df) != 34:
        #    # due to wma
        #    raise Exception("Dataframe must have 34 rows")

        data = df.copy()

        rsi = RSI(data['close'])
        k, d = STOCH(data['high'], data['low'], data['close'])
        macd, macdsignal, macdhist = MACD(data['close'],
                                          fastperiod=12,
                                          slowperiod=26,
                                          signalperiod=9)
        williams_r = WILLR(data['high'], data['low'], data['close'])
        rate_of_change = ROC(data['close'])
        on_balance_volume = OBV(data['close'], data['volume'])
        weighted_moving_average = WMA(data['close'])
        normalized_average_true_range = NATR(data['high'], data['low'],
                                             data['close'])

        data['rsi'] = rsi
        data['k'] = k
        data['d'] = d
        data['macd'] = macd
        data['williams_r'] = williams_r
        data['rate_of_change'] = rate_of_change
        data['on_balance_volume'] = on_balance_volume
        data['weighted_moving_average'] = weighted_moving_average
        data['normalized_average_true_range'] = normalized_average_true_range

        data = data.dropna(axis=0)

        data = self.normalizeDataframe(data)

        with open(
                pathlib.Path(__file__).resolve().parent /
                "random_forest_params", "rb") as file:
            model = pickle.load(file)

        features = data.values
        prediction = model.predict(features)
        return prediction[0]
Ejemplo n.º 6
0
def WMAdecision(table, days=20):
    decision = []
    close = table['Close']
    del table
    data = WMA(np.array(close), days)

    for i in np.arange(len(close)):
        if np.isnan(data[i]):
            decision.append(None)
        if data[i] > close[i]:
            decision.append('Sell')
        if data[i] < close[i]:
            decision.append('Buy')
    return {'decision': decision, 'data': data}
Ejemplo n.º 7
0
def WMAdecision(table, days=20):
    decision = []
    close = table['Close']
    del table
    data = WMA(np.array(close), days)

    for i in np.arange(len(close)):
        if np.isnan(data[i]):
            decision.append(None)
        if data[i] > close[i]:
            decision.append(TransactionType.SELL)
        if data[i] < close[i]:
            decision.append(TransactionType.BUY)
    return {'decision': decision, 'data': data}


#TODO revisar el csv de aeromex con los del koala en dropbox
Ejemplo n.º 8
0
    def _calc_indicator(self, OHLCV_input):
        """
        Calculates the Weighted Moving Average technical indicator using a wrapper for the TA-lib

        Args:
            :param OHLCV_input:  the dataframe with the Open, High, Low, Close and Volume values
            :type OHLCV_input: pandas DataFrame

        Returns:
            DataFrame with the indicators values.
        """
        try:
            close = OHLCV_input['close'].values[:, 0]
        except IndexError:
            close = OHLCV_input['close'].values

        output = DataFrame(WMA(close, self.__timeperiod))
        output.columns = ['WMA%d' % self.__timeperiod]
        return output
Ejemplo n.º 9
0
def wma(close, length=None, asc=None, offset=None, **kwargs):
    """Indicator: Weighted Moving Average (WMA)"""
    # Validate Arguments
    close = verify_series(close)
    length = int(length) if length and length > 0 else 10
    asc = asc if asc else True
    offset = get_offset(offset)

    # Calculate Result
    if Imports["talib"]:
        from talib import WMA
        wma = WMA(close, length)
    else:
        total_weight = 0.5 * length * (length + 1)
        weights_ = np.arange(1, length + 1)
        weights = weights_ if asc else np.flip(weights_)

        def _linear(x):
            return np.dot(x, weights) / total_weight

        values = [
            _linear(each)
            for each in np.lib.stride_tricks.sliding_window_view(np.array(close), length)
        ]
        wma_ds = Series([np.NaN] * (length - 1) + values)
        wma_ds.index = close.index

    # Offset
    if offset != 0:
        wma_ds = wma_ds.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        wma_ds.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        wma_ds.fillna(method=kwargs["fill_method"], inplace=True)

    # Name & Category
    wma_ds.name = f"WMA_{length}"
    wma_ds.category = "overlap"

    return wma_ds
corrected_data['Open']=corrected_data.apply(lambda x: x.Open_x if pd.isna(x.Open_y) else x.Open_y, axis=1)
corrected_data['High']=corrected_data.apply(lambda x: x.High_x if pd.isna(x.High_y) else x.High_y, axis=1)
corrected_data['Low']=corrected_data.apply(lambda x: x.Low_x if pd.isna(x.Low_y) else x.Low_y, axis=1)
corrected_data['Close']=corrected_data.apply(lambda x: x.Close_x if pd.isna(x.Close_y) else x.Close_y, axis=1)
corrected_data['Volume']=corrected_data.apply(lambda x: x.Volume_x if pd.isna(x.Volume_y) else x.Volume_y, axis=1)
corrected_data=corrected_data[['Open','High','Low','Close','Volume']]
corrected_data=corrected_data[~((corrected_data['High']==0) |
               (corrected_data['Open']==0)  |
                (corrected_data['Close']==0) |
                (corrected_data['Low']==0) |
                (corrected_data['Volume']==0))]
print(corrected_data.shape)

print('<<< Extract Technical Indicators....')  
corrected_data['SMA_10']=corrected_data['Close'].rolling(window=10).mean()
corrected_data['WMA_10']=WMA(corrected_data['Close'], timeperiod=10)
corrected_data['rsi']=RSI(corrected_data['Close'], timeperiod=10)
corrected_data['stoc_k'], corrected_data['stoc_d'] = STOCH(corrected_data['High'],corrected_data['Low'],corrected_data['Close'],10,6,0,6)
corrected_data['mom']=MOM(corrected_data['Close'], timeperiod=10)
corrected_data['macd'],_,_=MACD(corrected_data['Close'], fastperiod=12, slowperiod=26, signalperiod=10)
corrected_data['adosc']=ADOSC(corrected_data['High'], corrected_data['Low'], corrected_data['Close'], corrected_data['Volume'], fastperiod=3, slowperiod=10)
corrected_data['cci']=CCI(corrected_data['High'], corrected_data['Low'], corrected_data['Close'],timeperiod=10)
corrected_data['willr']=WILLR(corrected_data['High'], corrected_data['Low'], corrected_data['Close'],timeperiod=10)
null_value_checks(corrected_data)
corrected_data=corrected_data[~corrected_data['macd'].isnull()]
null_value_checks(corrected_data)
corrected_data_ta=corrected_data

print('<<< Completed extraction. Reading Forex Data....')  
exchange_rate=pd.read_csv('./Data/GBP_USD.csv')
print(exchange_rate.head(2))
abertura = brsr6CSV['ABERTURA'].values
fechamento = brsr6CSV['FECHAMENTO'].values
abertura = brsr6CSV['ABERTURA'].values
minimo = brsr6CSV['MINIMO'].values
maximo = brsr6CSV['MAXIMO'].values
variacao = brsr6CSV['VARIACAO'].values
volume = brsr6CSV['VOLUME'].values

upBR, midBR, lowBR = BBANDS(fechamento,
                            timeperiod=20,
                            nbdevup=2,
                            nbdevdn=2,
                            matype=0)
ema = EMA(fechamento,
          timeperiod=30)  #curto prazo 21. Medio prazo 24. Longo prazo 89
wma = WMA(fechamento, timeperiod=30)

# Momentum Indicators
macd, macdsignal, macdhist = MACD(fechamento,
                                  fastperiod=12,
                                  slowperiod=26,
                                  signalperiod=9)
# print('-----------------------------------MACD-----------------------------------')
# print(macd[34:37])
# print(macdsignal[34:37])
# print(macdhist[34:37])
#
rsi = RSI(fechamento, timeperiod=14)
# print('-----------------------------------RSI-----------------------------------')
# print(rsi[34:37])
# Momentum Indicators # Volume Indicators
Ejemplo n.º 12
0
def HMA(close, timeperiod=14):
    import math
    from talib import WMA
    sqrt_period = math.sqrt(timeperiod)
    wma1 = (2*WMA(close, timeperiod = int(timeperiod/2)))-WMA(close, timeperiod = timeperiod)
    return WMA(wma1,timeperiod =int(sqrt_period))
Ejemplo n.º 13
0
def priceTechnicalIndicator(value, tot_lags, prefix):
    lags = np.array(tot_lags)
    lags = lags[lags >= 2]

    data_result = pd.DataFrame([])
    # MA series
    for lag in lags:
        # SMA
        sma = pd.Series(SMA(value, timeperiod=lag), name='%sMA_%dD' % (prefix, lag))
        data_result = pd.concat([data_result, sma], axis=1)

        # SMA derivatives
        tmp = ma_derivative_indicator(value, sma, 'MA', lag, prefix)
        data_result = data_result.join(tmp)

        # EMA
        ema = pd.Series(EMA(value, lag), name='%sEMA_%dD' % (prefix, lag))
        data_result = data_result.join(ema)

        # EMA derivatives
        tmp = ma_derivative_indicator(value, ema, 'EMA', lag, prefix)
        data_result = data_result.join(tmp)

        # WMA
        wma = pd.Series(WMA(value, lag), name='%sWMA_%dD' % (prefix, lag))
        data_result = data_result.join(wma)

        # WMA derivatives
        tmp = ma_derivative_indicator(value, wma, 'WMA', lag, prefix)
        data_result = data_result.join(tmp)

    # change percent
    lags = tot_lags
    for lag in lags:
        tmp = pd.Series(value.diff(lag) / value.shift(lag), name='%sRET_%dD' % (prefix, lag))
        data_result = data_result.join(tmp)

    # volatility
    lags = np.array(tot_lags)
    lags = lags[lags >= 5]
    for lag in lags:
        tmp = pd.Series(value.rolling(window=lag).std(), name='%sSTD_%dD' % (prefix, lag))
        data_result = data_result.join(tmp)

    # technical indicators
    lags = [7, 14, 21, 28]  # ****** 待修改,技术指标的参数只用最常用的一套
    for lag in lags:
        # bollinger brands
        tmp_upper, tmp_middle, tmp_lower = BBANDS(value, lag, 2, 2)
        tmp_upper.name = '%sBBANDS_UPPER_%dD' % (prefix, lag)
        tmp_lower.name = '%sBBANDS_LOWER_%dD' % (prefix, lag)
        data_result = data_result.join(tmp_upper)
        data_result = data_result.join(tmp_lower)

        # MACD
        tmp, tmp_signal, tmp_hist = MACD(value, 12, 26, lag)
        tmp.name = '%sMACD_DIF_12_26D' % prefix  # macd 对应 macd_dif 线
        tmp_signal.name = '%sMACD_DEA_12_26_%dD' % (prefix, lag)  # macd_signal 对应 macd_dea 线
        tmp_hist = 2 * tmp_hist
        tmp_hist.name = '%sMACD_12_26_%dD' % (prefix, lag)  # 2 * macd_hist 对应 macd 线
        if tmp.name not in data_result.columns:  # macd_dif is the same for all lags
            data_result = data_result.join(tmp)
        data_result = data_result.join(tmp_signal)
        data_result = data_result.join(tmp_hist)


    return data_result