def Feature_Extraction_Volume(df):
    df['A/D'] = tas.AD(df['high'], df['low'], df['close'], df['volume'])
    df = Williams_AD(df)
    df['OBV'] = tas.OBV(df['close'], df['volume'])
    df['ADOSC'] = tas.ADOSC(df['high'], df['low'], df['close'], df['volume'])
    df = df.fillna(0)
    return df
Example #2
0
def devfea(df, high, low, close, open, volume):
    df['AD'] = talib.AD(high, low, close, volume)
    df['CCI'] = talib.CCI(high, low, close)
    df['macd'], df['macdsignal'], df['macdhist'] = talib.MACD(close,
                                                              fastperiod=12,
                                                              slowperiod=26,
                                                              signalperiod=9)
    df['ATR'] = talib.ATR(high, low, close, timeperiod=14)
    df['ADOSC'] = talib.ADOSC(high, low, close, volume)
    df['ADX'] = talib.ADX(high, low, close)
    df['BBANDS_upper'], df['BBANDS_mid'], df['BBANDS_lower'] = talib.BBANDS(
        close)
    df['RSI'] = talib.RSI(close)
    df['MA5'] = talib.MA(close, 5)
    df['MA10'] = talib.MA(close, 10)
    df['MA20'] = talib.MA(close, 20)
    df['OBV'] = talib.OBV(close, volume)
    df['SAR'] = talib.SAR(high, low)
    df['lgvol'] = np.log(volume)
    #上影线
    df['upshadow'] = np.abs(high - ((open + close) +
                                    (np.abs(open - close))) / 2)
    #下影线
    df['downshadow'] = np.abs(low - ((open + close) -
                                     (np.abs(open - close))) / 2)
    return df
Example #3
0
def handle_volume_indicators(args, axes, i, klines_df, close_times,
                             display_count):
    # talib
    if args.AD:  # AD
        name = 'AD'
        real = talib.AD(klines_df["high"], klines_df["low"],
                        klines_df["close"], klines_df["volume"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.ADOSC:  # ADOSC
        name = 'ADOSC'
        real = talib.ADOSC(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           klines_df["volume"],
                           fastperiod=3,
                           slowperiod=10)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.OBV:  # OBV
        name = 'OBV'
        real = talib.OBV(klines_df["close"], klines_df["volume"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)
Example #4
0
def getRequirementData(req: ReqParam):
    stocks = getStocks()
    for count, ticker in enumerate(stocks):
        df = data.get(ticker)

        if req.condition == 1:
            if req.indicatorPeriod is None:
                raise ValueError('Need to provide indicator period')
            df['ADX'] = talib.ADX(df['High'].values, df['Low'].values, df['Close'].values, req.indicatorPeriod)
            adxMap[ticker + '_' + str(req.indicatorPeriod)] = removeNaN(df['ADX'].values)
        if req.condition == 2:
            if req.fastPeriod is None or req.slowPeriod is None:
                raise ValueError('Need to provide fastperiod or slowperiod')
            df['chaikin'] = talib.ADOSC(df['High'].values, df['Low'].values, df['Close'].values, df['Volume'].values,
                                        req.fastPeriod, req.slowPeriod)
            chaikinMap[ticker + '_' + str(req.fastPeriod) + '_' + str(req.slowPeriod)] = removeNaN(df['chaikin'].values)
        if req.condition == 3:
            if req.indicatorPeriod is None or req.fastPeriod is None or req.slowPeriod is None:
                raise ValueError('Need to provide indicatorPeriod, fastPeriod or slowPeriod')
            _, __, df['MACDHist'] = talib.MACD(df['Close'].values, fastperiod=req.fastPeriod, slowperiod=req.slowPeriod,
                                               signalperiod=req.indicatorPeriod)
            histMap[ticker + '_' + str(req.indicatorPeriod) + '_' + str(req.fastPeriod) + '_' + str(req.slowPeriod)] = \
                removeNaN(df['MACDHist'].values)
        if req.condition == 4:
            if req.rollingPeriod is None:
                raise ValueError('Need to provide rollingPeriod')
            df['vol'] = np.where(df['Volume'] > df['Volume'].rolling(req.rollingPeriod).mean())
            volMap[ticker + '_' + str(req.rollingPeriod)] = df['vol'].values
    def updateIndicator(self, data, candles_visible):
        # ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)
        chaikin_oscillator = talib.ADOSC(data[2], data[3], data[4], data[5], fastperiod=3, slowperiod=10)
        chaikin_oscillator = chaikin_oscillator[-candles_visible:]

        self.oscillator.clear()
        for i in range(candles_visible):
            self.oscillator.append(i + 0.5, chaikin_oscillator[i])

        # detach and remove old axes
        for ax in self.oscillator.attachedAxes():
            self.oscillator.detachAxis(ax)
        for ax in self.axes():
            self.removeAxis(ax)

        # set x axes
        ax = QtChart.QValueAxis()
        ax.setRange(0, candles_visible)
        ax.hide()

        # set x axes
        ay = QtChart.QValueAxis()
        bound = max(abs(min(chaikin_oscillator)), max(chaikin_oscillator))
        ay.setRange(-bound, bound)
        ay.setGridLinePen(QtGui.QPen(QtGui.QColor(80, 80, 80), 0.5))
        ay.setLinePen(QtGui.QPen(QtGui.QColor(0, 0, 0), 0.5))
        ay.applyNiceNumbers()
        ay.setTickCount(3)

        # add and attach new axes
        self.addAxis(ax, QtCore.Qt.AlignBottom)
        self.addAxis(ay, QtCore.Qt.AlignRight)
        self.oscillator.attachAxis(ax)
        self.oscillator.attachAxis(ay)
Example #6
0
def adosc(portfolio_item,transaction_volume, buy_threshold_difference=2, sell_threshold_difference=2, period='5d',
          fastperiod=3, slowperiod=10):
    """
    strategy that trades based on reversals in the chaikin oscillator
    :param transaction_volume:
    :param portfolio_item:
    :param buy_threshold_difference:
    :param sell_threshold_difference:
    :param period:
    :param fastperiod:
    :param slowperiod:
    :return:
    """
    from yahooquery import Ticker
    from time import sleep
    from math import floor
    import talib
    from .TradeHistoryItem import log_trade
    from API.Help import pct_change, initialize_alpaca

    alpaca = initialize_alpaca()
    ticker = str(portfolio_item)
    yahoo_ticker = Ticker(ticker)
    history = yahoo_ticker.history(period=period, interval=portfolio_item.portfolio.get_trading_frequency())
    ticker_adosc = talib.ADOSC(high=history['high'], low=history['low'], close=history['close'],
                               volume=history['volume'], fastperiod=fastperiod, slowperiod=slowperiod)
    ticker_adosc_pct = pct_change(ticker_adosc)

    # Buy when in the bottom of a dip in the chalking oscillator graph
    if ticker_adosc_pct[-2] < 0 and \
            abs(ticker_adosc_pct[-2] - ticker_adosc_pct[-1]) > buy_threshold_difference and \
            ticker_adosc_pct[-1] > 0 and portfolio_item.transaction_status != portfolio_item.BUY:
        if portfolio_item.transaction_status == 2:  # only buy to cover if stock has been shorted before
            print('buying to cover {} shares of {}'.format(transaction_volume, ticker))
            alpaca.submit_order(ticker, transaction_volume, 'buy', 'market', 'day')
            portfolio_item.buy_to_cover(transaction_volume=transaction_volume)
            log_trade(portfolio_item=portfolio_item, transaction_volume=transaction_volume, transaction_type=2)
            sleep(1)  # hopefully combats 403 alpaca error
        print('buying {} shares of {}'.format(transaction_volume, ticker))
        alpaca.submit_order(ticker, transaction_volume, 'buy', 'market', 'day')
        portfolio_item.buy(transaction_volume=transaction_volume)
        log_trade(portfolio_item=portfolio_item, transaction_volume=transaction_volume, transaction_type=0)

    # Sell at a tip in chaikin oscillator
    elif ticker_adosc_pct[-2] > 0 and \
            abs(ticker_adosc_pct[-2] - ticker_adosc_pct[-1]) > sell_threshold_difference and \
            ticker_adosc_pct[-1] < 0:
        if portfolio_item.transaction_status == portfolio_item.BUY:  # making sure stock exists before selling it
            print('selling {} shares of {}'.format(transaction_volume, ticker))
            alpaca.submit_order(ticker, transaction_volume, 'sell', 'market', 'day')
            portfolio_item.sell(transaction_volume=transaction_volume)
            log_trade(portfolio_item=portfolio_item, transaction_volume=transaction_volume, transaction_type=1)
            sleep(1)
        if portfolio_item.transaction_status != portfolio_item.SHORT:  # make sure we dont short twice in a row
            transaction_volume = floor(portfolio_item.cash_allocated / (
                        portfolio_item.ticker.price_now * 1.1))  # gives us a 10% buffer if the stock goes the other way
            print('shorting {} shares of {}'.format(transaction_volume, ticker))
            alpaca.submit_order(ticker, transaction_volume, 'sell', 'market', 'day')
            portfolio_item.short(transaction_volume=transaction_volume)
            log_trade(portfolio_item=portfolio_item, transaction_volume=transaction_volume, transaction_type=3)
Example #7
0
def ta_ADOSC(ADOSC_conf, curr_high_price_seq, curr_low_price_seq,
             curr_close_price_seq, curr_trade_price_seq):

    ADOSC_seqs = []
    curr_feature_list = []

    ADOSC_period_num = len(ADOSC_conf["period"])

    for i in range(ADOSC_period_num):
        curr_fast_period = ADOSC_conf["period"][i][0]
        curr_slow_period = ADOSC_conf["period"][i][1]

        curr_feature_list.append("ADOSC_" + str(curr_fast_period) + "_" +
                                 str(curr_slow_period))

        curr_ADOSC_seqs = talib.ADOSC(curr_high_price_seq,
                                      curr_low_price_seq,
                                      curr_close_price_seq,
                                      curr_trade_price_seq,
                                      fastperiod=curr_fast_period,
                                      slowperiod=curr_slow_period)

        ADOSC_seqs.append(curr_ADOSC_seqs.copy())

    return ADOSC_seqs, curr_feature_list
Example #8
0
def ChaikinADOSC(high=None,
                 low=None,
                 close=None,
                 volume=None,
                 fast_period=3,
                 slow_period=10,
                 verbose=False):
    """ChaikinADOSC

    Wrapper for talib.ADOSC for running unittests
    on ci/cd tools that do not provide talib

    .. code-block:: python

        real = ADOSC(
            high,
            low,
            close,
            volume,
            fastperiod=3,
            slowperiod=10)

    :param value: list of values
        (default should be ``close``)
    :param volume: list of volume values
    :param verbose: show logs
    """
    if verbose:
        log.info('chaikinadosc - start')
    return talib.ADOSC(high, low, close, volume, fast_period, slow_period)
Example #9
0
 def ADOSC_factor(self, df, fastperiod=3, slowperiod=10):
     return talib.ADOSC(
         df.loc[:, self.map_dict['high']].values,
         df.loc[:, self.map_dict['low']].values,
         df.loc[:, self.map_dict['close']].values,
         df.loc[:, self.map_dict['volume']].values,
         fastperiod, slowperiod)
Example #10
0
def add_indicators(df):
    high = df["HA_High"].values
    close = df["HA_Close"].values
    low = df["HA_Low"].values
    _open = df["HA_Open"].values
    volume = df["volume"].values.astype('uint32')

    df["APO"] = talib.APO(close, fastperiod=9, slowperiod=21, matype=0)
    df["APO"] = talib.APO(close, fastperiod=9, slowperiod=21, matype=0)
    df["aroondown"], df["aroonup"] = talib.AROON(high, low, timeperiod=14)
    df["BOP"] = talib.BOP(_open, high, low, close)
    df["CCI"] = talib.CCI(high, low, close, timeperiod=10)
    df["DX"] = talib.DX(high, low, close, timeperiod=10)
    df["MOM"] = talib.MOM(close, timeperiod=10)
    df["slowk"], df["slowd"] = talib.STOCH(high,
                                           low,
                                           close,
                                           fastk_period=5,
                                           slowk_period=3,
                                           slowk_matype=0,
                                           slowd_period=3,
                                           slowd_matype=0)
    df["OBV"] = talib.OBV(close, np.asarray(volume, dtype='float'))
    df["ADOSC"] = talib.ADOSC(high,
                              low,
                              close,
                              np.asarray(volume, dtype='float'),
                              fastperiod=3,
                              slowperiod=10)
    df["upperband"], df["middleband"], df["lowerband"] = talib.BBANDS(
        close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)

    return df
Example #11
0
 def calculations(self):
     '''calculations'''
     self.df['rsi'] = ta.RSI(self.df['close'], timeperiod=5)
     self.df['apo'] = ta.APO(self.df['close'],
                             fastperiod=10,
                             slowperiod=5,
                             matype=0)
     self.df['upperband'], self.df['middleband'], self.df[
         'lowerband'] = ta.BBANDS(self.df['close'],
                                  timeperiod=5,
                                  nbdevup=2,
                                  nbdevdn=2,
                                  matype=0)
     self.df['ema'] = ta.EMA(self.df['close'], timeperiod=5)
     self.df['ma'] = ta.MA(self.df['close'], timeperiod=5, matype=0)
     self.df['sma'] = ta.MA(self.df['close'], timeperiod=5)
     self.df['t3'] = ta.T3(self.df['close'], timeperiod=5, vfactor=0)
     self.df['wma'] = ta.WMA(self.df['close'], timeperiod=5)
     self.df['aroonosc'] = ta.AROONOSC(self.df['high'],
                                       self.df['low'],
                                       timeperiod=5)
     self.df['cci'] = ta.CCI(self.df['high'],
                             self.df['low'],
                             self.df['close'],
                             timeperiod=5)
     self.df['cmo'] = ta.CMO(self.df['close'], timeperiod=14)
     self.df['macd'], self.df['macdsignal'], self.df[
         'macdhist'] = ta.MACDEXT(self.df['close'],
                                  fastperiod=12,
                                  fastmatype=0,
                                  slowperiod=26,
                                  slowmatype=0,
                                  signalperiod=9,
                                  signalmatype=0)
     self.df['slowk'], self.df['slowd'] = ta.STOCH(self.df['high'],
                                                   self.df['low'],
                                                   self.df['close'],
                                                   fastk_period=5,
                                                   slowk_period=3,
                                                   slowk_matype=0,
                                                   slowd_period=3,
                                                   slowd_matype=0)
     self.df['fastk'], self.df['fastd'] = ta.STOCHRSI(self.df['close'],
                                                      timeperiod=5,
                                                      fastk_period=5,
                                                      fastd_period=3,
                                                      fastd_matype=0)
     self.df['ultosc'] = ta.ULTOSC(self.df['high'],
                                   self.df['low'],
                                   self.df['close'],
                                   timeperiod1=7,
                                   timeperiod2=14,
                                   timeperiod3=28)
     self.df['adosc'] = ta.ADOSC(self.df['high'],
                                 self.df['low'],
                                 self.df['close'],
                                 self.df['volume'],
                                 fastperiod=3,
                                 slowperiod=10)
     return self.df
Example #12
0
def calculate(data):
    timestamp = data[len(data)-1][0]
    nopen = [] 
    nhigh = []
    nlow = [] 
    nclose = []
    nvolume = []
    for entry in data:
        nopen.append(entry[1])
        nhigh.append(entry[2])
        nlow.append(entry[3])
        nclose.append(entry[4])
        nvolume.append(entry[5])
    nc = np.array(nclose)
    hc = np.array(nhigh)
    lc = np.array(nlow)
    cc = np.array(nclose)
    vc = np.array(nvolume)

    rsi = talib.RSI(nc, timeperiod=14)
    macdsignal = talib.MACD(nc, fastperiod=12, slowperiod=26, signalperiod=9)
    sar = talib.SAR(hc, lc, acceleration=0, maximum=0)
    adosc = talib.ADOSC(hc, lc, cc, vc, fastperiod=3, slowperiod=10)
    aroon = talib.AROONOSC(hc, lc, timeperiod=14)
    ult = talib.ULTOSC(hc, lc, cc, timeperiod1=7, timeperiod2=14, timeperiod3=28)
    obj, sent = twitter_api.get_sentiment()

    database.insert_predictions(timestamp, rsi[-1], macdsignal[0][-1], sar[-1], adosc[-1], aroon[-1], ult[-1], sent, obj)
    return timestamp, rsi[-1], macdsignal[0][-1], sar[-1], adosc[-1], aroon[-1], ult[-1], sent, obj
Example #13
0
def technical_indicators(ohlcv_path="data/OHLC_NDX.csv"):
    """
    Calculate Technical Indicators from the ti_dict dictionary and export to .csv
    :param ohlcv_path: OHLCV dataset path
    """
    ohlcv = pd.read_csv(ohlcv_path)
    ti_dict = {
        'SMA5': talib.SMA(ohlcv.Close, 5),
        'SMA10': talib.SMA(ohlcv.Close, 10),
        'SMA50': talib.SMA(ohlcv.Close, 50),
        'EMA20': talib.EMA(ohlcv.Close, 20),
        'stoch5': talib.STOCH(ohlcv.High, ohlcv.Low, ohlcv.Close, 5, 3, 0, 3, 0)[0],
        'ADOSC': talib.ADOSC(ohlcv.High, ohlcv.Low, ohlcv.Close, ohlcv.Volume, fastperiod=3, slowperiod=10),
        'MACDhist': talib.MACD(ohlcv.Close, fastperiod=12, slowperiod=26, signalperiod=9)[2],
        'WILLR': talib.WILLR(ohlcv.High, ohlcv.Low, ohlcv.Close, timeperiod=14),
        'RSI': talib.RSI(ohlcv.Close, timeperiod=14),
        'MOM': talib.MOM(ohlcv.Close, timeperiod=10),
        'ROC': talib.ROC(ohlcv.Close, timeperiod=10),
        'OBV': talib.OBV(ohlcv.Close, ohlcv.Volume),
        'CCI': talib.CCI(ohlcv.High, ohlcv.Low, ohlcv.Close, timeperiod=14)
    }

    # Create a dataframe from TI dictionary
    df_ti = pd.DataFrame(ti_dict, index=ohlcv.index)
    del ti_dict
    del ohlcv

    # Save Technical Indicators dataframe
    if not os.path.isdir('data_preprocessed/'):
        os.mkdir('data_preprocessed/')
    df_ti.to_csv('data_preprocessed/technical_indicators.csv', index=False)
    del df_ti

    return 1
Example #14
0
 def add_adosc(self, fast_period=3, slow_period=10):
     self.stk_df['ADOSC'] = talib.ADOSC(self.stk_df.high,
                                        self.stk_df.low,
                                        self.stk_df.close,
                                        self.stk_df.volume,
                                        fastperiod=fast_period,
                                        slowperiod=slow_period)
Example #15
0
File: adosc.py Project: wcy/jesse
def adosc(candles: np.ndarray,
          fast_period: int = 3,
          slow_period: int = 10,
          sequential: bool = False) -> Union[float, np.ndarray]:
    """
    ADOSC - Chaikin A/D Oscillator

    :param candles: np.ndarray
    :param fast_period: int - default: 3
    :param slow_period: int - default: 10
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    warmup_candles_num = get_config('env.data.warmup_candles_num', 240)
    if not sequential and len(candles) > warmup_candles_num:
        candles = candles[-warmup_candles_num:]

    res = talib.ADOSC(candles[:, 3],
                      candles[:, 4],
                      candles[:, 2],
                      candles[:, 5],
                      fastperiod=fast_period,
                      slowperiod=slow_period)

    if sequential:
        return res
    else:
        return None if np.isnan(res[-1]) else res[-1]
Example #16
0
def genTA(data, y, t): #t is timeperiod
    indicators  = {}
    y_ind = copy.deepcopy(y)
   
    for ticker in data:
    ## Overlap
        indicators[ticker] = ta.SMA(data[ticker].iloc[:,3], timeperiod=t).to_frame()        
        indicators[ticker]['EMA'] = ta.EMA(data[ticker].iloc[:,3], timeperiod=t)       
        indicators[ticker]['BBAND_Upper'], indicators[ticker]['BBAND_Middle' ], indicators[ticker]['BBAND_Lower' ] = ta.BBANDS(data[ticker].iloc[:,3], timeperiod=t, nbdevup=2, nbdevdn=2, matype=0)         
        indicators[ticker]['HT_TRENDLINE'] = ta.HT_TRENDLINE(data[ticker].iloc[:,3])
        indicators[ticker]['SAR'] = ta.SAR(data[ticker].iloc[:,1], data[ticker].iloc[:,2], acceleration=0, maximum=0)
        #rename SMA column
        indicators[ticker].rename(columns={indicators[ticker].columns[0]: "SMA"}, inplace=True)
    ## Momentum
        indicators[ticker]['RSI'] = ta.RSI(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['MOM'] = ta.MOM(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['ROC'] = ta.ROC(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['ROCP']= ta.ROCP(data[ticker].iloc[:,3],timeperiod=(t-1))
        indicators[ticker]['STOCH_SLOWK'], indicators[ticker]['STOCH_SLOWD'] = ta.STOCH(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], fastk_period=t, slowk_period=int(.6*t), slowk_matype=0, slowd_period=int(.6*t), slowd_matype=0)
        indicators[ticker]['MACD'], indicators[ticker]['MACDSIGNAL'], indicators[ticker]['MACDHIST'] = ta.MACD(data[ticker].iloc[:,3], fastperiod=t,slowperiod=2*t,signalperiod=int(.7*t))
        
    ## Volume
        indicators[ticker]['OBV'] = ta.OBV(data[ticker].iloc[:,3], data[ticker].iloc[:,4])
        indicators[ticker]['AD'] = ta.AD(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], data[ticker].iloc[:,4])
        indicators[ticker]['ADOSC'] = ta.ADOSC(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], data[ticker].iloc[:,4], fastperiod=int(.3*t), slowperiod=t)
        
    ## Cycle
        indicators[ticker]['HT_DCPERIOD'] = ta.HT_DCPERIOD(data[ticker].iloc[:,3])
        indicators[ticker]['HT_TRENDMODE']= ta.HT_TRENDMODE(data[ticker].iloc[:,3])
    
    ## Price
        indicators[ticker]['AVGPRICE'] = ta.AVGPRICE(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['TYPPRICE'] = ta.TYPPRICE(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
    
    ## Volatility
        indicators[ticker]['ATR'] = ta.ATR(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3],  timeperiod=(t-1))
    
    ## Statistics
        indicators[ticker]['BETA'] = ta.BETA(data[ticker].iloc[:,1], data[ticker].iloc[:,2], timeperiod=(t-1))
        indicators[ticker]['LINEARREG'] = ta.LINEARREG(data[ticker].iloc[:,3], timeperiod=t)
        indicators[ticker]['VAR'] = ta.VAR(data[ticker].iloc[:,3], timeperiod=t, nbdev=1)
    
    ## Math Transform
        indicators[ticker]['EXP'] = ta.EXP(data[ticker].iloc[:,3])
        indicators[ticker]['LN'] = ta.LN(data[ticker].iloc[:,3])
    
    ## Patterns (returns integers - but norming might not really do anything but wondering if they should be normed)
        indicators[ticker]['CDLENGULFING'] = ta.CDLENGULFING(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLDOJI']      = ta.CDLDOJI(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLHAMMER']    = ta.CDLHAMMER(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLHANGINGMAN']= ta.CDLHANGINGMAN(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        
    #drop 'nan' values
        indicators[ticker].drop(indicators[ticker].index[np.arange(0,63)], inplace=True)
        y_ind[ticker].drop(y_ind[ticker].index[np.arange(0,63)], inplace=True)
        
    #Normalize Features
    indicators_norm = normData(indicators)
        
    return indicators_norm, indicators, y_ind
Example #17
0
def adosc(candles: np.ndarray,
          fastperiod=3,
          slowperiod=10,
          sequential=False) -> Union[float, np.ndarray]:
    """
    ADOSC - Chaikin A/D Oscillator

    :param candles: np.ndarray
    :param fastperiod: int - default: 3
    :param slowperiod: int - default: 10
    :param sequential: bool - default=False

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

    res = talib.ADOSC(candles[:, 3],
                      candles[:, 4],
                      candles[:, 2],
                      candles[:, 5],
                      fastperiod=fastperiod,
                      slowperiod=slowperiod)

    if sequential:
        return res
    else:
        return None if np.isnan(res[-1]) else res[-1]
def get_feature_df(df, company_symbol=None, feature="Trend"):
    if (company_symbol != None):
        df_comp = df[df["symbol"] == company_symbol]
    else:
        df_comp = df

    df_comp = df_comp.sort_values(by=['time'])
    if (feature == "Trend"):
        df_comp[feature] = ta.EMA(df_comp.close, timeperiod=90)
    elif (feature == "Volatility"):
        df_comp[feature] = ta.ATR(df_comp.high,
                                  df_comp.low,
                                  df_comp.close,
                                  timeperiod=90)
    elif (feature == "Volume"):
        df_comp[feature] = ta.ADOSC(df_comp.high,
                                    df_comp.low,
                                    df_comp.close,
                                    df_comp.volume,
                                    fastperiod=30,
                                    slowperiod=90)
    elif (feature == "Momemtum"):
        df_comp[feature + "_1"] = ta.RSI(df_comp.close, timeperiod=90)
        df_comp[feature + "_2"] = ta.ROC(df_comp.close, timeperiod=90)
    elif (feature == "Open_Close"):
        df_comp[feature + "_1"] = df_comp["open"]
        df_comp[feature + "_2"] = df_comp["close"]

    return df_comp
Example #19
0
def add_volume_indicators(data_list):
    # (volume) Indicators common for all Time-frames
    for data in data_list:

        # 1) AD - Chaikin A / D Line
        real = talib.AD(data.High, data.Low, data.Close, data.Volume)
        data['AD'] = real

        # 2) ADOSC - Chaikin A/D Oscillator
        real = talib.ADOSC(data.High,
                           data.Low,
                           data.Close,
                           data.Volume,
                           fastperiod=3,
                           slowperiod=10)
        data['ADOSC'] = real

        # 3) OBV - On Balance Volume
        real = talib.OBV(data.Close, data.Volume)
        data['OBV'] = real

    data_weekly = data_list[6]
    data_monthly = data_list[7]
    data_15min = data_list[2]
    data_daily = data_list[5]
    data_60min = data_list[4]
    data_1min = data_list[0]
    data_5min = data_list[1]
    data_30min = data_list[3]

    # Create (volume) indicators for a only to a particular timeframe here..

    return data_list
Example #20
0
 def Indicators(self,df): # date close open high low volume 컬럼순 
                     # 결측치 33줄 생김 0~32 까지
     df['sma5'] = talib.SMA(np.asarray(df['close']), 5)
     df['sma20'] = talib.SMA(np.asarray(df['close']), 20)
     #df['sma120'] = talib.SMA(np.asarray(df['close']), 120)
     df['ema12'] = talib.SMA(np.asarray(df['close']), 12)
     df['ema26'] = talib.SMA(np.asarray(df['close']), 26)
     upper, middle, lower = talib.BBANDS(np.asarray(df['close']), timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
     df['dn'] = lower
     df['mavg'] = middle
     df['up'] = upper
     df['pctB'] = (df.close - df.dn)/(df.up - df.dn)
     rsi14 = talib.RSI(np.asarray(df['close']), 14)
     df['rsi14'] = rsi14
     macd, macdsignal, macdhist = talib.MACD(np.asarray(df['close']), 12, 26, 9)  
     df['macd'] = macd
     df['macdsignal'] = macdsignal
     df['obv']=talib.OBV(df['close'], df['volume'])
     df['ad'] = talib.AD(df['high'], df['low'], df['close'], df['volume'])
     df['ADOSC'] = talib.ADOSC(df['high'], df['low'], df['close'], df['volume'], fastperiod=3, slowperiod=10)
     df=df.iloc[33:]
     df=df.fillna(0)
     df=df.drop(columns=['date'])
     
     self.add_columns_data = df
Example #21
0
    def ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10):
        # Chaikin A/D Oscillator
        param = {
            'fastperiod': fastperiod,
            'slowperiod': slowperiod,
        }

        return talib.ADOSC(high, low, close, volume, **param)
Example #22
0
 def adosc(self, n, array=False):
     """
     ADOSC.
     """
     result = talib.ADOSC(self.high, self.low, self.close, self.volume, n)
     if array:
         return result
     return result[-1]
Example #23
0
def Chaikin(df):
    chaikin = talib.ADOSC(np.array(df.high), np.array(df.low),
                          np.array(df.close), np.array(df.volume))
    buy_signal = np.where(np.isnan(chaikin), chaikin,
                          np.where(chaikin > 0, 1, 0))
    sell_signal = np.where(np.isnan(chaikin), chaikin,
                           np.where(chaikin < 0, 1, 0))
    return (buy_signal, sell_signal)
Example #24
0
 def adosc(self, n: int, array: bool = False) -> Union[float, np.ndarray]:
     """
     ADOSC.
     """
     result = talib.ADOSC(self.high, self.low, self.close, self.volume, n)
     if array:
         return result
     return result[-1]
Example #25
0
 def adosc(self, fastperiod=3,slowperiod = 10, array: bool = False) -> Union[float, np.ndarray]:
     """
     ADOSC.
     """
     result = talib.ADOSC(self.high, self.low, self.close, self.volume, fastperiod,slowperiod)
     if array:
         return result
     return result[-1]
Example #26
0
 def LoadData(self):
     
     ds = YahooStockDataSource(cachedFolderName=cachedFolderName,
                         dataSetId=dataSetId,
                         instrumentIds=self.instrumentIds,
                         startDateStr=startDateStr,
                         endDateStr=endDateStr,
                         event='history')
    
     self.stkData = [ds.getBookDataByFeature()['open'],
             ds.getBookDataByFeature()['high'],
             ds.getBookDataByFeature()['low'],
             ds.getBookDataByFeature()['close'],
             ds.getBookDataByFeature()['adjClose'],
             ds.getBookDataByFeature()['volume']]
     tbRSI = tb.RSI(self.stkData[4][self.instrumentIds[0]],14)
     
     tbChaikin = tb.ADOSC(self.stkData[1][self.instrumentIds[0]],
                         self.stkData[2][self.instrumentIds[0]],
                         self.stkData[3][self.instrumentIds[0]],
                         self.stkData[5][self.instrumentIds[0]])
     
 
     '''
     Task1
     Create new dataframe here with 5 columns 
     column  1 : Date of stock price 
     column  2 : Day of the week (Monday Tuesday etc)
     Columnn 3 :  tbRSI
     Column 4 : tbChaikin
     column 5 :  Stock's adjusted price.
     Index : column1 
     '''
     dfdata = {'Adj_Close':self.stkData[4][self.instrumentIds[0]],
              'RSI':tbRSI,
              'Chaikin':tbChaikin}
     df = pd.DataFrame(dfdata)
     df['Trade_Date'] = pd.to_datetime(df.index)
     df['day_of_week'] = df['Trade_Date'].dt.day_name()
     
     dfFinal = df[["Trade_Date", "day_of_week", "RSI", "Chaikin", "Adj_Close"]]
     # dfFinal2 = df[["Trade_Date", "day_of_week", "RSI", "Chaikin", "Adj_Close"]]
     #df_rsi = pd.DataFrame(dfFinal['RSI'])
     #print(df_rsi)
     #df_rsi.to_csv('yahooData/weeklyTradeTest/RSI_Value.csv')
     
     
     
     '''
     Task 2
     filter above dataframe using column  2 value (e.g. 'Wednesday') and store in other dataframe 
     '''
     # dfFinal2 = dfFinal.loc[df['day_of_week'] == 'Wednesday']
     # dfFinal.to_csv(dir_path)    
     # print(dfFinal.head(50)
     # dfFinal = dfFinal.loc[df['day_of_week'] == 'Friday']
     dfFinal.to_csv(dir_path)    
     print(dfFinal.head(50))
Example #27
0
    def __ta_array_adosc(cls, high, low, close, volume, fastperiod,
                         slowperiod):
        high_array = np.array(high)
        low_array = np.array(low)
        close_array = np.array(close)
        volume_array = np.array(volume)

        return talib.ADOSC(high_array, low_array, close_array, volume_array,
                           fastperiod, slowperiod)
Example #28
0
def getVolumeIndicators(df):
    high = df['High']
    low = df['Low']
    close = df['Close']
    open = df['Open']
    volume = df['Volume']

    df['AD'] = ta.AD(high, low, close, volume)
    df['ADOSC'] = ta.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)
    df['OBV']= ta.OBV(close, volume)
Example #29
0
def adosc(prices, signal):
    """
    Accumulation / Distribution Oscillator
    """

    signal['data'] = talib.ADOSC(prices['high'],
                                 prices['low'],
                                 prices['close'],
                                 prices['volume'],
                                 fastperiod=3,
                                 slowperiod=10).to_numpy()[:, None]
Example #30
0
def get_adosc(ohlc):
    adosc = ta.ADOSC(ohlc['2_high'],
                     ohlc['3_low'],
                     ohlc['4_close'],
                     ohlc['5_volume'],
                     fastperiod=3,
                     slowperiod=10)

    ohlc['adosc'] = adosc

    return ohlc