Exemple #1
0
 def willr(self, n: int, array: bool = False) -> Union[float, np.ndarray]:
     """
     WILLR.
     """
     result = talib.WILLR(self.high, self.low, self.close, n)
     if array:
         return result
     return result[-1]
def willr(prices, signal):
    """
    Williams R Oscillator
    """

    window = signal['params']['window']
    signal['data'] = talib.WILLR(prices['high'], prices['low'],
                                 prices['close'], window).to_numpy()[:, None]
Exemple #3
0
 def willr(self, n, array=False):
     """
     WILLR.
     """
     result = talib.WILLR(self.high, self.low, self.close, n)
     if array:
         return result
     return result[-1]
Exemple #4
0
    def GetWR( self, lst ):

        C = np.array( self.df[ '收盤' ], dtype = float, ndmin = 1 )
        H = np.array( self.df[ '最高' ], dtype = float, ndmin = 1 )
        L = np.array( self.df[ '最低' ], dtype = float, ndmin = 1 )

        for val in lst:
            self.df[ 'WILLR' + str( val ) ] = talib.WILLR( H, L, C, timeperiod = val )
 def WR(single_stock_df, col_h='high', col_l='low', col_c='close', timeperiod=10):
     """
     计算威廉指标,timeperiod=10
     重要参数:high最高价 low最低价 close收盘价,此处算出为负值需要取绝对值
     """
     single_stock_df['wr'] = talib.WILLR(single_stock_df[col_h], single_stock_df[col_l],single_stock_df[col_c],timeperiod=timeperiod)
     single_stock_df['wr'] = single_stock_df['wr'].abs()
     return single_stock_df
Exemple #6
0
    def entry(self, df_ohlc, np_emas, tick):
        self.master_df_updated = df_ohlc
        self.master_df_updated['wr'] = ta.WILLR(
            self.master_df_updated['high'],
            self.master_df_updated['low'],
            self.master_df_updated['close'],
            timeperiod=40)
        list_r = self.master_df_updated['wr'].tolist()
        if self.activated is False:
            for i in range(-1, -1 * len(list_r), -1):
                if list_r[i] < -80 and self.data['long'] is True:
                    self.activated = True
                    break
                if list_r[i] > -20 and self.data['long'] is True:
                    self.activated = False
                    break
                if list_r[i] > -20 and self.data['short'] is True:
                    self.activated = True
                    break
                if list_r[i] <= -80 and self.data['short'] is True:
                    self.activated = False
                    break

        elif self.activated is True:
            print(self.data['symbol'])
            if self.data['long'] is True and tick['last_price'] > np_emas[
                    0, -1] and tick['last_price'] > np_emas[
                        1, -1] and list_r[-1] >= -20:
                self.long_position = True
                self.activated = False
                self.buy_price = tick['last_price']
                # threading
                order_id = self.kite.place_order(
                    tradingsymbol=self.data['symbol'],
                    exchange=self.kite.EXCHANGE_NSE,
                    transaction_type=self.kite.TRANSACTION_TYPE_BUY,
                    quantity=self.data['quantity'],
                    variety=self.kite.VARIETY_REGULAR,
                    order_type=self.kite.ORDER_TYPE_MARKET,
                    product=self.kite.PRODUCT_MIS)
                print(order_id)

            if self.data['short'] is True and tick['last_price'] < np_emas[
                    0, -1] and tick['last_price'] < np_emas[
                        1, -1] and list_r[-1] <= -80:
                self.short_position = True
                self.activated = False
                self.sell_price = tick['last_price']
                order_id = self.kite.place_order(
                    tradingsymbol=self.data['symbol'],
                    exchange=self.kite.EXCHANGE_NSE,
                    transaction_type=self.kite.TRANSACTION_TYPE_SELL,
                    quantity=self.data['quantity'],
                    variety=self.kite.VARIETY_REGULAR,
                    order_type=self.kite.ORDER_TYPE_MARKET,
                    product=self.kite.PRODUCT_MIS)

                print(order_id)
Exemple #7
0
def getMomentumIndicators(df):

    high = df['High']
    low = df['Low']
    close = df['Close']
    open = df['Open']
    volume = df['Volume']
    df['ADX'] = ta.ADX(high, low, close, timeperiod=14)
    df['SMA'] = ta.ADXR(high, low, close, timeperiod=14)
    df['APO'] = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
    df['AROONDOWN'], df['AROOONUP'] = ta.AROON(high, low, timeperiod=14)
    df['AROONOSC'] = ta.AROONOSC(high, low, timeperiod=14)
    df['BOP'] = ta.BOP(open, high, low, close)
    df['CCI'] = ta.CCI(high, low, close, timeperiod=14)
    df['CMO'] = ta.CMO(close, timeperiod=14)
    df['DX'] = ta.DX(high, low, close, timeperiod=14)
    df['MACD'], df['MACDSIGNAL'], df['MACDHIST'] = ta.MACD(close,
                                                           fastperiod=12,
                                                           slowperiod=26,
                                                           signalperiod=9)
    df['MFI'] = ta.MFI(high, low, close, volume, timeperiod=14)
    df['MINUS_DI'] = ta.MINUS_DI(high, low, close, timeperiod=14)
    df['MINUS_DM'] = ta.MINUS_DM(high, low, timeperiod=14)
    df['MOM'] = ta.MOM(close, timeperiod=10)
    df['PLUS_DM'] = ta.PLUS_DM(high, low, timeperiod=14)
    df['PPO'] = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
    df['ROC'] = ta.ROC(close, timeperiod=10)
    df['ROCP'] = ta.ROCP(close, timeperiod=10)
    df['ROCR'] = ta.ROCR(close, timeperiod=10)
    df['ROCR100'] = ta.ROCR100(close, timeperiod=10)
    df['RSI'] = ta.RSI(close, timeperiod=14)
    df['SLOWK'], df['SLOWD'] = ta.STOCH(high,
                                        low,
                                        close,
                                        fastk_period=5,
                                        slowk_period=3,
                                        slowk_matype=0,
                                        slowd_period=3,
                                        slowd_matype=0)
    df['FASTK'], df['FASTD'] = ta.STOCHF(high,
                                         low,
                                         close,
                                         fastk_period=5,
                                         fastd_period=3,
                                         fastd_matype=0)
    df['FASTK2'], df['FASTD2'] = ta.STOCHRSI(close,
                                             timeperiod=14,
                                             fastk_period=5,
                                             fastd_period=3,
                                             fastd_matype=0)
    df['TRIX'] = ta.TRIX(close, timeperiod=30)
    df['ULTOSC'] = ta.ULTOSC(high,
                             low,
                             close,
                             timeperiod1=7,
                             timeperiod2=14,
                             timeperiod3=28)
    df['WILLR'] = ta.WILLR(high, low, close, timeperiod=14)
def run_techicals(df):
    '''
    Preform technical anlysis calcuaitons and add to a dataframe.

    Algorithms stem from the TAlib module other helper functions, including distretizing data,
    using alternate series, and time shifting

    TAlib docs: https://github.com/mrjbq7/ta-lib/blob/master/docs/func_groups/momentum_indicators.md
    '''
    days_back = 0
    opn = np.roll(df['exp_smooth_open'], days_back)
    high = np.roll(df['exp_smooth_high'], 0)
    low = np.roll(df['exp_smooth_low'], 0)
    close = np.roll(df['exp_smooth_close'], days_back)
    volume = np.roll(df['exp_smooth_volume'], 0)

    # series = df['close'].values
    series = close

    # df['roc'] = talib.ROCP(series, timeperiod=1)
    df['roc'] = rate_of_change(df['close'], 1)  # > 0.04
    df['roc_d'] = discrete_series_pos_neg(df['roc'])  # > 80.638
    df['rsi'] = talib.RSI(series, timeperiod=14)  # > 80.638
    df['rsi_d'] = continuous_to_discrete_w_bounds(df['rsi'], 30,
                                                  70)  # > 80.638
    df['willr'] = talib.WILLR(high, low, series, timeperiod=14)  # > -11
    df['willr_d'] = discrete_trend(df['willr'])  # > -11
    df['cci'] = talib.CCI(high, low, series, timeperiod=14)  # > -11
    df['cci_d'] = continuous_to_discrete_w_bounds(df['cci'], -200,
                                                  200)  # > -11
    df['obv'] = talib.OBV(series, volume)
    df['mom'] = talib.MOM(series)
    df['mom_d'] = discrete_series_pos_neg(df['mom'])
    df['sma20'] = discrete_series_compare(close, talib.SMA(
        series, 20))  # > talib.MA(series, 200)
    df['sma50'] = discrete_series_compare(close, talib.SMA(
        series, 50))  # > talib.MA(series, 200)
    df['sma200'] = discrete_series_compare(close, talib.SMA(
        series, 200))  # > talib.MA(series, 200)
    df['wma10'] = discrete_series_compare(close, talib.WMA(series, 10))
    df['macd'], df['macd_sig'], macdhist = talib.MACD(series,
                                                      fastperiod=12,
                                                      slowperiod=26,
                                                      signalperiod=9)
    df['macd_d'] = discrete_trend(df['macd'])  # > -11
    df['stok'], df['stod'] = talib.STOCH(high,
                                         low,
                                         series,
                                         fastk_period=5,
                                         slowk_period=3,
                                         slowk_matype=0,
                                         slowd_period=3,
                                         slowd_matype=0)
    df['stok_d'] = discrete_trend(df['stok'])  # > -11
    df['stod_d'] = discrete_trend(df['stod'])  # > -11
    #df['sto'] = slowk #> 80

    return df
Exemple #9
0
def calcFeatures(df,indx):
    
    df1 = pd.DataFrame({'A' : []})

    #for i in range(0,7):
    for i in range(len(indx)):
        
        if (indx[i] and i==0):
            s1 = df['Open'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==1):
            s1 = df['High'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==2):
            s1 = df['Low'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==3):
            s1 = df['Close'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==4):
            s1 = df['Adj Close'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==5):
            s1 = df['Volume'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==6):
            s1 = pd.DataFrame( {'RSI': talib.RSI(np.array(df['Close'].values),timeperiod=14) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==7):
            s1 = pd.DataFrame( {'ROC': talib.ROC(np.array(df['Close'].values), timeperiod=10) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==8):
            s1 = pd.DataFrame( {'BETA': talib.BETA(np.array(df['High'].values), \
                np.array(df['Low'].values), timeperiod=5) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==9):
            s1 = pd.DataFrame( {'STDDEV': talib.STDDEV(np.array(df['Close'].values), \
                timeperiod=5, nbdev=1) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==10):
            s1 = pd.DataFrame( {'WILLR': talib.WILLR(np.array(df['Open'].values), \
                np.array(df['High'].values),np.array(df['Close'].values),timeperiod=40) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==11):
            s1 = pd.DataFrame( {'SMA1': talib.SMA(np.array(df['Close'].values), timeperiod=30) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==12):
            s1 = pd.DataFrame( {'SMA2': talib.SMA(np.array(df['Close'].values), timeperiod=60) }) 
            df1 = pd.concat([df1, s1], axis=1)

    #Delete 'A' column
    df1=df1.drop(columns=['A'])
    
    #Numpy array
    out=np.array(df1.values)
    out=out[~np.any(np.isnan(out), axis=1)]
    
    return out
Exemple #10
0
def get_feature(a, n):
    #1. data gathering & processing
    data = get_stock_data(a)
    data = data.replace(0, np.nan)
    data.dropna(inplace=True)

    #2. exponential smoothing
    S = X = np.array(data['Close'])
    alpha = 0.9
    for i in range(1, len(S)):
        S[i] = alpha * X[i] + (1 - alpha) * S[i - 1]
    data['Close'] = S

    #3.data extraction
    macd, dea, bar = talib.MACD(data['Close'].values,
                                fastperiod=12,
                                slowperiod=26,
                                signalperiod=9)
    fastk, fastd = talib.STOCHF(data['High'],
                                data['Low'],
                                data['Close'],
                                fastk_period=14,
                                fastd_period=3,
                                fastd_matype=0)
    data['dif'] = data['Close'].diff(-n)
    data['MACD'] = macd
    data['STOCH'] = fastk
    data['WILLR'] = talib.WILLR(data['High'],
                                data['Low'],
                                data['Close'],
                                timeperiod=14)
    data['OBV'] = talib.OBV(data['Close'], data['Volume'])
    data['RSI'] = talib.RSI(data['Close'], timeperiod=14)
    data['ATR'] = talib.ATR(data['High'],
                            data['Low'],
                            data['Close'],
                            timeperiod=14)
    data = pd.DataFrame(data)
    data.dropna(inplace=True)

    #4. Labels are the values we want to predict
    diff = np.array(data['dif'])
    labels = np.zeros(len(diff))
    sum = 0
    for i in range(len(diff)):
        if diff[i] > 0:
            labels[i] = 1
            sum += 1

    # print (sum/len(diff))

    #5. Data for the features
    features = data[['MACD', 'STOCH', 'WILLR', 'OBV', 'ATR', 'RSI']]

    #6. Saving feature names for later use
    feature_list = list(features.columns)
    return features, labels, feature_list
 def WILLR(self, timeperiod=14):
     real_data = np.array([self.df.high, self.df.low, self.df.close], dtype='f8')
     willr = talib.WILLR(real_data[0], real_data[1], real_data[2], timeperiod=timeperiod)
     # return go.Scatter(
     #     x=self.df.index,
     #     y=willr,
     #     name='WILLR'
     # )
     return willr
def technical_index(context):
    #EMA,RSI指标
    context.var.ts['EMA_5min'] = talib.EMA(np.array(context.var.ts.close), timeperiod=5)
    context.var.ts['EMA_10min'] = talib.EMA(np.array(context.var.ts.close), timeperiod=10)
    context.var.ts['EMA_15min'] = talib.EMA(np.array(context.var.ts.close), timeperiod=15)
    context.var.ts['EMA_20min'] = talib.EMA(np.array(context.var.ts.close), timeperiod=20)
    context.var.ts['RSI'] = talib.RSI(np.array(context.var.ts.close))
    STOCHRSI_usual = talib.STOCHRSI(np.array(context.var.ts.close))
    
    # BOLL-BAND指标
    BBANDS_usual = talib.BBANDS(np.array(context.var.ts.close))
    upperband, middleband, lowerband = BBANDS_usual
    context.var.ts['upperband'] = upperband
    context.var.ts['middleband'] = middleband
    context.var.ts['lowerband'] = lowerband
    
    arrClose = np.array(context.var.ts.close)
    arrHigh = np.array(context.var.ts.high)
    arrLow = np.array(context.var.ts.low)
    arrVolume = np.array(context.var.ts.volume,dtype=np.float)
    # MACD指标
    MACD_usual = talib.MACD(arrClose)
    macd, macdsignal, macdhist = MACD_usual
    context.var.ts['macd'] = macd
    context.var.ts['macdsignal'] = macdsignal
    context.var.ts['macdhist'] = macdhist
    
    # KDJ指标
    KDJ_usual = talib.STOCH(arrHigh, arrLow, arrClose)
    slowk, slowd = KDJ_usual
    context.var.ts['slowk'] = slowk
    context.var.ts['slowd'] = slowd
    
    # ATR指标
    ATR_usual   = talib.ATR(arrHigh, arrLow, arrClose)
    context.var.ts['ATR'] = ATR_usual
    
    # WILLR指标
    WILLR_usual = talib.WILLR(arrHigh, arrLow, arrClose)
    context.var.ts['WILLR'] = WILLR_usual
    
    # BOV指标
    OBV_usual  = talib.OBV(arrClose, arrVolume)
    context.var.ts['OBV'] = OBV_usual
    
    # SAR指标
    SAR_usual  = talib.SAR(arrHigh, arrLow)
    context.var.ts['SAR'] = SAR_usual
    
    # DEMA指标
    DEMA_usual = talib.DEMA(arrClose)
    context.var.ts['DEMA'] = DEMA_usual
    
    #MOM指标
    MOM_usual  = talib.MOM(arrClose)
    context.var.ts['MOM'] = MOM_usual
Exemple #13
0
def result_willams(data):
    try:
        willams = talib.WILLR(data.high.values, data.low.values, data.close.values, timeperiod=14)
        if willams[-2] > -20 > willams[-1]:
            return "turn to short"
        if willams[-2] < -80 < willams[-1]:
            return "turn to long"
    except:
        logging.info("could not get williams values")
    return 'undefined'
Exemple #14
0
    def MakeMiddleData(self,code,df):
        PDI = tl.PLUS_DI(df.high, df.low, df.close, timeperiod=14)
        MDI = tl.MINUS_DI(df.high, df.low, df.close, timeperiod=14)
        ADX = tl.ADX(df.high, df.low, df.close, timeperiod=14)
        R = tl.WILLR(df.high, df.low, df.close, timeperiod=14)

        if list(R)[-1] < -80:
            if list(PDI)[-1] > list(MDI)[-1]:
                print("R : ",R[len(df)-1])
                print("Name : ",self.dicStockInfo['info'][code])
Exemple #15
0
def main(df):
    highs = df['high'].values
    lows = df['low'].values
    closes=df['close'].values
    dftmp = df[[]]
    dftmp["w"] = talib.WILLR(highs,lows,closes,50)
    dftmp["w2"] = dftmp["w"].shift(1)
    
    df["ta_sig_ta_WILLR_2_1"] = dftmp.apply(lambda row: adx_signal(row), axis = 1) 
    return df
Exemple #16
0
    def evaluate(self, kite_fetcher, instrument):
        period = int(self.period)
        df = self.get_small_data(kite_fetcher=kite_fetcher,
                                 instrument=instrument)

        result = talib.WILLR(high=df['high'],
                             low=df['low'],
                             close=df['close'],
                             timeperiod=period)
        return np.round(result.iloc[-1], 3)
Exemple #17
0
def williamsR(df, n):
    """Calculate William's R using Ta-Lib library's built-in function.
    
    :param df: pandas.DataFrame
    :return: pandas.DataFrame
    """
    williamsR = talib.WILLR(df['High'], df['Low'], df['Close'], timeperiod=n)
    williamsR_series = pd.Series(williamsR, name='WilliamsR_' + str(n))
    df = df.join(williamsR_series)
    return df
Exemple #18
0
    def calculate(self, stock_code, date, time_period1=14, time_period2=6):
        wr_14 = 0.0
        wr_6 = 0.0
        data = su.get_basic_data(stock_code, date,
                                 time_period1 + 1).sort_index(ascending=False)

        if data.shape[0] >= time_period1 + 1:
            wr_14 = round(
                ta.WILLR(data['HIGH'].as_matrix(), data['LOW'].as_matrix(),
                         data['CLOSE'].as_matrix(), time_period1)[-1] * -1, 3)
            wr_6 = round(
                ta.WILLR(data['HIGH'].as_matrix(), data['LOW'].as_matrix(),
                         data['CLOSE'].as_matrix(), time_period2)[-1] * -1, 3)
        if np.isnan(wr_14) or np.isinf(wr_14) or np.isneginf(wr_14):
            wr_14 = 0.0
        if np.isnan(wr_6) or np.isinf(wr_6) or np.isneginf(wr_6):
            wr_6 = 0.0
        self.save_tech_data(stock_code, date, {'WR_14': wr_14, 'WR_6': wr_6})
        return wr_14, wr_6
Exemple #19
0
def main(df):
    highs = df['high'].values
    lows = df['low'].values
    closes=df['close'].values

    df["ta_tmp"] = talib.WILLR(highs,lows,closes,2)
    
    df["ta_sig_ta_WILLR_2_2"] = df.apply(lambda row: adx_signal(row), axis = 1) 
    del df["ta_tmp"]
    return df
Exemple #20
0
 def _get_indicators(security, open_name, close_name, high_name, low_name,
                     volume_name):
     """
     expand the features of the data through technical analysis across 26 different signals
     :param security: data which features are going to be expanded
     :param open_name: open price column name
     :param close_name: close price column name
     :param high_name: high price column name
     :param low_name: low price column name
     :param volume_name: traded volumn column name
     :return: expanded and extracted data
     """
     open_price = security[open_name].values
     close_price = security[close_name].values
     low_price = security[low_name].values
     high_price = security[high_name].values
     volume = security[volume_name].values if volume_name else None
     security['MOM'] = talib.MOM(close_price)
     security['HT_DCPERIOD'] = talib.HT_DCPERIOD(close_price)
     security['HT_DCPHASE'] = talib.HT_DCPHASE(close_price)
     security['SINE'], security['LEADSINE'] = talib.HT_SINE(close_price)
     security['INPHASE'], security['QUADRATURE'] = talib.HT_PHASOR(
         close_price)
     security['ADXR'] = talib.ADXR(high_price, low_price, close_price)
     security['APO'] = talib.APO(close_price)
     security['AROON_UP'], _ = talib.AROON(high_price, low_price)
     security['CCI'] = talib.CCI(high_price, low_price, close_price)
     security['PLUS_DI'] = talib.PLUS_DI(high_price, low_price, close_price)
     security['PPO'] = talib.PPO(close_price)
     security['MACD'], security['MACD_SIG'], security[
         'MACD_HIST'] = talib.MACD(close_price)
     security['CMO'] = talib.CMO(close_price)
     security['ROCP'] = talib.ROCP(close_price)
     security['FASTK'], security['FASTD'] = talib.STOCHF(
         high_price, low_price, close_price)
     security['TRIX'] = talib.TRIX(close_price)
     security['ULTOSC'] = talib.ULTOSC(high_price, low_price, close_price)
     security['WILLR'] = talib.WILLR(high_price, low_price, close_price)
     security['NATR'] = talib.NATR(high_price, low_price, close_price)
     security['RSI'] = talib.RSI(close_price)
     security['EMA'] = talib.EMA(close_price)
     security['SAREXT'] = talib.SAREXT(high_price, low_price)
     # security['TEMA'] = talib.EMA(close_price)
     security['RR'] = security[close_name] / security[close_name].shift(
         1).fillna(1)
     security['LOG_RR'] = np.log(security['RR'])
     if volume_name:
         security['MFI'] = talib.MFI(high_price, low_price, close_price,
                                     volume)
         # security['AD'] = talib.AD(high_price, low_price, close_price, volume)
         # security['OBV'] = talib.OBV(close_price, volume)
         security[volume_name] = np.log(security[volume_name])
     security.drop([open_name, close_name, high_name, low_name], axis=1)
     security = security.dropna().astype(np.float32)
     return security
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 = data.copy()
    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)

    # Exclude columns you don't want
    feature_df = feature_df[feature_df.columns[
        ~feature_df.columns.isin(['Open', 'High', 'Low', 'Close'])]]
    matrix = feature_df.values

    return feature_df, matrix
Exemple #22
0
 def test_william_r(self):
     """
     Test William's %R.
     """
     periods = 200
     william_qufilab = qufilab.willr(self.close, self.high, self.low,
                                     periods)
     william_talib = talib.WILLR(self.high, self.low, self.close, periods)
     np.testing.assert_allclose(william_qufilab,
                                william_talib,
                                rtol=self.tolerance)
Exemple #23
0
 def PipelineEstrategiaWPR(self, timeperiodEstrategy, VectorLimits,
                           shiftParaComparar, NombreEstrategia):
     Est = PreParacionDatosModelo(self.Base)
     self.Base['WPR'] = ta.WILLR(np.array(self.Base['High']),
                                 np.array(self.Base['Low']),
                                 np.array(self.Base['Close']),
                                 timeperiod=timeperiodEstrategy)
     self.Base = Est.GenerarEstrategiaWPR(VectorLimits, shiftParaComparar,
                                          NombreEstrategia)
     precision = self.CalcularPrecision(NombreEstrategia)
     return self.Base
def cal_technical_indicators(df):
    # Simple Moving Average SMA 简单移动平均
    df['SMA5'] = talib.MA(df['close'], timeperiod=5)
    df['SMA10'] = talib.MA(df['close'], timeperiod=10)
    df['SMA20'] = talib.MA(df['close'], timeperiod=20)
    # Williams Overbought/Oversold Index WR 威廉指标
    df['WR14'] = talib.WILLR(df['high'], df['low'], df['close'], timeperiod=14)
    df['WR18'] = talib.WILLR(df['high'], df['low'], df['close'], timeperiod=18)
    df['WR22'] = talib.WILLR(df['high'], df['low'], df['close'], timeperiod=22)
    # Moving Average Convergence / Divergence MACD 指数平滑移动平均线
    DIFF1, DEA1, df['MACD9'] = talib.MACD(np.array(df['close']), fastperiod=12, slowperiod=26, signalperiod=9)
    DIFF2, DEA2, df['MACD10'] = talib.MACD(np.array(df['close']), fastperiod=14, slowperiod=28, signalperiod=10)
    df['MACD9'] = df['MACD9'] * 2
    df['MACD10'] = df['MACD10'] * 2
    # Relative Strength Index RSI 相对强弱指数
    df['RSI15'] = talib.RSI(np.array(df['close']), timeperiod=15)
    df['RSI20'] = talib.RSI(np.array(df['close']), timeperiod=20)
    df['RSI25'] = talib.RSI(np.array(df['close']), timeperiod=25)
    df['RSI30'] = talib.RSI(np.array(df['close']), timeperiod=30)
    # Stochastic Oscillator Slow STOCH 常用的KDJ指标中的KD指标
    df['STOCH'] = \
    talib.STOCH(df['high'], df['low'], df['close'], fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3,
                slowd_matype=0)[1]
    # On Balance Volume OBV 能量潮
    df['OBV'] = talib.OBV(np.array(df['close']), df['vol'])
    # Simple moving average SMA 简单移动平均
    df['SMA15'] = talib.SMA(df['close'], timeperiod=15)
    df['SMA20'] = talib.SMA(df['close'], timeperiod=20)
    df['SMA25'] = talib.SMA(df['close'], timeperiod=25)
    df['SMA30'] = talib.SMA(df['close'], timeperiod=30)
    # Money Flow Index MFI MFI指标
    df['MFI14'] = talib.MFI(df['high'], df['low'], df['close'], df['vol'], timeperiod=14)
    df['MFI18'] = talib.MFI(df['high'], df['low'], df['close'], df['vol'], timeperiod=18)
    df['MFI22'] = talib.MFI(df['high'], df['low'], df['close'], df['vol'], timeperiod=22)
    # Ultimate Oscillator UO 终极指标
    df['UO7'] = talib.ULTOSC(df['high'], df['low'], df['close'], timeperiod1=7, timeperiod2=14, timeperiod3=28)
    df['UO8'] = talib.ULTOSC(df['high'], df['low'], df['close'], timeperiod1=8, timeperiod2=16, timeperiod3=22)
    df['UO9'] = talib.ULTOSC(df['high'], df['low'], df['close'], timeperiod1=9, timeperiod2=18, timeperiod3=26)
    # Rate of change Percentage ROCP 价格变化率
    df['ROCP'] = talib.ROCP(df['close'], timeperiod=10)
    return df
Exemple #25
0
def handle_data(context):
    # 获取历史数据
    hist = context.data.get_price(context.security,
                                  count=context.user_data.wr_period,
                                  frequency=context.frequency)
    if len(hist.index) < context.user_data.wr_period:
        context.log.warn("bar的数量不足, 等待下一根bar...")
        return

    # 收盘价
    close = np.array(hist["close"])
    # 最高价
    high = np.array(hist["high"])
    # 最低价
    low = np.array(hist["low"])

    try:
        # talib计算WR值
        wr_temp = talib.WILLR(high,
                              low,
                              close,
                              timeperiod=context.user_data.wr_period)
        # talib计算的WR为负数,我们在这里变为正值
        wr_current_dt = -1 * wr_temp[-1]
    except:
        context.log.error("计算WR时出现错误...")
        return

    context.log.info("当前 WR = %s" % wr_current_dt)

    # 根据WR值来判断交易:
    if wr_current_dt > context.user_data.over_sell:
        context.log.info("WR值超过了超卖线,产生买入信号")
        if context.account.huobi_cny_cash >= HUOBI_CNY_BTC_MIN_ORDER_CASH_AMOUNT:
            # WR大于超卖线且有现金,全仓买入
            context.log.info("正在买入 %s" % context.security)
            context.log.info("下单金额为 %s 元" % context.account.huobi_cny_cash)
            context.order.buy(context.security,
                              cash_amount=str(context.account.huobi_cny_cash))
        else:
            context.log.info("现金不足,无法下单")
    elif wr_current_dt < context.user_data.over_buy:
        context.log.info("WR值超过了超买线,产生卖出信号")
        if context.account.huobi_cny_btc >= HUOBI_CNY_BTC_MIN_ORDER_QUANTITY:
            # WR小于超买线且持有仓位,全仓卖出
            context.log.info("正在卖出 %s" % context.security)
            context.log.info("卖出数量为 %s" % context.account.huobi_cny_btc)
            context.order.sell(context.security,
                               quantity=str(context.account.huobi_cny_btc))
        else:
            context.log.info("仓位不足,无法卖出")
    else:
        context.log.info("无交易信号,进入下一根bar")
def stock_William(userstock):
    stock=TheConstructor(userstock)
    ret = pd.DataFrame(talib.WILLR(stock['High'], stock['Low'], stock['Open']), columns= ['Williams'])

    ### 開始畫圖 ###
    ret.plot(color=['#5599FF'], linestyle='dashed')
    stock['Close'].plot(secondary_y=True,color='#FF0000')
    plt.title("Williams_Overbought") # 標題設定
    plt.show()
    plt.savefig('Williams_Overbought.png') #存檔
    plt. close() # 殺掉記憶體中的圖片
    return Imgur.showImgur('Williams_Overbought')#開始利用imgur幫我們存圖片,以便於等等發送到手機 
Exemple #27
0
def WILLR(high, low, close, timeperiod=14):
    ''' Williams' %R 威廉指标

    分组: Momentum Indicator 动量指标

    简介: WMS表示的是市场处于超买还是超卖状态。
    股票投资分析方法主要有如下三种:基本分析、技术分析、演化分析。
    在实际应用中,它们既相互联系,又有重要区别。

    real = WILLR(high, low, close, timeperiod=14)
    '''
    return talib.WILLR(high, low, close, timeperiod)
Exemple #28
0
 def get_momentum_studies(open, low, high, close, volume, df):
     # Momentum studies
     # https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html
     df['MACD'], df['MACD_SIGN'], df['MACD_HIST'] = talib.MACD(
         close, fastperiod=12, slowperiod=26, signalperiod=9)
     df['STOCH-SLOW-K'], df['STOCH-SLOW-D'] = talib.STOCH(high,
                                                          low,
                                                          close,
                                                          fastk_period=5,
                                                          slowk_period=3,
                                                          slowk_matype=0,
                                                          slowd_period=3,
                                                          slowd_matype=0)
     df['STOCH-FAST-K'], df['STOCH-FAST-D'] = talib.STOCHF(high,
                                                           low,
                                                           close,
                                                           fastk_period=5,
                                                           fastd_period=3,
                                                           fastd_matype=0)
     df['STOCH-RSI-K'], df['STOCH-RSI-D'] = talib.STOCHRSI(close,
                                                           timeperiod=14,
                                                           fastk_period=5,
                                                           fastd_period=3,
                                                           fastd_matype=0)
     df['AROON-DOWN'], df['AROON-UP'] = talib.AROON(high,
                                                    low,
                                                    timeperiod=14)
     df["MINUS_DI"] = talib.MINUS_DI(high, low, close, timeperiod=14)
     df["MINUS_DM"] = talib.MINUS_DM(high, low, timeperiod=14)
     df["PLUS_DI"] = talib.PLUS_DI(high, low, close, timeperiod=14)
     df["PLUS_DM"] = talib.PLUS_DM(high, low, timeperiod=14)
     df["MOM"] = talib.MOM(close, timeperiod=10)
     df["MFI"] = talib.MFI(high, low, close, volume, timeperiod=14)
     df["ADX"] = talib.ADX(high, low, close, timeperiod=14)
     df["ADXR"] = talib.ADXR(high, low, close, timeperiod=14)
     df["APO"] = talib.APO(close, fastperiod=12, slowperiod=26, matype=0)
     df["AROONOSC"] = talib.AROONOSC(high, low, timeperiod=14)
     df["BOP"] = talib.BOP(open, high, low, close)
     df["CCI"] = talib.CCI(high, low, close, timeperiod=14)
     df["CMO"] = talib.CMO(close, timeperiod=14)
     df["DX"] = talib.DX(high, low, close, timeperiod=14)
     df["PPO"] = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0)
     df["ROC"] = talib.ROC(close, timeperiod=10)
     df["RSI"] = talib.RSI(close, timeperiod=14)
     df["TRIX"] = talib.TRIX(close, timeperiod=30)
     df["ULT"] = talib.ULTOSC(high,
                              low,
                              close,
                              timeperiod1=7,
                              timeperiod2=14,
                              timeperiod3=28)
     df["WILLR"] = talib.WILLR(high, low, close, timeperiod=14)
def get_list_of_willams_deals(test_dateframe):
    start_index = ""
    buy_or_sell = ""
    list_of_deals = list()
    for index, row in test_dateframe[14:].iterrows():
        temp_slice = test_dateframe.iloc[:test_dateframe.index.searchsorted(
            datetime.fromtimestamp(index.timestamp())) + 1]
        willams = talib.WILLR(temp_slice.high.values,
                              temp_slice.low.values,
                              temp_slice.close.values,
                              timeperiod=14)

        # if willams[-2] > -20 > willams[-1]:
        #     # "turn to short"
        #     if start_index == "":
        #         start_index = index
        #         buy_or_sell = "sell"

        if willams[-2] < -80 < willams[-1]:
            # "turn to long"
            adx = talib.ADX(temp_slice.high.values,
                            temp_slice.low.values,
                            temp_slice.close.values,
                            timeperiod=14)
            if start_index == "" and adx[-2] > adx[-1]:
                start_index = index
                buy_or_sell = "buy"

        if start_index != "":
            if buy_or_sell == "buy":
                if willams[-1] > -20:
                    deal = Deal(
                        test_dateframe.iloc[test_dateframe.index.searchsorted(
                            datetime.fromtimestamp(start_index.timestamp())
                        ):test_dateframe.index.searchsorted(
                            datetime.fromtimestamp(index.timestamp())) + 1],
                        buy_or_sell)
                    list_of_deals.append(deal)
                    start_index = ""
                    buy_or_sell = ""
            if buy_or_sell == "sell":
                if willams[-1] < -80:
                    # deal = Deal(
                    #     week_dateframe.iloc[
                    #     week_dateframe.index.searchsorted(datetime.fromtimestamp(start_index.timestamp())):
                    #     week_dateframe.index.searchsorted(datetime.fromtimestamp(index.timestamp())) + 1],
                    #     buy_or_sell)
                    # list_of_deals.append(deal)
                    start_index = ""
                    buy_or_sell = ""

    return list_of_deals
def wpr(df, n=14, normalize=False):
    h = df['High'].as_matrix()
    l = df['Low'].as_matrix()
    c = df['Close'].as_matrix()

    _wpr = pd.Series(ta.WILLR(h, l, c, timeperiod=n),
                     index=df.index,
                     name="WPR_" + str(n))

    if normalize:
        _wpr = z_score(_wpr)

    return _wpr