Ejemplo 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
Ejemplo n.º 2
0
def sma_crossover(prices, initial_balance, commision):
    macd = ta.macd(prices)

    def signal_fn(i):
        if macd[i] > 0 and macd[i - 1] <= 0:
            return SIGNAL.SELL
        elif macd[i] < 0 and macd[i - 1] >= 0:
            return SIGNAL.BUY
        return SIGNAL.HOLD

    return trade_strategy(prices, initial_balance, commision, signal_fn)
Ejemplo n.º 3
0
def sma_crossover(prices):
    macd = ta.macd(prices)

    def signal_fn(i):
        if macd[i] > 0 and macd[i - 1] <= 0:
            return SIGNALS.BUY
        elif macd[i] < 0 and macd[i - 1] >= 0:
            return SIGNALS.SELL

        return SIGNALS.HOLD

    return signal_fn
Ejemplo n.º 4
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
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
Ejemplo n.º 6
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
Ejemplo n.º 8
0
        def sma_policy():
            """
            The SMA Crossover algorithm.

            Returns:
                Tuple[int, int]: The Action-Amount pair.

            """
            prices = self.env.full_data_df["Close"]
            cur_step = self.env.cur_step

            macd = ta.macd(prices)

            if macd[cur_step] > 0 >= macd[cur_step - 1]:
                return 0, 10

            elif macd[cur_step] < 0 <= macd[cur_step - 1]:
                return 2, 10

            return 1, 10
Ejemplo n.º 9
0
df = pd.read_csv('./data/coinbase_daily.csv')
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"])
Ejemplo n.º 10
0
    async def handle_second_bar(conn, channel, data):
        symbol = data.symbol

        # First, aggregate 1s bars for up-to-date MACD calculations
        ts = data.start
        ts -= timedelta(seconds=ts.second, microseconds=ts.microsecond)
        try:
            current = minute_history[data.symbol].loc[ts]
        except KeyError:
            current = None
        new_data = []
        if current is None:
            new_data = [
                data.open, data.high, data.low, data.close, data.volume
            ]
        else:
            new_data = [
                current.open,
                data.high if data.high > current.high else current.high,
                data.low if data.low < current.low else current.low,
                data.close, current.volume + data.volume
            ]
        minute_history[symbol].loc[ts] = new_data

        # Next, check for existing orders for the stock
        existing_order = open_orders.get(symbol)
        if existing_order is not None:
            # Make sure the order's not too old
            submission_ts = existing_order.submitted_at.astimezone(
                timezone('America/New_York'))
            order_lifetime = ts - submission_ts
            if order_lifetime.seconds // 60 > 1:
                # Cancel it so we can try again for a fill
                api.cancel_order(existing_order.id)
            return

        # Now we check to see if it might be time to buy or sell
        since_market_open = ts - market_open_dt
        until_market_close = market_close_dt - ts
        if (since_market_open.seconds // 60 > 15
                and since_market_open.seconds // 60 < 60):
            # Check for buy signals

            # See if we've already bought in first
            position = positions.get(symbol, 0)
            if position > 0:
                return

            # See how high the price went during the first 15 minutes
            lbound = market_open_dt
            ubound = lbound + timedelta(minutes=15)
            high_15m = 0
            try:
                high_15m = minute_history[symbol][lbound:ubound]['high'].max()
            except Exception as e:
                # Because we're aggregating on the fly, sometimes the datetime
                # index can get messy until it's healed by the minute bars
                return

            # Get the change since yesterday's market close
            daily_pct_change = ((data.close - prev_closes[symbol]) /
                                prev_closes[symbol])
            if (daily_pct_change > .04 and data.close > high_15m
                    and volume_today[symbol] > 30000):
                # check for a positive, increasing MACD
                hist = macd(minute_history[symbol]['close'].dropna(),
                            n_fast=12,
                            n_slow=26)
                if (hist[-1] < 0 or not (hist[-3] < hist[-2] < hist[-1])):
                    return
                hist = macd(minute_history[symbol]['close'].dropna(),
                            n_fast=40,
                            n_slow=60)
                if hist[-1] < 0 or np.diff(hist)[-1] < 0:
                    return

                # Stock has passed all checks; figure out how much to buy
                stop_price = find_stop(data.close, minute_history[symbol], ts)
                stop_prices[symbol] = stop_price
                target_prices[symbol] = data.close + (
                    (data.close - stop_price) * 3)
                shares_to_buy = portfolio_value * risk // (data.close -
                                                           stop_price)
                if shares_to_buy == 0:
                    shares_to_buy = 1
                shares_to_buy -= positions.get(symbol, 0)
                if shares_to_buy <= 0:
                    return

                print('Submitting buy for {} shares of {} at {}'.format(
                    shares_to_buy, symbol, data.close))
                try:
                    o = api.submit_order(symbol=symbol,
                                         qty=str(shares_to_buy),
                                         side='buy',
                                         type='limit',
                                         time_in_force='day',
                                         limit_price=str(data.close))
                    open_orders[symbol] = o
                    latest_cost_basis[symbol] = data.close
                except Exception as e:
                    print(e)
                return
        if (since_market_open.seconds // 60 >= 24
                and until_market_close.seconds // 60 > 15):
            # Check for liquidation signals

            # We can't liquidate if there's no position
            position = positions.get(symbol, 0)
            if position == 0:
                return

            # Sell for a loss if it's fallen below our stop price
            # Sell for a loss if it's below our cost basis and MACD < 0
            # Sell for a profit if it's above our target price
            hist = macd(minute_history[symbol]['close'].dropna(),
                        n_fast=13,
                        n_slow=21)
            if (data.close <= stop_prices[symbol]
                    or (data.close >= target_prices[symbol] and hist[-1] <= 0)
                    or
                (data.close <= latest_cost_basis[symbol] and hist[-1] <= 0)):
                print('Submitting sell for {} shares of {} at {}'.format(
                    position, symbol, data.close))
                try:
                    o = api.submit_order(symbol=symbol,
                                         qty=str(position),
                                         side='sell',
                                         type='limit',
                                         time_in_force='day',
                                         limit_price=str(data.close))
                    open_orders[symbol] = o
                    latest_cost_basis[symbol] = data.close
                except Exception as e:
                    print(e)
            return
        elif (until_market_close.seconds // 60 <= 15):
            # Liquidate remaining positions on watched symbols at market
            try:
                position = api.get_position(symbol)
            except Exception as e:
                # Exception here indicates that we have no position
                return
            print('Trading over, liquidating remaining position in {}'.format(
                symbol))
            api.submit_order(symbol=symbol,
                             qty=position.qty,
                             side='sell',
                             type='market',
                             time_in_force='day')
            symbols.remove(symbol)
            if len(symbols) <= 0:
                conn.close()
            conn.deregister(['A.{}'.format(symbol), 'AM.{}'.format(symbol)])
    def getDatas(self):
        self.score = ta.macd(self.data, self.swindow_size, self.lwindow_size)

        return self.score