Exemplo n.º 1
0
    def preproc(self):
        self.dat = df = pd.read_csv(self.path)
        s = np.asanyarray(ta.stoch(
            df["High"], df["Low"], df["Close"], 14)).reshape(
                (-1, 1)) - np.asanyarray(
                    ta.stoch_signal(df["High"], df["Low"], df["Close"],
                                    14)).reshape((-1, 1))
        m = np.asanyarray(ta.macd(df["Close"])).reshape(
            (-1, 1)) - np.asanyarray(ta.macd_signal(df["Close"])).reshape(
                (-1, 1))
        trend3 = np.asanyarray(self.dat[["Close"]]) - np.asanyarray(
            ta.ema(self.dat["Close"], 20)).reshape((-1, 1))
        cross1 = np.asanyarray(ta.ema(self.dat["Close"], 20)).reshape(
            (-1, 1)) - np.asanyarray(ta.ema(self.dat["Close"], 5)).reshape(
                (-1, 1))
        y = np.asanyarray(self.dat[["Open"]])
        x = np.concatenate([s, m, cross1], 1)

        gen = tf.keras.preprocessing.sequence.TimeseriesGenerator(
            x, y, self.window_size)
        self.x = []
        self.y = []
        for i in gen:
            self.x.extend(i[0].tolist())
            self.y.extend(i[1].tolist())
        self.x = np.asanyarray(
            self.x)  #.reshape((-1, self.window_size, x.shape[-1]))
        self.y = np.asanyarray(self.y)

        self.df = self.x
        self.trend = self.y
Exemplo n.º 2
0
 def macd():
     macd = ta.macd(close, n_fast=12, n_slow=26, fillna=False)
     macd_sig = ta.macd_signal(close,
                               n_fast=12,
                               n_slow=26,
                               n_sign=9,
                               fillna=False)
     if macd[-1] > macd_sig[-1]:
         trn_macd_status = "Buy"
     elif macd[-1] < macd_sig[-1]:
         trn_macd_status = "Sell"
     else:
         trn_macd_status = "Hold"
     return trn_macd_status
Exemplo n.º 3
0
    def do_ta(self, data_series):

        open = Series(data_series['open'].astype('float64'))
        high = Series(data_series['high'].astype('float64'))
        low = Series(data_series['low'].astype('float64'))
        close = Series(data_series['close'].astype('float64'))

        #      Trend
        # ----------------
        ema30 = ta.ema(series=close, periods=30)
        ema50 = ta.ema(series=close, periods=50)
        ema100 = ta.ema(series=close, periods=100)
        ema200 = ta.ema(series=close, periods=200)
        macd_diff = ta.macd_diff(close=close, n_fast=12, n_slow=26, n_sign=9)
        macd_signal = ta.macd_signal(close=close,
                                     n_fast=12,
                                     n_slow=26,
                                     n_sign=9)

        data_series['ema30'] = ema30
        data_series['ema50'] = ema50
        data_series['ema100'] = ema100
        data_series['ema200'] = ema200
        data_series['macd_diff'] = macd_diff
        data_series['macd_signal'] = macd_signal

        #     Momentum
        # ----------------
        rsi = ta.rsi(close=close)
        stochastic = ta.stoch(high=high, low=low, close=close)

        data_series['rsi'] = rsi
        data_series['stochastic'] = stochastic

        #    Volatility
        # ----------------
        bollinger_h = ta.bollinger_hband(close=close)
        bollinger_l = ta.bollinger_lband(close=close)
        bollinger_h_indicator = ta.bollinger_hband_indicator(close=close)
        bollinger_l_indicator = ta.bollinger_lband_indicator(close=close)

        data_series['bollinger_h'] = bollinger_h
        data_series['bollinger_l'] = bollinger_l
        data_series['bollinger_h_indicator'] = bollinger_h_indicator
        data_series['bollinger_l_indicator'] = bollinger_l_indicator
        data_series['last_candle_change'] = self.lcc(close=close)

        return data_series
Exemplo n.º 4
0
    def __init__(self,
                 prices,
                 balance,
                 atr_period=48,
                 fast_period=12,
                 slow_period=26,
                 signal_period=9,
                 max_entry=1,
                 **kwargs):
        self.name = 'SMA strategy'
        self.prices = prices
        self.balance = balance

        self.signals = pd.DataFrame()
        self.signals['ATR'] = ta.average_true_range(self.prices['High'],
                                                    self.prices['Low'],
                                                    self.prices['Close'],
                                                    n=atr_period)
        self.signals['MACD'] = ta.macd(self.prices['Close'],
                                       n_fast=fast_period,
                                       n_slow=slow_period)
        self.signals['MACD_SIG'] = ta.macd_signal(self.prices['Close'],
                                                  n_fast=fast_period,
                                                  n_slow=slow_period,
                                                  n_sign=signal_period)
        self.signals['MACD_HIST'] = ta.macd_diff(self.prices['Close'],
                                                 n_fast=fast_period,
                                                 n_slow=slow_period,
                                                 n_sign=signal_period)
        self.signals['MACD'].fillna(0)

        self.init_period = slow_period
        self.stop_period = 10

        self.max_entry = max_entry
        self.gamma_z = 0.1

        self.entrySig = [0]
        self.exitSig = [0]
        self.stopSig = [0]
        self.unit = np.zeros(len(self.prices))

        self.entryFlag = False
        self.entryPrice = None
        self.entryCounter = 0
def analyze(data):

    # Moving average (5, 20, 75 days)
    sma5 = data['close'].rolling(window=5).mean()
    sma20 = data['close'].rolling(window=20).mean()
    sma75 = data['close'].rolling(window=75).mean()

    # MACD (12, 26 days)
    macd12_26 = ta.macd(data['close'], n_fast=12, n_slow=26)
    macd12_26_sig = ta.macd_signal(data['close'],
                                   n_fast=12,
                                   n_slow=26,
                                   n_sign=9)

    # Stochastics (%K: 5(not used), 9(not used), 14 day, %D: 3 days)
    stoch14_k = ta.stoch(data['high'], data['low'], data['close'], n=14)
    stoch14_d = ta.stoch_signal(data['high'],
                                data['low'],
                                data['close'],
                                n=14,
                                d_n=3)

    # Bollinger band (+3 sigma ~ -3 sigma)
    bb20_h1 = ta.bollinger_hband(data['close'], n=20, ndev=1)
    bb20_h2 = ta.bollinger_hband(data['close'], n=20, ndev=2)
    bb20_h3 = ta.bollinger_hband(data['close'], n=20, ndev=3)
    bb20_l1 = ta.bollinger_lband(data['close'], n=20, ndev=1)
    bb20_l2 = ta.bollinger_lband(data['close'], n=20, ndev=2)
    bb20_l3 = ta.bollinger_lband(data['close'], n=20, ndev=3)

    # Concatenate
    analysis = pd.concat([
        sma5, sma20, sma75, macd12_26, macd12_26_sig, stoch14_k, stoch14_d,
        bb20_h1, bb20_h2, bb20_h3, bb20_l1, bb20_l2, bb20_l3
    ],
                         axis=1)
    analysis.columns = [
        '5-Day SMA', '20-Day SMA', '75-Day SMA', 'MACD (12-16)',
        'MACD Signal (12-26-9)', 'Stochastics %K (14 Day)',
        'Stochastics %D (14 Day)', 'BB +1sigma', 'BB +2sigma', 'BB +3sigma',
        'BB -1sigma', 'BB -2sigma', 'BB -3sigma'
    ]

    return analysis
Exemplo n.º 6
0
df = df.dropna().reset_index().sort_values('Date')

ta_df = pd.DataFrame()

ta_df['RSI'] = ta.rsi(df["Close"])
ta_df['MFI'] = ta.money_flow_index(
    df["High"], df["Low"], df["Close"], df["Volume BTC"])
ta_df['TSI'] = ta.tsi(df["Close"])
ta_df['UO'] = ta.uo(df["High"], df["Low"], df["Close"])
ta_df['Stoch'] = ta.stoch(df["High"], df["Low"], df["Close"])
ta_df['Stoch_Signal'] = ta.stoch_signal(df["High"], df["Low"], df["Close"])
ta_df['WR'] = ta.wr(df["High"], df["Low"], df["Close"])
ta_df['AO'] = ta.ao(df["High"], df["Low"])

ta_df['MACD'] = ta.macd(df["Close"])
ta_df['MACD_signal'] = ta.macd_signal(df["Close"])
ta_df['MACD_diff'] = ta.macd_diff(df["Close"])
ta_df['EMA_fast'] = ta.ema_indicator(df["Close"])
ta_df['EMA_slow'] = ta.ema_indicator(df["Close"])
ta_df['Vortex_pos'] = ta.vortex_indicator_pos(
    df["High"], df["Low"], df["Close"])
ta_df['Vortex_neg'] = ta.vortex_indicator_neg(
    df["High"], df["Low"], df["Close"])
ta_df['Vortex_diff'] = abs(
    ta_df['Vortex_pos'] -
    ta_df['Vortex_neg'])
ta_df['Trix'] = ta.trix(df["Close"])
ta_df['Mass_index'] = ta.mass_index(df["High"], df["Low"])
ta_df['CCI'] = ta.cci(df["High"], df["Low"], df["Close"])
ta_df['DPO'] = ta.dpo(df["Close"])
ta_df['KST'] = ta.kst(df["Close"])
Exemplo n.º 7
0
def get_data(context, data_, window):
    # Crear ventana de datos.

    h1 = data_.history(
        context.symbols,
        context.row_features,
        bar_count=window,
        frequency=str(context.bar_period) + "T",
    )

    h1 = h1.swapaxes(2, 0)

    norm_data = []
    close_prices = []

    for i, asset in enumerate(context.assets):
        data = h1.iloc[i]
        close = h1.iloc[i].close
        if context.include_ha:
            ha = heikenashi(data)
            data = pd.concat((data, ha), axis=1)

        for period in [3, 6, 8, 10, 15, 20]:
            data["rsi" + str(period)] = ta.rsi(data.close,
                                               n=period,
                                               fillna=True)
            data["stoch" + str(period)] = ta.stoch(data.high,
                                                   data.low,
                                                   data.close,
                                                   n=period,
                                                   fillna=True)
            data["stoch_signal" + str(period)] = ta.stoch_signal(
                high=data.high,
                low=data.low,
                close=data.close,
                n=period,
                d_n=3,
                fillna=True)

            data["dpo" + str(period)] = ta.dpo(close=data.close,
                                               n=period,
                                               fillna=True)
            data["atr" + str(period)] = ta.average_true_range(high=data.high,
                                                              low=data.low,
                                                              close=data.close,
                                                              n=period,
                                                              fillna=True)

        for period in [6, 7, 8, 9, 10]:
            data["williams" + str(period)] = ta.wr(high=data.high,
                                                   low=data.low,
                                                   close=data.close,
                                                   lbp=period,
                                                   fillna=True)
        for period in [12, 13, 14, 15]:
            data["proc" + str(period)] = ta.trix(close=data.close,
                                                 n=period,
                                                 fillna=True)

        data["macd_diff"] = ta.macd_diff(close=data.close,
                                         n_fast=15,
                                         n_slow=30,
                                         n_sign=9,
                                         fillna=True)

        data["macd_signal"] = ta.macd_signal(close=data.close,
                                             n_fast=15,
                                             n_slow=30,
                                             n_sign=9,
                                             fillna=True)

        data["bb_high_indicator"] = ta.bollinger_hband_indicator(
            close=data.close, n=15, ndev=2, fillna=True)

        data["bb_low_indicator"] = ta.bollinger_lband_indicator(
            close=data.close, n=15, ndev=2, fillna=True)

        data["dc_high_indicator"] = ta.donchian_channel_hband_indicator(
            close=data.close, n=20, fillna=True)

        data["dc_low_indicator"] = ta.donchian_channel_lband_indicator(
            close=data.close, n=20, fillna=True)

        data["ichimoku_a"] = ta.ichimoku_a(high=data.high,
                                           low=data.low,
                                           n1=9,
                                           n2=26,
                                           fillna=True)

        data.fillna(method="bfill")

        # Normalizar los valores
        for feature in data.columns:
            norm_feature = preprocessing.normalize(
                data[feature].values.reshape(-1, 1), axis=0)
            data[feature] = pd.DataFrame(data=norm_feature,
                                         index=data.index,
                                         columns=[feature])

        norm_data.append(data.values)
        close_prices.append(close)
        context.features = data.columns

    return np.array(norm_data), np.array(close_prices)
Exemplo n.º 8
0
                                                      fillna=True)
X['average_true_range'] = ta.average_true_range(price['High'],
                                                price['Low'],
                                                price['Adj. Close'],
                                                n=14,
                                                fillna=True)
# X['KCU'] = ta.keltner_channel_hband_indicator(price['High'], price['Low'], price['Adj. Close'], n=10, fillna=True)
X['keltner_channel_lband_indicator'] = ta.keltner_channel_lband_indicator(
    price['High'], price['Low'], price['Adj. Close'], n=10, fillna=True)
X['donchian_channel_hband_indicator'] = ta.donchian_channel_hband_indicator(
    price['Adj. Close'], n=20, fillna=True)
X['donchian_channel_lband_indicator'] = ta.donchian_channel_lband_indicator(
    price['Adj. Close'], n=20, fillna=True)
X['macd_signal'] = ta.macd_signal(price['Adj. Close'],
                                  n_fast=12,
                                  n_slow=26,
                                  n_sign=9,
                                  fillna=True)
X['adx_pos'] = ta.adx_pos(price['High'],
                          price['Low'],
                          price['Adj. Close'],
                          n=14,
                          fillna=True)
X['adx_neg'] = ta.adx_neg(price['High'],
                          price['Low'],
                          price['Adj. Close'],
                          n=14,
                          fillna=True)
X['vortex_indicator_neg'] = ta.vortex_indicator_neg(price['High'],
                                                    price['Low'],
                                                    price['Adj. Close'],
    def get_trayectory(self, t_intervals):
        """
        :param t_intervals: número de intervalos en cada trayectoria
        :return: Datos con características de la trayectoria sintética y precios de cierre en bruto de al misma
        """
        trayectories = []
        closes = []
        p = True
        for i, asset in enumerate(self.context.assets):
            synthetic_return = np.exp(
                self.drift[i] + self.stdev[i] * norm.ppf(np.random.rand((t_intervals * self.frequency) + self.frequency, 1)))
            initial_close = self.close[i, -1]
            synthetic_close = np.zeros_like(synthetic_return)
            synthetic_close[0] = initial_close

            for t in range(1, synthetic_return.shape[0]):
                synthetic_close[t] = synthetic_close[t - 1] * synthetic_return[t]

            OHLC = []

            for t in range(synthetic_return.shape[0]):
                if t % self.frequency == 0 and t > 0:
                    open = synthetic_close[t - self.frequency]
                    high = np.max(synthetic_close[t - self.frequency: t])
                    low = np.min(synthetic_close[t - self.frequency: t])
                    close = synthetic_close[t]

                    OHLC.append([open, high, close, low])

            data = pd.DataFrame(data=OHLC, columns=["open", "high", "low", "close"])

            close = data.close

            if self.context.include_ha:
                ha = heikenashi(data)
                data = pd.concat((data, ha), axis=1)

            for period in [3, 6, 8, 10, 15, 20]:
                data["rsi" + str(period)] = ta.rsi(data.close, n=period, fillna=True)
                data["stoch" + str(period)] = ta.stoch(data.high, data.low, data.close, n=period, fillna=True)
                data["stoch_signal" + str(period)] = ta.stoch_signal(high=data.high,
                                                                     low=data.low,
                                                                     close=data.close,
                                                                     n=period,
                                                                     d_n=3,
                                                                     fillna=True)

                data["dpo" + str(period)] = ta.dpo(close=data.close,
                                                   n=period,
                                                   fillna=True)

                data["atr" + str(period)] = ta.average_true_range(high=data.high,
                                                                  low=data.low,
                                                                  close=data.close,
                                                                  n=period,
                                                                  fillna=True)

            for period in [6, 7, 8, 9, 10]:
                data["williams" + str(period)] = ta.wr(high=data.high,
                                                       low=data.low,
                                                       close=data.close,
                                                       lbp=period,
                                                       fillna=True)
            for period in [12, 13, 14, 15]:
                data["proc" + str(period)] = ta.trix(close=data.close,
                                                     n=period,
                                                     fillna=True)

            data["macd_diff"] = ta.macd_diff(close=data.close,
                                             n_fast=15,
                                             n_slow=30,
                                             n_sign=9,
                                             fillna=True)

            data["macd_signal"] = ta.macd_signal(close=data.close,
                                                 n_fast=15,
                                                 n_slow=30,
                                                 n_sign=9,
                                                 fillna=True)

            data["bb_high_indicator"] = ta.bollinger_hband_indicator(close=data.close,
                                                                     n=15,
                                                                     ndev=2,
                                                                     fillna=True)

            data["bb_low_indicator"] = ta.bollinger_lband_indicator(close=data.close,
                                                                    n=15,
                                                                    ndev=2,
                                                                    fillna=True)

            data["dc_high_indicator"] = ta.donchian_channel_hband_indicator(close=data.close,
                                                                            n=20,
                                                                            fillna=True)

            data["dc_low_indicator"] = ta.donchian_channel_lband_indicator(close=data.close,
                                                                           n=20,
                                                                           fillna=True)

            data["ichimoku_a"] = ta.ichimoku_a(high=data.high,
                                               low=data.low,
                                               n1=9,
                                               n2=26,
                                               fillna=True)

            data.fillna(method="bfill")

            # Normalizar los valores
            for feature in data.columns:
                norm_feature = preprocessing.normalize(data[feature].values.reshape(-1, 1), axis=0)
                data[feature] = pd.DataFrame(data=norm_feature, index=data.index, columns=[feature])

            self.assets = data.columns

            trayectories.append(data.values)
            closes.append(close)

        return np.array(trayectories), np.array(closes)