Exemple #1
0
    def analyze(self, historical_data, signal=["obv"], hot_thresh=None, cold_thresh=None):
        """Performs OBV analysis on the historical data

        Args:
            historical_data (list): A matrix of historical OHCLV data.
            signal (list, optional): Defaults to obv. The indicator line to check hot/cold
                against.
            hot_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to purchase.
            cold_thresh (float, optional): Defaults to None. The threshold at which this might be
                good to sell.

        Returns:
            pandas.DataFrame: A dataframe containing the indicators and hot/cold values.
        """

        dataframe = self.convert_to_dataframe(historical_data)
        obv_values = abstract.OBV(dataframe).to_frame()

        obv_values.dropna(how="all", inplace=True)
        obv_values.rename(columns={obv_values.columns[0]: "obv"}, inplace=True)

        if obv_values[signal[0]].shape[0]:
            obv_values["is_hot"] = obv_values[signal[0]] > hot_thresh
            obv_values["is_cold"] = obv_values[signal[0]] < cold_thresh

        return obv_values
Exemple #2
0
def calculator_talib(data):
    ETF = {
        'open': data[OHLCV_columns[0]].dropna().astype(float),
        'high': data[OHLCV_columns[1]].dropna().astype(float),
        'low': data[OHLCV_columns[2]].dropna().astype(float),
        'close': data[OHLCV_columns[3]].dropna().astype(float),
        'volume': data[OHLCV_columns[4]].dropna().astype(float)
    }

    def talib2df(talib_output):
        if type(talib_output) == list:
            ret = pd.DataFrame(talib_output).transpose()
        else:
            ret = pd.Series(talib_output)
        ret.index = data['收盤價'].index
        return ret

    KD = talib2df(abstract.STOCH(ETF, fastk_period=9))
    #計算MACD#
    MACD = talib2df(abstract.MACD(ETF))
    #計算OBV#
    OBV = talib2df(abstract.OBV(ETF))
    #計算威廉指數#
    WILLR = talib2df(abstract.WILLR(ETF))
    #ATR 計算#
    ATR = talib2df(abstract.ATR(ETF))

    ETF = pd.DataFrame()
    ETF = pd.concat([data, KD, MACD, OBV, WILLR, ATR], axis=1)
    return ETF
    def get_data(self, ticker):
        #取得資料和RSI,要先整理成Talib接受的小寫格式...
        self.df = pdr.DataReader(ticker, 'yahoo')
        self.df.drop(columns=['Adj Close'], inplace=True)
        self.df.rename(columns={
            'Open': 'open',
            'High': 'high',
            'Low': 'low',
            'Close': 'close',
            'Volume': 'volume'
        },
                       inplace=True)
        self.df['RSI'] = abstract.RSI(self.df)
        self.df['OBV'] = abstract.OBV(self.df)
        self.df['short_ma'] = self.df['close'].rolling(window=5).mean()
        self.df['mid_ma'] = self.df['close'].rolling(window=10).mean()
        self.df['long_ma'] = self.df['close'].rolling(
            window=self.monitor_days).mean()
        self.df.dropna(inplace=True)  #drop掉nan的部分

        #因為是RSI,所以把收盤價以外的drop掉
        self.df_analysis = self.df.drop(
            columns=['open', 'high', 'low', 'volume'])
        self.df_analysis['RSI_check'] = np.nan
        self.df_analysis['OBV_check'] = np.nan
        self.df_analysis['both_check'] = np.nan
        self.df_analysis['direction'] = np.nan
        self.df_analysis['direction_switch'] = np.nan
def apply_indicators(df: pd.DataFrame):

    # ADX
    df['adx'] = ta.ADX(df)

    # EMA
    df['ema_5'] = ta.EMA(df, 5)
    df['ema_10'] = ta.EMA(df, 10)
    df['ema_20'] = ta.EMA(df, 20)
    df['ema_50'] = ta.EMA(df, 50)
    df['ema_100'] = ta.EMA(df, 100)
    df['ema_200'] = ta.EMA(df, 200)

    # MACD
    macd = ta.MACD(df)
    df['macd'] = macd['macd']
    df['macdsignal'] = macd['macdsignal']
    df['macdhist'] = macd['macdhist']

    # inverse Fisher rsi/ RSI
    df['rsi'] = ta.RSI(df)
    rsi = 0.1 - (df['rsi'] - 50)
    df['i_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)

    # Stoch fast
    stoch_fast = ta.STOCHF(df)
    df['fastd'] = stoch_fast['fastd']
    df['fastk'] = stoch_fast['fastk']

    # Stock slow
    stoch_slow = ta.STOCH(df)
    df['slowd'] = stoch_slow['slowd']
    df['slowk'] = stoch_slow['slowk']

    # Bollinger bands
    bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(df),
                                        window=20,
                                        stds=2)
    df['bb_lowerband'] = bollinger['lower']
    df['bb_middleband'] = bollinger['mid']
    df['bb_upperband'] = bollinger['upper']

    # ROC
    df['roc'] = ta.ROC(df, 10)

    # CCI
    df['cci'] = ta.CCI(df, 14)

    # on balance volume
    df['obv'] = ta.OBV(df)

    # Average True Range
    df['atr'] = ta.ATR(df, 14)

    df = ichimoku(df)

    return df
Exemple #5
0
    def __init__(self, ticker, start_day=None, length=730):
        self.ticker = ticker
        if (start_day == None):
            today = datetime.today()
            start_day = today - timedelta(days=length)
            start_str = str(start_day.strftime('%Y-%m-%d'))
            end_str = str(today.strftime('%Y-%m-%d'))
        else:
            start_str = start_day
            #start = time.strptime(start_day, "%Y-%m-%d")
            start = datetime.strptime(start_str, "%Y-%m-%d")
            end_day = start + timedelta(days=length)
            end_str = str(end_day.strftime('%Y-%m-%d'))

        i = y.get_historical_prices(ticker, start_str, end_str)

        #Lag Pandas DataFrame
        self.df = pd.DataFrame(i)

        #Snu Dataframe
        self.df = self.df.transpose()

        #endre datatype til float
        self.df = self.df.astype(float)
        self.df = self.df.rename(
            columns={
                'Close': 'close',
                'High': 'high',
                'Open': 'open',
                'Low': 'low',
                'Volume': 'volume'
            })

        stoch = abstract.STOCH(self.df, 14, 1, 3)
        macd = abstract.MACD(self.df)
        atr = abstract.ATR(self.df)
        obv = abstract.OBV(self.df)
        rsi = abstract.RSI(self.df)

        self.df['atr'] = pd.DataFrame(atr)
        self.df['obv'] = pd.DataFrame(obv)
        self.df['rsi'] = pd.DataFrame(rsi)

        #kombinerer to dataframes
        self.df = pd.merge(self.df,
                           pd.DataFrame(macd),
                           left_index=True,
                           right_index=True,
                           how='outer')
        self.df = pd.merge(self.df,
                           stoch,
                           left_index=True,
                           right_index=True,
                           how='outer')
Exemple #6
0
def populate_indicators(dataframe: DataFrame) -> DataFrame:
    """
    Adds several different TA indicators to the given DataFrame
    """
    dataframe['sar'] = ta.SAR(dataframe)
    dataframe['adx'] = ta.ADX(dataframe)
    stoch = ta.STOCHF(dataframe)
    dataframe['fastd'] = stoch['fastd']
    dataframe['fastk'] = stoch['fastk']
    dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2,
                                    nbdevdn=2)['lowerband']
    dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
    dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
    dataframe['mfi'] = ta.MFI(dataframe)
    dataframe['cci'] = ta.CCI(dataframe)
    dataframe['rsi'] = ta.RSI(dataframe)
    dataframe['mom'] = ta.MOM(dataframe)
    dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
    dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
    dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
    dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
    dataframe['ao'] = awesome_oscillator(dataframe)
    macd = ta.MACD(dataframe)
    dataframe['macd'] = macd['macd']
    dataframe['macdsignal'] = macd['macdsignal']
    dataframe['macdhist'] = macd['macdhist']

    # add volatility indicators
    dataframe['natr'] = ta.NATR(dataframe)

    # add volume indicators
    dataframe['obv'] = ta.OBV(dataframe)

    # add more momentum indicators
    dataframe['rocp'] = ta.ROCP(dataframe)

    # add some pattern recognition
    dataframe['CDL2CROWS'] = ta.CDL2CROWS(dataframe)
    dataframe['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(dataframe)
    dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe)
    dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe)
    dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe)
    dataframe['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(dataframe)
    dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe)
    dataframe['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(dataframe)
    dataframe['CDLBELTHOLD'] = ta.CDLBELTHOLD(dataframe)
    dataframe['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(dataframe)
    dataframe['CDLDOJI'] = ta.CDLDOJI(dataframe)
    dataframe['CDLDOJISTAR'] = ta.CDLDOJISTAR(dataframe)
    dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe)
    dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe)
    dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe)
    dataframe['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(dataframe)
    dataframe['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(dataframe)

    # enter categorical time
    hour = datetime.strptime(str(dataframe['date'][len(dataframe) - 1]),
                             "%Y-%m-%d %H:%M:%S").hour
    for h in range(24):
        dataframe['hour_{0:02}'.format(h)] = int(h == hour)

    return dataframe
Exemple #7
0
 def cal_obv(self):
     self.analysis_data['obv'] = ta.OBV(self.close, self.volume)
        ret = pd.DataFrame(talib_output).transpose()
    else :
        ret = pd.Series(talib_output)
    ret.index = taini['close'].index
    ret.fillna(0)
    return ret

#ax.set_xlim(, right)
#KD
talib2df(talib.abstract.STOCH(taini)).plot()
taini['close'].plot(secondary_y=True)
plt.savefig("kd.png")
plt.show()
plt.cla()

#RSI
talib2df(talib.abstract.RSI(taini)).plot()
taini['close'].plot(secondary_y=True)
plt.savefig("rsi.png")
plt.cla()
#MACD
talib2df(abstract.STOCH(taini, fastk_period=9)).plot()
taini['close'].plot(secondary_y=True)
plt.savefig("macd.png")
plt.show()
plt.cla()
#OBV
talib2df(abstract.OBV(taini)).plot()
taini['close'].plot(secondary_y=True)
plt.savefig("obv.png")
plt.cla()