示例#1
0
    def STOCH(self):
        STOCH = tb.STOCH(self.dataframe,
                         fastk_period=5,
                         slowk_period=3,
                         slowk_matype=0,
                         slowd_period=3,
                         slowd_matype=0)
        slowk = STOCH["slowk"][len(STOCH) - 1]  #main
        slowd = STOCH["slowd"][len(STOCH) - 1]  #signal
        oldSlowk = STOCH["slowk"][len(STOCH) - 2]  #main
        oldSlowd = STOCH["slowd"][len(STOCH) - 2]  #signal

        #sell when main line > upper band (80) and main line crosses the signal line from above-down
        #buy when main line < lower band (20) and main line crosses the signal line from bottom-up

        if (slowk > 80):
            #print("RSI: " + str(value) + " overbought")
            return "overbought"
        elif (slowk > 60):
            #print("RSI: " + str(value) + " buy")
            return "buy"
        elif (slowk < 20):
            #print("RSI: " + str(value) + " oversold")
            return "oversold"
        elif (slowk < 40):
            #print("RSI: " + str(value) + " sell")
            return "sell"
        else:
            #print("RSI: " + str(value) + " neutral")
            return "neutral"
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        """
        Adds several different TA indicators to the given DataFrame

        Performance Note: For the best performance be frugal on the number of indicators
        you are using. Let uncomment only the indicator you are using in your strategies
        or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
        """

        # Stoch
        stoch = ta.STOCH(dataframe)
        dataframe['slowk'] = stoch['slowk']

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # Inverse Fisher transform on RSI, values [-1.0, 1.0] (https://goo.gl/2JGGoy)
        rsi = 0.1 * (dataframe['rsi'] - 50)
        dataframe['fisher_rsi'] = (numpy.exp(2 * rsi) -
                                   1) / (numpy.exp(2 * rsi) + 1)

        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']

        # SAR Parabol
        dataframe['sar'] = ta.SAR(dataframe)

        # Hammer: values [0, 100]
        dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe)

        return dataframe
示例#3
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 KD_signal(self, fastk=9):

        # KD指標,呈現過去一段時間股價強弱趨勢
        # 用K和D判斷目前價格相對過去一段時間的高低變化
        # KD指標呈現「最新股價的相對高低位置」,估股價目前處於相對高點或低點。
        # RSV= (今日收盤價 – 最近n天的最低價) ÷ (最近n天的最高價 – 最近n天最低價) × 100
        # 今日K值(快線)= 昨日K值 × (2/3 ) +今日RSV × ( 1/3)
        # 今日D值(慢線)= 昨日D值 × (2/3) +今日K值 × ( 1/3)
        # ※RSV中的n天,常見天數有以9天、14天等來比較,依標的屬性來調整。
        # fastk : RSV以 fastk 天為期

        df = self.stock_data
        df.columns = [col.lower() for col in df.columns]
        df_KD = abstract.STOCH(df, fastk_period=fastk)

        if (df_KD.iloc[-1, 0] > df_KD.iloc[-1, 1]) & (df_KD.iloc[-2, 0] < df_KD.iloc[-2, 1])\
                & (df_KD.iloc[-2, 0] < 20) & (df_KD.iloc[-2, 1] < 20):
            print('k值轉為大於d值,黃金交叉')
            return 1

        elif (df_KD.iloc[-1, 0] < df_KD.iloc[-1, 1]) & (df_KD.iloc[-2, 0] > df_KD.iloc[-2, 1])\
                & (df_KD.iloc[-2, 0] > 80) & (df_KD.iloc[-2, 1] > 80):
            print('k值轉為小於d值,死亡交叉')
            return -1

        # if (df_KD.iloc[-2, 0] < 80) & (df_KD.iloc[-1, 0] >= 80):
        #     return 1
        # elif (df_KD.iloc[-2, 0] > 30) & (df_KD.iloc[-1, 0] <= 30):
        #     return -1
        return 0
    def do_populate_indicators(self, dataframe: DataFrame,
                               metadata: dict) -> DataFrame:
        """
        Adds multiple TA indicators to MoniGoMani's DataFrame per pair.
        Should be called with 'informative_pair' (1h candles) during backtesting/hyperopting with TimeFrame-Zoom!

        Performance Note: For the best performance be frugal on the number of indicators you are using.
        Only add in indicators that you are using in your weighted signal configuration for MoniGoMani,
        otherwise you will waste your memory and CPU usage.

        :param dataframe: (DataFrame) DataFrame with data from the exchange
        :param metadata: (dict) Additional information, like the currently traded pair
        :return DataFrame: DataFrame for MoniGoMani with all mandatory indicator data populated
        """

        # Momentum Indicators (timeperiod is expressed in candles)
        # -------------------

        # Parabolic SAR
        dataframe['sar'] = ta.SAR(dataframe)

        # Stochastic Slow
        stoch = ta.STOCH(dataframe)
        dataframe['slowk'] = stoch['slowk']

        # MACD - Moving Average Convergence Divergence
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd[
            'macd']  # MACD - Blue TradingView Line (Bullish if on top)
        dataframe['macdsignal'] = macd[
            'macdsignal']  # Signal - Orange TradingView Line (Bearish if on top)

        # MFI - Money Flow Index (Under bought / Over sold & Over bought / Under sold / volume Indicator)
        dataframe['mfi'] = ta.MFI(dataframe)

        # Overlap Studies
        # ---------------

        # Bollinger Bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_middleband'] = bollinger['mid']

        # SMA's & EMA's are trend following tools (Should not be used when line goes sideways)
        # SMA - Simple Moving Average (Moves slower compared to EMA, price trend over X periods)
        dataframe['sma9'] = ta.SMA(dataframe, timeperiod=9)
        dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50)
        dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)

        # TEMA - Triple Exponential Moving Average
        dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)

        # Volume Indicators
        # -----------------

        # Rolling VWAP - Volume Weighted Average Price
        dataframe['rolling_vwap'] = qtpylib.rolling_vwap(dataframe)

        return dataframe
示例#6
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        """
        Adds several different TA indicators to the given DataFrame

        Performance Note: For the best performance be frugal on the number of indicators
        you are using. Let uncomment only the indicator you are using in your strategies
        or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
        """
        dataframe['gap'] = dataframe['close'].shift(1) - (
            (dataframe['high'].shift(1) - dataframe['low'].shift(1)) * 0.1)
        dataframe['adx'] = ta.ADX(dataframe)
        # MFI
        dataframe['mfi'] = ta.MFI(dataframe)
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)
        # Stochastic Fast
        stoch_fast = ta.STOCH(dataframe)
        dataframe['slowd'] = stoch_fast['slowd']
        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        return dataframe
示例#7
0
    def KDJ(self):  #(933)
        kd = abstract.STOCH(self.company_stock, fastk_period=9)

        self.company_stock['K'] = kd['slowk']
        self.company_stock['D'] = kd['slowd']
        self.company_stock[
            'J'] = 3 * self.company_stock['D'] - 2 * self.company_stock['K']
示例#8
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Dynamic TA indicators
        Used so hyperopt can optimized around the period of various indicators
        """
        for rsip in range(rsiStart, (rsiEnd + 1)):
            dataframe[f'rsi({rsip})'] = ta.RSI(dataframe, timeperiod=rsip)

        for temap in range(temaStart, (temaEnd + 1)):
            dataframe[f'tema({temap})'] = ta.TEMA(dataframe, timeperiod=temap)

        """
        Static TA indicators.
        RSI and TEMA Only used when --spaces does not include buy or sell
        """
        # Stochastic Slow
        # fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        stoch_slow = ta.STOCH(dataframe, fastk_period=fastkPeriod, slowk_period=slowkPeriod, slowd_period=slowdPeriod)
        dataframe['stoch-slowk'] = stoch_slow['slowk']
        dataframe['stoch-slowd'] = stoch_slow['slowd']

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # TEMA - Triple Exponential Moving Average
        dataframe['tema'] = ta.TEMA(dataframe)

        return dataframe
示例#9
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        # WAVETREND
        try:
            ap = (dataframe['high'] + dataframe['low'] +
                  dataframe['close']) / 3

            esa = ta.EMA(ap, 10)

            d = ta.EMA((ap - esa).abs(), 10)
            ci = (ap - esa).div(0.0015 * d)
            tci = ta.EMA(ci, 21)

            wt1 = tci
            wt2 = ta.SMA(np.nan_to_num(wt1), 4)

            dataframe['wt1'], dataframe['wt2'] = wt1, wt2

            stoch = ta.STOCH(dataframe, 14)
            slowk = stoch['slowk']
            dataframe['slowk'] = slowk
            # print(dataframe.iloc[:, 6:].keys())
            x = dataframe.iloc[:, 6:].values  # returns a numpy array
            min_max_scaler = preprocessing.MinMaxScaler()
            x_scaled = min_max_scaler.fit_transform(x)
            dataframe.iloc[:, 6:] = pd.DataFrame(x_scaled)
            # print('wt:\t', dataframe['wt'].min(), dataframe['wt'].max())
            # print('stoch:\t', dataframe['stoch'].min(), dataframe['stoch'].max())
            dataframe['def'] = dataframe['slowk'] - dataframe['wt1']
            # print('def:\t', dataframe['def'].min(), "\t", dataframe['def'].max())
        except:
            dataframe['wt1'], dataframe['wt2'], dataframe['def'], dataframe[
                'slowk'] = 0, 10, 100, 1000
        return dataframe
示例#10
0
    def __init__(self, equityDataFrame, tickerCode):
        """
        Create the STOCH-specific logic. Everything else lives in the Indicator Base Class.

        :param equityDataFrame: A Pandas DataFrame from the Equity Class.
        :param tickerCode: Ticker Code (String).
        """

        tableName = "Indicator_STOCH"
        tickerCode = tickerCode

        insertQuery = "insert or replace into %s (Date, STOCH_K, STOCH_D, STOCH_K_ROC, STOCH_D_ROC, Code) values (?,?,?,?,?,?)" % (
            tableName)

        # Stick the Indicator Values into the new DataFrame
        indicatorDataFrame = abstract.STOCH(equityDataFrame,
                                            fastk_period=5,
                                            slowk_period=3,
                                            slowk_matype=0,
                                            slowd_period=3,
                                            slowd_matype=0,
                                            prices=['High', 'Low', 'Close'])
        indicatorDataFrame['STOCH_K_ROC'] = abstract.ROC(indicatorDataFrame,
                                                         timeperiod=5,
                                                         price='slowk')
        indicatorDataFrame['STOCH_D_ROC'] = abstract.ROC(indicatorDataFrame,
                                                         timeperiod=5,
                                                         price='slowd')
        indicatorDataFrame['Code'] = tickerCode

        Indicator.__init__(self, tableName, tickerCode, insertQuery,
                           equityDataFrame, indicatorDataFrame)
示例#11
0
    def parse_data(self, response):
        """Parse data."""
        data = json.loads(response.text)
        date = response.meta['date']
        if data['hits']['total']['value'] == 0:
            stock_ids = []
            self.logger.info(f'{date} doesn\'t have data')
        else:
            stock_ids = [
                hit['_source']['stock_id'] for hit in data['hits']['hits']
            ]

            for stock_id in stock_ids:
                df = self.get_history_pirce_by_id(stock_id, date)
                s_item = items.TechnicalIndexItem()
                s_item['date'] = date
                s_item['stock_id'] = stock_id
                sma5 = self.filter_nan(abstract.SMA(df, timeperiod=5)[0])
                if sma5 is not None:
                    s_item['sma5'] = sma5
                sma10 = self.filter_nan(abstract.SMA(df, timeperiod=10)[0])
                if sma10 is not None:
                    s_item['sma10'] = sma10
                sma20 = self.filter_nan(abstract.SMA(df, timeperiod=20)[0])
                if sma20 is not None:
                    s_item['sma20'] = sma20
                sma60 = self.filter_nan(abstract.SMA(df, timeperiod=60)[0])
                if sma60 is not None:
                    s_item['sma60'] = sma60
                sma100 = self.filter_nan(abstract.SMA(df, timeperiod=100)[0])
                if sma100 is not None:
                    s_item['sma100'] = sma100
                rsi = self.filter_nan(abstract.RSI(df, timeperiod=14)[0])
                if rsi is not None:
                    s_item['rsi'] = rsi
                stoch_df = abstract.STOCH(df)
                slowk = self.filter_nan(stoch_df['slowk'][0])
                if slowk is not None:
                    s_item['slowk'] = slowk
                slowd = self.filter_nan(stoch_df['slowd'][0])
                if slowd is not None:
                    s_item['slowd'] = slowd
                if df.shape[0] >= 2:
                    s_item['double_volume'] = df['trade_volume'][0] > (
                        df['trade_volume'][1] * 2)
                    s_item['triple_volume'] = df['trade_volume'][0] > (
                        df['trade_volume'][1] * 3)

                    if df['close'][1] != 0:
                        quote_change = (df['close'][0] -
                                        df['close'][1]) / df['close'][1] * 100
                        # TODO: 取小數後兩位
                        s_item['quote_change'] = float(
                            '{:.2f}'.format(quote_change))
                s_item['id'] = f"{s_item['date']}-{s_item['stock_id']}"

                yield s_item

            self.logger.info(f'complete crawl \"{date}\"')
示例#12
0
def update_basic_info(n_clicks, year, input_value):

    data = Data()
    conn = sqlite3.connect('dataBase.db')
    strid = str(input_value)

    sPrice = data.get('收盤價', 1)[strid].values[0]
    try:
        sName = data.get('公司名稱', 1)[strid]
    except:
        sName = data.get('公司名稱', -1)[strid].values[0]
    sNumber = format(data.get('成交股數', 1)[strid].values[0], ',')
    sPER = data.get('本益比', 1)[strid].values[0]
    sClose = data.dates['price'].iloc[-1].name.strftime("%Y/%m/%d")
    sPBR = getPB(strid)
    sEPS = data.get('基本每股盈餘合計', 1)[strid].values[0]

    #基本圖figure
    revenueFig = getMonthRevenue(strid)
    epsFigure = getOneSeasonEPS(strid)
    chasflowFigure = getCashFlow(strid)
    incometableFigure = getIncomeTable(strid)

    #技術圖

    date = str(year[0]) + '-01-01'
    df = pdr.DataReader(str(strid) + '.TW', 'yahoo', start=date)
    fig = go.Figure(data=go.Candlestick(x=df.index,
                                        open=df['Open'],
                                        high=df['High'],
                                        low=df['Low'],
                                        close=df['Close']))
    fig.update_layout(xaxis_rangeslider_visible=False)

    alldf = pdr.DataReader(str(strid) + '.TW', 'yahoo', start=date)
    alldf = alldf.rename(columns={
        'High': 'high',
        'Low': 'low',
        'OPen': 'open',
        'Close': 'close'
    })

    #RSI
    RSI = abstract.RSI(alldf)
    #rsifig = px.line(RSI)
    rsifig = go.Scatter(x=RSI.index, y=RSI.values)

    tf = make_subplots(specs=[[{"secondary_y": True}]])

    #STOCH
    STOCH = abstract.STOCH(alldf)
    stochfig = px.line(STOCH)

    #SMA
    SMA = abstract.SMA(alldf)
    SMAfig = px.line(SMA)

    return sName, sPrice, sNumber, sPER, sPBR, sEPS, sClose, revenueFig, epsFigure, chasflowFigure, incometableFigure, fig, stochfig, SMAfig, year[
        0]
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
def generate_indicators(dataset,
                        timeperiod=5,
                        generate_target=True,
                        reset_index=False):

    # To avoid changes from original dataset
    df = pd.DataFrame(dataset).copy()

    # To prevent index from being Date
    if (reset_index):
        df = df.reset_index()

    df.columns = df.columns.str.lower()

    # check the given dataset has necessary_columns
    __check_columns(df)

    df = df[necessary_columns]

    # df_indicators has all columns except date, this is for talib to produces other indicators
    df_indicators = df.iloc[:, 1:]

    # Produce other indicators
    RSI = abstract.RSI(df_indicators.close, timeperiod)
    RSI = pd.DataFrame({'RSI': RSI})

    MOM = abstract.MOM(df_indicators.close, timeperiod)
    MOM = pd.DataFrame({'MOM': MOM})

    KD = abstract.STOCH(df_indicators)
    KD = pd.DataFrame(KD)  # KD has slowd and slowk

    MACD = abstract.MACD(df_indicators)
    MACD = pd.DataFrame(MACD)  # MACD has its own column names

    ADX = abstract.ADX(df_indicators)
    ADX = pd.DataFrame({'ADX': ADX})

    SMA = abstract.SMA(df_indicators.close)
    SMA = pd.DataFrame({'SMA': SMA})

    upper, middle, lower = talib.BBANDS(df_indicators.close, matype=MA_Type.T3)
    bb_df = pd.DataFrame({ \
        'upper_bb' : upper,
        'middel_bb' : middle,
        'lower_bb' : lower})

    # Combine all metrix
    frames = [df, RSI, MOM, KD, MACD, ADX, SMA, bb_df]
    combined = pd.concat(frames, axis=1)

    if (generate_target):
        target_name = 'next_' + str(timeperiod) + 'day_trend'
        combined[target_name] = np.where(
            combined.close.shift(-timeperiod) > combined.close, 1, 0)

    return combined
示例#15
0
    def add_indicators(self, df: pd.DataFrame = None) -> pd.DataFrame:
        """Add indicators."""

        cols = ['high', 'low', 'open', 'close', 'volume']
        HLOCV = {key: df[key].values for key in df if key in cols}

        try:
            df['volume'] = df['volumeto']
        except:
            pass

        # Moving Averages
        df['sma'] = abstract_ta.SMA(df, timeperiod=25)
        df['ema20'] = abstract_ta.EMA(df, timeperiod=20)
        df['ema50'] = abstract_ta.EMA(df, timeperiod=50)
        df['ema100'] = abstract_ta.EMA(df, timeperiod=100)
        df['ema200'] = abstract_ta.EMA(df, timeperiod=200)
        df['ema300'] = abstract_ta.EMA(df, timeperiod=300)

        # Bollinger Bands
        u, m, l = abstract_ta.BBANDS(HLOCV,
                                     timeperiod=24,
                                     nbdevup=2.5,
                                     nbdevdn=2.5,
                                     matype=MA_Type.T3)
        df['upper'] = u
        df['middle'] = m
        df['lower'] = l

        # Stochastic
        # uses high, low, close (default)
        slowk, slowd = abstract_ta.STOCH(HLOCV, 5, 3, 0, 3,
                                         0)  # uses high, low, close by default
        df['slowk'] = slowk
        df['slowd'] = slowd
        df['slow_stoch'] = (slowk + slowd) / 2
        df['slow_stoch_sma14'] = df.slow_stoch.rolling(window=14).mean()
        df['slow_stoch_sma26'] = df.slow_stoch.rolling(window=26).mean()

        # Relative Strength Index
        rsi = abstract_ta.RSI(df, timeperiod=14)
        df['rsi'] = rsi

        # Money Flow Index
        mfi = abstract_ta.MFI(df, timeperiod=14)
        df['mfi'] = mfi

        # Medivh Relative Flow Index
        mrfi_df = MRFI(df)
        df['mrfi'] = mrfi_df['mrfi'].astype(float)
        df['smrfi'] = mrfi_df['smrfi'].astype(float)
        df['mrfi_basis'] = mrfi_df['mrfi_basis'].astype(float)
        df['mrfi_inverse'] = mrfi_df['mrfi_inverse'].astype(float)

        return df
示例#16
0
def main():
    engine = db.create_engine('sqlite:///sql_pratice_db')
    conn = engine.connect()

    data = {}
    n_days = 16
    date = datetime.datetime.now()
    fail_count = 0
    allow_continuous_fail_count = 5
    while len(data) < n_days:
        table_name = date.date().__str__()
        if table_exists(table_name, engine):
            try:
                data[date.date()] = pd.read_sql_table(table_name=table_name, con=conn)
                data[date.date()] = data[date.date()].set_index('靡ㄩ腹')
                fail_count = 0
                print("parsing ", date, " success")
            except:
                print("parsing ", date, " failed")
                fail_count += 1
                if fail_count >= allow_continuous_fail_count:
                    raise
                    break
        date -= datetime.timedelta(days=1)

    close_price = pd.DataFrame({k: d['Μ絃基'] for k, d in data.items()}).transpose()
    close_price.index = pd.to_datetime(close_price.index)

    open_price = pd.DataFrame({k: d['秨絃基'] for k, d in data.items()}).transpose()
    open_price.index = pd.to_datetime(open_price.index)

    high_price = pd.DataFrame({k: d['程蔼基'] for k, d in data.items()}).transpose()
    high_price.index = pd.to_datetime(high_price.index)

    low_price = pd.DataFrame({k: d['程基'] for k, d in data.items()}).transpose()
    low_price.index = pd.to_datetime(low_price.index)

    volume = pd.DataFrame({k: d['Θユ计'] for k, d in data.items()}).transpose()
    volume.index = pd.to_datetime(volume.index)

    tsmc = pd.DataFrame({
        'close': close_price['2330']['2019'].dropna().astype(float),
        'open': open_price['2330']['2019'].dropna().astype(float),
        'high': high_price['2330']['2019'].dropna().astype(float),
        'low': low_price['2330']['2019'].dropna().astype(float),
        'volume': volume['2330']['2019'].dropna().astype(float),
    }).sort_index()

    print(tsmc)

    kd = abstract.STOCH(tsmc)
    print(kd)
    kd.plot()
    tsmc['close'].plot(secondary_y=True)
示例#17
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')
示例#18
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # Stochastic Slow
        stoch = ta.STOCH(dataframe)
        dataframe['slowd'] = stoch['slowd']
        dataframe['slowk'] = stoch['slowk']

        return dataframe
示例#19
0
def TA_processing(dataframe):
    bias(dataframe, days=[3, 6, 10, 25])
    moving_average(dataframe, days=[5, 10, 20])
    dataframe['ROC'] = abstract.ROC(dataframe, timeperiod=10)
    dataframe['MACD'] = abstract.MACD(dataframe, fastperiod=12, slowperiod=26, signalperiod=9)['macd']
    dataframe['MACD_signal'] = abstract.MACD(dataframe, fastperiod=12, slowperiod=26, signalperiod=9)['macdsignal']
    dataframe['UBBANDS'] = abstract.BBANDS(dataframe, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)['upperband']
    dataframe['MBBANDS'] = abstract.BBANDS(dataframe, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)['middleband']
    dataframe['LBBANDS'] = abstract.BBANDS(dataframe, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)['lowerband']
    dataframe['%K'] = abstract.STOCH(dataframe, fastk_period=9)['slowk']/100
    dataframe['%D'] = abstract.STOCH(dataframe, fastk_period=9)['slowd']/100
    dataframe['W%R'] = abstract.WILLR(dataframe, timeperiod=14)/100
    dataframe['RSI9'] = abstract.RSI(dataframe, timeperiod = 9)/100
    dataframe['RSI14'] = abstract.RSI(dataframe, timeperiod = 14)/100
    dataframe['CCI'] = abstract.CCI(dataframe, timeperiod=14)/100
    counter_daily_potential(dataframe)
    dataframe['MOM'] = abstract.MOM(dataframe, timeperiod=10)
    dataframe['DX'] = abstract.DX(dataframe, timeperiod=14)/100
    psy_line(dataframe)
    volumn_ratio(dataframe, d=26)
    on_balance_volume(dataframe)
示例#20
0
    def populate_indicators(self, dataframe, metadata):
        stoch = ta.STOCH(dataframe)
        rsi = ta.RSI(dataframe)
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe))

        dataframe["slowk"] = stoch["slowk"]
        dataframe["rsi"] = rsi

        rsi = 0.1 * (rsi - 50)
        dataframe["fisher"] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)
        dataframe["bb_lowerband"] = bollinger["lower"]
        dataframe["sar"] = ta.SAR(dataframe)
        dataframe["CDLHAMMER"] = ta.CDLHAMMER(dataframe)

        return dataframe
示例#21
0
文件: api.py 项目: seoulai/market
def _get_statistics(n=1, start_time=None, end_time=None):
    ohlc = _get_ohlc(3, start_time, end_time)
    # TODO: maybe handle nan differently
    limit = n * -1
    stoch = np.nan_to_num(abstract.STOCH(ohlc))
    macd = np.nan_to_num(abstract.MACD(ohlc))
    output = dict(
        macd=macd[0][limit:].tolist(),
        macd_signal=macd[1][limit:].tolist(),
        macd_hist=macd[2][limit:].tolist(),
        stoch_slowk=stoch[0][limit:].tolist(),
        stoch_slowd=stoch[1][limit:].tolist(),
        vave=np.nan_to_num(abstract.MA(ohlc)[limit:]).tolist(),
        sma=np.nan_to_num(abstract.SMA(ohlc)[limit:]).tolist(),
        rsi=np.nan_to_num(abstract.RSI(ohlc)[limit:]).tolist(),
        stddev=np.nan_to_num(abstract.STDDEV(ohlc)[limit:]).tolist())
    return output
示例#22
0
def taCalcSTOCH(df):

    df = copy.deepcopy(df)

    inputs = {
        'open': df['OPEN'].values.astype(float),
        'high': df['HIGH'].values.astype(float),
        'low': df['LOW'].values.astype(float),
        'close': df['CLOSE'].values.astype(float),
        'volume': df['VOLUME'].values.astype(float)
    }

    slowk, slowd = abstract.STOCH(inputs, 5, 3, 0, 3, 0)

    df['K'] = slowk
    df['D'] = slowd

    return df['K'], df['D']
示例#23
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        for rsip in range(self.rsiStart, (self.rsiEnd + 1)):
            dataframe[f'rsi({rsip})'] = ta.RSI(dataframe, timeperiod=rsip)

        for temap in range(self.temaStart, (self.temaEnd + 1)):
            dataframe[f'tema({temap})'] = ta.TEMA(dataframe, timeperiod=temap)

        # Stochastic Slow
        # fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        stoch_slow = ta.STOCH(dataframe,
                              fastk_period=self.fastkPeriod,
                              slowk_period=self.slowkPeriod,
                              slowd_period=self.slowdPeriod)
        dataframe['stoch-slowk'] = stoch_slow['slowk']
        dataframe['stoch-slowd'] = stoch_slow['slowd']

        return dataframe
示例#24
0
    def test_ta_lib_abstract_api(self):
        """Test the abstract API of TA-Lib"""

        with IQFeedHistoryProvider() as provider:
            df = provider.request_data(BarsFilter(ticker="AAPL",
                                                  interval_len=300,
                                                  interval_type='s',
                                                  max_bars=1000),
                                       sync_timestamps=False)
            close = df['close']

            output = abstract.SMA(df)
            self.assertTrue(isinstance(output, pd.Series))
            self.assertFalse(output.empty)
            self.assertTrue(pd.isna(output[0]))
            self.assertFalse(pd.isna(output[-1]))
            self.assertEqual(close.shape, output.shape)
            self.assertEqual(close.dtype, output.dtype)
            assert_index_equal(close.index, output.index)

            bbands = abstract.BBANDS(df, matype=talib.MA_Type.T3)
            self.assertTrue(isinstance(bbands, pd.DataFrame))
            assert_index_equal(close.index, bbands.index)

            for _, bband in bbands.iteritems():
                self.assertTrue(isinstance(bband, pd.Series))
                self.assertFalse(bband.empty)
                self.assertEqual(close.shape, bband.shape)
                self.assertEqual(close.dtype, bband.dtype)
                self.assertTrue(pd.isna(bband[0]))
                self.assertFalse(pd.isna(bband[-1]))

            stoch = abstract.STOCH(df, 5, 3, 0, 3, 0)
            self.assertTrue(isinstance(stoch, pd.DataFrame))
            assert_index_equal(close.index, stoch.index)

            for _, s in stoch.iteritems():
                self.assertTrue(isinstance(s, pd.Series))
                self.assertFalse(s.empty)
                self.assertEqual(close.shape, s.shape)
                self.assertEqual(close.dtype, s.dtype)
                self.assertTrue(pd.isna(s[0]))
                self.assertFalse(pd.isna(s[-1]))
示例#25
0
    def stoch(self):
        stoch = tb.STOCH(self.dataframe,
                         fastk_period=5,
                         slowk_period=3,
                         slowk_matype=0,
                         slowd_period=3,
                         slowd_matype=0)
        slowk = stoch["slowk"][len(stoch) - 1]

        if slowk > 80:
            return "overbought"
        elif slowk > 60:
            return "buy"
        elif slowk < 20:
            return "oversold"
        elif slowk < 40:
            return "sell"
        else:
            return "neutral"
示例#26
0
    def _process(self, v, param):
        data = {
            "open" : v["open"].astype(float),
            "high" : v["high"].astype(float),
            "low" : v["low"].astype(float),
            "close" : v["close"].astype(float),
            "volume" : v["jdiff_vol"].astype(float)
        }

        # 이동평균선
        if "SMA" in param:
            for p in param["SMA"]:
                v["SMA" + str(p)] = Series(abstract.SMA(data, p), index=v.index)

        # Bollinger Bands
        if "BBANDS" in param:
            temp = abstract.BBANDS(data, param["BBANDS"][0], param["BBANDS"][1], param["BBANDS"][1])
            v["BBANDS-UPPER"] = temp[0]
            v["BBANDS-MIDDLE"] = temp[1]
            v["BBANDS-LOWER"] = temp[2]

        # Slow stochastic
        if "STOCH" in param:
            temp = abstract.STOCH(data, param["STOCH"][0], param["STOCH"][1], param["STOCH"][2])
            v["STOCH-K"] = temp[0]
            v["STOCH-D"] = temp[1]

        # ATR (Average True Range)
        if "ATR" in param:
            v["ATR"] = Series(abstract.ATR(data, param["ATR"]), index=v.index)

        # MACD (Moving Average Convergence/Divergence)
        if "MACD" in param:
            temp = abstract.MACD(data, param["MACD"][0], param["MACD"][1], param["MACD"][2])
            v["MACD-OUT"] = temp[0]
            v["MACD-SIGNAL"] = temp[1]
            v["MACD-HIST"] = temp[2]

        # RSI (Relative Strength Index)
        if "RSI" in param:
            v["RSI"] = Series(abstract.RSI(data, param["RSI"]), index=v.index)
示例#27
0
文件: Stoch.py 项目: madkep/strat
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # Stochastic Slow
        # fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        stoch_slow = ta.STOCH(
            dataframe,
            fastk_period=self.stoch_params['stoch-fastk-period'],
            slowk_period=self.stoch_params['stoch-slowk-period'],
            slowd_period=self.stoch_params['stoch-slowd-period'])
        dataframe['stoch-slowk'] = stoch_slow['slowk']
        dataframe['stoch-slowd'] = stoch_slow['slowd']

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe,
                                  timeperiod=self.buy_params['rsi-period'])

        # TEMA - Triple Exponential Moving Average
        dataframe['tema'] = ta.TEMA(dataframe,
                                    timeperiod=self.sell_params['tema-period'])

        return dataframe
示例#28
0
    def STOCH(self, window_size):
        from talib import abstract

        input_arrays = {
            'open': self.data['Open'].values,
            'high': self.data['High'].values,
            'low': self.data['Low'].values,
            'close': self.data['Close'].values,
            'volume': self.data['Volume'].values
        }

        #slowk, slowd = STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        #return abstract.STOCH(input_arrays, fastk_period=window_size * self.no_of_intervals_per_day, slowk_period=window_size * self.no_of_intervals_per_day, slowk_matype=0, slowd_period=window_size * self.no_of_intervals_per_day, slowd_matype=0)

        return abstract.STOCH(input_arrays,
                              fastk_period=window_size *
                              self.no_of_intervals_per_day,
                              slowk_period=3 * self.no_of_intervals_per_day,
                              slowk_matype=0,
                              slowd_period=3 * self.no_of_intervals_per_day,
                              slowd_matype=0)
示例#29
0
def feature_add(df):
    ma_period = 10
    # rsi_period
    fastk = 9
    macd_fast = 6
    macd_slow = 12
    macd_period = 9

    df['MA' + str(ma_period)] = talib.SMA(df['close'], timeperiod=ma_period)
    df['RSI_14'] = talib.RSI(df['close'])
    _, _, df['MACDhist'] = talib.MACD(df['close'])

    vix_close = yf.Ticker('^VIX').history(period='max')['Close']
    tw_weighted = yf.Ticker('^TWII').history(period='max')['Close']
    sp500 = yf.Ticker('^GSPC').history(period='max').rename(
        columns={'Close': 'sp500'})['sp500']
    dowj = yf.Ticker('^DJI').history(period='max').rename(
        columns={'Close': 'Dowj'})['Dowj']
    # idx50 = yf.Tikcer('0050.TW').rename(columns={'Close': '0050'})['0050']
    # idx56 = yf.Tikcer('0056.TW').rename(columns={'Close': '0056'})['0056']
    df = pd.concat([
        df,
        abstract.STOCH(df, fastk_period=fastk), vix_close, tw_weighted, sp500,
        dowj
    ],
                   axis=1).dropna()
    try:
        df.drop(columns=['adj close'], inplace=True)
    except:
        pass

    normalizer = MinMaxScaler()
    scaled_features = normalizer.fit_transform(df.values)
    df_scaled = pd.DataFrame(scaled_features, index=df.index)
    data = [list(row.values) for idx, row in df_scaled.iterrows()]

    max_price = max(df['close'])
    min_price = min(df['close'])

    return data, [max_price, min_price]
示例#30
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # Stochastic Slow
        stoch = ta.STOCH(dataframe)
        dataframe['slowd'] = stoch['slowd']
        dataframe['slowk'] = stoch['slowk']

        # Bollinger Bands
        bollinger1 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=1)
        dataframe['bb_lowerband1'] = bollinger1['lower']
        dataframe['bb_middleband1'] = bollinger1['mid']
        dataframe['bb_upperband1'] = bollinger1['upper']

        bollinger2 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=2)
        dataframe['bb_lowerband2'] = bollinger2['lower']
        dataframe['bb_middleband2'] = bollinger2['mid']
        dataframe['bb_upperband2'] = bollinger2['upper']

        bollinger3 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=3)
        dataframe['bb_lowerband3'] = bollinger3['lower']
        dataframe['bb_middleband3'] = bollinger3['mid']
        dataframe['bb_upperband3'] = bollinger3['upper']

        bollinger4 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=4)
        dataframe['bb_lowerband4'] = bollinger4['lower']
        dataframe['bb_middleband4'] = bollinger4['mid']
        dataframe['bb_upperband4'] = bollinger4['upper']

        return dataframe