Beispiel #1
0
    def _calc_indicator(self, OHLCV_input):
        """
        Calculates the Williams' %R 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:
            high = OHLCV_input['high'].values[:, 0]
        except IndexError:
            high = OHLCV_input['high'].values

        try:
            low = OHLCV_input['low'].values[:, 0]
        except IndexError:
            low = OHLCV_input['low'].values

        try:
            close = OHLCV_input['close'].values[:, 0]
        except IndexError:
            close = OHLCV_input['close'].values

        output = DataFrame(WILLR(high, low, close, self.__timeperiod))
        output.columns = ['WILLR%d' % self.__timeperiod]
        return output
Beispiel #2
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]
Beispiel #3
0
def willr(high, low, close, length=None, talib=None, offset=None, **kwargs):
    """Indicator: William's Percent R (WILLR)"""
    # Validate arguments
    length = int(length) if length and length > 0 else 14
    min_periods = int(
        kwargs["min_periods"]) if "min_periods" in kwargs and kwargs[
            "min_periods"] is not None else length
    _length = max(length, min_periods)
    high = verify_series(high, _length)
    low = verify_series(low, _length)
    close = verify_series(close, _length)
    offset = get_offset(offset)
    mode_tal = bool(talib) if isinstance(talib, bool) else True

    if high is None or low is None or close is None: return

    # Calculate Result
    if Imports["talib"] and mode_tal:
        from talib import WILLR
        willr = WILLR(high, low, close, length)
    else:
        lowest_low = low.rolling(length, min_periods=min_periods).min()
        highest_high = high.rolling(length, min_periods=min_periods).max()

        willr = 100 * ((close - lowest_low) / (highest_high - lowest_low) - 1)

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

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

    # Name and Categorize it
    willr.name = f"WILLR_{length}"
    willr.category = "momentum"

    return willr
def priceTechnicalIndicatorOHLCV(open_price, high_price, low_price, close_price, volume):
    data_result = pd.DataFrame([])

    lags = [7, 14, 21, 28]  # ****** 待修改,技术指标的参数只用最常用的一套
    # accumlation/distribution
    ad = AD(high_price, low_price, close_price, volume)
    for lag in lags:
        # n day diff of AD
        tmp = ad.diff(lag)
        tmp.name = 'AD_DIFF_%dD' % lag
        data_result = pd.concat([data_result, tmp], axis=1)

        #Average Directional Movement Index
        tmp = ADX(high_price, low_price, close_price, lag)
        tmp.name = 'ADX_%dD' % lag
        data_result = data_result.join(tmp)

        # Commodity Channel Index
        tmp = CCI(high_price, low_price, close_price, lag)
        tmp.name = 'CCI_%dD' % lag
        data_result = data_result.join(tmp)

        # RSI
        tmp = RSI(close_price, lag)
        tmp.name = 'RSI_%dD' % lag
        data_result = data_result.join(tmp)

        # Stochastic
        tmp_k, tmp_d = STOCH(high_price, low_price, close_price, fastk_period=lag, slowk_period=3, slowd_period=3)
        tmp_k.name = 'STOCH_K_%dD' % lag
        tmp_d.name = 'STOCH_D_%dD' % lag
        data_result = data_result.join(tmp_k)
        data_result =data_result.join(tmp_d)

        # WILLR - Williams' %R
        tmp = WILLR(high_price, low_price, close_price, lag)
        tmp.name = 'WILLER_%dD' % lag
        data_result =data_result.join(tmp)

        # volatility ratio
        tmp = VR(high_price, low_price, close_price, lag)
        tmp.name = 'VR_%dD' % lag
        data_result = data_result.join(tmp)

    return data_result
def getTechnicalInd(data, window=10):
    close = data['Close']
    high = data['High']
    low = data['Low']
    volume = data['Volume']
    #madev = roc = willr=rsi=apo=atr=obv=adosc=slowk=fastk=slowd=fastd=vpos=vneg={}
    window = 10
    for i in range(0, window):

        # momentum indicators
        # rate of change: (price/prevPrice - 1)*100
        data["roc{0}".format(i)] = ROC(close.shift(i), timeperiod=10)
        # williams oscillator
        data["willr{0}".format(i)] = WILLR(high.shift(i),
                                           low.shift(i),
                                           close.shift(i),
                                           timeperiod=14)

        # relative strength index
        data["rsi{0}".format(i)] = RSI(close.shift(i), timeperiod=14)

        # absolute price oscillator: slowMA(price) - fastMA(price)
        data["apo{0}".format(i)] = APO(close.shift(i),
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        # volatility indicator

        data["atr{0}".format(i)] = ATR(high.shift(i),
                                       low.shift(i),
                                       close.shift(i),
                                       timeperiod=14)  # average true range
        # Volume indicator
        # on balance volume
        data["obv{0}".format(i)] = OBV(close.shift(i), volume.shift(i))
        # chaikin A/D oscillator
        data["adosc{0}".format(i)] = ADOSC(high.shift(i),
                                           low.shift(i),
                                           close.shift(i),
                                           volume.shift(i),
                                           fastperiod=3,
                                           slowperiod=10)

        # Stochastic Oscillator Slow %k: (C-L)/(H-L)*100
        data["slowk{0}".format(i)], data["slowd{0}".format(i)] = STOCH(
            high.shift(i),
            low.shift(i),
            close.shift(i),
            fastk_period=5,
            slowk_period=3,
            slowk_matype=0,
            slowd_period=3,
            slowd_matype=0)

        # STOCHF - Stochastic Fast
        data["fastk{0}".format(i)], data["fastd{0}".format(i)] = STOCHF(
            high.shift(i),
            low.shift(i),
            close.shift(i),
            fastk_period=5,
            fastd_period=3,
            fastd_matype=0)

        #vortex
        data["vortex_indicator_pos{0}".format(i)] = vortex_indicator_pos(
            high.shift(i), low.shift(i), close.shift(i), n=14, fillna=False)
        data["vortex_indicator_neg{0}".format(i)] = vortex_indicator_neg(
            high.shift(i), low.shift(i), close.shift(i), n=14, fillna=False)

        # returns
    for i in range(1, window):
        # overlap studies
        data["madev{0}".format(i)] = close - close.shift(1).rolling(
            window=i).mean()
        data["return{0}".format(i)] = close - close.shift(i)
    # std
    for i in range(2, window):
        data["std{0}".format(i)] = close.rolling(
            i).std()  #Standard deviation for a period of 5 days

    return data  #madev, roc,willr,rsi,apo,atr,obv,adosc,slowk,slowd,fastk,fastd,vpos, vneg, returns, stds
               (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))
exchange_rate['Match_Date']=pd.to_datetime(exchange_rate['Date'],format='%b %d, %Y')
print('Shape of Exchange Rate: ', exchange_rate.shape)
null_value_checks(exchange_rate)
exchange_rate=exchange_rate[::-1]

exchange_rate['Change %']=exchange_rate['Change %'].str.replace('%','')
exchange_rate['Change %']=exchange_rate['Change %'].astype(float)
Beispiel #7
0
    minValue = train_df.to_numpy().min()
    diff = maxValue - minValue
    train = train_df.transform(lambda x: (x - minValue) / diff)
    # test = test_df.transform(lambda x: (x - minValue) / diff)

    # Use technical analysis to expand the data
    train["upperband"], train["middleband"], train["lowerband"] = BBANDS(
        train.close.to_numpy())
    train["sar"] = SAR(train.high.to_numpy(), train.low.to_numpy())
    train["rsi"] = RSI(train.close.to_numpy(), timeperiod=5)
    train["slowk"], train["slowd"] = STOCH(train.high.to_numpy(),
                                           train.low.to_numpy(),
                                           train.close.to_numpy())
    train["ema"] = EMA(train.close.to_numpy(), timeperiod=5)
    train["willr"] = WILLR(train.high.to_numpy(),
                           train.low.to_numpy(),
                           train.close.to_numpy(),
                           timeperiod=5)

    train_data = train.dropna()
    train_data = train_data.reset_index(drop=True)
    """
    test["upperband"], test["middleband"], test["lowerband"] = BBANDS(test.close.to_numpy())
    test["sar"] = SAR(test.high.to_numpy(), test.low.to_numpy())
    test["rsi"] = RSI(test.close.to_numpy(), timeperiod=5)
    test["slowk"], test["slowd"] = STOCH(test.high.to_numpy(), test.low.to_numpy(), test.close.to_numpy())
    """
    # 2->bullish, 0->bearish, 1->do nothing
    y = list()
    for i in range(len(train_data)):
        isBull = (train_data["open"][i] > train_data["sar"][i],
                  train_data["open"][i] >= train_data["middleband"][i],