Exemplo n.º 1
0
    def ATR(self, df, period = 14, multiplier = 1):
        """ ATR bands input ATR(time = 14, multiplier = 1)."""
        
        df.columns = map(str.lower, df.columns) 
        df.sort_index(inplace = True)
        df = df.reset_index() 

        if type(period) == int:
            z = ta.average_true_range(df['high'], df['low'], df['close'], period)
            z = z.iloc[-1]
            return float(z)*multiplier

        else:
            for i in period:
                df[f'ATR{i}'] = ta.average_true_range(df['high'], df['low'], df['close'], i)
            return df.iloc[-1]
Exemplo n.º 2
0
def multiplied_keltner_channel_lband(high,
                                     low,
                                     close,
                                     n=14,
                                     m=2,
                                     fillna=False):
    """Multiplied Keltner channel (MKC)

    Showing a simple moving average line (low) of typical price.

    https://en.wikipedia.org/wiki/Keltner_channel

    Args:
        high(pandas.Series): dataset 'High' column.
        low(pandas.Series): dataset 'Low' column.
        close(pandas.Series): dataset 'Close' column.
        n(int): n period.
        m(int): multiplier

    Returns:
        pandas.Series: New feature generated.
    """
    lower = ta.ema_fast(close, n, fillna) - (
        m * ta.average_true_range(high, low, close, n, fillna))
    if fillna:
        lower = lower.fillna(method='backfill')
    return pd.Series(lower, name='mkc_lband')
Exemplo n.º 3
0
    def __init__(self,
                 prices,
                 balance,
                 atr_period=48,
                 entry_period=48,
                 exit_period=24,
                 max_entry=10,
                 **kwargs):
        self.name = 'Turtle Trading'
        self.prices = prices
        self.balance = balance
        self.signals = pd.DataFrame({
            'ATR':
            ta.average_true_range(self.prices['High'],
                                  self.prices['Low'],
                                  self.prices['Close'],
                                  n=atr_period)
        })
        self.init_period = atr_period
        self.max_entry = max_entry

        self.entry_period = entry_period
        self.exit_period = exit_period
        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
Exemplo n.º 4
0
def enrich_sampleset(df):
    df['OBV'] = ta.on_balance_volume(df['close'], df['volume'])
    df['ADX'] = ta.adx(df['high'], df['low'], df['close'], n=14)
    df['VPT'] = ta.volume_price_trend(df['close'], df['volume'])
    df['ATR'] = ta.average_true_range(df['high'], df['low'], df['close'], n=14)
    df['MFI'] = ta.money_flow_index(df['high'], df['low'], df['close'],
                                    df['volume'])
    df['KST'] = ta.kst(df['close'])
    return ta.utils.dropna(df)
Exemplo n.º 5
0
        def at():
            atr = ta.average_true_range(high, low, close, n=14, fillna=False)

            if atr[-1] >= 1.5 + mean(atr[-10:]):
                vot_status_atr = "Buy"
            elif atr[-1] <= mean(atr[-10:] - 1.5):
                vot_status_atr = "Sell"
            else:
                vot_status_atr = "Hold"
            return vot_status_atr
Exemplo n.º 6
0
    def ATR(self, df, period=14, multiplier=1):
        """ ATR bands input ATR(time = 14, multiplier = 1)."""

        df.columns = map(str.lower, df.columns)  #UPGRADE
        df.sort_index(inplace=True)
        df = df.reset_index()  #UPGRADE
        z = ta.average_true_range(df['high'], df['low'], df['close'], period)
        z = z.iloc[-1]

        return float(z) * multiplier
def process_data(data):
    data['BB_5'] = ta.bollinger_mavg(
        data['CLOSE'], 5)  #bollinger_moving average 5 trading periods
    data['BB_10'] = ta.bollinger_mavg(
        data['CLOSE'], 10)  #bollinger_moving average 10 trading periods
    data['BB_20'] = ta.bollinger_mavg(
        data['CLOSE'], 20)  # bollinger_moving average 20 periods
    data['ADX'] = ta.adx(data['HIGH'], data['LOW'], data['CLOSE'],
                         14)  #Average Directional Index
    data['ATR'] = ta.average_true_range(data['HIGH'], data['LOW'],
                                        data['CLOSE'], 14)  #Average True Range
    data['CCI'] = ta.cci(data['HIGH'], data['LOW'], data['CLOSE'],
                         14)  #Commodity Channel Index
    data['DCH'] = ta.donchian_channel_hband(
        data['CLOSE'])  #Donchian Channel High Band
    data['DCL'] = ta.donchian_channel_lband(
        data['CLOSE'])  #Donchian Channel Low Band
    data['DPO'] = ta.dpo(data['CLOSE'])  #Detrend Price Oscilator
    data['EMAf'] = ta.ema_fast(
        data['CLOSE'])  #Expornential Moving Average fast
    data['EMAs'] = ta.ema_slow(
        data['CLOSE'])  #Expornential Moving Average slow
    data['FI'] = ta.force_index(
        data['CLOSE'],
        data['VOLUME'])  # Force Index(reveals the value of a trend)
    data['ICHa'] = ta.ichimoku_a(data['HIGH'], data['LOW'])  #Ichimoku A
    data['ICHb'] = ta.ichimoku_b(data['HIGH'], data['LOW'])  #Ichimoku B
    data['KC'] = ta.keltner_channel_central(
        data['HIGH'], data['LOW'], data['CLOSE'])  #Keltner channel(KC) Central
    data['KST'] = ta.kst(
        data['CLOSE']
    )  #KST Oscillator (KST) identify major stock market cycle junctures
    data['MACD'] = ta.macd(
        data['CLOSE'])  # Moving Average convergence divergence
    data['OBV'] = ta.on_balance_volume_mean(
        data['CLOSE'], data['VOLUME'])  # on_balance_volume_mean
    data['RSI'] = ta.rsi(data['CLOSE'])  # Relative Strength Index (RSI)
    data['TRIX'] = ta.trix(
        data['CLOSE']
    )  #Shows the percent rate of change of a triple exponentially smoothed moving average
    data['TSI'] = ta.tsi(data['CLOSE'])  #True strength index (TSI)
    data['ROC1'] = (data['CLOSE'] - data['OPEN']) / data['OPEN']
    data['RET'] = data['CLOSE'].pct_change()
    data['y'] = np.where(data['OPEN'] <= data['CLOSE'], 1, -1)
    data = data.dropna()
    return data
Exemplo n.º 8
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
Exemplo n.º 9
0
ta_df['KST'] = ta.kst(df["Close"])
ta_df['KST_sig'] = ta.kst_sig(df["Close"])
ta_df['KST_diff'] = (
    ta_df['KST'] -
    ta_df['KST_sig'])
ta_df['Ichimoku_a'] = ta.ichimoku_a(df["High"], df["Low"], visual=True)
ta_df['Ichimoku_b'] = ta.ichimoku_b(df["High"], df["Low"], visual=True)
ta_df['Aroon_up'] = ta.aroon_up(df["Close"])
ta_df['Aroon_down'] = ta.aroon_down(df["Close"])
ta_df['Aroon_ind'] = (
    ta_df['Aroon_up'] -
    ta_df['Aroon_down']
)

ta_df['ATR'] = ta.average_true_range(
    df["High"],
    df["Low"],
    df["Close"])
ta_df['BBH'] = ta.bollinger_hband(df["Close"])
ta_df['BBL'] = ta.bollinger_lband(df["Close"])
ta_df['BBM'] = ta.bollinger_mavg(df["Close"])
ta_df['BBHI'] = ta.bollinger_hband_indicator(
    df["Close"])
ta_df['BBLI'] = ta.bollinger_lband_indicator(
    df["Close"])
ta_df['KCC'] = ta.keltner_channel_central(
    df["High"],
    df["Low"],
    df["Close"])
ta_df['KCH'] = ta.keltner_channel_hband(
    df["High"],
    df["Low"],
Exemplo n.º 10
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.º 11
0
                                  fillna=True)
X['ease_of_movement'] = ta.ease_of_movement(price['High'],
                                            price['Low'],
                                            price['Adj. Close'],
                                            price['Volume'],
                                            n=20,
                                            fillna=True)
X['volume_price_trend'] = ta.volume_price_trend(price['Adj. Close'],
                                                price['Volume'],
                                                fillna=True)
X['negative_volume_index'] = ta.negative_volume_index(price['Adj. Close'],
                                                      price['Volume'],
                                                      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'],
    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)