Exemple #1
0
def show(args, klines, kline_column_names, display_count, disp_ic_keys):
    for index, value in enumerate(kline_column_names):
        if value == "high":
            highindex = index
        if value == "low":
            lowindex = index
        if value == "open":
            openindex = index
        if value == "close":
            closeindex = index
        if value == "volume":
            volumeindex = index
        if value == "open_time":
            opentimeindex = index

    klines_df = pd.DataFrame(klines, columns=kline_column_names)
    open_times = [
        datetime.fromtimestamp((float(open_time) / 1000))
        for open_time in klines_df["open_time"][-display_count:]
    ]
    close_times = [
        datetime.fromtimestamp((float(close_time) / 1000))
        for close_time in klines_df["close_time"][-display_count:]
    ]

    fig, axes = plt.subplots(len(disp_ic_keys) + 1, 1, sharex=True)
    fig.subplots_adjust(left=0.05,
                        bottom=0.04,
                        right=1,
                        top=1,
                        wspace=0,
                        hspace=0)
    fig.suptitle(args.s + '    ' + args.i)

    quotes = []
    for k in klines[-display_count:]:
        d = datetime.fromtimestamp(k[0] / 1000)
        quote = (dts.date2num(d), float(k[1]), float(k[4]), float(k[2]),
                 float(k[3]))
        quotes.append(quote)

    i = -1

    # kine
    i += 1
    ax = axes[i]
    mpf.candlestick_ochl(axes[i],
                         quotes,
                         width=0.02,
                         colorup='g',
                         colordown='r')
    ax.set_ylabel('price')
    ax.grid(True)
    ax.autoscale_view()
    ax.xaxis_date()

    handle_overlap_studies(args, ax, klines_df, close_times, display_count)
    """
    if args.EBANDS: # BANDS
        name = 'EBANDS'
        upperband, middleband, lowerband = tal.EBANDS(klines_df, timeperiod=26)
        ax.plot(close_times, middleband[-display_count:], "b--", label=name)
        ax.plot(close_times, upperband[-display_count:], 'y--', label=name+' upperband')
        ax.plot(close_times, lowerband[-display_count:], 'y--', label=name+' lowerband')
    """

    ic_key = 'macd'
    if ic_key in disp_ic_keys:
        i += 1
        ax = axes[i]
        ax.set_ylabel('macd')
        ax.grid(True)

        klines_df = ic.pd_macd(klines_df)
        difs = [round(a, 2) for a in klines_df["dif"]]
        deas = [round(a, 2) for a in klines_df["dea"]]
        macds = [round(a, 2) for a in klines_df["macd"]]
        ax.plot(close_times, difs[-display_count:], "y", label="dif")
        ax.plot(close_times, deas[-display_count:], "b", label="dea")
        ax.plot(close_times,
                macds[-display_count:],
                "r",
                drawstyle="steps",
                label="macd")

    ic_key = 'RSI'
    if ic_key in disp_ic_keys:
        i += 1
        ax = axes[i]
        ax.set_ylabel(ic_key)
        ax.grid(True)
        rsis = talib.RSI(klines_df["close"], timeperiod=14)
        rsis = [round(a, 2) for a in rsis][-display_count:]
        ax.plot(close_times, rsis, "r", label=ic_key)
        ax.plot(close_times, [70] * len(rsis), '-', color='r')
        ax.plot(close_times, [30] * len(rsis), '-', color='r')
        """
        rs2 = ic.py_rsis(klines, closeindex, period=14)
        rs2 = [round(a, 2) for a in rs2][-display_count:]
        axes[i].plot(close_times, rs2, "y", label="rsi2")
        """
    """
    fastk, fastd = talib.STOCHRSI(klines_df["close"], timeperiod=14)
    rsifks = [round(a, 2) for a in fastk][-display_count:]
    rsifds = [round(a, 2) for a in fastd][-display_count:]
    axes[i].plot(close_times, rsifks, "b", label="rsi")
    axes[i].plot(close_times, rsifds, "y", label="rsi")
    """

    ic_key = 'KDJ'
    if ic_key in disp_ic_keys:
        i += 1
        ax = axes[i]
        ax.set_ylabel(ic_key)
        ax.grid(True)
        """
        ks, ds = talib.STOCH(klines_df["high"], klines_df["low"], klines_df["close"],
            fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        js = ks - ds
        """
        ks, ds, js = ic.pd_kdj(klines_df)
        ks = [round(a, 2) for a in ks][-display_count:]
        ds = [round(a, 2) for a in ds][-display_count:]
        js = [round(a, 2) for a in js][-display_count:]
        ax.plot(close_times, ks, "b", label="K")
        ax.plot(close_times, ds, "y", label="D")
        ax.plot(close_times, js, "m", label="J")

    # Volume Indicator
    ic_key = 'AD'
    if ic_key in disp_ic_keys:
        real = talib.AD(klines_df["high"], klines_df["low"],
                        klines_df["close"], klines_df["volume"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'ADOSC'
    if ic_key in disp_ic_keys:
        real = talib.ADOSC(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           klines_df["volume"],
                           fastperiod=3,
                           slowperiod=10)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'OBV'
    if ic_key in disp_ic_keys:
        real = talib.OBV(klines_df["close"], klines_df["volume"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Volatility Indicator
    ic_key = 'ATR'
    if ic_key in disp_ic_keys:
        real = talib.ATR(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'NATR'
    if ic_key in disp_ic_keys:
        real = talib.NATR(klines_df["high"],
                          klines_df["low"],
                          klines_df["close"],
                          timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'TRANGE'
    if ic_key in disp_ic_keys:
        real = talib.TRANGE(klines_df["high"], klines_df["low"],
                            klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Price Transform
    ic_key = 'AVGPRICE'
    if ic_key in disp_ic_keys:
        real = talib.AVGPRICE(klines_df["open"], klines_df["high"],
                              klines_df["low"], klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'MEDPRICE'
    if ic_key in disp_ic_keys:
        real = talib.MEDPRICE(klines_df["high"], klines_df["low"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'TYPPRICE'
    if ic_key in disp_ic_keys:
        real = talib.TYPPRICE(klines_df["high"], klines_df["low"],
                              klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'WCLPRICE'
    if ic_key in disp_ic_keys:
        real = talib.WCLPRICE(klines_df["high"], klines_df["low"],
                              klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Cycle Indicator
    ic_key = 'HT_DCPERIOD'
    if ic_key in disp_ic_keys:
        real = talib.HT_DCPERIOD(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_DCPHASE'
    if ic_key in disp_ic_keys:
        real = talib.HT_DCPHASE(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_PHASOR'
    if ic_key in disp_ic_keys:
        real = talib.HT_PHASOR(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_SINE'
    if ic_key in disp_ic_keys:
        real = talib.HT_SINE(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'HT_TRENDMODE'
    if ic_key in disp_ic_keys:
        real = talib.HT_TRENDMODE(klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Statistic
    ic_key = 'BETA'
    if ic_key in disp_ic_keys:
        real = talib.BETA(klines_df["high"], klines_df["low"], timeperiod=5)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'CORREL'
    if ic_key in disp_ic_keys:
        real = talib.CORREL(klines_df["high"], klines_df["low"], timeperiod=30)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG_ANGLE'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG_ANGLE(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG_INTERCEPT'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG_INTERCEPT(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'LINEARREG_SLOPE'
    if ic_key in disp_ic_keys:
        real = talib.LINEARREG_SLOPE(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'STDDEV'  # Standard Deviation
    if ic_key in disp_ic_keys:
        real = talib.STDDEV(klines_df["close"], timeperiod=5, nbdev=1)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'TSF'  # Time Series Forecast
    if ic_key in disp_ic_keys:
        real = talib.TSF(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")
    ic_key = 'VAR'  # Variance
    if ic_key in disp_ic_keys:
        real = talib.VAR(klines_df["close"], timeperiod=5, nbdev=1)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    # Momentum Indicator
    ic_key = 'DX'
    if ic_key in disp_ic_keys:
        dxs = talib.DX(klines_df["high"],
                       klines_df["low"],
                       klines_df["close"],
                       timeperiod=14)
        adxs = talib.ADX(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        adxrs = talib.ADXR(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, dxs[-display_count:], "r:")
        ts.ax(axes[i], ic_key, close_times, adxs[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, adxrs[-display_count:], "k:")

    ic_key = 'APO'
    if ic_key in disp_ic_keys:
        real = talib.APO(klines_df["close"],
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'AROON'
    if ic_key in disp_ic_keys:
        aroondown, aroonup = talib.AROON(klines_df["high"],
                                         klines_df["low"],
                                         timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key + ' DOWN', close_times,
              aroondown[-display_count:], "y:")
        ts.ax(axes[i], ic_key + ' UP', close_times, aroonup[-display_count:],
              "y:")

    ic_key = 'AROONOSC'
    if ic_key in disp_ic_keys:
        real = talib.AROONOSC(klines_df["high"],
                              klines_df["low"],
                              timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'BOP'
    if ic_key in disp_ic_keys:
        real = talib.BOP(klines_df["open"], klines_df["high"],
                         klines_df["low"], klines_df["close"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'CCI'
    if ic_key in disp_ic_keys:
        real = talib.CCI(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'CMO'
    if ic_key in disp_ic_keys:
        real = talib.CMO(klines_df["close"], timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MACD'
    if ic_key in disp_ic_keys:
        macd, macdsignal, macdhist = talib.MACD(klines_df["close"],
                                                fastperiod=12,
                                                slowperiod=26,
                                                signalperiod=9)
        i += 1
        ts.ax(axes[i], ic_key, close_times, macd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, macdsignal[-display_count:], "b")
        ts.ax(axes[i],
              ic_key,
              close_times,
              macdhist[-display_count:],
              "r",
              drawstyle="steps")

    ic_key = 'MACDEXT'
    if ic_key in disp_ic_keys:
        macd, macdsignal, macdhist = talib.MACDEXT(klines_df["close"],
                                                   fastperiod=12,
                                                   fastmatype=0,
                                                   slowperiod=26,
                                                   slowmatype=0,
                                                   signalperiod=9,
                                                   signalmatype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, macd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, macdsignal[-display_count:], "b")
        ts.ax(axes[i],
              ic_key,
              close_times,
              macdhist[-display_count:],
              "r",
              drawstyle="steps")

    ic_key = 'MACDFIX'
    if ic_key in disp_ic_keys:
        macd, macdsignal, macdhist = talib.MACDFIX(klines_df["close"],
                                                   signalperiod=9)
        i += 1
        ts.ax(axes[i], ic_key, close_times, macd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, macdsignal[-display_count:], "b")
        ts.ax(axes[i],
              ic_key,
              close_times,
              macdhist[-display_count:],
              "r",
              drawstyle="steps")

    ic_key = 'MFI'
    if ic_key in disp_ic_keys:
        real = talib.MFI(klines_df["high"], klines_df["low"],
                         klines_df["close"], klines_df["volume"])
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MINUS_DI'
    if ic_key in disp_ic_keys:
        real = talib.MINUS_DI(klines_df["high"],
                              klines_df["low"],
                              klines_df["close"],
                              timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MINUS_DM'
    if ic_key in disp_ic_keys:
        real = talib.MINUS_DM(klines_df["high"],
                              klines_df["low"],
                              timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'MOM'
    if ic_key in disp_ic_keys:
        real = talib.MOM(klines_df["close"], timeperiod=10)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'PLUS_DI'
    if ic_key in disp_ic_keys:
        real = talib.PLUS_DI(klines_df["high"],
                             klines_df["low"],
                             klines_df["close"],
                             timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'PLUS_DM'
    if ic_key in disp_ic_keys:
        real = talib.PLUS_DM(klines_df["high"],
                             klines_df["low"],
                             timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'PPO'
    if ic_key in disp_ic_keys:
        real = talib.PPO(klines_df["close"],
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'ROC'
    if ic_key in disp_ic_keys:
        real1 = talib.ROC(klines_df["close"], timeperiod=10)
        real2 = talib.ROCP(klines_df["close"], timeperiod=10)
        real3 = talib.ROCR(klines_df["close"], timeperiod=10)
        real4 = talib.ROCR100(klines_df["close"], timeperiod=10)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real1[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, real2[-display_count:], "k:")
        ts.ax(axes[i], ic_key, close_times, real3[-display_count:], "m:")
        ts.ax(axes[i], ic_key, close_times, real4[-display_count:], "b:")

    ic_key = 'STOCH'
    if ic_key in disp_ic_keys:
        slowk, slowd = talib.STOCH(klines_df["high"],
                                   klines_df["low"],
                                   klines_df["close"],
                                   fastk_period=5,
                                   slowk_period=3,
                                   slowk_matype=0,
                                   slowd_period=3,
                                   slowd_matype=0)
        i += 1
        slowj = 3 * slowk - 2 * slowd
        ts.ax(axes[i], ic_key, close_times, slowk[-display_count:], "b")
        ts.ax(axes[i], ic_key, close_times, slowd[-display_count:], "y")
        ts.ax(axes[i], ic_key, close_times, slowj[-display_count:], "m")

    ic_key = 'STOCHF'
    if ic_key in disp_ic_keys:
        fastk, fastd = talib.STOCHF(klines_df["high"],
                                    klines_df["low"],
                                    klines_df["close"],
                                    fastk_period=5,
                                    fastd_period=3,
                                    fastd_matype=0)
        i += 1
        fastj = 3 * fastk - 2 * fastd
        ts.ax(axes[i], ic_key, close_times, fastk[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, fastd[-display_count:], "b:")
        ts.ax(axes[i], ic_key, close_times, fastj[-display_count:], "m")

    ic_key = 'STOCHRSI'
    if ic_key in disp_ic_keys:
        fastk, fastd = talib.STOCHRSI(klines_df["close"],
                                      timeperiod=14,
                                      fastk_period=5,
                                      fastd_period=3,
                                      fastd_matype=0)
        i += 1
        ts.ax(axes[i], ic_key, close_times, fastk[-display_count:], "y:")
        ts.ax(axes[i], ic_key, close_times, fastd[-display_count:], "b:")

    ic_key = 'TRIX'
    if ic_key in disp_ic_keys:
        real = talib.TRIX(klines_df["close"], timeperiod=30)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'ULTOSC'
    if ic_key in disp_ic_keys:
        real = talib.ULTOSC(klines_df["high"],
                            klines_df["low"],
                            klines_df["close"],
                            timeperiod1=7,
                            timeperiod2=14,
                            timeperiod3=28)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    ic_key = 'WILLR'
    if ic_key in disp_ic_keys:
        real = talib.WILLR(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           timeperiod=14)
        i += 1
        ts.ax(axes[i], ic_key, close_times, real[-display_count:], "y:")

    plt.show()
Exemple #2
0
def ROCR(data, **kwargs):
    _check_talib_presence()
    prices = _extract_series(data)
    return talib.ROCR(prices, **kwargs)
Exemple #3
0
def momentum_process(event):
    print(event.widget.get())
    momentum = event.widget.get()

    upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
    fig, axes = plt.subplots(2, 1, sharex=True)
    ax1, ax2 = axes[0], axes[1]
    axes[0].plot(close, 'rd-', markersize=3)
    axes[0].plot(upperband, 'y-')
    axes[0].plot(middleband, 'b-')
    axes[0].plot(lowerband, 'y-')
    axes[0].set_title(momentum, fontproperties="SimHei")

    if momentum == '绝对价格振荡器':
        real = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
        axes[1].plot(real, 'r-')
    elif momentum == '钱德动量摆动指标':
        real = ta.CMO(close, timeperiod=14)
        axes[1].plot(real, 'r-')
    elif momentum == '移动平均收敛/散度':
        macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
        axes[1].plot(macd, 'r-')
        axes[1].plot(macdsignal, 'g-')
        axes[1].plot(macdhist, 'b-')
    elif momentum == '带可控MA类型的MACD':
        macd, macdsignal, macdhist = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
        axes[1].plot(macd, 'r-')
        axes[1].plot(macdsignal, 'g-')
        axes[1].plot(macdhist, 'b-')
    elif momentum == '移动平均收敛/散度 固定 12/26':
        macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9)
        axes[1].plot(macd, 'r-')
        axes[1].plot(macdsignal, 'g-')
        axes[1].plot(macdhist, 'b-')
    elif momentum == '动量':
        real = ta.MOM(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '比例价格振荡器':
        real = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率':
        real = ta.ROC(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率百分比':
        real = ta.ROCP(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率的比率':
        real = ta.ROCR(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '变化率的比率100倍':
        real = ta.ROCR100(close, timeperiod=10)
        axes[1].plot(real, 'r-')
    elif momentum == '相对强弱指数':
        real = ta.RSI(close, timeperiod=14)
        axes[1].plot(real, 'r-')
    elif momentum == '随机相对强弱指标':
        fastk, fastd = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
        axes[1].plot(fastk, 'r-')
        axes[1].plot(fastd, 'r-')
    elif momentum == '三重光滑EMA的日变化率':
        real = ta.TRIX(close, timeperiod=30)
        axes[1].plot(real, 'r-')

    plt.show()
Exemple #4
0
def Momentum_Indicators(dataframe):
	"""
	Momentum Indicators:

	ADX                  Average Directional Movement Index
	ADXR                 Average Directional Movement Index Rating
	APO                  Absolute Price Oscillator
	AROON                Aroon
	AROONOSC             Aroon Oscillator
	BOP                  Balance Of Power
	CCI                  Commodity Channel Index
	CMO                  Chande Momentum Oscillator
	DX                   Directional Movement Index
	MACD                 Moving Average Convergence/Divergence
	MACDEXT              MACD with controllable MA type
	MACDFIX              Moving Average Convergence/Divergence Fix 12/26
	MFI                  Money FLow Index
	MINUS_DI             Minus Directional Indicator
	MINUS_DM             Minus Directional Movement
	MOM                  Momentum
	PLUS_DI              Plus Directional Indicator
	PLUS_DM              Plus Directional Movement
	PPO                  Percentage Price Oscillator
	ROC                  Rate of change : ((price/prevPrice)-1)*100
	ROCP                 Rate of change Percentage: (price-prevPrice)/prevPrice
	ROCR                 Rate of change ratio: (price/prevPrice)
	ROCR100              Rate of change ratio 100 scale: (price/prevPrice)*100
	RSI                  Relative Strength Index
	STOCH                Stochastic
	STOCHF               Stochastic Fast
	STOCHRSI             Stochastic Relative Strength Index
	TRIX                 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
	ULTOSC               Ultimate Oscillator
	WILLR                Williams' %R
	"""
	#ADX - Average Directional Movement Index
	df[f'{ratio}_ADX'] = talib.ADX(High, Low, Close, timeperiod=14)
	#ADXR - Average Directional Movement Index Rating
	df[f'{ratio}_ADXR'] = talib.ADXR(High, Low, Close, timeperiod=14)
	#APO - Absolute Price Oscillator
	#df[f'{ratio}_APO'] = talib.APO(Close, fastperiod=12, sLowperiod=26, matype=0)
	#AROON - Aroon
	aroondown, aroonup = talib.AROON(High, Low, timeperiod=14)
	#AROONOSC - Aroon Oscillator
	df[f'{ratio}_AROONOSC'] = talib.AROONOSC(High, Low, timeperiod=14)
	#BOP - Balance Of Power
	df[f'{ratio}_BOP'] = talib.BOP(Open, High, Low, Close)
	#CCI - Commodity Channel Index
	df[f'{ratio}_CCI'] = talib.CCI(High, Low, Close, timeperiod=14)
	#CMO - Chande Momentum Oscillator
	df[f'{ratio}_CMO'] = talib.CMO(Close, timeperiod=14)
	#DX - Directional Movement Index
	df[f'{ratio}_DX'] = talib.DX(High, Low, Close, timeperiod=14)
	
	#MACD - Moving Average Convergence/Divergence
	#macd, macdsignal, macdhist = talib.MACD(Close, fastperiod=12, sLowperiod=26, signalperiod=9)
	#MACDEXT - MACD with controllable MA type
	#macd, macdsignal, macdhist = talib.MACDEXT(Close, fastperiod=12, fastmatype=0, sLowperiod=26, sLowmatype=0, signalperiod=9, signalmatype=0)
	#MACDFIX - Moving Average Convergence/Divergence Fix 12/26
	#macd, macdsignal, macdhist = talib.MACDFIX(Close, signalperiod=9)
	#MFI - Money FLow Index
	#df[f'{ratio}_MFI'] = talib.MFI(High, Low, Close, volume, timeperiod=14)
	
	#MINUS_DI - Minus Directional Indicator
	df[f'{ratio}_MINUS_DI'] = talib.MINUS_DI(High, Low, Close, timeperiod=14) 
	#MINUS_DM - Minus Directional Movement
	df[f'{ratio}_MINUS_DM'] = talib.MINUS_DM(High, Low, timeperiod=14)
	#Minus Directional Movement 
	#MOM - Momentum
	df[f'{ratio}_MOM'] = talib.MOM(Close, timeperiod=10) 
	#PLUS_DI - Plus Directional Indicator
	df[f'{ratio}_PLUS_DI'] = talib.PLUS_DI(High, Low, Close, timeperiod=14)
	#PLUS_DM - Plus Directional Movement
	df[f'{ratio}_PLUS_DM'] = talib.PLUS_DM(High, Low, timeperiod=14) 
	
	#PPO - Percentage Price Oscillator
	#df[f'{ratio}_PPO'] = talib.PPO(Close, fastperiod=12, sLowperiod=26, matype=0)
	#ROC - Rate of change : ((price/prevPrice)-1)*100
	df[f'{ratio}_ROC'] = talib.ROC(Close, timeperiod=10)
	#ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice
	df[f'{ratio}_ROCP'] = talib.ROCP(Close, timeperiod=10)
	#ROCR - Rate of change ratio: (price/prevPrice)
	df[f'{ratio}_ROCR'] = talib.ROCR(Close, timeperiod=10)
	#ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
	df[f'{ratio}_ROCR100'] = talib.ROCR100(Close, timeperiod=10)
	#RSI - Relative Strength Index
	#NOTE: The RSI function has an unstable period.
	df[f'{ratio}_RSI'] = talib.RSI(Close, timeperiod=14)
	
	#STOCH - Stochastic
	#sLowk, sLowd = talib.STOCH(High, Low, Close, fastk_period=5, sLowk_period=3, sLowk_matype=0, sLowd_period=3, sLowd_matype=0)
	#STOCHF - Stochastic Fast
	fastk, fastd = talib.STOCHF(High, Low, Close, fastk_period=5, fastd_period=3, fastd_matype=0)
	#STOCHRSI - Stochastic Relative Strength Index
	fastk, fastd = talib.STOCHRSI(Close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
	#TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
	df[f'{ratio}_TRIX'] = talib.TRIX(Close, timeperiod=30)
	#ULTOSC - Ultimate Oscillator
	df[f'{ratio}_ULTOSC'] = talib.ULTOSC(High, Low, Close, timeperiod1=7, timeperiod2=14, timeperiod3=28)
	#WILLR - Williams' %R
	df[f'{ratio}_ULTOSC'] = talib.WILLR(High, Low, Close, timeperiod=14)

	return
 def talib_023(self):
     data_ROCR = copy.deepcopy(self.close)
     for symbol in symbols:
         data_ROCR[symbol] = ta.ROCR(self.close[symbol].values, timeperiod=10)
     return data_ROCR
def get_technical_indicators(dataset):
    # Create 7 and 21 days Moving Average
    dataset['ma7'] = dataset['Adj Close'].rolling(window=7).mean()
    dataset['ma21'] = dataset['Adj Close'].rolling(window=21).mean()

    # Create Exponential moving average
    dataset['ema'] = dataset['Adj Close'].ewm(com=0.5).mean()

    # Create MACD
    dataset['26ema'] = dataset['Adj Close'].ewm(span=26).mean()
    dataset['12ema'] = dataset['Adj Close'].ewm(span=12).mean()
    dataset['MACD'] = (dataset['12ema'] - dataset['26ema'])

    # Create Momentum
    dataset['momentum'] = dataset['Adj Close'] - 1

    # Create Bollinger Bands
    dataset['20sd'] = dataset['Adj Close'].rolling(20).std()
    dataset['upper_band'] = dataset['ma21'] + (dataset['20sd'] * 2)
    dataset['lower_band'] = dataset['ma21'] - (dataset['20sd'] * 2)

    # Create RSI indicator
    dataset['RSI'] = ta.RSI(np.array(dataset['Adj Close']))

    #Part I: Create Cycle Indicators
    #Create HT_DCPERIOD - Hilbert Transform - Dominant Cycle Period
    dataset['HT_DCPERIOD'] = ta.HT_DCPERIOD(np.array(dataset['Adj Close']))

    #Create HT_DCPHASE - Hilbert Transform - Dominant Cycle Phase
    dataset['HT_DCPHASE'] = ta.HT_DCPHASE(np.array(dataset['Adj Close']))

    #HT_TRENDMODE - Hilbert Transform - Trend vs Cycle Mode
    dataset['HT_TRENDMODE'] = ta.HT_TRENDMODE(np.array(dataset['Adj Close']))

    #Part II: Create Volatility Indicators
    #Create Average True Range
    dataset['ATR'] = ta.ATR(np.array(dataset['High']),
                            np.array(dataset['Low']),
                            np.array(dataset['Adj Close']),
                            timeperiod=14)

    #Create NATR - Normalized Average True Range
    dataset['NATR'] = ta.NATR(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)

    #Create TRANGE - True Range
    dataset['TRANGE'] = ta.TRANGE(np.array(dataset['High']),
                                  np.array(dataset['Low']),
                                  np.array(dataset['Adj Close']))

    #Part III Overlap Studies
    #Create DEMA - Double Exponential Moving Average
    dataset['DEMA'] = ta.DEMA(np.array(dataset['Adj Close']), timeperiod=30)

    #Create HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline
    dataset['HT_TRENDLINE'] = ta.HT_TRENDLINE(np.array(dataset['Adj Close']))

    #Create KAMA - Kaufman Adaptive Moving Average
    dataset['KAMA'] = ta.KAMA(np.array(dataset['Adj Close']), timeperiod=30)

    #Create MIDPOINT - MidPoint over period
    dataset['MIDPOINT'] = ta.MIDPOINT(np.array(dataset['Adj Close']),
                                      timeperiod=14)

    #Create MIDPRICE - Midpoint Price over period
    dataset['MIDPRICE'] = ta.MIDPRICE(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      timeperiod=14)

    #Create SAR - Parabolic SAR
    dataset['SAR'] = ta.SAR(np.array(dataset['High']),
                            np.array(dataset['Low']),
                            acceleration=0,
                            maximum=0)

    #Create SMA - Simple Moving Average
    dataset['SMA10'] = ta.SMA(np.array(dataset['Adj Close']), timeperiod=10)

    #Create T3 - Triple Exponential Moving Average (T3)
    dataset['T3'] = ta.T3(np.array(dataset['Adj Close']),
                          timeperiod=5,
                          vfactor=0)

    #Create TRIMA - Triangular Moving Average
    dataset['TRIMA'] = ta.TRIMA(np.array(dataset['Adj Close']), timeperiod=30)

    #Create WMA - Weighted Moving Average
    dataset['WMA'] = ta.WMA(np.array(dataset['Adj Close']), timeperiod=30)

    #PART IV Momentum Indicators
    #Create ADX - Average Directional Movement Index
    dataset['ADX14'] = ta.ADX(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)
    dataset['ADX20'] = ta.ADX(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=20)

    #Create ADXR - Average Directional Movement Index Rating
    dataset['ADXR'] = ta.ADXR(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)

    #Create APO - Absolute Price Oscillator
    dataset['APO'] = ta.APO(np.array(dataset['Adj Close']),
                            fastperiod=12,
                            slowperiod=26,
                            matype=0)

    #Create AROONOSC - Aroon Oscillator
    dataset['AROONOSC'] = ta.AROONOSC(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      timeperiod=14)

    #Create BOP - Balance Of Power
    dataset['BOP'] = ta.BOP(np.array(dataset['Open']),
                            np.array(dataset['High']),
                            np.array(dataset['Low']),
                            np.array(dataset['Adj Close']))

    #Create CCI - Commodity Channel Index
    dataset['CCI3'] = ta.CCI(np.array(dataset['High']),
                             np.array(dataset['Low']),
                             np.array(dataset['Adj Close']),
                             timeperiod=3)
    dataset['CCI5'] = ta.CCI(np.array(dataset['High']),
                             np.array(dataset['Low']),
                             np.array(dataset['Adj Close']),
                             timeperiod=5)
    dataset['CCI10'] = ta.CCI(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=10)
    dataset['CCI14'] = ta.CCI(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)

    #Create CMO - Chande Momentum Oscillator
    dataset['CMO'] = ta.CMO(np.array(dataset['Adj Close']), timeperiod=14)

    #Create DX - Directional Movement Index
    dataset['DX'] = ta.DX(np.array(dataset['High']),
                          np.array(dataset['Low']),
                          np.array(dataset['Adj Close']),
                          timeperiod=14)

    #Create MINUS_DI - Minus Directional Indicator
    dataset['MINUS_DI'] = ta.MINUS_DI(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      np.array(dataset['Adj Close']),
                                      timeperiod=14)

    #Create MINUS_DM - Minus Directional Movement
    dataset['MINUS_DM'] = ta.MINUS_DM(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      timeperiod=14)

    #Create MOM - Momentum
    dataset['MOM3'] = ta.MOM(np.array(dataset['Adj Close']), timeperiod=3)
    dataset['MOM5'] = ta.MOM(np.array(dataset['Adj Close']), timeperiod=5)
    dataset['MOM10'] = ta.MOM(np.array(dataset['Adj Close']), timeperiod=10)

    #Create PLUS_DI - Plus Directional Indicator
    dataset['PLUS_DI'] = ta.PLUS_DI(np.array(dataset['High']),
                                    np.array(dataset['Low']),
                                    np.array(dataset['Adj Close']),
                                    timeperiod=14)

    #Create PLUS_DM - Plus Directional Movement
    dataset['PLUS_DM'] = ta.PLUS_DM(np.array(dataset['High']),
                                    np.array(dataset['Low']),
                                    timeperiod=14)

    #Create PPO - Percentage Price Oscillator
    dataset['PPO'] = ta.PPO(np.array(dataset['Adj Close']),
                            fastperiod=12,
                            slowperiod=26,
                            matype=0)

    #Create ROC - Rate of change : ((price/prevPrice)-1)*100
    dataset['ROC'] = ta.ROC(np.array(dataset['Adj Close']), timeperiod=10)

    #Create ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice
    dataset['ROCP'] = ta.ROCP(np.array(dataset['Adj Close']), timeperiod=10)

    #Create ROCR - Rate of change ratio: (price/prevPrice)
    dataset['ROCR'] = ta.ROCR(np.array(dataset['Adj Close']), timeperiod=10)

    #Create ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    dataset['ROCR100'] = ta.ROCR100(np.array(dataset['Adj Close']),
                                    timeperiod=10)

    #Create RSI - Relative Strength Index
    dataset['RSI5'] = ta.RSI(np.array(dataset['Adj Close']), timeperiod=5)
    dataset['RSI10'] = ta.RSI(np.array(dataset['Adj Close']), timeperiod=10)
    dataset['RSI14'] = ta.RSI(np.array(dataset['Adj Close']), timeperiod=14)

    #Create TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    dataset['TRIX'] = ta.TRIX(np.array(dataset['Adj Close']), timeperiod=30)

    #Create ULTOSC - Ultimate Oscillator
    dataset['ULTOSC'] = ta.ULTOSC(np.array(dataset['High']),
                                  np.array(dataset['Low']),
                                  np.array(dataset['Adj Close']),
                                  timeperiod1=7,
                                  timeperiod2=14,
                                  timeperiod3=28)

    #Create WILLR - Williams' %R
    dataset['WILLR'] = ta.WILLR(np.array(dataset['High']),
                                np.array(dataset['Low']),
                                np.array(dataset['Adj Close']),
                                timeperiod=14)

    #Part V Pattern Recognition
    #Create  CDL2CROWS - Two Crows
    dataset['CDL2CROWS'] = ta.CDL2CROWS(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDL3BLACKCROWS - Three Black Crows
    dataset['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDL3INSIDE - Three Inside Up/Down
    dataset['CDL3INSIDE'] = ta.CDL3INSIDE(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDL3LINESTRIKE - Three-Line Strike
    dataset['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDL3OUTSIDE - Three Outside Up/Down
    dataset['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDL3STARSINSOUTH - Three Stars In The South
    dataset['CDL3STARSINSOUTH '] = ta.CDL3STARSINSOUTH(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDL3WHITESOLDIERS - Three Advancing White Soldiers
    dataset['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLABANDONEDBABY - Abandoned Baby
    dataset['CDLABANDONEDBABY'] = ta.CDLABANDONEDBABY(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLADVANCEBLOCK - Advance Block
    dataset['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLBELTHOLD - Belt-hold
    dataset['CDLBELTHOLD'] = ta.CDLBELTHOLD(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLBREAKAWAY - Breakaway
    dataset['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLCLOSINGMARUBOZU - Closing Marubozu
    dataset['CDLCLOSINGMARUBOZU'] = ta.CDLCLOSINGMARUBOZU(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLCONCEALBABYSWALL - Concealing Baby Swalnp.array(dataset['Low'])
    dataset['CDLCONCEALBABYSWALL'] = ta.CDLCONCEALBABYSWALL(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLCOUNTERATTACK - Counterattack
    dataset['CDLCOUNTERATTACK'] = ta.CDLCOUNTERATTACK(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLDARKCLOUDCOVER - Dark Cloud Cover
    dataset['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLDOJI - Doji
    dataset['CDLDOJI'] = ta.CDLDOJI(np.array(dataset['Open']),
                                    np.array(dataset['High']),
                                    np.array(dataset['Low']),
                                    np.array(dataset['Adj Close']))

    #Create CDLDOJISTAR - Doji Star
    dataset['CDLDOJISTAR'] = ta.CDLDOJISTAR(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLDRAGONFLYDOJI - Dragonfly Doji
    dataset['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLENGULFING - Engulfing Pattern
    dataset['CDLENGULFING'] = ta.CDLENGULFING(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLEVENINGDOJISTAR - Evening Doji Star
    dataset['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLEVENINGSTAR - Evening Star
    dataset['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(np.array(dataset['Open']),
                                                  np.array(dataset['High']),
                                                  np.array(dataset['Low']),
                                                  np.array(
                                                      dataset['Adj Close']),
                                                  penetration=0)

    #Create CDLGAPSIDESIDEWHITE - Up/Down-gap side-by-side white lines
    dataset['CDLGAPSIDESIDEWHITE'] = ta.CDLGAPSIDESIDEWHITE(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLGRAVESTONEDOJI - Gravestone Doji
    dataset['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLHAMMER - Hammer
    dataset['CDLHAMMER'] = ta.CDLHAMMER(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLHANGINGMAN - Hanging Man
    dataset['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(np.array(dataset['Open']),
                                                np.array(dataset['High']),
                                                np.array(dataset['Low']),
                                                np.array(dataset['Adj Close']))

    #Create CDLHARAMI - Harami Pattern
    dataset['CDLHARAMI'] = ta.CDLHARAMI(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLHARAMICROSS - Harami Cross Pattern
    dataset['CDLHARAMICROSS'] = ta.CDLHARAMICROSS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLHIGHWAVE - High-Wave Candle
    dataset['CDLHIGHWAVE'] = ta.CDLHIGHWAVE(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLHIKKAKE - Hikkake Pattern
    dataset['CDLHIKKAKE'] = ta.CDLHIKKAKE(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDLHIKKAKEMOD - Modified Hikkake Pattern
    dataset['CDLHIKKAKEMOD'] = ta.CDLHIKKAKEMOD(np.array(dataset['Open']),
                                                np.array(dataset['High']),
                                                np.array(dataset['Low']),
                                                np.array(dataset['Adj Close']))

    #Create CDLHOMINGPIGEON - Homing Pigeon
    dataset['CDLHOMINGPIGEON'] = ta.CDLHOMINGPIGEON(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLIDENTICAL3CROWS - Identical Three Crows
    dataset['CDLIDENTICAL3CROWS'] = ta.CDLIDENTICAL3CROWS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLINNECK - In-Neck Pattern
    dataset['CDLINNECK'] = ta.CDLINNECK(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLINVERTEDHAMMER - Inverted Hammer
    dataset['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLKICKING - Kicking
    dataset['CDLKICKING'] = ta.CDLKICKING(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDLKICKINGBYLENGTH - Kicking - bull/bear determined by the longer marubozu
    dataset['CDLKICKINGBYLENGTH'] = ta.CDLKICKINGBYLENGTH(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLLADDERBOTTOM - Ladder Bottom
    dataset['CDLLADDERBOTTOM'] = ta.CDLLADDERBOTTOM(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLLONGLEGGEDDOJI - Long Legged Doji
    dataset['CDLLONGLEGGEDDOJI'] = ta.CDLLONGLEGGEDDOJI(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLLONGLINE - Long Line Candle
    dataset['CDLLONGLINE'] = ta.CDLLONGLINE(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLMARUBOZU - Marubozu
    dataset['CDLMARUBOZU'] = ta.CDLMARUBOZU(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLMATCHINGLOW - Matching Low
    dataset['CDLMATCHINGLOW'] = ta.CDLMATCHINGLOW(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLMATHOLD - Mat Hold
    dataset['CDLMATHOLD'] = ta.CDLMATHOLD(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']),
                                          penetration=0)

    #Create CDLMORNINGDOJISTAR - Morning Doji Star
    dataset['CDLMORNINGDOJISTAR'] = ta.CDLMORNINGDOJISTAR(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLMORNINGSTAR - Morning Star
    dataset['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(np.array(dataset['Open']),
                                                  np.array(dataset['High']),
                                                  np.array(dataset['Low']),
                                                  np.array(
                                                      dataset['Adj Close']),
                                                  penetration=0)

    #Create CDLONNECK - On-Neck Pattern
    dataset['CDLONNECK'] = ta.CDLONNECK(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLPIERCING - Piercing Pattern
    dataset['CDLPIERCING'] = ta.CDLPIERCING(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLRICKSHAWMAN - Rickshaw Man
    dataset['CDLRICKSHAWMAN'] = ta.CDLRICKSHAWMAN(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLRISEFALL3METHODS - Rising/Falling Three Methods
    dataset['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSEPARATINGLINES - Separating Lines
    dataset['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSHOOTINGSTAR - Shooting Star
    dataset['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSHORTLINE - Short Line Candle
    dataset['CDLSHORTLINE'] = ta.CDLSHORTLINE(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLSPINNINGTOP - Spinning Top
    dataset['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSTALLEDPATTERN - Stalled Pattern
    dataset['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSTICKSANDWICH - Stick Sandwich
    dataset['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLTAKURI - Takuri (Dragonfly Doji with very long np.array(dataset['Low'])er shadow)
    dataset['CDLTAKURI'] = ta.CDLTAKURI(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLTASUKIGAP - Tasuki Gap
    dataset['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLTHRUSTING - Thrusting Pattern
    dataset['CDLTHRUSTING'] = ta.CDLTHRUSTING(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLTRISTAR - Tristar Pattern
    dataset['CDLTRISTAR'] = ta.CDLTRISTAR(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDLUNIQUE3RIVER - Unique 3 River
    dataset['CDLUNIQUE3RIVER'] = ta.CDLUNIQUE3RIVER(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLUPSIDEGAP2CROWS - Upside Gap Two Crows
    dataset['CDLUPSIDEGAP2CROWS'] = ta.CDLUPSIDEGAP2CROWS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLXSIDEGAP3METHODS - Upside/Downside Gap Three Methods
    dataset['CDLXSIDEGAP3METHODS'] = ta.CDLXSIDEGAP3METHODS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    return dataset
def _extract_feature(candle, params, candle_type, target_dt):
    '''
    前に余分に必要なデータ量: {(stockf_fastk_period_l + stockf_fastk_period_l) * 最大分足 (min)} + window_size
    = (12 + 12) * 5 + 5 = 125 (min)
    '''
    o = candle.open
    h = candle.high
    l = candle.low
    c = candle.close
    v = candle.volume

    # OHLCV
    features = pd.DataFrame()
    features['open'] = o
    features['high'] = h
    features['low'] = l
    features['close'] = c
    features['volume'] = v

    ####################################
    #
    # Momentum Indicator Functions
    #
    ####################################

    # ADX = SUM((+DI - (-DI)) / (+DI + (-DI)), N) / N
    # N — 計算期間
    # SUM (..., N) — N期間の合計
    # +DI — プラスの価格変動の値(positive directional index)
    # -DI — マイナスの価格変動の値(negative directional index)
    # rsi_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要

    features['adx_s'] = ta.ADX(h, l, c, timeperiod=params['adx_timeperiod_s'])
    features['adx_m'] = ta.ADX(h, l, c, timeperiod=params['adx_timeperiod_m'])
    features['adx_l'] = ta.ADX(h, l, c, timeperiod=params['adx_timeperiod_l'])

    features['adxr_s'] = ta.ADXR(h, l, c, timeperiod=params['adxr_timeperiod_s'])
    features['adxr_m'] = ta.ADXR(h, l, c, timeperiod=params['adxr_timeperiod_m'])
    features['adxr_l'] = ta.ADXR(h, l, c, timeperiod=params['adxr_timeperiod_l'])

    # APO = Shorter Period EMA – Longer Period EMA
    features['apo_s'] = ta.APO(c, fastperiod=params['apo_fastperiod_s'], slowperiod=params['apo_slowperiod_s'], matype=ta.MA_Type.EMA)
    features['apo_m'] = ta.APO(c, fastperiod=params['apo_fastperiod_m'], slowperiod=params['apo_slowperiod_m'], matype=ta.MA_Type.EMA)

    # AroonUp = (N - 過去N日間の最高値からの経過期間) ÷ N × 100
    # AroonDown = (N - 過去N日間の最安値からの経過期間) ÷ N × 100
    # aroon_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要
    #features['aroondown_s'], features['aroonup_s'] = ta.AROON(h, l, timeperiod=params['aroon_timeperiod_s'])
    #features['aroondown_m'], features['aroonup_m'] = ta.AROON(h, l, timeperiod=params['aroon_timeperiod_m'])
    #features['aroondown_l'], features['aroonup_l'] = ta.AROON(h, l, timeperiod=params['aroon_timeperiod_l'])

    # Aronnオシレーター = AroonUp - AroonDown
    # aroonosc_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要
    features['aroonosc_s'] = ta.AROONOSC(h, l, timeperiod=params['aroonosc_timeperiod_s'])
    features['aroonosc_m'] = ta.AROONOSC(h, l, timeperiod=params['aroonosc_timeperiod_m'])
    features['aroonosc_l'] = ta.AROONOSC(h, l, timeperiod=params['aroonosc_timeperiod_l'])

    # BOP = (close - open) / (high - low)
    features['bop'] = ta.BOP(o, h, l, c)

    # CCI = (TP - MA) / (0.015 * MD)
    # TP: (高値+安値+終値) / 3
    # MA: TPの移動平均
    # MD: 平均偏差 = ((MA - TP1) + (MA - TP2) + ...) / N
    features['cci_s'] = ta.CCI(h, l, c, timeperiod=params['cci_timeperiod_s'])
    features['cci_m'] = ta.CCI(h, l, c, timeperiod=params['cci_timeperiod_m'])
    features['cci_l'] = ta.CCI(h, l, c, timeperiod=params['cci_timeperiod_l'])

    # CMO - Chande Momentum Oscillator
    #features['cmo_s'] = ta.CMO(c, timeperiod=params['cmo_timeperiod_s'])
    #features['cmo_m'] = ta.CMO(c, timeperiod=params['cmo_timeperiod_m'])
    #features['cmo_l'] = ta.CMO(c, timeperiod=params['cmo_timeperiod_l'])

    # DX - Directional Movement Index
    features['dx_s'] = ta.DX(h, l, c, timeperiod=params['dx_timeperiod_s'])
    features['dx_m'] = ta.DX(h, l, c, timeperiod=params['dx_timeperiod_m'])
    features['dx_l'] = ta.DX(h, l, c, timeperiod=params['dx_timeperiod_l'])

    # MACD=基準線-相対線
    # 基準線(EMA):過去12日(週・月)間の終値指数平滑平均
    # 相対線(EMA):過去26日(週・月)間の終値指数平滑平均
    # https://www.sevendata.co.jp/shihyou/technical/macd.html
    # macd_slowperiod_m = 30 の場合30分足で((30 + macd_signalperiod_m) * 30)/ 60 = 16.5時間必要(macd_signalperiod_m=3の時)
    macd, macdsignal, macdhist = ta.MACDEXT(c, fastperiod=params['macd_fastperiod_s'],
                                            slowperiod=params['macd_slowperiod_s'],
                                            signalperiod=params['macd_signalperiod_s'],
                                            fastmatype=ta.MA_Type.EMA, slowmatype=ta.MA_Type.EMA,
                                            signalmatype=ta.MA_Type.EMA)
    change_macd = calc_change(macd, macdsignal)
    change_macd.index = macd.index
    features['macd_s'] = macd
    features['macdsignal_s'] = macdsignal
    features['macdhist_s'] = macdhist
    features['change_macd_s'] = change_macd
    macd, macdsignal, macdhist = ta.MACDEXT(c, fastperiod=params['macd_fastperiod_m'],
                                            slowperiod=params['macd_slowperiod_m'],
                                            signalperiod=params['macd_signalperiod_m'],
                                            fastmatype=ta.MA_Type.EMA, slowmatype=ta.MA_Type.EMA,
                                            signalmatype=ta.MA_Type.EMA)
    change_macd = calc_change(macd, macdsignal)
    change_macd.index = macd.index
    features['macd_m'] = macd
    features['macdsignal_m'] = macdsignal
    features['macdhist_m'] = macdhist
    features['change_macd_m'] = change_macd

    # MFI - Money Flow Index
    features['mfi_s'] = ta.MFI(h, l, c, v, timeperiod=params['mfi_timeperiod_s'])
    features['mfi_m'] = ta.MFI(h, l, c, v, timeperiod=params['mfi_timeperiod_m'])
    features['mfi_l'] = ta.MFI(h, l, c, v, timeperiod=params['mfi_timeperiod_l'])

    # MINUS_DI - Minus Directional Indicator
    features['minus_di_s'] = ta.MINUS_DI(h, l, c, timeperiod=params['minus_di_timeperiod_s'])
    features['minus_di_m'] = ta.MINUS_DI(h, l, c, timeperiod=params['minus_di_timeperiod_m'])
    features['minus_di_l'] = ta.MINUS_DI(h, l, c, timeperiod=params['minus_di_timeperiod_l'])

    # MINUS_DM - Minus Directional Movement
    features['minus_dm_s'] = ta.MINUS_DM(h, l, timeperiod=params['minus_dm_timeperiod_s'])
    features['minus_dm_m'] = ta.MINUS_DM(h, l, timeperiod=params['minus_dm_timeperiod_m'])
    features['minus_dm_l'] = ta.MINUS_DM(h, l, timeperiod=params['minus_dm_timeperiod_l'])

    # MOM - Momentum
    features['mom_s'] = ta.MOM(c, timeperiod=params['mom_timeperiod_s'])
    features['mom_m'] = ta.MOM(c, timeperiod=params['mom_timeperiod_m'])
    features['mom_l'] = ta.MOM(c, timeperiod=params['mom_timeperiod_l'])

    # PLUS_DI - Minus Directional Indicator
    features['plus_di_s'] = ta.PLUS_DI(h, l, c, timeperiod=params['plus_di_timeperiod_s'])
    features['plus_di_m'] = ta.PLUS_DI(h, l, c, timeperiod=params['plus_di_timeperiod_m'])
    features['plus_di_l'] = ta.PLUS_DI(h, l, c, timeperiod=params['plus_di_timeperiod_l'])

    # PLUS_DM - Minus Directional Movement
    features['plus_dm_s'] = ta.PLUS_DM(h, l, timeperiod=params['plus_dm_timeperiod_s'])
    features['plus_dm_m'] = ta.PLUS_DM(h, l, timeperiod=params['plus_dm_timeperiod_m'])
    features['plus_dm_l'] = ta.PLUS_DM(h, l, timeperiod=params['plus_dm_timeperiod_l'])

    # PPO - Percentage Price Oscillator
    #features['ppo_s'] = ta.PPO(c, fastperiod=params['ppo_fastperiod_s'], slowperiod=params['ppo_slowperiod_s'], matype=ta.MA_Type.EMA)
    #features['ppo_m'] = ta.PPO(c, fastperiod=params['ppo_fastperiod_m'], slowperiod=params['ppo_slowperiod_m'], matype=ta.MA_Type.EMA)

    # ROC - Rate of change : ((price/prevPrice)-1)*100
    features['roc_s'] = ta.ROC(c, timeperiod=params['roc_timeperiod_s'])
    features['roc_m'] = ta.ROC(c, timeperiod=params['roc_timeperiod_m'])
    features['roc_l'] = ta.ROC(c, timeperiod=params['roc_timeperiod_l'])

    # ROCP = (price-prevPrice) / prevPrice
    # http://www.tadoc.org/indicator/ROCP.htm
    # rocp_timeperiod_l = 30 の場合、30分足で(30 * 30) / 60 = 15時間必要
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_s'])
    change_rocp = calc_change(rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_s'] = rocp
    features['change_rocp_s'] = change_rocp
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_m'])
    change_rocp = calc_change(rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_m'] = rocp
    features['change_rocp_m'] = change_rocp
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_l'])
    change_rocp = calc_change(rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_l'] = rocp
    features['change_rocp_l'] = change_rocp

    # ROCR - Rate of change ratio: (price/prevPrice)
    features['rocr_s'] = ta.ROCR(c, timeperiod=params['rocr_timeperiod_s'])
    features['rocr_m'] = ta.ROCR(c, timeperiod=params['rocr_timeperiod_m'])
    features['rocr_l'] = ta.ROCR(c, timeperiod=params['rocr_timeperiod_l'])

    # ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    features['rocr100_s'] = ta.ROCR100(c, timeperiod=params['rocr100_timeperiod_s'])
    features['rocr100_m'] = ta.ROCR100(c, timeperiod=params['rocr100_timeperiod_m'])
    features['rocr100_l'] = ta.ROCR100(c, timeperiod=params['rocr100_timeperiod_l'])

    # RSI = (100 * a) / (a + b) (a: x日間の値上がり幅の合計, b: x日間の値下がり幅の合計)
    # https://www.sevendata.co.jp/shihyou/technical/rsi.html
    # rsi_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要
    #features['rsi_s'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_s'])
    #features['rsi_m'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_m'])
    #features['rsi_l'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_l'])


    # FASTK(KPeriod) = 100 * (Today's Close - LowestLow) / (HighestHigh - LowestLow)
    # FASTD(FastDperiod) = MA Smoothed FASTK over FastDperiod
    # http://www.tadoc.org/indicator/STOCHF.htm
    # stockf_fastk_period_l=30の場合30分足で、(((30 + 30) * 30) / 60(min)) = 30時間必要 (LowestLowが移動平均の30分余分に必要なので60period余分に計算する)
    fastk, fastd = ta.STOCHF(h, l, c, fastk_period=params['stockf_fastk_period_s'], fastd_period=params['stockf_fastd_period_s'], fastd_matype=ta.MA_Type.EMA)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_s'] = fastk
    features['fastd_s'] = fastd
    features['fast_change_s'] = change_stockf
    fastk, fastd = ta.STOCHF(h, l, c, fastk_period=params['stockf_fastk_period_m'], fastd_period=params['stockf_fastd_period_m'], fastd_matype=ta.MA_Type.EMA)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_m'] = fastk
    features['fastd_m'] = fastd
    features['fast_change_m'] = change_stockf
    fastk, fastd = ta.STOCHF(h, l, c, fastk_period=params['stockf_fastk_period_l'], fastd_period=params['stockf_fastk_period_l'], fastd_matype=ta.MA_Type.EMA)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_l'] = fastk
    features['fastd_l'] = fastd
    features['fast_change_l'] = change_stockf

    # TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    features['trix_s'] = ta.TRIX(c, timeperiod=params['trix_timeperiod_s'])
    features['trix_m'] = ta.TRIX(c, timeperiod=params['trix_timeperiod_m'])
    features['trix_l'] = ta.TRIX(c, timeperiod=params['trix_timeperiod_l'])

    # ULTOSC - Ultimate Oscillator
    features['ultosc_s'] = ta.ULTOSC(h, l, c, timeperiod1=params['ultosc_timeperiod_s1'], timeperiod2=params['ultosc_timeperiod_s2'], timeperiod3=params['ultosc_timeperiod_s3'])

    # WILLR = (当日終値 - N日間の最高値) / (N日間の最高値 - N日間の最安値)× 100
    # https://inet-sec.co.jp/study/technical-manual/williamsr/
    # willr_timeperiod_l=30の場合30分足で、(30 * 30 / 60) = 15時間必要
    features['willr_s'] = ta.WILLR(h, l, c, timeperiod=params['willr_timeperiod_s'])
    features['willr_m'] = ta.WILLR(h, l, c, timeperiod=params['willr_timeperiod_m'])
    features['willr_l'] = ta.WILLR(h, l, c, timeperiod=params['willr_timeperiod_l'])

    ####################################
    #
    # Volume Indicator Functions
    #
    ####################################

    # Volume Indicator Functions
    # slowperiod_adosc_s = 10の場合、30分足で(10 * 30) / 60 = 5時間必要
    features['ad'] = ta.AD(h, l, c, v)
    features['adosc_s'] = ta.ADOSC(h, l, c, v, fastperiod=params['fastperiod_adosc_s'], slowperiod=params['slowperiod_adosc_s'])
    features['obv'] = ta.OBV(c, v)

    ####################################
    #
    # Volatility Indicator Functions
    #
    ####################################

    # ATR - Average True Range
    features['atr_s'] = ta.ATR(h, l, c, timeperiod=params['atr_timeperiod_s'])
    features['atr_m'] = ta.ATR(h, l, c, timeperiod=params['atr_timeperiod_m'])
    features['atr_l'] = ta.ATR(h, l, c, timeperiod=params['atr_timeperiod_l'])

    # NATR - Normalized Average True Range
    #features['natr_s'] = ta.NATR(h, l, c, timeperiod=params['natr_timeperiod_s'])
    #features['natr_m'] = ta.NATR(h, l, c, timeperiod=params['natr_timeperiod_m'])
    #features['natr_l'] = ta.NATR(h, l, c, timeperiod=params['natr_timeperiod_l'])

    # TRANGE - True Range
    features['trange'] = ta.TRANGE(h, l, c)

    ####################################
    #
    # Price Transform Functions
    #
    ####################################

    features['avgprice'] = ta.AVGPRICE(o, h, l, c)
    features['medprice'] = ta.MEDPRICE(h, l)
    #features['typprice'] = ta.TYPPRICE(h, l, c)
    #features['wclprice'] = ta.WCLPRICE(h, l, c)

    ####################################
    #
    # Cycle Indicator Functions
    #
    ####################################

    #features['ht_dcperiod'] = ta.HT_DCPERIOD(c)
    #features['ht_dcphase'] = ta.HT_DCPHASE(c)
    #features['inphase'], features['quadrature'] = ta.HT_PHASOR(c)
    #features['sine'], features['leadsine'] = ta.HT_SINE(c)
    features['integer'] = ta.HT_TRENDMODE(c)

    ####################################
    #
    # Statistic Functions
    #
    ####################################

    # BETA - Beta

    features['beta_s'] = ta.BETA(h, l, timeperiod=params['beta_timeperiod_s'])
    features['beta_m'] = ta.BETA(h, l, timeperiod=params['beta_timeperiod_m'])
    features['beta_l'] = ta.BETA(h, l, timeperiod=params['beta_timeperiod_l'])

    # CORREL - Pearson's Correlation Coefficient (r)
    #features['correl_s'] = ta.CORREL(h, l, timeperiod=params['correl_timeperiod_s'])
    #features['correl_m'] = ta.CORREL(h, l, timeperiod=params['correl_timeperiod_m'])
    #features['correl_l'] = ta.CORREL(h, l, timeperiod=params['correl_timeperiod_l'])

    # LINEARREG - Linear Regression
    #features['linearreg_s'] = ta.LINEARREG(c, timeperiod=params['linearreg_timeperiod_s'])
    #features['linearreg_m'] = ta.LINEARREG(c, timeperiod=params['linearreg_timeperiod_m'])
    #features['linearreg_l'] = ta.LINEARREG(c, timeperiod=params['linearreg_timeperiod_l'])

    # LINEARREG_ANGLE - Linear Regression Angle
    features['linearreg_angle_s'] = ta.LINEARREG_ANGLE(c, timeperiod=params['linearreg_angle_timeperiod_s'])
    features['linearreg_angle_m'] = ta.LINEARREG_ANGLE(c, timeperiod=params['linearreg_angle_timeperiod_m'])
    features['linearreg_angle_l'] = ta.LINEARREG_ANGLE(c, timeperiod=params['linearreg_angle_timeperiod_l'])

    # LINEARREG_INTERCEPT - Linear Regression Intercept
    features['linearreg_intercept_s'] = ta.LINEARREG_INTERCEPT(c, timeperiod=params['linearreg_intercept_timeperiod_s'])
    features['linearreg_intercept_m'] = ta.LINEARREG_INTERCEPT(c, timeperiod=params['linearreg_intercept_timeperiod_m'])
    features['linearreg_intercept_l'] = ta.LINEARREG_INTERCEPT(c, timeperiod=params['linearreg_intercept_timeperiod_l'])

    # LINEARREG_SLOPE - Linear Regression Slope
    features['linearreg_slope_s'] = ta.LINEARREG_SLOPE(c, timeperiod=params['linearreg_slope_timeperiod_s'])
    features['linearreg_slope_m'] = ta.LINEARREG_SLOPE(c, timeperiod=params['linearreg_slope_timeperiod_m'])
    features['linearreg_slope_l'] = ta.LINEARREG_SLOPE(c, timeperiod=params['linearreg_slope_timeperiod_l'])

    # STDDEV - Standard Deviation
    features['stddev_s'] = ta.STDDEV(c, timeperiod=params['stddev_timeperiod_s'], nbdev=1)
    features['stddev_m'] = ta.STDDEV(c, timeperiod=params['stddev_timeperiod_m'], nbdev=1)
    features['stddev_l'] = ta.STDDEV(c, timeperiod=params['stddev_timeperiod_l'], nbdev=1)

    # TSF - Time Series Forecast
    features['tsf_s'] = ta.TSF(c, timeperiod=params['tsf_timeperiod_s'])
    features['tsf_m'] = ta.TSF(c, timeperiod=params['tsf_timeperiod_m'])
    features['tsf_l'] = ta.TSF(c, timeperiod=params['tsf_timeperiod_l'])

    # VAR - Variance
    #features['var_s'] = ta.VAR(c, timeperiod=params['var_timeperiod_s'], nbdev=1)
    #features['var_m'] = ta.VAR(c, timeperiod=params['var_timeperiod_m'], nbdev=1)
    #features['var_l'] = ta.VAR(c, timeperiod=params['var_timeperiod_l'], nbdev=1)

    # ボリンジャーバンド
    # bbands_timeperiod_l = 30の場合、30分足で(30 * 30) / 60 = 15時間必要
    bb_upper, bb_middle, bb_lower = ta.BBANDS(c, timeperiod=params['bbands_timeperiod_s'],
                                              nbdevup=params['bbands_nbdevup_s'], nbdevdn=params['bbands_nbdevdn_s'],
                                              matype=ta.MA_Type.EMA)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_s'] = bb_upper
    features['bb_middle_s'] = bb_middle
    features['bb_lower_s'] = bb_lower
    features['bb_trend1_s'] = bb_trend1
    features['bb_trend2_s'] = bb_trend2
    bb_upper, bb_middle, bb_lower = ta.BBANDS(c, timeperiod=params['bbands_timeperiod_m'],
                                              nbdevup=params['bbands_nbdevup_m'], nbdevdn=params['bbands_nbdevdn_m'],
                                              matype=ta.MA_Type.EMA)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_m'] = bb_upper
    features['bb_middle_m'] = bb_middle
    features['bb_lower_m'] = bb_lower
    features['bb_trend1_m'] = bb_trend1
    features['bb_trend2_m'] = bb_trend2
    bb_upper, bb_middle, bb_lower = ta.BBANDS(c, timeperiod=params['bbands_timeperiod_l'],
                                              nbdevup=params['bbands_nbdevup_l'], nbdevdn=params['bbands_nbdevdn_l'],
                                              matype=ta.MA_Type.EMA)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_l'] = bb_upper
    features['bb_middle_l'] = bb_middle
    features['bb_lower_l'] = bb_lower
    features['bb_trend1_l'] = bb_trend1
    features['bb_trend2_l'] = bb_trend2

    # ローソク足
    features['CDL2CROWS'] = ta.CDL2CROWS(o, h, l, c)
    features['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(o, h, l, c)
    features['CDL3INSIDE'] = ta.CDL3INSIDE(o, h, l, c)
    features['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(o, h, l, c)
    features['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(o, h, l, c)
    features['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(o, h, l, c)
    features['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(o, h, l, c)
    features['CDLABANDONEDBABY'] = ta.CDLABANDONEDBABY(o, h, l, c, penetration=0)
    features['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(o, h, l, c)
    features['CDLBELTHOLD'] = ta.CDLBELTHOLD(o, h, l, c)
    features['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(o, h, l, c)
    features['CDLCLOSINGMARUBOZU'] = ta.CDLCLOSINGMARUBOZU(o, h, l, c)
    features['CDLCONCEALBABYSWALL'] = ta.CDLCONCEALBABYSWALL(o, h, l, c)
    features['CDLCOUNTERATTACK'] = ta.CDLCOUNTERATTACK(o, h, l, c)
    features['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(o, h, l, c, penetration=0)
    #features['CDLDOJI'] = ta.CDLDOJI(o, h, l, c)
    features['CDLDOJISTAR'] = ta.CDLDOJISTAR(o, h, l, c)
    features['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(o, h, l, c)
    features['CDLENGULFING'] = ta.CDLENGULFING(o, h, l, c)
    features['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(o, h, l, c, penetration=0)
    features['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(o, h, l, c, penetration=0)
    #features['CDLGAPSIDESIDEWHITE'] = ta.CDLGAPSIDESIDEWHITE(o, h, l, c)
    features['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(o, h, l, c)
    features['CDLHAMMER'] = ta.CDLHAMMER(o, h, l, c)
    #features['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(o, h, l, c)
    features['CDLHARAMI'] = ta.CDLHARAMI(o, h, l, c)
    features['CDLHARAMICROSS'] = ta.CDLHARAMICROSS(o, h, l, c)
    features['CDLHIGHWAVE'] = ta.CDLHIGHWAVE(o, h, l, c)
    #features['CDLHIKKAKE'] = ta.CDLHIKKAKE(o, h, l, c)
    features['CDLHIKKAKEMOD'] = ta.CDLHIKKAKEMOD(o, h, l, c)
    features['CDLHOMINGPIGEON'] = ta.CDLHOMINGPIGEON(o, h, l, c)
    #features['CDLIDENTICAL3CROWS'] = ta.CDLIDENTICAL3CROWS(o, h, l, c)
    features['CDLINNECK'] = ta.CDLINNECK(o, h, l, c)
    #features['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(o, h, l, c)
    features['CDLKICKING'] = ta.CDLKICKING(o, h, l, c)
    features['CDLKICKINGBYLENGTH'] = ta.CDLKICKINGBYLENGTH(o, h, l, c)
    features['CDLLADDERBOTTOM'] = ta.CDLLADDERBOTTOM(o, h, l, c)
    #features['CDLLONGLEGGEDDOJI'] = ta.CDLLONGLEGGEDDOJI(o, h, l, c)
    features['CDLMARUBOZU'] = ta.CDLMARUBOZU(o, h, l, c)
    #features['CDLMATCHINGLOW'] = ta.CDLMATCHINGLOW(o, h, l, c)
    features['CDLMATHOLD'] = ta.CDLMATHOLD(o, h, l, c, penetration=0)
    features['CDLMORNINGDOJISTAR'] = ta.CDLMORNINGDOJISTAR(o, h, l, c, penetration=0)
    features['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(o, h, l, c, penetration=0)
    features['CDLONNECK'] = ta.CDLONNECK(o, h, l, c)
    features['CDLPIERCING'] = ta.CDLPIERCING(o, h, l, c)
    features['CDLRICKSHAWMAN'] = ta.CDLRICKSHAWMAN(o, h, l, c)
    features['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(o, h, l, c)
    features['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(o, h, l, c)
    #features['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(o, h, l, c)
    features['CDLSHORTLINE'] = ta.CDLSHORTLINE(o, h, l, c)
    #features['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(o, h, l, c)
    features['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(o, h, l, c)
    features['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(o, h, l, c)
    features['CDLTAKURI'] = ta.CDLTAKURI(o, h, l, c)
    features['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(o, h, l, c)
    features['CDLTHRUSTING'] = ta.CDLTHRUSTING(o, h, l, c)
    features['CDLTRISTAR'] = ta.CDLTRISTAR(o, h, l, c)
    features['CDLUNIQUE3RIVER'] = ta.CDLUNIQUE3RIVER(o, h, l, c)
    features['CDLUPSIDEGAP2CROWS'] = ta.CDLUPSIDEGAP2CROWS(o, h, l, c)
    features['CDLXSIDEGAP3METHODS'] = ta.CDLXSIDEGAP3METHODS(o, h, l, c)

    '''
    # トレンドライン
    for dt in datetimerange(candle.index[0], candle.index[-1] + timedelta(minutes=1)):
        start_dt = (dt - timedelta(minutes=130)).strftime('%Y-%m-%d %H:%M:%S')
        end_dt = dt.strftime('%Y-%m-%d %H:%M:%S')
        tmp = candle.loc[(start_dt <= candle.index) & (candle.index <= end_dt)]
        for w_size, stride in [(15, 5), (30, 10), (60, 10), (120, 10)]:
        # for w_size, stride in [(120, 10)]:
            trendlines = calc_trendlines(tmp, w_size, stride)
            if len(trendlines) == 0:
                continue
            trendline_feature = calc_trendline_feature(tmp, trendlines)

            print('{}-{} {} {} {}'.format(dt - timedelta(minutes=130), dt, trendline_feature['high_a'], trendline_feature['high_b'], trendline_feature['high_diff']))

            features.loc[features.index == end_dt, 'trendline_high_a_{}'.format(w_size)] = trendline_feature['high_a']
            features.loc[features.index == end_dt, 'trendline_high_b_{}'.format(w_size)] = trendline_feature['high_b']
            features.loc[features.index == end_dt, 'trendline_high_diff_{}'.format(w_size)] = trendline_feature['high_diff']
            features.loc[features.index == end_dt, 'trendline_low_a_{}'.format(w_size)] = trendline_feature['low_a']
            features.loc[features.index == end_dt, 'trendline_low_b_{}'.format(w_size)] = trendline_feature['low_b']
            features.loc[features.index == end_dt, 'trendline_low_diff_{}'.format(w_size)] = trendline_feature['low_diff']
    '''

    window = 5
    features_ext = features
    for w in range(window):
        tmp = features.shift(periods=60 * (w + 1), freq='S')
        tmp.columns = [c + '_' + str(w + 1) + 'w' for c in features.columns]
        features_ext = pd.concat([features_ext, tmp], axis=1)
    
    if candle_type == '5min':
        features_ext = features_ext.shift(periods=300, freq='S')
        features_ext = features_ext.fillna(method='ffill')
    features_ext = features_ext[features_ext.index == target_dt]
    return features_ext
Exemple #8
0
def main(df):
    opens = df['open'].values
    highs = df['high'].values
    lows = df['low'].values
    closes = df['close'].values
    volumes = df['volume'].values

    #Cycle Indicators': {{{
    df['ta_HT_DCPERIOD'] = talib.HT_DCPERIOD(closes)
    df['ta_HT_DCPHASE'] = talib.HT_DCPHASE(closes)
    #df['ta_HT_PHASOR'] = talib.HT_PHASOR(closes)
    #df['ta_HT_SINE'] =   talib.HT_SINE(closes)
    #df['ta_HT_TRENDMODE'] = talib.HT_TRENDLINE(closes)
    #}}}

    #'Momentum Indicators': {{{
    for i in [7, 10, 14, 28]:
        df['ta_ADX_%d' % i] = talib.ADX(highs, lows, closes, i)
        df['ta_ADXR_%d' % i] = talib.ADXR(highs, lows, closes, i)
    #for couple in [(6, 13), (12, 26), (24, 52)]:
    #    df['ta_APO_%d_%d' % (couple[0], couple[1])] = talib.APO(closes, couple[0], couple[1])
    #for i in range(7, 52):
    #    df['ta_AROON_%d' % i] = talib.AROON(highs, lows, i)
    #    df['ta_AROONOSC_%d' % i] = talib.AROONOSC(highs, lows, i)
    df['ta_BOP'] = talib.BOP(opens, highs, lows, closes)
    df['ta_CCI'] = talib.CCI(highs, lows, closes)
    for i in [7, 10, 14, 28]:
        df['ta_CMO_%d' % i] = talib.CMO(closes, i)
        #df['ta_DX_%d' %i] = talib.DX(closes, i)
    #for tri in [(6,13,8),(12, 26, 9), (24, 52, 18)]:
    #    macd = talib.MACD(closes, tri[0], tri[1], tri[2])
    #    #df['ta_MACD_macd_%d_%d_%d'%(tri[0],tri[1],tri[2])] = macd[0]
    #    #df['ta_MACD_macdsignal_%d_%d_%d'%(tri[0],tri[1],tri[2])] = macd[1]
    #    #df['ta_MACD_macdhist_%d_%d_%d'%(tri[0],tri[1],tri[2])] = macd[2]
    #
    #for i in range(6,18):
    #    macd = talib.MACDFIX(closes,i)
    #    df['ta_MACDFIX_macd_%d'% i]= macd[0]
    #    df['ta_MACDFIX_macdsignal_%d'% i]= macd[1]
    #    df['ta_MACDFIX_macdhist_%d'% i]= macd[2]
    for i in [7, 10, 14, 28]:
        df['ta_MFI_%d' % i] = talib.MFI(highs, lows, closes, volumes)
    for i in [7, 10, 14, 28]:
        df['ta_MINUS_DI_%d' % i] = talib.MINUS_DI(highs, lows, closes, i)
        df['ta_MINUS_DM_%d' % i] = talib.MINUS_DM(highs, lows, i)
        #df['ta_MOM_%d' % i]     = talib.MOM(closes, i)
        df['ta_PLUS_DI_%d' % i] = talib.PLUS_DI(highs, lows, closes, i)
        df['ta_PLUS_DM_%d' % i] = talib.PLUS_DM(highs, lows, i)
    for couple in [(6, 13), (12, 26)]:
        df['ta_PPO_%d_%d' % (couple[0], couple[1])] = talib.PPO(
            closes, couple[0], couple[1])
    for i in [2, 5, 7, 10, 14, 28]:
        df['ta_ROC_%d' % i] = talib.ROC(closes, i)
        df['ta_ROCP_%d' % i] = talib.ROCP(closes, i)
        df['ta_ROCR_%d' % i] = talib.ROCR(closes, i)
        df['ta_ROCR100_%d' % i] = talib.ROCR100(closes, i)
        df['ta_RSI_%d' % i] = talib.RSI(closes, i)
    for tri in [(5, 3, 3), (10, 6, 6), (20, 12, 12)]:
        stoch = talib.STOCH(highs,
                            lows,
                            closes,
                            fastk_period=tri[0],
                            slowk_period=tri[1],
                            slowd_period=tri[2])
        df['ta_STOCH_slowk_%d_%d_%d' % (tri[0], tri[1], tri[2])] = stoch[0]
        df['ta_STOCH_slowd_%d_%d_%d' % (tri[0], tri[1], tri[2])] = stoch[1]
    for i in [2, 5, 7, 10, 14, 28]:
        for c in [(5, 3), (10, 6), (20, 12)]:
            stochrsi = talib.STOCHRSI(closes, i, c[0], c[1])
            df['ta_STOCHRSI_slowk_%d_%d_%d' % (i, c[0], c[1])] = stochrsi[0]
            df['ta_STOCHRSI_slowd_%d_%d_%d' % (i, c[0], c[1])] = stochrsi[1]
    for i in [2, 5, 7, 10, 14, 28]:
        df['ta_TRIX_%d' % i] = talib.TRIX(closes, i)
    for tr in [(7, 14, 28)]:
        df['ta_ULTOSC_%d_%d_%d' % (tr[0], tr[1], tr[2])] = talib.ULTOSC(
            highs, lows, closes, tr[0], tr[1], tr[2])
    for i in [2, 5, 7, 10, 14, 28]:
        df['ta_WILLR_%d' % i] = talib.WILLR(highs, lows, closes, i)
    #}}}

    # 'Overlap Studies': {{{
    #for i in range(7,52):
    #df['ta_DEMA_%d'%i] = talib.DEMA(closes, i)
    #df['ta_EMA_%d'%i]  = talib.EMA(closes,i)
    #df['ta_HT_TRENDLINE'] = talib.HT_TRENDLINE(closes)
    #for i in range(7,52):
    #    df['ta_KAMA_%d'%i] = talib.KAMA(closes, i)
    #for c in [(2,30),(4,30),(4,50)]:
    #    df['ta_MAVP_%d_%d'%(c[0],c[1])] = talib.MAVP(closes, 14, c[0],c[1])
    #for i in range(7,52):
    #    df['ta_MIDPOINT_%d'%i] = talib.MIDPOINT(closes, i)
    #    df['ta_MIDPRICE_%d'%i] = talib.MIDPRICE(highs, lows,i)
    #df['ta_SAR'] = talib.SAR(highs,lows, 0.02, 0.2)
    #for i in range(7,52):
    #    df['ta_SMA_%d'%i] = talib.SMA(closes, i)
    #for i in range(2,21):
    #    df['ta_T3_%d'%i] = talib.T3(closes, i, 0.7)
    #for i in range(7,52):
    #    df['ta_TEMA_%d'%i] = talib.TEMA(closes, i)
    #    df['ta_TRIMA_%d'%i] = talib.TRIMA(closes, i)
    #    df['ta_WMA_%d'%i] = talib.WMA(closes, i)

    # 'Pattern Recognition': [
    #df = cdl(df)

    # 'Volatility Indicators': [
    for i in [7, 10, 14, 28]:
        #df['ta_ATR_%d'%i] = talib.ATR(highs, lows, closes, i)
        df['ta_NATR_%d' % i] = talib.NATR(highs, lows, closes, i)
    #df['ta_TRANGE'] = talib.TRANGE(highs, lows, closes)

    # 'Volume Indicators': [
    #df['ta_AD'] = talib.AD(highs, lows, closes, volumes)
    #for c in [(3,10), (6,20),(12,40)]:
    #    df['ta_ADOSC_%d_%d'%(c[0],c[1])] = talib.ADOSC(highs, lows, closes, volumes,c[0],c[1])
    #df['ta_OBV'] = talib.OBV(closes, volumes)
    return df
Exemple #9
0
    def techIndi(self, gubun):
        try:
            file = open("C:/Users/jini/PycharmProjects/stock/sql/sqlOra116Real.sql", 'r')
            sqlOra116 = ''
            line = file.readline()
            while line:
                sqlOra116 += ' ' + line.strip('\n').strip('\t')
                line = file.readline()

            file.close()

            summaryG = self.selectDB(sqlOra116)
        except Exception as e:
            e.msg = "techIndi Sql 에러"
            print(e)

        print("-----------------------------------------------------------------")
        print("["+ datetime.today().strftime("%Y-%m-%d %H:%M:%S") + "] " + "보조지표 만들기 시작!" )

        try:
            if len(summaryG) > 0:
                for row_data in summaryG:
                    print("[" + datetime.today().strftime("%Y-%m-%d %H:%M:%S") + "] " + "종목코드 : " + row_data[0])
                    try:
                        sql = "SELECT RN, STOCK_CODE, TRADE_TIME,  START_PRICE, HIGH_PRICE, LOW_PRICE, CURRENT_PRICE, VOLUME " \
                              "FROM ( " \
                              "       SELECT A.*, ROW_NUMBER() OVER(PARTITION BY A.STOCK_CODE ORDER BY TRADE_TIME DESC) RN" \
                              "                 , ROW_NUMBER() OVER(PARTITION BY A.STOCK_CODE ORDER BY TRADE_TIME ASC) RN2 " \
                              "                 , ROW_NUMBER() over (PARTITION BY A.STOCK_CODE, A.TRADE_TIME ORDER BY VOLUME DESC) RN3" \
                              "         FROM  TRADE_CRR_BACK A " \
                              "             , (SELECT DISTINCT YYYYMMDD, STOCK_CODE FROM TRADE_LIST WHERE YYYYMMDD BETWEEN '20201001' AND '20201231' UNION SELECT DISTINCT YYYYMMDD, STOCK_CODE FROM TRADE_LIST_TMP) B " \
                              "        WHERE 1=1 " \
                              "          AND A.STOCK_CODE = '%s' " \
                              "          AND A.STOCK_CODE = B.STOCK_CODE " \
                              "          AND A.STOCK_CODE NOT IN ('155960','900090') " \
                              "          AND A.TRADE_TIME >= '20200915' || '090000' " \
                              "          AND A.TRADE_TIME <= '20201231' || '160000' " \
                              "      ) X " \
                              "WHERE RN3 = 1 " % row_data[0]

                        sql2 = "ORDER BY RN2"

                        summaryGc = self.selectDB(sql + sql2)
                    except Exception as e:
                        print(e)

                    df = pd.DataFrame(summaryGc)

                    try:
                        if len(df) > 0:
                            df.columns = ["rn", "stockCd", "tradeTime", "open", "high", "low", "close", "volume"]

                            # cloF = pd.Series(df.iloc[len(df) - 1]['open'], name='close')  # 3분봉 종가 만들어주는 로직
                            # clo = pd.Series(df.iloc[1:len(df)]['open'], name='close')
                            # clo = pd.DataFrame(clo.append(cloF))
                            # clo = clo.reset_index(drop=True)
                            #
                            # df = df.join(clo)

                            macd, macdsignal, macdhist = talib.MACD(df['close'], fastperiod=12, slowperiod=26,
                                                                    signalperiod=9)
                            slowk, slowd = talib.STOCH(df['high'], df['low'], df['close'], fastk_period=5, slowk_period=3,
                                                       slowk_matype=3,
                                                       slowd_period=3, slowd_matype=0)
                            fastk, fastd = talib.STOCHF(df['high'], df['low'], df['close'], fastk_period=20,
                                                        fastd_period=10)
                            sma5 = talib.SMA(df['close'], 5)
                            sma10 = talib.SMA(df['close'], 10)
                            sma20 = talib.SMA(df['close'], 20)
                            sma60 = talib.SMA(df['close'], 60)
                            sma120 = talib.SMA(df['close'], 120)
                            cci = talib.CCI(df['high'], df['low'], df['close'], 20)
                            rsi = talib.RSI(df['close'], 14)
                            roc1 = talib.ROC(df['close'], 1)
                            roc5 = talib.ROC(df['close'], 5)
                            rocr1 = talib.ROCR(df['close'], 1)
                            rocr5 = talib.ROCR(df['close'], 5)

                            df = df.join(pd.DataFrame(pd.Series(macd, name="MACD")))
                            df = df.join(pd.DataFrame(pd.Series(macdsignal, name="MACDSIG")))
                            df = df.join(pd.DataFrame(pd.Series(slowd, name="SLOWD")))
                            df = df.join(pd.DataFrame(pd.Series(fastd, name="FASTD")))
                            df = df.join(pd.DataFrame(pd.Series(sma5, name="SMA5")))
                            df = df.join(pd.DataFrame(pd.Series(sma10, name="SMA10")))
                            df = df.join(pd.DataFrame(pd.Series(sma20, name="SMA20")))
                            df = df.join(pd.DataFrame(pd.Series(sma60, name="SMA60")))
                            df = df.join(pd.DataFrame(pd.Series(sma120, name="SMA120")))
                            df = df.join(pd.DataFrame(pd.Series(cci, name="CCI")))
                            df = df.join(pd.DataFrame(pd.Series(rsi, name="RSI")))
                            df = df.join(pd.DataFrame(pd.Series(roc1, name="ROC1")))
                            df = df.join(pd.DataFrame(pd.Series(roc5, name="ROC5")))
                            df = df.join(pd.DataFrame(pd.Series(rocr1, name="ROCR1")))
                            df = df.join(pd.DataFrame(pd.Series(rocr5, name="ROCR5")))

                            df = df.fillna(0)

                            try:
                                for i in range(4, len(df)):
                                    if df.iloc[i]['SMA5'] == 0:
                                        dis5 = 0
                                    else:
                                        dis5 = float(df.iloc[i]['close']) / float(df.iloc[i]['SMA5']) * 100

                                    if df.iloc[i]['SMA10'] == 0:
                                        dis10 = 0
                                    else:
                                        dis10 = float(df.iloc[i]['close']) / float(df.iloc[i]['SMA10']) * 100

                                    if df.iloc[i]['SMA20'] == 0:
                                        dis20 = 0
                                    else:
                                        dis20 = float(df.iloc[i]['close']) / float(df.iloc[i]['SMA20']) * 100

                                    if df.iloc[i]['SMA60'] == 0:
                                        dis60 = 0
                                    else:
                                        dis60 = float(df.iloc[i]['close']) / float(df.iloc[i]['SMA60']) * 100

                                    file = open("C:/Users/jini/PycharmProjects/stock/sql/sqlOra72.sql", 'r') # TRADE_TECH에 데이터 넣기
                                    sqlOra72 = ''
                                    line = file.readline()
                                    while line:
                                        sqlOra72 += ' ' + line.strip('\n').strip('\t')
                                        line = file.readline()

                                    file.close()

                                    sqlOra72 = sqlOra72 % (
                                               df.iloc[i]['tradeTime'], df.iloc[i]['stockCd']
                                               , df.iloc[i - 3]['high'], df.iloc[i - 2]['high'], df.iloc[i - 1]['high']
                                               , df.iloc[i]['high'], df.iloc[i - 3]['low'], df.iloc[i - 2]['low'],
                                               df.iloc[i - 1]['low']
                                               , df.iloc[i]['low'], df.iloc[i - 3]['open'], df.iloc[i - 2]['open'],
                                               df.iloc[i - 1]['open']
                                               , df.iloc[i]['open'], df.iloc[i - 3]['close'], df.iloc[i - 2]['close']
                                               , df.iloc[i - 1]['close'], df.iloc[i]['close'], df.iloc[i - 3]['volume']
                                               , df.iloc[i - 2]['volume'], df.iloc[i - 1]['volume'],
                                               df.iloc[i]['volume']
                                               , (df.iloc[i - 2]['high'] - df.iloc[i - 3]['high']) / df.iloc[i - 3][
                                                   'high']
                                               , (df.iloc[i - 1]['high'] - df.iloc[i - 2]['high']) / df.iloc[i - 2][
                                                   'high']
                                               , (df.iloc[i]['high'] - df.iloc[i - 1]['high']) / df.iloc[i - 1]['high']
                                               , (df.iloc[i]['high'] - df.iloc[i - 3]['high']) / df.iloc[i - 3]['high']
                                               , (df.iloc[i]['high'] - df.iloc[i - 2]['high']) / df.iloc[i - 2]['high']
                                               , (df.iloc[i - 2]['low'] - df.iloc[i - 3]['low']) / df.iloc[i - 3]['low']
                                               , (df.iloc[i - 1]['low'] - df.iloc[i - 2]['low']) / df.iloc[i - 2]['low']
                                               , (df.iloc[i]['low'] - df.iloc[i - 1]['low']) / df.iloc[i - 1]['low']
                                               , (df.iloc[i]['low'] - df.iloc[i - 3]['low']) / df.iloc[i - 3]['low']
                                               , (df.iloc[i]['low'] - df.iloc[i - 2]['low']) / df.iloc[i - 2]['low']
                                               , df.iloc[i]['SMA5'], df.iloc[i]['SMA10'], df.iloc[i]['SMA20'], df.iloc[i]['SMA60']
                                               , df.iloc[i]['SMA120'], df.iloc[i]['RSI'], df.iloc[i]['CCI']
                                               , float(dis10)
                                               , float(dis20)
                                               , df.iloc[i]['MACD'], df.iloc[i]['MACDSIG'], df.iloc[i]['SLOWD'], df.iloc[i]['FASTD']
                                               , (max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high']) - min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low']))
                                               /  min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low']) * 100
                                               , df.iloc[i]['MACD'] - df.iloc[i]['MACDSIG']
                                               , (df.iloc[i]['close'] - df.iloc[i]['high']) * 100 / df.iloc[i]['high']
                                               , (df.iloc[i]['close'] - max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])) * 100
                                               / max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])
                                               , (df.iloc[i]['open'] - max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])) * 100
                                               / max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])
                                               , (df.iloc[i]['close'] - min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low'])) * 100
                                               / min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low'])
                                               , float(dis5)
                                               , float(dis60)
                                               , df.iloc[i]['tradeTime']
                                               )

                                    try:
                                        self.updateDB(sqlOra72)
                                    except Exception as e:
                                        print(e)
                            except Exception as e:
                                print(e)

                    except Exception as e:
                        print(e)

        except Exception as e:
            print(e)

        print("["+ datetime.today().strftime("%Y-%m-%d %H:%M:%S") + "] " + "보조지표 만들기 끝!" )
def get_factors(high,
                low,
                close,
                volume,
                BBANDS=False,
                DEMA=False,
                EMA=False,
                HT_TRENDLINE=False,
                KAMA=False,
                MA=False,
                MAMA=False,
                MAVP=False,
                MIDPOINT=False,
                MIDPRICE=False,
                SAR=False,
                SAREXT=False,
                SMA=False,
                T3=False,
                TEMA=False,
                TRIMA=False,
                WMA=False,
                AD=False,
                ADOSC=False,
                OBV=False,
                HT_DCPERIOD=False,
                HT_DCPHASE=False,
                HT_PHASOR=False,
                HT_SINE=False,
                HT_TRENDMODE=False,
                AVGPRICE=False,
                MEDPRICE=False,
                TYPPRICE=False,
                WCLPRICE=False,
                ATR=False,
                NATR=False,
                TRANGE=False,
                ADX=False,
                ADXR=False,
                APO=False,
                AROON=False,
                AROONOSC=False,
                BOP=False,
                CCI=False,
                CMO=False,
                DX=False,
                MACD=False,
                ivergence=False,
                MACDEXT=False,
                MACDFIX=False,
                MFI=False,
                MINUS_DI=False,
                MINUS_DM=False,
                MOM=False,
                PLUS_DI=False,
                PLUS_DM=False,
                PPO=False,
                ROC=False,
                ROCP=False,
                ROCR=False,
                ROCR100=False,
                RSI=False,
                STOCH=False,
                STOCHF=False,
                STOCHRSI=False,
                TRIX=False,
                ULTOSC=False,
                WILLR=False):
    fators = [
        'BBANDS', 'DEMA', 'EMA', 'HT_TRENDLINE', 'KAMA', 'MA', 'MAMA',
        'MIDPOINT', 'MIDPRICE', 'SAR', 'SAREXT', 'SMA', 'T3', 'TEMA', 'TRIMA',
        'WMA', 'AD', 'ADOSC', 'OBV', 'HT_DCPERIOD', 'HT_DCPHASE', 'HT_PHASOR',
        'HT_SINE', 'HT_TRENDMODE', 'AVGPRICE', 'MEDPRICE', 'TYPPRICE',
        'WCLPRICE', 'ATR', 'NATR', 'TRANGE', 'ADX', 'ADXR', 'APO', 'AROON',
        'AROONOSC', 'BOP', 'CCI', 'CMO', 'DX', 'MACD', 'ivergence', 'MACDEXT',
        'MACDFIX', 'MFI,MINUS_DI', 'MINUS_DM', 'MOM', 'PLUS_DI', 'PLUS_DM',
        'PPO', 'ROC', 'ROCP', 'ROCR', 'ROCR100', 'RSI', 'STOCH', 'STOCHF',
        'STOCHRSI', 'TRIX', 'ULTOSC', 'WILLR'
    ]
    data_sets = np.zeros([len(high), 1])
    if BBANDS == True:
        upperband, middleband, lowerband = ta.BBANDS(close,
                                                     timeperiod=5,
                                                     nbdevup=2,
                                                     nbdevdn=2,
                                                     matype=0)
        upperband = array_process(upperband)
        middleband = array_process(middleband)
        lowerband = array_process(lowerband)
        data_sets = np.hstack([data_sets, upperband, middleband, lowerband])
    if DEMA == True:
        dema = ta.DEMA(close, timeperiod=30)
        dema = array_process(dema)
        data_sets = np.hstack([data_sets, dema])
    if EMA == True:
        ema = ta.EMA(close, timeperiod=30)
        ema = array_process(ema)
        data_sets = np.hstack([data_sets, ema])
    if HT_TRENDLINE == True:
        trendline = ta.HT_TRENDLINE(close)
        trendline = array_process(trendline)
        data_sets = np.hstack([data_sets, trendline])
    if KAMA == True:
        kama = ta.KAMA(close, timeperiod=30)
        kama = array_process(kama)
        data_sets = np.hstack([data_sets, kama])
    if MA == True:
        ma = ta.MA(close, timeperiod=30, matype=0)
        ma = array_process(ma)
        data_sets = np.hstack([data_sets, ma])
    if MAMA == True:
        mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0)
        mama = array_process(mama)
        fama = array_process(fama)
        data_sets = np.hstack([data_sets, mama, fama])
    if MIDPOINT == True:
        midpoint = ta.MIDPOINT(close, timeperiod=14)
        midpoint = array_process(midpoint)
        data_sets = np.hstack([data_sets, midpoint])
    if MIDPRICE == True:
        midprice = ta.MIDPRICE(high, low, timeperiod=14)
        midprice = array_process(midprice)
        data_sets = np.hstack([data_sets, midprice])
    if SAR == True:
        sar = ta.SAR(high, low, acceleration=0, maximum=0)
        sar = array_process(sar)
        data_sets = np.hstack([data_sets, sar])
    if SAREXT == True:
        sarext = ta.SAREXT(high,
                           low,
                           startvalue=0,
                           offsetonreverse=0,
                           accelerationinitlong=0,
                           accelerationlong=0,
                           accelerationmaxlong=0,
                           accelerationinitshort=0,
                           accelerationshort=0,
                           accelerationmaxshort=0)
        sarext = array_process(sarext)
        data_sets = np.hstack([data_sets, sarext])
    if SMA == True:
        sma = ta.SMA(close, timeperiod=30)
        sma = array_process(sma)
        data_sets = np.hstack([data_sets, sma])
    if T3 == True:
        t3 = ta.T3(close, timeperiod=5, vfactor=0)
        t3 = array_process(t3)
        data_sets = np.hstack([data_sets, t3])
    if TEMA == True:
        tema = ta.TEMA(close, timeperiod=30)
        tema = array_process(tema)
        data_sets = np.hstack([data_sets, tema])
    if TRIMA == True:
        trima = ta.TRIMA(close, timeperiod=30)
        trima = array_process(trima)
        data_sets = np.hstack([data_sets, trima])
    if WMA == True:
        wma = ta.WMA(close, timeperiod=30)
        wma = array_process(wma)
        data_sets = np.hstack([data_sets, wma])
    if AD == True:
        ad = ta.AD(high, low, close, volume)
        ad = array_process(ad)
        data_sets = np.hstack([data_sets, ad])
    if ADOSC == True:
        adosc = ta.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)
        adosc = array_process(adosc)
        data_sets = np.hstack([data_sets, adosc])
    if OBV == True:
        obv = ta.OBV(close, volume)
        obv = array_process(obv)
        data_sets = np.hstack([data_sets, obv])
    if HT_DCPERIOD == True:
        dcperiod = ta.HT_DCPERIOD(close)
        dcperiod = array_process(dcperiod)
        data_sets = np.hstack([data_sets, dcperiod])
    if HT_DCPHASE == True:
        dcphase = ta.HT_DCPHASE(close)
        dcphase = array_process(dcphase)
        data_sets = np.hstack([data_sets, dcphase])
    if HT_PHASOR == True:
        inphase, quadrature = ta.HT_PHASOR(close)
        inphase = array_process(inphase)
        data_sets = np.hstack([data_sets, inphase])
        quadrature = array_process(quadrature)
        data_sets = np.hstack([data_sets, quadrature])
    if HT_SINE == True:
        sine, leadsine = ta.HT_SINE(close)
        sine = array_process(sine)
        data_sets = np.hstack([data_sets, sine])
        leadsine = array_process(leadsine)
        data_sets = np.hstack([data_sets, leadsine])
    if HT_TRENDMODE == True:
        integer = ta.HT_TRENDMODE(close)
        integer = array_process(integer)
        data_sets = np.hstack([data_sets, integer])
    if AVGPRICE == True:
        avgprice = ta.AVGPRICE(open, high, low, close)
        avgprice = array_process(avgprice)
        data_sets = np.hstack([data_sets, avgprice])
    if MEDPRICE == True:
        medprice = ta.MEDPRICE(high, low)
        medprice = array_process(medprice)
        data_sets = np.hstack([data_sets, medprice])
    if TYPPRICE == True:
        typprice = ta.TYPPRICE(high, low, close)
        typprice = array_process(typprice)
        data_sets = np.hstack([data_sets, typprice])
    if WCLPRICE == True:
        wclprice = ta.WCLPRICE(high, low, close)
        wclprice = array_process(wclprice)
        data_sets = np.hstack([data_sets, wclprice])
    if ATR == True:
        atr = ta.ATR(high, low, close, timeperiod=14)
        atr = array_process(atr)
        data_sets = np.hstack([data_sets, atr])
    if NATR == True:
        natr = ta.NATR(high, low, close, timeperiod=14)
        natr = array_process(natr)
        data_sets = np.hstack([data_sets, natr])
    if TRANGE == True:
        trange = ta.TRANGE(high, low, close)
        natr = array_process(trange)
        data_sets = np.hstack([data_sets, trange])
    if ADX == True:
        adx = ta.ADX(high, low, close, timeperiod=14)
        adx = array_process(adx)
        data_sets = np.hstack([data_sets, adx])
    if ADXR == True:
        adxr = ta.ADXR(high, low, close, timeperiod=14)
        adxr = array_process(adxr)
        data_sets = np.hstack([data_sets, adxr])
    if APO == True:
        apo = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
        apo = array_process(apo)
        data_sets = np.hstack([data_sets, apo])
    if AROON == True:
        aroondown, aroonup = ta.AROON(high, low, timeperiod=14)
        aroondown = array_process(aroondown)
        data_sets = np.hstack([data_sets, aroondown])
        aroonup = array_process(aroonup)
        data_sets = np.hstack([data_sets, aroonup])
    if AROONOSC == True:
        aroonosc = ta.AROONOSC(high, low, timeperiod=14)
        aroonosc = array_process(aroonosc)
        data_sets = np.hstack([data_sets, aroonosc])
    if BOP == True:
        bop = ta.BOP(open, high, low, close)
        bop = array_process(bop)
        data_sets = np.hstack([data_sets, bop])
    if CCI == True:
        cci = ta.CCI(high, low, close, timeperiod=14)
        cci = array_process(cci)
        data_sets = np.hstack([data_sets, cci])
    if CMO == True:
        cmo = ta.CMO(close, timeperiod=14)
        cmo = array_process(cmo)
        data_sets = np.hstack([data_sets, cmo])
    if DX == True:
        dx = ta.DX(high, low, close, timeperiod=14)
        dx = array_process(dx)
        data_sets = np.hstack([data_sets, dx])
    if MACD == True:
        macd, macdsignal, macdhist = ta.MACD(close,
                                             fastperiod=12,
                                             slowperiod=26,
                                             signalperiod=9)
        macd = array_process(macd)
        data_sets = np.hstack([data_sets, macd])
        macdhist = array_process(macdhist)
        data_sets = np.hstack([data_sets, macdhist])
        macdsignal = array_process(macdsignal)
        data_sets = np.hstack([data_sets, macdsignal])
    if MACDEXT == True:
        macd, macdsignal, macdhist = ta.MACDEXT(close,
                                                fastperiod=12,
                                                fastmatype=0,
                                                slowperiod=26,
                                                slowmatype=0,
                                                signalperiod=9,
                                                signalmatype=0)
        macd = array_process(macd)
        data_sets = np.hstack([data_sets, macd])
        macdhist = array_process(macdhist)
        data_sets = np.hstack([data_sets, macdhist])
        macdsignal = array_process(macdsignal)
        data_sets = np.hstack([data_sets, macdsignal])
    if MACDFIX == True:
        macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9)
        macd = array_process(macd)
        data_sets = np.hstack([data_sets, macd])
        macdhist = array_process(macdhist)
        data_sets = np.hstack([data_sets, macdhist])
        macdsignal = array_process(macdsignal)
        data_sets = np.hstack([data_sets, macdsignal])
    if MFI == True:
        mfi = ta.MFI(high, low, close, volume, timeperiod=14)
        mfi = array_process(mfi)
        data_sets = np.hstack([data_sets, mfi])
    if MINUS_DI == True:
        minus_di = ta.MINUS_DI(high, low, close, timeperiod=14)
        minus_di = array_process(minus_di)
        data_sets = np.hstack([data_sets, minus_di])
    if MINUS_DM == True:
        minus_dm = ta.MINUS_DM(high, low, timeperiod=14)
        minus_dm = array_process(minus_dm)
        data_sets = np.hstack([data_sets, minus_dm])
    if MOM == True:
        mom = ta.MOM(close, timeperiod=10)
        mom = array_process(mom)
        data_sets = np.hstack([data_sets, mom])
    if PLUS_DI == True:
        plus_di = ta.PLUS_DI(high, low, close, timeperiod=14)
        plus_di = array_process(plus_di)
        data_sets = np.hstack([data_sets, plus_di])
    if PLUS_DM == True:
        plus_dm = ta.PLUS_DM(high, low, timeperiod=14)
        plus_dm = array_process(plus_dm)
        data_sets = np.hstack([data_sets, plus_dm])
    if PPO == True:
        ppo = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
        ppo = array_process(ppo)
        data_sets = np.hstack([data_sets, ppo])
    if ROC == True:
        roc = ta.ROC(close, timeperiod=10)
        roc = array_process(roc)
        data_sets = np.hstack([data_sets, roc])
    if ROCP == True:
        rocp = ta.ROCP(close, timeperiod=10)
        rocp = array_process(rocp)
        data_sets = np.hstack([data_sets, rocp])
    if ROCR == True:
        rocr = ta.ROCR(close, timeperiod=10)
        rocr = array_process(rocr)
        data_sets = np.hstack([data_sets, rocr])
    if ROCR100 == True:
        rocr100 = ta.ROCR100(close, timeperiod=10)
        rocr100 = array_process(rocr100)
        data_sets = np.hstack([data_sets, rocr100])
    if RSI == True:
        rsi = ta.RSI(close, timeperiod=14)
        rsi = array_process(rsi)
        data_sets = np.hstack([data_sets, rsi])
    if STOCH == True:
        slowk, slowd = ta.STOCH(high,
                                low,
                                close,
                                fastk_period=5,
                                slowk_period=3,
                                slowk_matype=0,
                                slowd_period=3,
                                slowd_matype=0)
        slowd = array_process(slowd)
        data_sets = np.hstack([data_sets, slowd])
        slowk = array_process(slowk)
        data_sets = np.hstack([data_sets, slowk])
    if STOCHF == True:
        fastk, fastd = ta.STOCHF(high,
                                 low,
                                 close,
                                 fastk_period=5,
                                 fastd_period=3,
                                 fastd_matype=0)
        fastd = array_process(fastd)
        data_sets = np.hstack([data_sets, fastd])
        fastk = array_process(fastk)
        data_sets = np.hstack([data_sets, fastk])
    if STOCHRSI == True:
        fastk, fastd = ta.STOCHRSI(close,
                                   timeperiod=14,
                                   fastk_period=5,
                                   fastd_period=3,
                                   fastd_matype=0)
        fastk = array_process(fastk)
        data_sets = np.hstack([data_sets, fastk])
        fastd = array_process(fastd)
        data_sets = np.hstack([data_sets, fastd])
    if TRIX == True:
        trix = ta.TRIX(close, timeperiod=30)
        trix = array_process(trix)
        data_sets = np.hstack([data_sets, trix])
    if ULTOSC == True:
        ultosc = ta.ULTOSC(high,
                           low,
                           close,
                           timeperiod1=7,
                           timeperiod2=14,
                           timeperiod3=28)
        ultosc = array_process(ultosc)
        data_sets = np.hstack([data_sets, ultosc])
    if WILLR == True:
        willr = ta.WILLR(high, low, close, timeperiod=14)
        willr = array_process(willr)
        data_sets = np.hstack([data_sets, willr])
    return data_sets[:, 1:]
def handle_momentum_indicators(args, axes, i, klines_df, close_times,
                               display_count):
    if args.macd:  # macd
        name = 'macd'
        klines_df = ic.pd_macd(klines_df)
        difs = [round(a, 2) for a in klines_df["dif"]]
        deas = [round(a, 2) for a in klines_df["dea"]]
        macds = [round(a, 2) for a in klines_df["macd"]]
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, difs[-display_count:], "y", label="dif")
        axes[i].plot(close_times, deas[-display_count:], "b", label="dea")
        axes[i].plot(close_times,
                     macds[-display_count:],
                     "r",
                     drawstyle="steps",
                     label="macd")

    if args.mr:  # macd rate
        name = 'macd rate'
        klines_df = ic.pd_macd(klines_df)
        closes = klines_df["close"][-display_count:]
        closes = pd.to_numeric(closes)
        mrs = [
            round(a, 4) for a in (klines_df["macd"][-display_count:] / closes)
        ]
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, mrs, "r--", label="mr")

    if args.kdj:  # kdj
        name = 'kdj'
        ks, ds, js = ic.pd_kdj(klines_df)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, ks[-display_count:], "b", label="k")
        axes[i].plot(close_times, ds[-display_count:], "y", label="d")
        axes[i].plot(close_times, js[-display_count:], "m", label="j")

    # talib
    if args.ADX:  # ADX
        name = 'ADX'
        adxs = talib.ADX(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, adxs[-display_count:], "b", label=name)

    if args.ADXR:  # ADXR
        name = 'ADXR'
        adxrs = talib.ADXR(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, adxrs[-display_count:], "r", label=name)

    if args.APO:  # APO
        name = 'APO'
        real = talib.APO(klines_df["close"],
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.AROON:  # AROON
        name = 'AROON'
        aroondown, aroonup = talib.AROON(klines_df["high"],
                                         klines_df["low"],
                                         timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, aroondown[-display_count:], "y:", label=name)
        axes[i].plot(close_times, aroonup[-display_count:], "y:", label=name)

    if args.AROONOSC:  # AROONOSC
        name = 'AROONOSC'
        real = talib.AROONOSC(klines_df["high"],
                              klines_df["low"],
                              timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

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

    if args.CCI:  # CCI
        name = 'CCI'
        real = talib.CCI(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.CMO:  # CMO
        name = 'CMO'
        real = talib.CMO(klines_df["close"], timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.DX:  # DX
        name = 'DX'
        dxs = talib.DX(klines_df["high"],
                       klines_df["low"],
                       klines_df["close"],
                       timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, dxs[-display_count:], "y", label=name)

    if args.MACD:  # MACD
        name = 'MACD'
        fastperiod = 12
        slowperiod = 26
        signalperiod = 9
        macd, macdsignal, macdhist = talib.MACD(klines_df["close"],
                                                fastperiod=fastperiod,
                                                slowperiod=slowperiod,
                                                signalperiod=signalperiod)
        i += 1
        axes[i].set_ylabel("%s(%s,%s,%s)" %
                           (name, fastperiod, slowperiod, signalperiod))
        axes[i].grid(True)
        axes[i].plot(close_times, macd[-display_count:], "y", label="dif")
        axes[i].plot(close_times,
                     macdsignal[-display_count:],
                     "b",
                     label="dea")
        axes[i].plot(close_times,
                     macdhist[-display_count:],
                     "r",
                     drawstyle="steps",
                     label="macd")

    if args.MACDEXT:  # MACDEXT
        name = 'MACDEXT'
        fastperiod = 12
        slowperiod = 26
        signalperiod = 9
        macd, macdsignal, macdhist = talib.MACDEXT(klines_df["close"],
                                                   fastperiod=fastperiod,
                                                   fastmatype=0,
                                                   slowperiod=slowperiod,
                                                   slowmatype=0,
                                                   signalperiod=signalperiod,
                                                   signalmatype=0)
        i += 1
        axes[i].set_ylabel("%s(%s,%s,%s)" %
                           (name, fastperiod, slowperiod, signalperiod))
        axes[i].grid(True)
        axes[i].plot(close_times, macd[-display_count:], "y", label="dif")
        axes[i].plot(close_times,
                     macdsignal[-display_count:],
                     "b",
                     label="dea")
        axes[i].plot(close_times,
                     macdhist[-display_count:],
                     "r",
                     drawstyle="steps",
                     label="macd")

    if args.MACDFIX:  # MACDFIX
        name = 'MACDFIX'
        signalperiod = 9
        macd, macdsignal, macdhist = talib.MACDFIX(klines_df["close"],
                                                   signalperiod=signalperiod)
        i += 1
        axes[i].set_ylabel("%s(%s)" % (name, signalperiod))
        axes[i].grid(True)
        axes[i].plot(close_times, macd[-display_count:], "y", label="dif")
        axes[i].plot(close_times,
                     macdsignal[-display_count:],
                     "b",
                     label="dea")
        axes[i].plot(close_times,
                     macdhist[-display_count:],
                     "r",
                     drawstyle="steps",
                     label="macd")

    if args.MFI:  #
        name = 'MFI'
        real = talib.MFI(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.MINUS_DI:  #
        name = 'MINUS_DI'
        real = talib.MINUS_DI(klines_df["high"],
                              klines_df["low"],
                              klines_df["close"],
                              timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.MINUS_DM:  #
        name = 'MINUS_DM'
        real = talib.MINUS_DM(klines_df["high"],
                              klines_df["low"],
                              timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.MOM:  #
        name = 'MOM'
        real = talib.MOM(klines_df["close"], timeperiod=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.PLUS_DI:  #
        name = 'PLUS_DI'
        real = talib.PLUS_DI(klines_df["high"],
                             klines_df["low"],
                             klines_df["close"],
                             timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.PLUS_DM:  #
        name = 'PLUS_DM'
        real = talib.PLUS_DM(klines_df["high"],
                             klines_df["low"],
                             timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.PPO:  #
        name = 'PPO'
        real = talib.PPO(klines_df["close"],
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.ROC:  #
        name = 'ROC'
        real = talib.ROC(klines_df["close"], timeperiod=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.ROCP:  #
        name = 'ROCP'
        real = talib.ROCP(klines_df["close"], timeperiod=10)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "k:", label=name)

    if args.ROCR:  #
        name = 'ROCR'
        real = talib.ROCR(klines_df["close"], timeperiod=10)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "m:", label=name)

    if args.ROCR100:  #
        name = 'ROCR100'
        real = talib.ROCR100(klines_df["close"], timeperiod=10)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "b:", label=name)

    if args.RSI is not None:  # RSI
        name = 'RSI'
        i += 1
        axes[i].grid(True)

        if len(args.RSI) == 0:
            tps = [14]
        else:
            tps = args.RSI
        cs = ["r", "y", "b"]
        axes[i].set_ylabel("%s %s" % (name, tps))
        for idx, tp in enumerate(tps):
            rsis = talib.RSI(klines_df["close"], timeperiod=tp)
            rsis = [round(a, 3) for a in rsis][-display_count:]
            axes[i].plot(close_times, rsis, cs[idx], label="rsi")

            linetype = "."
            axes[i].plot(close_times, [90] * len(rsis), linetype, color='r')
            axes[i].plot(close_times, [80] * len(rsis), linetype, color='r')
            axes[i].plot(close_times, [50] * len(rsis), linetype, color='r')
            axes[i].plot(close_times, [40] * len(rsis), linetype, color='r')

            linetype = "."
            axes[i].plot(close_times, [65] * len(rsis), linetype, color='b')
            axes[i].plot(close_times, [55] * len(rsis), linetype, color='b')
            axes[i].plot(close_times, [30] * len(rsis), linetype, color='b')
            axes[i].plot(close_times, [20] * len(rsis), linetype, color='b')

    if args.STOCH:  # STOCH
        name = 'STOCH'
        slowk, slowd = talib.STOCH(klines_df["high"],
                                   klines_df["low"],
                                   klines_df["close"],
                                   fastk_period=5,
                                   slowk_period=3,
                                   slowk_matype=0,
                                   slowd_period=3,
                                   slowd_matype=0)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, slowk[-display_count:], "b", label="slowk")
        axes[i].plot(close_times, slowd[-display_count:], "y", label="slowd")

    if args.STOCHF:  #
        name = 'STOCHF'
        fastk, fastd = talib.STOCHF(klines_df["high"],
                                    klines_df["low"],
                                    klines_df["close"],
                                    fastk_period=5,
                                    fastd_period=3,
                                    fastd_matype=0)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, fastk[-display_count:], "b", label="fastk")
        axes[i].plot(close_times, fastd[-display_count:], "y", label="fastd")

    if args.STOCHRSI:  #
        name = 'STOCHRSI'
        fastk, fastd = talib.STOCHRSI(klines_df["close"],
                                      timeperiod=14,
                                      fastk_period=5,
                                      fastd_period=3,
                                      fastd_matype=0)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, fastk[-display_count:], "b", label="fastk")
        axes[i].plot(close_times, fastd[-display_count:], "y", label="fastd")

    if args.TRIX is not None:  #
        name = 'TRIX'
        i += 1
        axes[i].grid(True)
        if len(args.TRIX) == 0:
            tps = [30]
        else:
            tps = args.TRIX
        axes[i].set_ylabel("%s %s" % (name, tps))

        for idx, tp in enumerate(tps):
            real = talib.TRIX(klines_df["close"], timeperiod=tp)
            axes[i].plot(close_times,
                         real[-display_count:],
                         plot_colors[idx],
                         label=name)

    if args.ULTOSC:  #
        name = 'ULTOSC'
        real = talib.ULTOSC(klines_df["high"],
                            klines_df["low"],
                            klines_df["close"],
                            timeperiod1=7,
                            timeperiod2=14,
                            timeperiod3=28)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.WILLR:
        tp = 14
        name = 'WILLR %s' % tp
        real = talib.WILLR(klines_df["high"],
                           klines_df["low"],
                           klines_df["close"],
                           timeperiod=tp)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)
def rocr(stockData, point):
    return talib.ROCR(stockData['close'][:point], timeperiod=10)[-1]
Exemple #13
0
data["PPO"] = talib.PPO(data.Close, fastperiod=12, slowperiod=26, matype=0)

#Learn more about the Percentage Price Oscillator at tadoc.org.
#ROC - Rate of change : ((price/prevPrice)-1)*100

data["ROC"] = talib.ROC(data.Close, timeperiod=10)

#Learn more about the Rate of change : ((price/prevPrice)-1)*100 at tadoc.org.
#ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice

data["ROCP"] = talib.ROCP(data.Close, timeperiod=10)

#Learn more about the Rate of change Percentage: (price-prevPrice)/prevPrice at tadoc.org.
#ROCR - Rate of change ratio: (price/prevPrice)

data["ROCR"] = talib.ROCR(data.Close, timeperiod=10)

#Learn more about the Rate of change ratio: (price/prevPrice) at tadoc.org.
#ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100

data["ROCR100"] = talib.ROCR100(data.Close, timeperiod=10)

#Learn more about the Rate of change ratio 100 scale: (price/prevPrice)*100 at tadoc.org.
#RSI - Relative Strength Index

#NOTE: The RSI function has an unstable period.

data["RSI"] = talib.RSI(data.Close, timeperiod=14)

#Learn more about the Relative Strength Index at tadoc.org.
#STOCH - Stochastic
Exemple #14
0
 def ROCR_factor(self, df, timeperiod=10):
     return talib.ROCR(df.loc[:, self.map_dict['default']].values,
                       timeperiod)
Exemple #15
0
def rocr(col, timeperiod=10):
    return {"rocr": ta.ROCR(col, timeperiod)}
def ROCR(raw_df, timeperiod=10):
    # extract necessary data from raw dataframe (close)
    return ta.ROCR(raw_df.Close.values, timeperiod)
Exemple #17
0
    def add_ta_features(df):
        pr = df.price
        HL = (df.high, df.low)
        HLC = (df.high, df.low, df.close)
        OHLC = (df.open, df.high, df.low, df.close)
        HLCV = (df.high, df.low, df.close, df.vol)
        PV = (pr, df.vol)
        initial_col_count = df.columns.shape[0]
        df = (
            df.assign(SMA4=(ta.SMA(pr, timeperiod=4) - pr)).assign(SMA12=(
                ta.SMA(pr, timeperiod=12) -
                pr)).assign(SMA24=(ta.SMA(pr, timeperiod=24) - pr)).assign(
                    BBAND20_HI=(ta.BBANDS(pr, timeperiod=20)[0] - pr)).assign(
                        BBAND20_LO=(pr -
                                    ta.BBANDS(pr, timeperiod=20)[2])).assign(
                                        SAREXT=(ta.SAREXT(*HL) -
                                                pr)).assign(ADX=ta.ADX(*HLC)).
            assign(ADOSC=ta.ADOSC(*HLCV)).assign(
                CDL3STARSINSOUTH=(ta.CDL3STARSINSOUTH(*OHLC))).assign(
                    HT_TRENDLINE=ta.HT_TRENDLINE(pr) -
                    pr).assign(KAMA=ta.KAMA(pr) - pr).assign(
                        MIDPOINT=ta.MIDPOINT(pr) -
                        pr).assign(T3=ta.T3(pr) - pr).assign(
                            TEMA=ta.TEMA(pr) - pr).assign(
                                TRIMA=ta.TRIMA(pr) - pr).assign(ADXR=ta.ADXR(
                                    *HLC)).assign(APO=ta.APO(pr)).assign(
                                        AROON1=ta.AROON(*HL)[0]).assign(
                                            AROON2=ta.AROON(*HL)[1]).
            assign(AROONOSC=ta.AROONOSC(*HL)).assign(BOP=ta.BOP(
                *OHLC)).assign(CMO=ta.CMO(pr)).assign(DX=ta.DX(*HLC)).assign(
                    MACD1=ta.MACD(pr)[0]).assign(MACD2=ta.MACD(pr)[1]).assign(
                        MACDEXT1=ta.MACDEXT(pr)[0]).assign(
                            MACDEXT2=ta.MACDEXT(pr)[1]).assign(MFI=ta.MFI(
                                *HLCV)).assign(MINUS_DI=ta.MINUS_DI(
                                    *HLC)).assign(MINUS_DM=ta.MINUS_DM(
                                        *HL)).assign(CMOMCI=ta.MOM(pr)).assign(
                                            PLUS_DI=ta.PLUS_DI(*HLC)).assign(
                                                PLUS_DM=ta.PLUS_DM(*HL)).
            assign(PPO=ta.PPO(pr)).assign(ROC=ta.ROC(pr)).assign(
                ROCP=ta.ROCP(pr)).assign(ROCR=ta.ROCR(pr)).assign(
                    RSI=ta.RSI(pr)).assign(STOCH1=ta.STOCH(
                        *HLC)[0]).assign(STOCH2=ta.STOCH(*HLC)[1]).assign(
                            STOCHF1=ta.STOCHF(*HLC)[0]).assign(
                                STOCHF2=ta.STOCHF(*HLC)[1]).assign(
                                    STOCHRSI1=ta.STOCHRSI(pr)[0]).assign(
                                        STOCHRSI2=ta.STOCHRSI(pr)[1]).assign(
                                            ULTOSC=ta.ULTOSC(*HLC)).
            assign(WILLR=ta.WILLR(*HLC)).assign(AD=ta.AD(
                *HLCV)).assign(ADOSC=ta.ADOSC(*HLCV)).assign(OBV=ta.OBV(
                    *PV)).assign(HT_DCPERIOD=ta.HT_DCPERIOD(pr)).assign(
                        HT_DCPHASE=ta.HT_DCPHASE(pr)).assign(
                            HT_PHASOR1=ta.HT_PHASOR(pr)[0]).assign(
                                HT_PHASOR2=ta.HT_PHASOR(pr)[1]).assign(
                                    HT_SINE1=ta.HT_SINE(pr)[0]).assign(
                                        HT_SINE2=ta.HT_SINE(pr)[1]).assign(
                                            HT_TRENDMODE=ta.HT_TRENDMODE(pr)).
            assign(ATR14=ta.ATR(*HLC, timeperiod=14)).assign(
                NATR14=ta.NATR(*HLC, timeperiod=14)).assign(TRANGE=ta.TRANGE(
                    *HLC)).assign(ATR7=ta.ATR(*HLC, timeperiod=7)).assign(
                        NATR7=ta.NATR(*HLC, timeperiod=7)).assign(
                            ATR21=ta.ATR(*HLC, timeperiod=21)).assign(
                                NATR21=ta.NATR(*HLC, timeperiod=21))
            # .astype(int, errors='ignore')
        )
        # adding difference
        for col in df.columns[initial_col_count:]:
            df[col + '_change'] = df[col] - df[col].shift(1)
        candle_methods = [
            method_name for method_name in dir(ta)
            if method_name.startswith('CDL')
        ]
        for method in candle_methods:
            df[method] = getattr(ta, method)(*OHLC)

        # n_before = df.shape[0]
        df = df.dropna()
        # l.debug(f'TA indicators do require {n_before - df.shape[0]} steps of history')
        return df
Exemple #18
0
def extract_features(stock_df: pd.DataFrame) -> pd.DataFrame:
    #    stock_df = stock_df.reindex(pd.date_range(stock_df.first_valid_index(), stock_df.last_valid_index()))
    #    mask = stock_df.isna().as_matrix(['Open']).reshape(-1)
    stock_df = stock_df.fillna(method='pad')
    stock_raw = {
        'open': stock_df.as_matrix(['Open']).reshape(-1),
        'high': stock_df.as_matrix(['High']).reshape(-1),
        'low': stock_df.as_matrix(['Low']).reshape(-1),
        'close': stock_df.as_matrix(['Adj Close']).reshape(-1),
        'volume':
        stock_df.as_matrix(['Volume']).reshape(-1).astype(np.float64),
    }

    feat_data = {
        'Adj Close':
        stock_raw['close'],
        'OBV':
        talib.OBV(stock_raw['close'], stock_raw['volume']),
        'Volume':
        stock_raw['close'],
        'RSI6':
        talib.RSI(stock_raw['close'], timeperiod=6),
        'RSI12':
        talib.RSI(stock_raw['close'], timeperiod=12),
        'SMA3':
        talib.SMA(stock_raw['close'], timeperiod=3),
        'EMA6':
        talib.EMA(stock_raw['close'], timeperiod=6),
        'EMA12':
        talib.EMA(stock_raw['close'], timeperiod=12),
        'ATR14':
        talib.ATR(stock_raw['high'],
                  stock_raw['low'],
                  stock_raw['close'],
                  timeperiod=14),
        'MFI14':
        talib.MFI(stock_raw['high'],
                  stock_raw['low'],
                  stock_raw['close'],
                  stock_raw['volume'],
                  timeperiod=14),
        'ADX14':
        talib.ADX(stock_raw['high'],
                  stock_raw['low'],
                  stock_raw['close'],
                  timeperiod=14),
        'ADX20':
        talib.ADX(stock_raw['high'],
                  stock_raw['low'],
                  stock_raw['close'],
                  timeperiod=20),
        'MOM1':
        talib.MOM(stock_raw['close'], timeperiod=1),
        'MOM3':
        talib.MOM(stock_raw['close'], timeperiod=3),
        'CCI12':
        talib.CCI(stock_raw['high'],
                  stock_raw['low'],
                  stock_raw['close'],
                  timeperiod=12),
        'CCI20':
        talib.CCI(stock_raw['high'],
                  stock_raw['low'],
                  stock_raw['close'],
                  timeperiod=20),
        'ROCR3':
        talib.ROCR(stock_raw['close'], timeperiod=3),
        'ROCR12':
        talib.ROCR(stock_raw['close'], timeperiod=12),
        'outMACD':
        talib.MACD(stock_raw['close'])[0],
        'outMACDSignal':
        talib.MACD(stock_raw['close'])[1],
        'outMACDHist':
        talib.MACD(stock_raw['close'])[2],
        'WILLR':
        talib.WILLR(stock_raw['high'], stock_raw['low'], stock_raw['close']),
        'TSF10':
        talib.TSF(stock_raw['close'], timeperiod=10),
        'TSF20':
        talib.TSF(stock_raw['close'], timeperiod=20),
        'TRIX':
        talib.TRIX(stock_raw['close']),
        'BBANDSUPPER':
        talib.BBANDS(stock_raw['close'])[0],
        'BBANDSMIDDLE':
        talib.BBANDS(stock_raw['close'])[1],
        'BBANDSLOWER':
        talib.BBANDS(stock_raw['close'])[2],
    }

    for colname, colval in feat_data.items():
        stock_df[colname] = colval
    # stock_df = stock_df.loc[np.logical_not(mask)]
    return stock_df
Exemple #19
0
def get_rocr(ohlc):
    rocr = ta.ROCR(ohlc['4_close'], timeperiod=10)

    ohlc['rocr'] = rocr
    return ohlc
Exemple #20
0
def ROCR(matrix, timeperiod):
    matrix['ROCR' + str(timeperiod)] = talib.ROCR(
        real=matrix['1-Close'].values, timeperiod=timeperiod)
    return matrix
    df['MINUS_DM'] = talib.MINUS_DM(df["High"], df["Low"], timeperiod=14)
    # PLUS_DI - Plus Directional Indicator
    df['PLUS_DI'] = talib.PLUS_DI(df["High"],
                                  df["Low"],
                                  df["Close"],
                                  timeperiod=14)
    # PLUS_DM - Plus Directional Movement
    df['PLUS_DM'] = talib.PLUS_DM(df["High"], df["Low"], timeperiod=14)
    print('Time #7 batch TI: ' + str(time.time() - start_time) + ' seconds')
    start_time = time.time()
    # PPO - Percentage Price Oscillator
    df['PPO'] = talib.PPO(df["Close"], fastperiod=12, slowperiod=26, matype=0)
    # ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice
    df['ROCP'] = talib.ROCP(df["Close"], timeperiod=10)
    # ROCR - Rate of change ratio: (price/prevPrice)
    df['ROCR'] = talib.ROCR(df["Close"], timeperiod=10)
    # ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    df['ROCR100'] = talib.ROCR100(df["Close"], timeperiod=10)
    # RSI - Relative Strength Index
    df['RSI'] = talib.RSI(df["Close"], timeperiod=14)
    # TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    df['TRIX'] = talib.TRIX(df["Close"], timeperiod=30)
    # ULTOSC - Ultimate Oscillator
    df['ULTOSC'] = talib.ULTOSC(df["High"],
                                df["Low"],
                                df["Close"],
                                timeperiod1=7,
                                timeperiod2=14,
                                timeperiod3=28)

    # ######################## Volume Indicators ############################
Exemple #22
0
 def ROCR(self, window=10):
     real = talib.ROCR(self.close, timeperiod=window)
def add_ta_features(df, ta_settings):
    """Add technial analysis features from typical financial dataset that
    typically include columns such as "open", "high", "low", "price" and
    "volume".

    http://mrjbq7.github.io/ta-lib/

    Args:
        df(pandas.DataFrame): original DataFrame.
        ta_settings(dict): configuration.
    Returns:
        pandas.DataFrame: DataFrame with new features included.
    """

    open = df['open']
    high = df['high']
    low = df['low']
    close = df['price']
    volume = df['volume']

    if ta_settings['overlap']:

        df['ta_overlap_bbands_upper'], df['ta_overlap_bbands_middle'], df[
            'ta_overlap_bbands_lower'] = ta.BBANDS(close,
                                                   timeperiod=5,
                                                   nbdevup=2,
                                                   nbdevdn=2,
                                                   matype=0)
        df['ta_overlap_dema'] = ta.DEMA(
            close, timeperiod=15)  # NOTE: Changed to avoid a lot of Nan values
        df['ta_overlap_ema'] = ta.EMA(close, timeperiod=30)
        df['ta_overlap_kama'] = ta.KAMA(close, timeperiod=30)
        df['ta_overlap_ma'] = ta.MA(close, timeperiod=30, matype=0)
        df['ta_overlap_mama_mama'], df['ta_overlap_mama_fama'] = ta.MAMA(close)
        period = np.random.randint(10, 20, size=len(close)).astype(float)
        df['ta_overlap_mavp'] = ta.MAVP(close,
                                        period,
                                        minperiod=2,
                                        maxperiod=30,
                                        matype=0)
        df['ta_overlap_midpoint'] = ta.MIDPOINT(close, timeperiod=14)
        df['ta_overlap_midprice'] = ta.MIDPRICE(high, low, timeperiod=14)
        df['ta_overlap_sar'] = ta.SAR(high, low, acceleration=0, maximum=0)
        df['ta_overlap_sarext'] = ta.SAREXT(high,
                                            low,
                                            startvalue=0,
                                            offsetonreverse=0,
                                            accelerationinitlong=0,
                                            accelerationlong=0,
                                            accelerationmaxlong=0,
                                            accelerationinitshort=0,
                                            accelerationshort=0,
                                            accelerationmaxshort=0)
        df['ta_overlap_sma'] = ta.SMA(close, timeperiod=30)
        df['ta_overlap_t3'] = ta.T3(close, timeperiod=5, vfactor=0)
        df['ta_overlap_tema'] = ta.TEMA(
            close, timeperiod=12)  # NOTE: Changed to avoid a lot of Nan values
        df['ta_overlap_trima'] = ta.TRIMA(close, timeperiod=30)
        df['ta_overlap_wma'] = ta.WMA(close, timeperiod=30)

        # NOTE: Commented to avoid a lot of Nan values
        # df['ta_overlap_ht_trendline'] = ta.HT_TRENDLINE(close)

    if ta_settings['momentum']:

        df['ta_momentum_adx'] = ta.ADX(high, low, close, timeperiod=14)
        df['ta_momentum_adxr'] = ta.ADXR(high, low, close, timeperiod=14)
        df['ta_momentum_apo'] = ta.APO(close,
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        df['ta_momentum_aroondown'], df['ta_momentum_aroonup'] = ta.AROON(
            high, low, timeperiod=14)
        df['ta_momentum_aroonosc'] = ta.AROONOSC(high, low, timeperiod=14)
        df['ta_momentum_bop'] = ta.BOP(open, high, low, close)
        df['ta_momentum_cci'] = ta.CCI(high, low, close, timeperiod=14)
        df['ta_momentum_cmo'] = ta.CMO(close, timeperiod=14)
        df['ta_momentum_dx'] = ta.DX(high, low, close, timeperiod=14)
        df['ta_momentum_macd_macd'], df['ta_momentum_macd_signal'], df[
            'ta_momentum_macd_hist'] = ta.MACD(close,
                                               fastperiod=12,
                                               slowperiod=26,
                                               signalperiod=9)
        df['ta_momentum_macdext_macd'], df['ta_momentum_macdext_signal'], df[
            'ta_momentum_macdext_hist'] = ta.MACDEXT(close,
                                                     fastperiod=12,
                                                     fastmatype=0,
                                                     slowperiod=26,
                                                     slowmatype=0,
                                                     signalperiod=9,
                                                     signalmatype=0)
        df['ta_momentum_macdfix_macd'], df['ta_momentum_macdfix_signal'], df[
            'ta_momentum_macdfix_hist'] = ta.MACDFIX(close, signalperiod=9)
        df['ta_momentum_mfi'] = ta.MFI(high, low, close, volume, timeperiod=14)
        df['ta_momentum_minus_di'] = ta.MINUS_DI(high,
                                                 low,
                                                 close,
                                                 timeperiod=14)
        df['ta_momentum_minus_dm'] = ta.MINUS_DM(high, low, timeperiod=14)
        df['ta_momentum_mom'] = ta.MOM(close, timeperiod=10)
        df['ta_momentum_plus_di'] = ta.PLUS_DI(high, low, close, timeperiod=14)
        df['ta_momentum_plus_dm'] = ta.PLUS_DM(high, low, timeperiod=14)
        df['ta_momentum_ppo'] = ta.PPO(close,
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        df['ta_momentum_roc'] = ta.ROC(close, timeperiod=10)
        df['ta_momentum_rocp'] = ta.ROCP(close, timeperiod=10)
        df['ta_momentum_rocr'] = ta.ROCR(close, timeperiod=10)
        df['ta_momentum_rocr100'] = ta.ROCR100(close, timeperiod=10)
        df['ta_momentum_rsi'] = ta.RSI(close, timeperiod=14)
        df['ta_momentum_slowk'], df['ta_momentum_slowd'] = ta.STOCH(
            high,
            low,
            close,
            fastk_period=5,
            slowk_period=3,
            slowk_matype=0,
            slowd_period=3,
            slowd_matype=0)
        df['ta_momentum_fastk'], df['ta_momentum_fastd'] = ta.STOCHF(
            high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0)
        df['ta_momentum_fastk'], df['ta_momentum_fastd'] = ta.STOCHRSI(
            close,
            timeperiod=14,
            fastk_period=5,
            fastd_period=3,
            fastd_matype=0)
        df['ta_momentum_trix'] = ta.TRIX(
            close, timeperiod=12)  # NOTE: Changed to avoid a lot of Nan values
        df['ta_momentum_ultosc'] = ta.ULTOSC(high,
                                             low,
                                             close,
                                             timeperiod1=7,
                                             timeperiod2=14,
                                             timeperiod3=28)
        df['ta_momentum_willr'] = ta.WILLR(high, low, close, timeperiod=14)

    if ta_settings['volume']:

        df['ta_volume_ad'] = ta.AD(high, low, close, volume)
        df['ta_volume_adosc'] = ta.ADOSC(high,
                                         low,
                                         close,
                                         volume,
                                         fastperiod=3,
                                         slowperiod=10)
        df['ta_volume_obv'] = ta.OBV(close, volume)

    if ta_settings['volatility']:

        df['ta_volatility_atr'] = ta.ATR(high, low, close, timeperiod=14)
        df['ta_volatility_natr'] = ta.NATR(high, low, close, timeperiod=14)
        df['ta_volatility_trange'] = ta.TRANGE(high, low, close)

    if ta_settings['price']:

        df['ta_price_avgprice'] = ta.AVGPRICE(open, high, low, close)
        df['ta_price_medprice'] = ta.MEDPRICE(high, low)
        df['ta_price_typprice'] = ta.TYPPRICE(high, low, close)
        df['ta_price_wclprice'] = ta.WCLPRICE(high, low, close)

    if ta_settings['cycle']:

        df['ta_cycle_ht_dcperiod'] = ta.HT_DCPERIOD(close)
        df['ta_cycle_ht_phasor_inphase'], df[
            'ta_cycle_ht_phasor_quadrature'] = ta.HT_PHASOR(close)
        df['ta_cycle_ht_trendmode'] = ta.HT_TRENDMODE(close)

        # NOTE: Commented to avoid a lot of Nan values
        # df['ta_cycle_ht_dcphase'] = ta.HT_DCPHASE(close)
        # df['ta_cycle_ht_sine_sine'], df['ta_cycle_ht_sine_leadsine'] = ta.HT_SINE(close)

    if ta_settings['pattern']:

        df['ta_pattern_cdl2crows'] = ta.CDL2CROWS(open, high, low, close)
        df['ta_pattern_cdl3blackrows'] = ta.CDL3BLACKCROWS(
            open, high, low, close)
        df['ta_pattern_cdl3inside'] = ta.CDL3INSIDE(open, high, low, close)
        df['ta_pattern_cdl3linestrike'] = ta.CDL3LINESTRIKE(
            open, high, low, close)
        df['ta_pattern_cdl3outside'] = ta.CDL3OUTSIDE(open, high, low, close)
        df['ta_pattern_cdl3starsinsouth'] = ta.CDL3STARSINSOUTH(
            open, high, low, close)
        df['ta_pattern_cdl3whitesoldiers'] = ta.CDL3WHITESOLDIERS(
            open, high, low, close)
        df['ta_pattern_cdlabandonedbaby'] = ta.CDLABANDONEDBABY(open,
                                                                high,
                                                                low,
                                                                close,
                                                                penetration=0)
        df['ta_pattern_cdladvanceblock'] = ta.CDLADVANCEBLOCK(
            open, high, low, close)
        df['ta_pattern_cdlbelthold'] = ta.CDLBELTHOLD(open, high, low, close)
        df['ta_pattern_cdlbreakaway'] = ta.CDLBREAKAWAY(open, high, low, close)
        df['ta_pattern_cdlclosingmarubozu'] = ta.CDLCLOSINGMARUBOZU(
            open, high, low, close)
        df['ta_pattern_cdlconcealbabyswall'] = ta.CDLCONCEALBABYSWALL(
            open, high, low, close)
        df['ta_pattern_cdlcounterattack'] = ta.CDLCOUNTERATTACK(
            open, high, low, close)
        df['ta_pattern_cdldarkcloudcover'] = ta.CDLDARKCLOUDCOVER(
            open, high, low, close, penetration=0)
        df['ta_pattern_cdldoji'] = ta.CDLDOJI(open, high, low, close)
        df['ta_pattern_cdldojistar'] = ta.CDLDOJISTAR(open, high, low, close)
        df['ta_pattern_cdldragonflydoji'] = ta.CDLDRAGONFLYDOJI(
            open, high, low, close)
        df['ta_pattern_cdlengulfing'] = ta.CDLENGULFING(open, high, low, close)
        df['ta_pattern_cdleveningdojistar'] = ta.CDLEVENINGDOJISTAR(
            open, high, low, close, penetration=0)
        df['ta_pattern_cdleveningstar'] = ta.CDLEVENINGSTAR(open,
                                                            high,
                                                            low,
                                                            close,
                                                            penetration=0)
        df['ta_pattern_cdlgapsidesidewhite'] = ta.CDLGAPSIDESIDEWHITE(
            open, high, low, close)
        df['ta_pattern_cdlgravestonedoji'] = ta.CDLGRAVESTONEDOJI(
            open, high, low, close)
        df['ta_pattern_cdlhammer'] = ta.CDLHAMMER(open, high, low, close)
        df['ta_pattern_cdlhangingman'] = ta.CDLHANGINGMAN(
            open, high, low, close)
        df['ta_pattern_cdlharami'] = ta.CDLHARAMI(open, high, low, close)
        df['ta_pattern_cdlharamicross'] = ta.CDLHARAMICROSS(
            open, high, low, close)
        df['ta_pattern_cdlhighwave'] = ta.CDLHIGHWAVE(open, high, low, close)
        df['ta_pattern_cdlhikkake'] = ta.CDLHIKKAKE(open, high, low, close)
        df['ta_pattern_cdlhikkakemod'] = ta.CDLHIKKAKEMOD(
            open, high, low, close)
        df['ta_pattern_cdlhomingpigeon'] = ta.CDLHOMINGPIGEON(
            open, high, low, close)
        df['ta_pattern_cdlidentical3crows'] = ta.CDLIDENTICAL3CROWS(
            open, high, low, close)
        df['ta_pattern_cdlinneck'] = ta.CDLINNECK(open, high, low, close)
        df['ta_pattern_cdlinvertedhammer'] = ta.CDLINVERTEDHAMMER(
            open, high, low, close)
        df['ta_pattern_cdlkicking'] = ta.CDLKICKING(open, high, low, close)
        df['ta_pattern_cdlkickingbylength'] = ta.CDLKICKINGBYLENGTH(
            open, high, low, close)
        df['ta_pattern_cdlladderbottom'] = ta.CDLLADDERBOTTOM(
            open, high, low, close)
        df['ta_pattern_cdllongleggeddoji'] = ta.CDLLONGLEGGEDDOJI(
            open, high, low, close)
        df['ta_pattern_cdllongline'] = ta.CDLLONGLINE(open, high, low, close)
        df['ta_pattern_cdlmarubozu'] = ta.CDLMARUBOZU(open, high, low, close)
        df['ta_pattern_cdlmatchinglow'] = ta.CDLMATCHINGLOW(
            open, high, low, close)
        df['ta_pattern_cdlmathold'] = ta.CDLMATHOLD(open,
                                                    high,
                                                    low,
                                                    close,
                                                    penetration=0)
        df['ta_pattern_cdlmorningdojistar'] = ta.CDLMORNINGDOJISTAR(
            open, high, low, close, penetration=0)
        df['ta_pattern_cdlmorningstar'] = ta.CDLMORNINGSTAR(open,
                                                            high,
                                                            low,
                                                            close,
                                                            penetration=0)
        df['ta_pattern_cdllonneck'] = ta.CDLONNECK(open, high, low, close)
        df['ta_pattern_cdlpiercing'] = ta.CDLPIERCING(open, high, low, close)
        df['ta_pattern_cdlrickshawman'] = ta.CDLRICKSHAWMAN(
            open, high, low, close)
        df['ta_pattern_cdlrisefall3methods'] = ta.CDLRISEFALL3METHODS(
            open, high, low, close)
        df['ta_pattern_cdlseparatinglines'] = ta.CDLSEPARATINGLINES(
            open, high, low, close)
        df['ta_pattern_cdlshootingstar'] = ta.CDLSHOOTINGSTAR(
            open, high, low, close)
        df['ta_pattern_cdlshortline'] = ta.CDLSHORTLINE(open, high, low, close)
        df['ta_pattern_cdlspinningtop'] = ta.CDLSPINNINGTOP(
            open, high, low, close)
        df['ta_pattern_cdlstalledpattern'] = ta.CDLSTALLEDPATTERN(
            open, high, low, close)
        df['ta_pattern_cdlsticksandwich'] = ta.CDLSTICKSANDWICH(
            open, high, low, close)
        df['ta_pattern_cdltakuri'] = ta.CDLTAKURI(open, high, low, close)
        df['ta_pattern_cdltasukigap'] = ta.CDLTASUKIGAP(open, high, low, close)
        df['ta_pattern_cdlthrusting'] = ta.CDLTHRUSTING(open, high, low, close)
        df['ta_pattern_cdltristar'] = ta.CDLTRISTAR(open, high, low, close)
        df['ta_pattern_cdlunique3river'] = ta.CDLUNIQUE3RIVER(
            open, high, low, close)
        df['ta_pattern_cdlupsidegap2crows'] = ta.CDLUPSIDEGAP2CROWS(
            open, high, low, close)
        df['ta_pattern_cdlxsidegap3methods'] = ta.CDLXSIDEGAP3METHODS(
            open, high, low, close)

    if ta_settings['statistic']:

        df['ta_statistic_beta'] = ta.BETA(high, low, timeperiod=5)
        df['ta_statistic_correl'] = ta.CORREL(high, low, timeperiod=30)
        df['ta_statistic_linearreg'] = ta.LINEARREG(close, timeperiod=14)
        df['ta_statistic_linearreg_angle'] = ta.LINEARREG_ANGLE(close,
                                                                timeperiod=14)
        df['ta_statistic_linearreg_intercept'] = ta.LINEARREG_INTERCEPT(
            close, timeperiod=14)
        df['ta_statistic_linearreg_slope'] = ta.LINEARREG_SLOPE(close,
                                                                timeperiod=14)
        df['ta_statistic_stddev'] = ta.STDDEV(close, timeperiod=5, nbdev=1)
        df['ta_statistic_tsf'] = ta.TSF(close, timeperiod=14)
        df['ta_statistic_var'] = ta.VAR(close, timeperiod=5, nbdev=1)

    if ta_settings['math_transforms']:

        df['ta_math_transforms_atan'] = ta.ATAN(close)
        df['ta_math_transforms_ceil'] = ta.CEIL(close)
        df['ta_math_transforms_cos'] = ta.COS(close)
        df['ta_math_transforms_floor'] = ta.FLOOR(close)
        df['ta_math_transforms_ln'] = ta.LN(close)
        df['ta_math_transforms_log10'] = ta.LOG10(close)
        df['ta_math_transforms_sin'] = ta.SIN(close)
        df['ta_math_transforms_sqrt'] = ta.SQRT(close)
        df['ta_math_transforms_tan'] = ta.TAN(close)

    if ta_settings['math_operators']:

        df['ta_math_operators_add'] = ta.ADD(high, low)
        df['ta_math_operators_div'] = ta.DIV(high, low)
        df['ta_math_operators_min'], df['ta_math_operators_max'] = ta.MINMAX(
            close, timeperiod=30)
        df['ta_math_operators_minidx'], df[
            'ta_math_operators_maxidx'] = ta.MINMAXINDEX(close, timeperiod=30)
        df['ta_math_operators_mult'] = ta.MULT(high, low)
        df['ta_math_operators_sub'] = ta.SUB(high, low)
        df['ta_math_operators_sum'] = ta.SUM(close, timeperiod=30)

    return df
# MOM
ti_MOM = talib.MOM(bars['price'].values, time_period)

# OBV
ti_OBV = talib.OBV(bars['price'].values, vol['volume'].values)

# PLUS_DI
ti_PLUS_DI = talib.PLUS_DI(bars['high'].values, bars['low'].values,\
 bars['close'].values, time_period)

# ROCP
ti_ROCP = talib.ROCP(bars['price'].values, time_period)

# ROCR
ti_ROCR = talib.ROCR(bars['price'].values, time_period)

# RSI
ti_RSI = talib.RSI(bars['price'].values, time_period)

# SMA
ti_SMA = talib.SMA(bars['price'].values, time_period)

# STOCHRSI
ti_FASTK, ti_FASTD = talib.STOCHRSI(bars['price'].values, time_period)

# TRANGE
ti_TRANGE = talib.TRANGE(bars['high'].values, bars['low'].values,\
                         bars['close'].values)

# TYPPRICE
def get_talib_stock_daily(
        stock_code,
        s,
        e,
        append_ori_close=False,
        norms=['volume', 'amount', 'ht_dcphase', 'obv', 'adosc', 'ad', 'cci']):
    """获取经过talib处理后的股票日线数据"""
    stock_data = QA.QA_fetch_stock_day_adv(stock_code, s, e)
    stock_df = stock_data.to_qfq().data
    if append_ori_close:
        stock_df['o_close'] = stock_data.data['close']
    # stock_df['high_qfq'] = stock_data.to_qfq().data['high']
    # stock_df['low_hfq'] = stock_data.to_hfq().data['low']

    close = np.array(stock_df['close'])
    high = np.array(stock_df['high'])
    low = np.array(stock_df['low'])
    _open = np.array(stock_df['open'])
    _volume = np.array(stock_df['volume'])

    stock_df['dema'] = talib.DEMA(close)
    stock_df['ema'] = talib.EMA(close)
    stock_df['ht_tradeline'] = talib.HT_TRENDLINE(close)
    stock_df['kama'] = talib.KAMA(close)
    stock_df['ma'] = talib.MA(close)
    stock_df['mama'], stock_df['fama'] = talib.MAMA(close)
    # MAVP
    stock_df['midpoint'] = talib.MIDPOINT(close)
    stock_df['midprice'] = talib.MIDPRICE(high, low)
    stock_df['sar'] = talib.SAR(high, low)
    stock_df['sarext'] = talib.SAREXT(high, low)
    stock_df['sma'] = talib.SMA(close)
    stock_df['t3'] = talib.T3(close)
    stock_df['tema'] = talib.TEMA(close)
    stock_df['trima'] = talib.TRIMA(close)
    stock_df['wma'] = talib.WMA(close)

    stock_df['adx'] = talib.ADX(high, low, close)
    stock_df['adxr'] = talib.ADXR(high, low, close)
    stock_df['apo'] = talib.APO(close)

    stock_df['aroondown'], stock_df['aroonup'] = talib.AROON(high, low)
    stock_df['aroonosc'] = talib.AROONOSC(high, low)
    stock_df['bop'] = talib.BOP(_open, high, low, close)
    stock_df['cci'] = talib.CCI(high, low, close)
    stock_df['cmo'] = talib.CMO(close)
    stock_df['dx'] = talib.DX(high, low, close)
    # MACD
    stock_df['macd'], stock_df['macdsignal'], stock_df[
        'macdhist'] = talib.MACDEXT(close)
    # MACDFIX
    stock_df['mfi'] = talib.MFI(high, low, close, _volume)
    stock_df['minus_di'] = talib.MINUS_DI(high, low, close)
    stock_df['minus_dm'] = talib.MINUS_DM(high, low)
    stock_df['mom'] = talib.MOM(close)
    stock_df['plus_di'] = talib.PLUS_DI(high, low, close)
    stock_df['plus_dm'] = talib.PLUS_DM(high, low)
    stock_df['ppo'] = talib.PPO(close)
    stock_df['roc'] = talib.ROC(close)
    stock_df['rocp'] = talib.ROCP(close)
    stock_df['rocr'] = talib.ROCR(close)
    stock_df['rocr100'] = talib.ROCR100(close)
    stock_df['rsi'] = talib.RSI(close)
    stock_df['slowk'], stock_df['slowd'] = talib.STOCH(high, low, close)
    stock_df['fastk'], stock_df['fastd'] = talib.STOCHF(high, low, close)
    # STOCHRSI - Stochastic Relative Strength Index
    stock_df['trix'] = talib.TRIX(close)
    stock_df['ultosc'] = talib.ULTOSC(high, low, close)
    stock_df['willr'] = talib.WILLR(high, low, close)

    stock_df['ad'] = talib.AD(high, low, close, _volume)
    stock_df['adosc'] = talib.ADOSC(high, low, close, _volume)
    stock_df['obv'] = talib.OBV(close, _volume)

    stock_df['ht_dcperiod'] = talib.HT_DCPERIOD(close)
    stock_df['ht_dcphase'] = talib.HT_DCPHASE(close)
    stock_df['inphase'], stock_df['quadrature'] = talib.HT_PHASOR(close)
    stock_df['sine'], stock_df['leadsine'] = talib.HT_PHASOR(close)
    stock_df['ht_trendmode'] = talib.HT_TRENDMODE(close)

    stock_df['avgprice'] = talib.AVGPRICE(_open, high, low, close)
    stock_df['medprice'] = talib.MEDPRICE(high, low)
    stock_df['typprice'] = talib.TYPPRICE(high, low, close)
    stock_df['wclprice'] = talib.WCLPRICE(high, low, close)

    stock_df['atr'] = talib.ATR(high, low, close)
    stock_df['natr'] = talib.NATR(high, low, close)
    stock_df['trange'] = talib.TRANGE(high, low, close)

    stock_df['beta'] = talib.BETA(high, low)
    stock_df['correl'] = talib.CORREL(high, low)
    stock_df['linearreg'] = talib.LINEARREG(close)
    stock_df['linearreg_angle'] = talib.LINEARREG_ANGLE(close)
    stock_df['linearreg_intercept'] = talib.LINEARREG_INTERCEPT(close)
    stock_df['linearreg_slope'] = talib.LINEARREG_SLOPE(close)
    stock_df['stddev'] = talib.STDDEV(close)
    stock_df['tsf'] = talib.TSF(close)
    stock_df['var'] = talib.VAR(close)

    stock_df = stock_df.reset_index().set_index('date')

    if norms:
        x = stock_df[norms].values  # returns a numpy array
        x_scaled = MinMaxScaler().fit_transform(x)
        stock_df = stock_df.drop(columns=norms).join(
            pd.DataFrame(x_scaled, columns=norms, index=stock_df.index))

    # stock_df = stock_df.drop(columns=['code', 'open', 'high', 'low'])
    stock_df = stock_df.dropna()
    stock_df = stock_df.drop(columns=['code'])
    return stock_df
Exemple #26
0
    def techIndi(self, gubun):
        try:
            daySqlOra = "SELECT NVL(MAX(SUBSTR(TRADE_TIME,1,8)),TO_CHAR(SYSDATE,'YYYYMMDD')) YMD FROM TRADE_TECH " \
                     "WHERE SUBSTR(TRADE_TIME,1,8) <> '%s' " \
                     % datetime.today().strftime("%Y%m%d")
            dateD = self.selectDB(daySqlOra)
            dateS = dateD[0][0]
        except Exception as e:
            e.msg = "techindi daySql 에러"
            print(e)

        try:
            sqlOra71 = "SELECT DISTINCT TRIM(A.STOCK_CODE) STOCK_CODE " \
                  "FROM TRADE_HOLD A " \
                  "WHERE A.YMD = '%s' " \
                  "  AND A.REQ_VOLUME <> 0" \
                  "  AND (A.EARNING_RATE >= 3 AND A.CURR_RATE >= 15)" \
                  "UNION " \
                  "SELECT DISTINCT TRIM(B.STOCK_CODE) STOCK_CODE " \
                  "FROM TRADE_LIST B " \
                  "WHERE B.YMD BETWEEN '%s' AND '%s' " \
                  "  AND B.BUY_AMT < %s * 0.9" % (datetime.today().strftime("%Y%m%d")
                                                  , dateS
                                                  , datetime.today().strftime("%Y%m%d")
                                                  , self.unitPrice)

            summaryG = self.selectDB(sqlOra71)
        except Exception as e:
            e.msg = "techIndi Sql 에러"
            print(e)

        print("-----------------------------------------------------------------")
        print("["+ datetime.today().strftime("%Y-%m-%d %H:%M:%S") + "] " + "Process2 : 보조지표 만들기 시작!" )

        try:
            if len(summaryG) > 0:
                for row_data in summaryG:
                    try:
                        if gubun == "장중":
                            sql = "SELECT RN, STOCK_CODE, TRADE_TIME,  START_PRICE, HIGH_PRICE, LOW_PRICE, CURRENT_PRICE, VOLUME " \
                                  "FROM ( " \
                                  "       SELECT A.*, ROW_NUMBER() OVER(PARTITION BY STOCK_CODE ORDER BY TRADE_TIME DESC) RN" \
                                  "                 , ROW_NUMBER() OVER(PARTITION BY STOCK_CODE ORDER BY TRADE_TIME ASC) RN2" \
                                  "         FROM TRADE_CRR A" \
                                  "        WHERE A.TRADE_TIME BETWEEN '%s' AND '%s' " \
                                  "          AND A.STOCK_CODE = '%s' " \
                                  "          AND A.STOCK_CODE NOT IN ('155960','900090') " \
                                  "      ) X " % (
                                      dateS + "090000"
                                      , datetime.today().strftime("%Y%m%d") + "160000", row_data[0])

                            sql2 = "WHERE RN BETWEEN 1 AND 130 " \
                                   "ORDER BY RN2"
                        else:
                            sql = "SELECT RN, STOCK_CODE, TRADE_TIME,  START_PRICE, HIGH_PRICE, LOW_PRICE, CURRENT_PRICE, VOLUME " \
                                  "FROM ( " \
                                  "       SELECT A.*, ROW_NUMBER() OVER(PARTITION BY STOCK_CODE ORDER BY TRADE_TIME DESC) RN" \
                                  "                 , ROW_NUMBER() OVER(PARTITION BY STOCK_CODE ORDER BY TRADE_TIME ASC) RN2" \
                                  "         FROM TRADE_CRR A" \
                                  "        WHERE 1=1 " \
                                  "          AND A.STOCK_CODE = '%s' " \
                                  "          AND A.STOCK_CODE NOT IN ('155960','900090') " \
                                  "      ) X " % row_data[0]

                            sql2 = "ORDER BY RN2"

                        summaryG = self.selectDB(sql + sql2)
                    except Exception as e:
                        print(e)

                    df = pd.DataFrame(summaryG)

                    try:
                        if len(df) > 0:
                            df.columns = ["rn", "stockCd", "tradeTime", "open", "high", "low", "close", "volume"]

                            # cloF = pd.Series(df.iloc[len(df) - 1]['open'], name='close')  # 3분봉 종가 만들어주는 로직
                            # clo = pd.Series(df.iloc[1:len(df)]['open'], name='close')
                            # clo = pd.DataFrame(clo.append(cloF))
                            # clo = clo.reset_index(drop=True)
                            #
                            # df = df.join(clo)

                            macd, macdsignal, macdhist = talib.MACD(df['close'], fastperiod=12, slowperiod=26,
                                                                    signalperiod=9)
                            slowk, slowd = talib.STOCH(df['high'], df['low'], df['close'], fastk_period=5, slowk_period=3,
                                                       slowk_matype=3,
                                                       slowd_period=3, slowd_matype=0)
                            fastk, fastd = talib.STOCHF(df['high'], df['low'], df['close'], fastk_period=20,
                                                        fastd_period=10)
                            sma5 = talib.SMA(df['close'], 5)
                            sma10 = talib.SMA(df['close'], 10)
                            sma20 = talib.SMA(df['close'], 20)
                            sma60 = talib.SMA(df['close'], 60)
                            sma120 = talib.SMA(df['close'], 120)
                            cci = talib.CCI(df['high'], df['low'], df['close'], 20)
                            rsi = talib.RSI(df['close'], 14)
                            roc1 = talib.ROC(df['close'], 1)
                            roc5 = talib.ROC(df['close'], 5)
                            rocr1 = talib.ROCR(df['close'], 1)
                            rocr5 = talib.ROCR(df['close'], 5)

                            df = df.join(pd.DataFrame(pd.Series(macd, name="MACD")))
                            df = df.join(pd.DataFrame(pd.Series(macdsignal, name="MACDSIG")))
                            df = df.join(pd.DataFrame(pd.Series(slowd, name="SLOWD")))
                            df = df.join(pd.DataFrame(pd.Series(fastd, name="FASTD")))
                            df = df.join(pd.DataFrame(pd.Series(sma5, name="SMA5")))
                            df = df.join(pd.DataFrame(pd.Series(sma10, name="SMA10")))
                            df = df.join(pd.DataFrame(pd.Series(sma20, name="SMA20")))
                            df = df.join(pd.DataFrame(pd.Series(sma60, name="SMA60")))
                            df = df.join(pd.DataFrame(pd.Series(sma120, name="SMA120")))
                            df = df.join(pd.DataFrame(pd.Series(cci, name="CCI")))
                            df = df.join(pd.DataFrame(pd.Series(rsi, name="RSI")))
                            df = df.join(pd.DataFrame(pd.Series(roc1, name="ROC1")))
                            df = df.join(pd.DataFrame(pd.Series(roc5, name="ROC5")))
                            df = df.join(pd.DataFrame(pd.Series(rocr1, name="ROCR1")))
                            df = df.join(pd.DataFrame(pd.Series(rocr5, name="ROCR5")))

                            df = df.fillna(0)

                            try:
                                for i in range(4, len(df)):
                                    if df.iloc[i]['SMA10'] == 0:
                                        dis10 = 0
                                    else:
                                        dis10 = float(df.iloc[i]['close']) / float(df.iloc[i]['SMA10']) * 100

                                    if df.iloc[i]['SMA20'] == 0:
                                        dis20 = 0
                                    else:
                                        dis20 = float(df.iloc[i]['close']) / float(df.iloc[i]['SMA20']) * 100

                                    file = open("C:/Users/jini/sqlOra72.sql", 'r') # TRADE_TECH에 데이터 넣기
                                    sqlOra72 = ''
                                    line = file.readline()
                                    while line:
                                        sqlOra72 += ' ' + line.strip('\n').strip('\t')
                                        line = file.readline()

                                    file.close()

                                    sqlOra72 = sqlOra72 % (
                                               df.iloc[i]['tradeTime'], df.iloc[i]['stockCd']
                                               , df.iloc[i - 3]['high'], df.iloc[i - 2]['high'], df.iloc[i - 1]['high']
                                               , df.iloc[i]['high'], df.iloc[i - 3]['low'], df.iloc[i - 2]['low'],
                                               df.iloc[i - 1]['low']
                                               , df.iloc[i]['low'], df.iloc[i - 3]['open'], df.iloc[i - 2]['open'],
                                               df.iloc[i - 1]['open']
                                               , df.iloc[i]['open'], df.iloc[i - 3]['close'], df.iloc[i - 2]['close']
                                               , df.iloc[i - 1]['close'], df.iloc[i]['close'], df.iloc[i - 3]['volume']
                                               , df.iloc[i - 2]['volume'], df.iloc[i - 1]['volume'],
                                               df.iloc[i]['volume']
                                               , (df.iloc[i - 2]['high'] - df.iloc[i - 3]['high']) / df.iloc[i - 3][
                                                   'high']
                                               , (df.iloc[i - 1]['high'] - df.iloc[i - 2]['high']) / df.iloc[i - 2][
                                                   'high']
                                               , (df.iloc[i]['high'] - df.iloc[i - 1]['high']) / df.iloc[i - 1]['high']
                                               , (df.iloc[i]['high'] - df.iloc[i - 3]['high']) / df.iloc[i - 3]['high']
                                               , (df.iloc[i]['high'] - df.iloc[i - 2]['high']) / df.iloc[i - 2]['high']
                                               , (df.iloc[i - 2]['low'] - df.iloc[i - 3]['low']) / df.iloc[i - 3]['low']
                                               , (df.iloc[i - 1]['low'] - df.iloc[i - 2]['low']) / df.iloc[i - 2]['low']
                                               , (df.iloc[i]['low'] - df.iloc[i - 1]['low']) / df.iloc[i - 1]['low']
                                               , (df.iloc[i]['low'] - df.iloc[i - 3]['low']) / df.iloc[i - 3]['low']
                                               , (df.iloc[i]['low'] - df.iloc[i - 2]['low']) / df.iloc[i - 2]['low']
                                               , df.iloc[i]['SMA5'], df.iloc[i]['SMA10'], df.iloc[i]['SMA20'], df.iloc[i]['SMA60']
                                               , df.iloc[i]['SMA120'], df.iloc[i]['RSI'], df.iloc[i]['CCI']
                                               , float(dis10)
                                               , float(dis20)
                                               , df.iloc[i]['MACD'], df.iloc[i]['MACDSIG'], df.iloc[i]['SLOWD'], df.iloc[i]['FASTD']
                                               , (max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high']) - min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low']))
                                               /  min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low']) * 100
                                               , df.iloc[i]['MACD'] - df.iloc[i]['MACDSIG']
                                               , (df.iloc[i]['close'] - df.iloc[i]['high']) * 100 / df.iloc[i]['high']
                                               , (df.iloc[i]['close'] - max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])) * 100
                                               / max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])
                                               , (df.iloc[i]['open'] - max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])) * 100
                                               / max(df.iloc[i]['high'],df.iloc[i-1]['high'],df.iloc[i-2]['high'],df.iloc[i-3]['high'])
                                               , (df.iloc[i]['close'] - min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low'])) * 100
                                               / min(df.iloc[i]['low'],df.iloc[i-1]['low'],df.iloc[i-2]['low'])
                                               , df.iloc[i]['tradeTime'])

                                    try:
                                        self.updateDB(sqlOra72)
                                    except Exception as e:
                                        print(e)
                            except Exception as e:
                                print(e)

                    except Exception as e:
                        print(e)

        except Exception as e:
            print(e)

        print("["+ datetime.today().strftime("%Y-%m-%d %H:%M:%S") + "] " + "Process2 : 보조지표 만들기 끝!" )
Exemple #27
0
def third_making_indicator_5min(dataframe):
    Open_lis = np.array(dataframe['open'], dtype='float')
    High_lis = np.array(dataframe['high'], dtype='float')
    Low_lis = np.array(dataframe['low'], dtype='float')
    Clz_lis = np.array(dataframe['weigted_price'], dtype='float')
    Vol_lis = np.array(dataframe['volume'], dtype='float')

    ##지표##
    SMA_3_C = ta.SMA(Clz_lis, timeperiod=3)
    SMA_5_H = ta.SMA(High_lis, timeperiod=5)
    SMA_5_L = ta.SMA(Low_lis, timeperiod=5)
    SMA_5_C = ta.SMA(Clz_lis, timeperiod=5)
    SMA_10_H = ta.SMA(High_lis, timeperiod=10)
    SMA_10_L = ta.SMA(Low_lis, timeperiod=10)
    SMA_10_C = ta.SMA(Clz_lis, timeperiod=10)
    RSI_2_C = ta.RSI(Clz_lis, timeperiod=2)
    RSI_3_C = ta.RSI(Clz_lis, timeperiod=3)
    RSI_5_C = ta.RSI(Clz_lis, timeperiod=5)
    RSI_7_H = ta.RSI(High_lis, timeperiod=7)
    RSI_7_L = ta.RSI(Low_lis, timeperiod=7)
    RSI_7_C = ta.RSI(Clz_lis, timeperiod=7)
    RSI_14_H = ta.RSI(High_lis, timeperiod=14)
    RSI_14_L = ta.RSI(Low_lis, timeperiod=14)
    RSI_14_C = ta.RSI(Clz_lis, timeperiod=14)
    ADX = ta.ADX(High_lis, Low_lis, Clz_lis, timeperiod=14)
    ADXR = ta.ADXR(High_lis, Low_lis, Clz_lis, timeperiod=14)
    Aroondown, Aroonup = ta.AROON(High_lis, Low_lis, timeperiod=14)
    Aroonosc = ta.AROONOSC(High_lis, Low_lis, timeperiod=14)
    BOP = ta.BOP(Open_lis, High_lis, Low_lis, Clz_lis)
    CMO = ta.CMO(Clz_lis, timeperiod=14)
    DX = ta.DX(High_lis, Low_lis, Clz_lis, timeperiod=14)
    MFI = ta.MFI(High_lis, Low_lis, Clz_lis, Vol_lis, timeperiod=14)
    MINUS_DI = ta.MINUS_DI(High_lis, Low_lis, Clz_lis, timeperiod=14)
    PLUSDI = ta.PLUS_DI(High_lis, Low_lis, Clz_lis, timeperiod=14)
    PPO = ta.PPO(Clz_lis, fastperiod=12, slowperiod=26, matype=0)
    ROC = ta.ROC(Clz_lis, timeperiod=10)
    ROCP = ta.ROCP(Clz_lis, timeperiod=10)
    ROCR = ta.ROCR(Clz_lis, timeperiod=10)
    ROCR100 = ta.ROCR100(Clz_lis, timeperiod=10)
    Slowk, Slowd = ta.STOCH(High_lis,
                            Low_lis,
                            Clz_lis,
                            fastk_period=5,
                            slowk_period=3,
                            slowk_matype=0,
                            slowd_period=3,
                            slowd_matype=0)
    STOCHF_f, STOCHF_d = ta.STOCHF(High_lis,
                                   Low_lis,
                                   Clz_lis,
                                   fastk_period=5,
                                   fastd_period=3,
                                   fastd_matype=0)
    Fastk, Fastd = ta.STOCHRSI(Clz_lis,
                               timeperiod=14,
                               fastk_period=5,
                               fastd_period=3,
                               fastd_matype=0)
    TRIX = ta.TRIX(Clz_lis, timeperiod=30)
    ULTOSC = ta.ULTOSC(High_lis,
                       Low_lis,
                       Clz_lis,
                       timeperiod1=7,
                       timeperiod2=14,
                       timeperiod3=28)
    WILLR = ta.WILLR(High_lis, Low_lis, Clz_lis, timeperiod=14)
    ADOSC = ta.ADOSC(High_lis,
                     Low_lis,
                     Clz_lis,
                     Vol_lis,
                     fastperiod=3,
                     slowperiod=10)
    NATR = ta.NATR(High_lis, Low_lis, Clz_lis, timeperiod=14)
    HT_DCPERIOD = ta.HT_DCPERIOD(Clz_lis)
    sine, leadsine = ta.HT_SINE(Clz_lis)
    integer = ta.HT_TRENDMODE(Clz_lis)

    ########
    #append
    dataframe['SMA_3_C'] = SMA_3_C
    dataframe['SMA_5_H'] = SMA_5_H
    dataframe['SMA_5_L'] = SMA_5_L
    dataframe['SMA_5_C'] = SMA_5_C
    dataframe['SMA_10_H'] = SMA_10_H
    dataframe['SMA_10_L'] = SMA_10_L
    dataframe['SMA_10_C'] = SMA_10_C
    dataframe['RSI_2_C'] = (RSI_2_C / 100.) * 2 - 1.
    dataframe['RSI_3_C'] = (RSI_3_C / 100.) * 2 - 1.
    dataframe['RSI_5_C'] = (RSI_5_C / 100.) * 2 - 1.
    dataframe['RSI_7_H'] = (RSI_7_H / 100.) * 2 - 1.
    dataframe['RSI_7_L'] = (RSI_7_L / 100.) * 2 - 1.
    dataframe['RSI_7_C'] = (RSI_7_C / 100.) * 2 - 1.
    dataframe['RSI_14_H'] = (RSI_14_H / 100.) * 2 - 1.
    dataframe['RSI_14_L'] = (RSI_14_L / 100.) * 2 - 1.
    dataframe['RSI_14_C'] = (RSI_14_C / 100.) * 2 - 1.
    dataframe['ADX'] = (ADX / 100.) * 2 - 1.
    dataframe['ADXR'] = (ADXR / 100.) * 2 - 1.
    dataframe['Aroondown'] = (Aroondown / 100.) * 2 - 1
    dataframe['Aroonup'] = (Aroonup / 100.) * 2 - 1
    dataframe['Aroonosc'] = Aroonosc / 100.
    dataframe['BOP'] = BOP
    dataframe['CMO'] = CMO / 100.
    dataframe['DX'] = (DX / 100.) * 2 - 1
    dataframe['MFI'] = (MFI / 100.) * 2 - 1
    dataframe['MINUS_DI'] = (MINUS_DI / 100.) * 2 - 1
    dataframe['PLUSDI'] = (PLUSDI / 100.) * 2 - 1
    dataframe['PPO'] = PPO / 10.
    dataframe['ROC'] = ROC / 10.
    dataframe['ROCP'] = ROCP * 10
    dataframe['ROCR'] = (ROCR - 1.0) * 100.
    dataframe['ROCR100'] = ((ROCR100 / 100.) - 1.0) * 100.
    dataframe['Slowk'] = (Slowk / 100.) * 2 - 1
    dataframe['Slowd'] = (Slowd / 100.) * 2 - 1
    dataframe['STOCHF_f'] = (STOCHF_f / 100.) * 2 - 1
    dataframe['STOCHF_d'] = (STOCHF_d / 100.) * 2 - 1
    dataframe['Fastk'] = (Fastk / 100.) * 2 - 1
    dataframe['Fastd'] = (Fastd / 100.) * 2 - 1
    dataframe['TRIX'] = TRIX * 10.
    dataframe['ULTOSC'] = (ULTOSC / 100.) * 2 - 1
    dataframe['WILLR'] = (WILLR / 100.) * 2 + 1
    dataframe['ADOSC'] = ADOSC / 100.
    dataframe['NATR'] = NATR * 2 - 1
    dataframe['HT_DCPERIOD'] = (HT_DCPERIOD / 100.) * 2 - 1
    dataframe['sine'] = sine
    dataframe['leadsine'] = leadsine
    dataframe['integer'] = integer

    return dataframe
Exemple #28
0
     resorted['close'])
 mfi_real = talib.MFI(resorted['high'], resorted['low'],
                      resorted['close'], resorted['volume'])
 minus_di_real = talib.MINUS_DI(resorted['high'],
                                resorted['low'],
                                resorted['close'])
 minus_dm_real = talib.MINUS_DM(resorted['high'],
                                resorted['low'])
 mom_real = talib.MOM(resorted['close'])
 plus_di_real = talib.PLUS_DI(resorted['high'], resorted['low'],
                              resorted['close'])
 plus_dm_real = talib.PLUS_DM(resorted['high'], resorted['low'])
 ppo_real = talib.PPO(resorted['close'])
 roc_real = talib.ROC(resorted['close'])
 rocp_real = talib.ROCP(resorted['close'])
 rocr_real = talib.ROCR(resorted['close'])
 rocr100_real = talib.ROCR100(resorted['close'])
 rsi_real = talib.RSI(resorted['close'])
 slowk_real, slowd_real = talib.STOCH(resorted['high'],
                                      resorted['low'],
                                      resorted['close'])
 fastk_real, fastd_real = talib.STOCHF(resorted['high'],
                                       resorted['low'],
                                       resorted['close'])
 fastk_rsi_real, fastd_rsi_real = talib.STOCHRSI(
     resorted['close'])
 trix_real = talib.TRIX(resorted['close'])
 ultosc_real = talib.ULTOSC(resorted['high'], resorted['low'],
                            resorted['close'])
 willr_real = talib.WILLR(resorted['high'], resorted['low'],
                          resorted['close'])
                             timeperiod=n)
df['MOM'] = ta.MOM(np.array(df['Adj Close'].shift(1)), timeperiod=n)
df['PLUS_DI'] = ta.PLUS_DI(np.array(df['High'].shift(1)),
                           np.array(df['Low'].shift(1)),
                           np.array(df['Adj Close'].shift(1)),
                           timeperiod=n)
df['PLUS_DM'] = ta.PLUS_DM(np.array(df['High'].shift(1)),
                           np.array(df['Low'].shift(1)),
                           timeperiod=n)
df['PPO'] = ta.PPO(np.array(df['Adj Close'].shift(1)),
                   fastperiod=12,
                   slowperiod=26,
                   matype=0)
df['ROC'] = ta.ROC(np.array(df['Adj Close'].shift(1)), timeperiod=n)
df['ROCP'] = ta.ROCP(np.array(df['Adj Close'].shift(1)), timeperiod=n)
df['ROCR'] = ta.ROCR(np.array(df['Adj Close'].shift(1)), timeperiod=n)
df['ROCR100'] = ta.ROCR100(np.array(df['Adj Close'].shift(1)), timeperiod=n)
df['slowk'], df['slowd'] = ta.STOCH(np.array(df['High'].shift(1)),
                                    np.array(df['Low'].shift(1)),
                                    np.array(df['Adj Close']),
                                    fastk_period=5,
                                    slowk_period=3,
                                    slowk_matype=0,
                                    slowd_period=3,
                                    slowd_matype=0)
df['fastk'], df['fastd'] = ta.STOCHF(np.array(df['High'].shift(1)),
                                     np.array(df['Low'].shift(1)),
                                     np.array(df['Adj Close']),
                                     fastk_period=5,
                                     fastd_period=3,
                                     fastd_matype=0)
Exemple #30
0
 def ROCR(Close, timeperiod=10):
     return Close.apply(lambda col: ta.ROCR(col, timeperiod), axis=0)