Пример #1
0
 def MACD(price, nslow=26, nfast=12, m=9):
     emas = EMA(price, nslow)
     emaf = EMA(price, nfast)
     dif = emaf - emas
     dea = EMA(dif, m)
     macd = dif - dea
     return dif, dea, macd
Пример #2
0
    def refit(self, ohlcv, params=None, ba=None, **kwargs):
        """
        refit the strategy using given parameters and return signals

        :param ohlcv: a DataFrame object with OHLCV columns ordered by date, ascending
        :param params: optimal parameters
        :ba: bid ask spread
        :return: signal
        """

        required_params = ['trailing_window', 'ema_s', 'ema_l', 'bb']
        if not all(param in params for param in required_params):
            raise KeyError("incorrect parameters")
        lookback = params['trailing_window']
        close = ohlcv['close']
        ema_s = EMA(close[-lookback:], timeperiod=params['ema_s'])
        ema_l = EMA(close[-lookback:], timeperiod=params['ema_l'])
        bb = BBANDS(close[-lookback:], timeperiod=params['bb'])
        if ba in None:
            buy_signal = (ema_s > ema_l) and (close[-1] >
                                              (bb[1])) and (close[-1] > ema_s)
        else:
            bid = ba['bid']
            ask = ba['ask']
            mid = (bid[-1] + ask[-1]) / 2
            buy_signal = (ema_s > ema_l) and (mid > (bb[1])) and (mid > ema_s)

        return {'buy': buy_signal, 'sell': None}
def handle_data(context, data):
    #print(data.current(context.asset, ['open', 'high', 'low', 'close', 'price']))
    #print(context)
    trailing_window = data.history(context.asset, 'price', 40, '1m')
    if trailing_window.isnull().values.any():
        return
    short_ema = EMA(trailing_window.values, timeperiod=20)
    long_ema = EMA(trailing_window.values, timeperiod=40)
    #print(short_ema)
    #print(long_ema)
    buy = False
    sell = False

    if (short_ema[-1] > long_ema[-1]) and not context.invested:
        order(context.asset, 1000)
        context.invested = True
        buy = True
    elif (short_ema[-1] < long_ema[-1]) and context.invested:
        order(context.asset, -1000)
        context.invested = False
        sell = True

    record(BITMAP=data.current(context.asset, "price"),
           short_ema=short_ema[-1],
           long_ema=long_ema[-1],
           buy=buy,
           sell=sell)
Пример #4
0
def SSL(high,low, close, timeperiod=7):
    from talib import EMA
    sma_high = EMA(high,timeperiod )
    sma_low = EMA(low,timeperiod )
    
    ssl_up = np.full(len(close), np.nan)
    ssl_down = np.full(len(close), np.nan)
    lv = np.full(len(close), np.nan)
    lv[timeperiod-0]=1
    for i in range(0,len(close)):
        if(i>=timeperiod):
            if(close[i]<sma_low[i]):
                lv[i] = -1
            else:
                if(close[i]>sma_high[i]):
                    lv[i] = 1
                else:
                    lv[i] = 0
            if(lv[i]==0):
                lv[i] = lv[i-1]
                
            if(lv[i]>0):
                ssl_up[i] = sma_high[i]
                ssl_down[i] = sma_low[i]
            else:
                ssl_up[i] = sma_low[i]
                ssl_down[i] = sma_high[i]
    return ssl_up, ssl_down
Пример #5
0
def handle_data(context, data):
    trailing_window = data.history(context.asset, "price", 40, "1d")
    if trailing_window.isnull().values.any():
        return
    short_ema = EMA(trailing_window.values, timeperiod=20)
    long_ema = EMA(trailing_window.values, timeperiod=40)

    buy = False
    sell = False

    if (short_ema[-1] > long_ema[-1]) and not context.invested:
        order(context.asset, 100)
        context.invested = True
        buy = True
    elif (short_ema[-1] < long_ema[-1]) and context.invested:
        order(context.asset, -100)
        context.invested = False
        sell = True

    record(
        AAPL=data.current(context.asset, "price"),
        short_ema=short_ema[-1],
        long_ema=long_ema[-1],
        buy=buy,
        sell=sell,
    )
Пример #6
0
def adosc_chartschool(my_close, my_high, my_low, my_volume, fastperiod,
                      slowperiod):

    MFV = (((my_close - my_low) - (my_high - my_close)) /
           (my_high - my_low)) * my_volume
    ADL = np.cumsum(MFV)
    ADOSC = EMA(ADL.values, timeperiod=fastperiod) - EMA(ADL.values,
                                                         timeperiod=slowperiod)
    return ADOSC
def entry_exit_logic():

    now = str(pd.Timestamp.today())[0:16]
    logging.info('Calculating metrics for {now}...'.format(now=now))

    # Calculate metrics
    currency = 'ZUSD'
    crypto = 'XETH'
    pair = crypto + currency
    try:
        df = k.get_ohlc_data(pair, interval=30, ascending=True)[0]
        df.index = df.index.tz_localize(tz='UTC').tz_convert('US/Central')
        ewm_3 = EMA(df['close'], 3)[-1]
        ewm_20 = EMA(df['close'], 20)[-1]
        logging.info('3-EMA is: {ewm_3} and 20-EMA is: {ewm_20}'.format(ewm_3=ewm_3, ewm_20=ewm_20))
    except:
        logging.info('Data Request Error.')
        pass


    # Current holdings
    try:
        volume = k.get_account_balance()
        cash_on_hand = volume.loc[currency][0]
        current_price = df['close'][-1]
        leverage = 5
        margin_shares = (cash_on_hand*leverage)/current_price
    except:
        print('No USD On Hand.')
        pass
    try:
        crypto_on_hand = volume.loc[crypto][0]
        holding_crypto_position = [True if len(k.get_open_positions()) > 0 else False][0]
    except:
        print('No Cryptocurreny On Hand.')
        holding_crypto_position = False
        pass

    # Entry-Exit Logic
    if (ewm_3 > ewm_20) & (holding_crypto_position==False):
        type = 'buy'
        order = api.query_private('AddOrder', {'pair': pair, 'type': type, 'ordertype':'limit', 'price': current_price, 'leverage': str(leverage), 'volume': margin_shares})
        if len(order['error']) == 0:
            logging.info('Bought {shares} shares at {price}'.format(shares=margin_shares, price=current_price))
        else:
            logging.info('Trade Canceled: {error}'.format(error=order['error']))
    elif (ewm_3 <= ewm_20) & (holding_crypto_position==True):
        type = 'sell'
        order = api.query_private('AddOrder', {'pair': pair, 'type': type, 'ordertype':'market', 'leverage': str(leverage), 'volume': 0})
        if len(order['error']) == 0:
            logging.info('Sold {shares} shares at {price}'.format(shares=crypto_on_hand, price=current_price))
        else:
            logging.info('Trade Canceled: {error}'.format(error=order['error']))
    else:
        logging.info('Holding current position')
        pass
Пример #8
0
    def handle_single_asset_data(self, context, asset, data):
        short_ema_value, long_ema_value = self.current_parameter_

        trailing_window = data.history(asset, 'price', long_ema_value * 3,
                                       '1d')

        if trailing_window.isnull().values.any():
            return

        short_ema = EMA(trailing_window.values, timeperiod=short_ema_value)
        long_ema = EMA(trailing_window.values, timeperiod=long_ema_value)

        vv = data.history(asset, ['high', 'low'], 5, '1d')

        vv = (vv['high'] - vv['low']).mean()

        vvv = data.history(asset, ['high', 'low'], 3, '1d')

        vvv = (vvv['high'] - vvv['low']).mean() * .5

        _long = (short_ema[-1] > long_ema[-1]) and (short_ema[-2] >=
                                                    long_ema[-2])
        _short = (short_ema[-1] < long_ema[-1]) and (short_ema[-2] <=
                                                     long_ema[-2])

        pv = data.current(asset, "price")

        if context.price_highest[asset] < pv:
            context.price_highest[asset] = pv - vvv

        trailing_stop = MA(trailing_window.values,
                           timeperiod=3)[-1] < context.price_highest[asset]
        _short = _short or (context.portfolio_highest[asset] >
                            pv) or trailing_stop

        pct_per_stock = 1.0 / len(context.assets)
        cash = context.portfolio.cash * pct_per_stock

        if _long and cash > pv and context.stock_shares[asset] == 0:
            number_of_shares = int(cash / pv)
            order(asset, number_of_shares)
            context.portfolio_highest[asset] = pv - vv
            context.stock_shares[asset] = number_of_shares
            logging.debug('{} buy {} shares at {}'.format(
                asset, number_of_shares, pv))
        elif _short and context.stock_shares[asset] > 0:
            order_target_percent(asset, 0)
            number_of_shares = context.stock_shares[asset]
            context.portfolio_highest[asset] = 0.0
            context.price_highest[asset] = 0.0
            context.stock_shares[asset] = 0
            logging.debug('{} sell {} shares at {}'.format(
                asset, number_of_shares, pv))
Пример #9
0
    def ema_bullish_cross(self, timeframe="1d", fast_period=9, slow_period=26):
        ema_fast = EMA(self.tf[timeframe].close.as_matrix(), fast_period)
        ema_slow = EMA(self.tf[timeframe].close.as_matrix(), slow_period)

        # If EMA9 > EMA26, find out when the bullish cross happened
        if ema_fast[-1] > ema_slow[-1]:
            idx = 1
            while ema_fast[-idx] > ema_slow[-idx]:
                idx += 1

            return ema_fast[-1] > ema_slow[-1], idx
        else:
            return False, 0
Пример #10
0
    def process(self):
        logging.info('process')

        # Open trades
        response = API.trade.list_open(ACCOUNT_ID)
        trades = [
            Trade(t.id, t.instrument, True if t.initialUnits > 0 else False)
            for t in response.body['trades']
        ]

        # Order
        for instrument in self.instruments:
            symbol = instrument.symbol
            data = instrument.data
            t = data['time'].values[-1]
            close = data['close'].values
            ema3 = EMA(close, timeperiod=3)
            ema6 = EMA(close, timeperiod=6)
            ema18 = EMA(close, timeperiod=18)
            units = SIZE
            trade = next((t for t in trades if t.symbol == symbol),
                         Trade(0, symbol, None))
            buy = True

            # logging.info('symbol=%s, time=%s', symbol, t)

            # Enter long
            if cross_up(ema6, ema18) and trade.long in [None, False]:
                logging.info("long entry: symbol=%s", symbol)
                response = API.order.market(ACCOUNT_ID,
                                            instrument=symbol,
                                            units=SIZE)

            # Exit long
            if cross_down(ema3, ema6) and trade.long:
                logging.info("long exit: symbol=%s", symbol)
                API.trade.close(ACCOUNT_ID, trade.id)

            # Enter short
            if cross_down(ema6, ema18) and trade.long in [None, True]:
                logging.info("short entry: symbol=%s", symbol)
                response = API.order.market(ACCOUNT_ID,
                                            instrument=symbol,
                                            units=-SIZE)

            # Exit short
            if cross_up(ema3, ema6) and trade.long is False:
                logging.info("short exit: symbol=%s", symbol)
                API.trade.close(ACCOUNT_ID, trade.id)
Пример #11
0
def handle_data(context, data):
    # Skip first 300 days to get full windows
    context.i += 1
    if context.i < 100:
        return

    trailing_window = data.history(context.asset, 'price', 40, '1d')
    if trailing_window.isnull().values.any():
        return

    # Compute averages
    # data.history() has to be called with the same params
    # from above and returns a pandas dataframe.
    thirty_day_mavg = data.history(context.asset,
                                   'price',
                                   bar_count=30,
                                   frequency="1d").mean()
    hundred_day_mavg = data.history(context.asset,
                                    'price',
                                    bar_count=100,
                                    frequency="1d").mean()

    short_ema = EMA(trailing_window.values, timeperiod=20)
    long_ema = EMA(trailing_window.values, timeperiod=40)

    buy = False
    sell = False

    # Trading logic
    if thirty_day_mavg > hundred_day_mavg and not context.invested:
        # order_target orders as many shares as needed to
        # achieve the desired number of shares.
        buy = True
        order_target(context.asset, 100)
        context.invested = True

    elif thirty_day_mavg < hundred_day_mavg and context.invested:
        sell = True
        order_target(context.asset, 0)
        context.invested = False

    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           thirty_day_mavg=thirty_day_mavg,
           hundred_day_mavg=hundred_day_mavg,
           short_ema=short_ema[-1],
           long_ema=long_ema[-1],
           buy=buy,
           sell=sell)
Пример #12
0
    def data(self):
        for resolution in ['M15', 'H1']:
            logging.info('data resolution=%s', resolution)
            for instrument in self.instruments:
                from_time = getattr(instrument, 'since' + resolution)
                include_first = None
                if from_time is not None:
                    include_first = False

                # Candles
                response = API.instrument.candles(instrument.symbol,
                                                  granularity=resolution,
                                                  fromTime=from_time,
                                                  includeFirst=include_first)
                # candles = [c for c in filter(lambda c: c.complete, response.body['candles'])]
                candles = response.body['candles']
                records = [{
                    'time': pd.to_datetime(c.time),
                    'open': c.mid.o,
                    'high': c.mid.h,
                    'low': c.mid.l,
                    'close': c.mid.c,
                    'volume': c.volume
                } for c in candles]
                if len(records) == 0:
                    continue
                data = pd.DataFrame.from_records(records, index='time')
                key = 'data' + resolution
                if getattr(instrument, key) is None:
                    setattr(instrument, key, data)
                else:
                    setattr(
                        instrument, key,
                        getattr(instrument, key).append(data)[len(records):])
                close = getattr(instrument, key)['close']
                setattr(
                    instrument, key,
                    getattr(instrument,
                            key).assign(ema6=EMA(close, timeperiod=6),
                                        ema18=EMA(close, timeperiod=18),
                                        ema50=EMA(close, timeperiod=50),
                                        sma200=SMA(close, timeperiod=200),
                                        adx=ADX(getattr(instrument,
                                                        key)['high'],
                                                getattr(instrument,
                                                        key)['low'],
                                                close,
                                                timeperiod=14)))
                setattr(instrument, 'since' + resolution, candles[-1].time)
Пример #13
0
def calculateSignal(api,HQData):
    if np.isnan(HQData.close.values[-1]):
        return 0

    close = HQData.close.values
    closeSMA = EMA(close, api.windows_SMA)[-1]
    closeLMA = EMA(close, api.windows_LMA)[-1]

    signal01 = 1 if (closeSMA > closeLMA) else 0

    volume = HQData.volume.values
    volumeMA = EMA(volume[:-1],20)
    closeSMADouble08 = EMA(EMA(close, 8), 8)
    dailyRet = np.log(closeSMADouble08[-1]) - np.log(closeSMADouble08[-2])
    signal = 1 if (volume[-1] > 2.*volumeMA[-1]) and (dailyRet>0) else signal01
    return signal
Пример #14
0
def historicData(script, start_dt, end_dt):
    data = pd.DataFrame(
        u.get_ohlc(u.get_instrument_by_symbol('NSE_EQ', script),
                   OHLCInterval.Minute_5,
                   datetime.strptime(start_dt, "%d/%m/%Y").date(),
                   datetime.strptime(end_dt, "%d/%m/%Y").date()))
    data = data.tail(5)
    #change the name timestamp to date
    data = data[['timestamp', 'open', 'high', 'low', 'close']]
    data = data.rename({'timestamp': 'date'}, axis=1)
    #convert timestamp into date
    data['date'] = pd.to_datetime(data['date'], unit='ms')
    #convert to float
    data['open'] = data['open'].astype(float)
    data['high'] = data['high'].astype(float)
    data['low'] = data['low'].astype(float)
    data['close'] = data['close'].astype(float)
    data = data.reset_index()
    renko = indicators.Renko(data)
    renko.brick_size = 1
    renko.chart_type = indicators.Renko.PERIOD_CLOSE
    renkodata = renko.get_ohlc_data()

    renkodata['moving'] = EMA(renkodata['close'], timeperiod=10)
    renkodata['moving'] = renkodata['moving'].astype(float)
    #print(renkodata.tail(5))
    renkodata = renkodata.reset_index()
    return renkodata
Пример #15
0
def calculateIndex(filePath):
    File = open(filePath, "r")
    text = File.read()
    text = text.rstrip()
    File.close()

    OHLCV = json.loads(text)

    timePeriod = OHLCV['t']
    if timePeriod:
        nClose = np.array(OHLCV['c'])
        ema1 = EMA(nClose, EMA_1)
        ema2 = EMA(nClose, EMA_2)
        ema3 = EMA(nClose, EMA_3)
        return ema1, ema2, ema3
    else:
        return 0, 0, 0
Пример #16
0
def calculateIndex(filePath):
    File = open(filePath, "r")
    text = File.read()
    text = text.rstrip()
    File.close()

    OHLCV = json.loads(text)
    timePeriod = np.array(OHLCV['t'])
    nClose = np.array(OHLCV['c'])

    rsi = RSI(nClose, timeperiod=RSI_T)
    macd, macdSignal, macdHist = MACD(nClose, MACD_FAST, MACD_SLOW,
                                      MACD_SIGNAL)
    emaSlow = EMA(nClose, EMA_SLOW)
    emaMedium = EMA(nClose, EMA_MEDIUM)
    emaFast = EMA(nClose, EMA_FAST)

    #print("RSI (first 10 elements)\n", rsi[10:20])
    return timePeriod, rsi, macd, macdSignal, macdHist, emaSlow, emaMedium, emaFast
Пример #17
0
def EMAdecision(table, days=20):
    decision = []
    close = table['Close']
    del table
    data = EMA(np.array(close), days)
    for i in np.arange(len(close)):
        if np.isnan(data[i]):
            decision.append(None)
        if data[i] > close[i]:
            decision.append(TransactionType.SELL)
        if data[i] < close[i]:
            decision.append(TransactionType.BUY)
    return {'decision': decision, 'data': data}
Пример #18
0
            def handle_data(context, data):
                required_params = ['trailing_window', 'ema_s', 'ema_l', 'bb']
                if not all(param in context.params
                           for param in required_params):
                    raise KeyError("incorrect parameter list")
                trailing_window = data.history(
                    context.asset, 'close', context.params['trailing_window'],
                    '1d')
                if trailing_window.isnull().values.any():
                    return
                ema_s = EMA(trailing_window.values,
                            timeperiod=context.params['ema_s'])
                ema_l = EMA(trailing_window.values,
                            timeperiod=context.params['ema_l'])
                bb = BBANDS(trailing_window.values,
                            timeperiod=context.params['bb'])

                buy = False
                sell = False
                buy_signal = (ema_s[-1] > ema_l[-1]) and (
                    trailing_window.values[-1] >
                    (bb[1][-1])) and (trailing_window.values[-1] > ema_s[-1])

                if buy_signal and not context.invested:
                    order(context.asset, 100)
                    context.invested = True
                    buy = True

                elif not buy_signal and context.invested:
                    order(context.asset, -100)
                    context.invested = False
                    sell = True

                record(BTC=data.current(context.asset, "price"),
                       ema_s=ema_s[-1],
                       ema_l=ema_l[-1],
                       bb=bb[1][-1],
                       buy=buy,
                       sell=sell)
Пример #19
0
 def update(self, data):
     Candle.update(self, data)
     candles = self.dataline.get_nd_candles(
         data['token'], self.timeperiod, self.prev, count=200)
     r = None
     try:
         r = EMA(np.array(candles['close']), timeperiod=self.period)
     except:
         print("Exception in ExponentialMovingAverage")
         r = [0,0]
     #need to set self.d and self.p for calcualtion of crossover
     self.setd(0 if np.isnan(r[-1]) else r[-1])
     return self
Пример #20
0
    def _calc_indicator(self, OHLCV_input):
        """
        Calculates the EMA technical indicator using a wrapper for the TA-lib

        Args:
            :param OHLCV_input:  the dataframe with the Open, High, Low, Close and Volume values
            :type OHLCV_input: pandas DataFrame

        Returns:
            DataFrame with the indicators values.
        """
        try:
            close = OHLCV_input['close'].values[:, 0]
        except IndexError:
            close = OHLCV_input['close'].values

        output = DataFrame(EMA(close, self.__timeperiod))
        output.columns = ['EMA%d' % self.__timeperiod]
        return output
Пример #21
0
def ema(close, length=None, talib=None, offset=None, **kwargs):
    """Indicator: Exponential Moving Average (EMA)"""
    # Validate Arguments
    length = int(length) if length and length > 0 else 10
    adjust = kwargs.pop("adjust", False)
    sma = kwargs.pop("sma", True)
    close = verify_series(close, length)
    offset = get_offset(offset)
    mode_tal = bool(talib) if isinstance(talib, bool) else True

    if close is None: return

    # Calculate Result
    if Imports["talib"] and mode_tal:
        from talib import EMA
        ema = EMA(close, length)
    else:
        if sma:
            close = close.copy()
            sma_nth = close[0:length].mean()
            close[:length - 1] = npNaN
            close.iloc[length - 1] = sma_nth
        ema = close.ewm(span=length, adjust=adjust).mean()

    # Offset
    if offset != 0:
        ema = ema.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        ema.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        ema.fillna(method=kwargs["fill_method"], inplace=True)

    # Name & Category
    ema.name = f"EMA_{length}"
    ema.category = "overlap"

    return ema
Пример #22
0
    def trix200(self, df, pattern, patterntype):
        df = df.dropna()

        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)

        trixInput = df.head(60)
        trixInput = trixInput.iloc[::-1]
        trixOutput = TRIX(trixInput['close'].values, timeperiod=14)

        ##c. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        # print("EMA\n", ema[-1])

        ##d. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        # print("pricehigh\n", pricehigh)
        # print("pricelow\n", pricelow)

        if trixOutput[-2] < 0 and trixOutput[-1] > 0:
            crossover = 1
        elif trixOutput[-2] > 0 and trixOutput[-1] < 0:
            crossover = -1
        else:
            crossover = 0

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and crossover > 0: position = 1
        elif marketEMA == -1 and crossover < 0: position = -1
        else: position = 0
        amount = 50
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        if position * pattern > 0:
            confidence = abs(pattern)
        elif position * pattern < 0:
            confidence = abs(1 / pattern)
        elif position == 0:
            confidence = 0
        else:
            confidence = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Пример #23
0
    def macd200(self, df, pattern, patterntype):
        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)
        #####PLACEHOLDER
        # df = pd.read_csv('./database/AAPL.csv')
        #####END_PLACEHOLDER
        df = df.dropna()

        ###1. Getting Parameters

        ##b. MACD
        macdInput = df.head(34)
        macdInput = macdInput.iloc[::-1]
        MACDclose = macdInput['close'].values
        macd, macdsignal, macdhist = MACDFIX(MACDclose, signalperiod=9)
        # print("MACD\n", macd[-1])
        # print("Signal\n", macdsignal[-1])

        ##c. DelayedMACD
        delayedmacdInput = df.iloc[1:].head(34)
        delayedmacdInput = delayedmacdInput.iloc[::-1]
        delayedMACDclose = delayedmacdInput['close'].values
        delayedmacd, delayedmacdsignal, delayedmacdhist = MACDFIX(
            delayedMACDclose, signalperiod=9)

        ##c. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        # print("EMA\n", ema[-1])

        ##d. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        # print("pricehigh\n", pricehigh)
        # print("pricelow\n", pricelow)

        ###2. Analysing using the data provided

        ##macd-signal crossover type
        ## -1 means negative crossover
        ## 1 means positive crossover
        ## 0 means both
        if delayedmacd[-1] < delayedmacdsignal[-1] and macd[-1] > macdsignal[
                -1]:
            crossover = 1
        elif delayedmacd[-1] > delayedmacdsignal[-1] and macd[-1] < macdsignal[
                -1]:
            crossover = -1
        else:
            crossover = 0
        ##market-ema type
        ## 1 means low > 200EMA
        ## -1 means high < 200EMA
        ## 0 means otherwise

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and crossover > 0 and macd[-1] < 0: position = 1
        elif marketEMA == -1 and crossover < 0 and macd[-1] > 0: position = -1
        else: position = 0
        amount = 50
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        ##For test
        # position = 1

        if position * pattern > 0:
            confidence = abs(pattern)
        elif position * pattern < 0:
            confidence = abs(1 / pattern)
        elif position == 0:
            confidence = 0
        else:
            confidence = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Пример #24
0
    def SMA200(self, df, pattern, patterntype):
        df = df.dropna()

        ###1. Getting Parameters
        ##a. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]

        ##b. previous price action
        prevaction = df.iloc[1:].head(1)
        prevhigh = prevaction['high'].values[0]
        prevlow = prevaction['low'].values[0]
        prevclose = prevaction['close'].values[0]

        ##d. current SMAs
        smaCurrentInput = df.head(20)
        sma20Current = SMA(smaCurrentInput['close'].values, timeperiod=20)
        smaCurrentInput = smaCurrentInput.head(10)
        sma10Current = SMA(smaCurrentInput['close'].values, timeperiod=10)

        ##e. previous SMAs
        smaPreviousInput = df.iloc[1:].head(20)
        sma20Previous = SMA(smaPreviousInput['close'].values, timeperiod=20)
        smaPreviousInput = smaPreviousInput.head(10)
        sma10Previous = SMA(smaPreviousInput['close'].values, timeperiod=10)

        ##f. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        ##trade conditions

        if sma10Previous[-1] < sma20Previous[-1] and sma10Current[
                -1] > sma20Current[-1]:
            crossover = 1
        elif sma10Previous[-1] > sma20Previous[-1] and sma10Current[
                -1] < sma20Current[-1]:
            crossover = -1
        else:
            crossover = 0

        ## 200EMA filtering false signal
        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        if crossover == 1 and marketEMA == 1:
            position = 1
        elif crossover == -1 and marketEMA == -1:
            position = -1
        else:
            position = 0

        atr = atrcalc.ATRcalc(df)
        amount = 50
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        if position * pattern > 0:
            confidence = abs(pattern)
        elif position * pattern < 0:
            confidence = abs(1 / pattern)
        elif position == 0:
            confidence = 0
        else:
            confidence = 1
        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Пример #25
0
    def parabolic200(self, df, pattern, patterntype):
        df = df.dropna()

        ###1. Getting Parameters
        ##a. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        ##b. SAR current

        sarCurrentInput = df.head(2)
        sarCurrentInput = sarCurrentInput.iloc[::-1]
        sarCurrentInputHigh = sarCurrentInput['high'].values
        sarCurrentInputLow = sarCurrentInput['low'].values
        sarCurrent = SAR(sarCurrentInputHigh,
                         sarCurrentInputLow,
                         acceleration=0,
                         maximum=0)

        ##c. previous price action
        prevaction = df.iloc[1:].head(1)
        prevhigh = prevaction['high'].values[0]
        prevlow = prevaction['low'].values[0]
        prevclose = prevaction['close'].values[0]

        ##d. previous SAR
        sarPreviousInput = df.iloc[1:].head(2)
        sarPreviousInput = sarPreviousInput.iloc[::-1]
        sarPreviousInputHigh = sarPreviousInput['high'].values
        sarPreviousInputLow = sarPreviousInput['low'].values
        sarPrevious = SAR(sarPreviousInputHigh,
                          sarPreviousInputLow,
                          acceleration=0,
                          maximum=0)

        ##b. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        ## SAR reversal
        ## 1 if from -ve become +ve
        ## -1 if from +ve become -ve
        ## 0 otherwise

        if prevclose < sarPrevious[-1] and priceclose > sarCurrent[-1]:
            change = 1
        elif prevclose > sarPrevious[-1] and priceclose < sarCurrent[-1]:
            change = -1
        else:
            change = 0

        ## 200EMA filtering false signal
        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and change == 1: position = 1
        elif marketEMA == -1 and change == -1: position = -1
        else: position = 0

        amount = 50

        if position == 1:
            stoploss = sarCurrent[-1]
            takeprofit = priceclose + 1.45 * (priceclose - sarCurrent[-1])
            # amount = priceclose / (priceclose - stoploss)
            if (priceclose - stoploss) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        elif position == -1:
            stoploss = sarCurrent[-1]
            takeprofit = priceclose - 1.45 * (sarCurrent[-1] - priceclose)
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0
        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        ##For test
        # position = 1

        if position * pattern > 0:
            confidence = abs(pattern)
        elif position * pattern < 0:
            confidence = abs(1 / pattern)
        elif position == 0:
            confidence = 0
        else:
            confidence = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Пример #26
0
    def ichimoku200(self, df, pattern, patterntype):
        ## Step 1:
        #####PLACEHOLDER
        # df = pd.read_csv('./database/TSLA/temp2.csv')
        #####END_PLACEHOLDER
        df = df.dropna()
        ###1. Getting Parameters

        ##a. Senkou Span B Ahead
        Currentfifty_two = df.head(52)
        Currentfifty_two_high = Currentfifty_two['high'].max()
        Currentfifty_two_low = Currentfifty_two['low'].min()
        AheadSenkouB = (Currentfifty_two_high + Currentfifty_two_low) / 2
        # print("SenkouBAhead\n", AheadSenkouB)

        ##b. Current Kijun-Sen
        Currenttwenty_six = Currentfifty_two.head(26)
        Currenttwenty_six_high = Currenttwenty_six['high'].max()
        Currenttwenty_six_low = Currenttwenty_six['low'].min()
        CurrentKijun = (Currenttwenty_six_high + Currenttwenty_six_low) / 2
        # print("Kijun-Sen\n" , CurrentKijun)

        ##c. Current Tenkan-Sen
        Currentnine = Currenttwenty_six.head(9)
        Currentnine_high = Currentnine['high'].max()
        Currentnine_low = Currentnine['low'].min()
        CurrentTenkan = (Currentnine_high + Currentnine_low) / 2

        # print("Tenkan-Sen\n", CurrentTenkan)

        ##d. Senkou Span A Ahead
        AheadSenkouA = (CurrentKijun + CurrentTenkan) / 2
        # print("SenkouAAhead\n", AheadSenkouA)

        ##e. Senkou Span B Current
        Pastfifty_two = df.iloc[26:].head(52)
        Pastfifty_two_high = Pastfifty_two['high'].max()
        Pastfifty_two_low = Pastfifty_two['low'].min()
        CurrentSenkouB = (Pastfifty_two_high + Pastfifty_two_low) / 2
        # print("SenkouBCurrent\n", CurrentSenkouB)

        ##f. Past Kijun-Sen
        Pasttwenty_six = Pastfifty_two.head(26)
        Pasttwenty_six_high = Pasttwenty_six['high'].max()
        Pasttwenty_six_low = Pasttwenty_six['low'].min()
        PastKijun = (Pasttwenty_six_low + Pasttwenty_six_high) / 2
        # print("PastKijun-Sen\n",PastKijun)

        ##g. Past Tenkan-Sen
        Pastnine = Pasttwenty_six.head(9)
        Pastnine_high = Pastnine['high'].max()
        Pastnine_low = Pastnine['low'].min()
        PastTenkan = (Pastnine_high + Pastnine_low) / 2
        # print("PastTenkan-Sen\n", PastTenkan)

        ##h. Senkou Span A Current
        CurrentSenkouA = (PastKijun + PastTenkan) / 2
        # print("SenkouACurrent\n", CurrentSenkouA)

        ##i. Senkou Span B Past
        PastPastfifty_two = df.iloc[52:].head(52)
        PastPastfifty_two_high = PastPastfifty_two['high'].max()
        PastPastfifty_two_low = PastPastfifty_two['low'].min()
        PastSenkouB = (PastPastfifty_two_high + PastPastfifty_two_low) / 2

        ##j. Past Past Kijun - Sen
        PastPasttwenty_six = PastPastfifty_two.head(26)
        PastPasttwenty_six_high = PastPasttwenty_six['high'].max()
        PastPasttwenty_six_low = PastPasttwenty_six['low'].min()
        PastPastKijun = (PastPasttwenty_six_low + PastPasttwenty_six_high) / 2

        ##k. Past Past Tenkan-Sen
        PastPastnine = PastPasttwenty_six.head(9)
        PastPastnine_high = PastPastnine['high'].max()
        PastPastnine_low = PastPastnine['low'].min()
        PastPastTenkan = (PastPastnine_high + PastPastnine_low) / 2

        ##l. Senkou Span A Past
        PastSenkouA = (PastPastKijun + PastPastTenkan) / 2

        ##m. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)
        # print("EMA\n", ema[-1])

        ##n. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]
        ### IMPT CHIKOU SPAN = PRICE CLOSE

        # print("pricehigh\n", pricehigh)
        # print("pricelow\n", pricelow)

        ### 2. Analysing using Data Provided
        ##tenkan-kijun crossover type
        ## -1 means negative crossover
        ## 1 means positive crossover
        ## 0 means both

        delayOnePeriod = df.iloc[1:]

        ##b. Current Kijun-Sen
        Delaytwenty_six = delayOnePeriod.head(26)
        Delaytwenty_six_high = Delaytwenty_six['high'].max()
        Delaytwenty_six_low = Delaytwenty_six['low'].min()
        DelayKijun = (Delaytwenty_six_high + Delaytwenty_six_low) / 2
        # print("Delay Kijun-Sen\n" , DelayKijun)

        ##c. Current Tenkan-Sen
        Delaynine = Delaytwenty_six.head(9)
        Delaynine_high = Delaynine['high'].max()
        Delaynine_low = Delaynine['low'].min()
        DelayTenkan = (Delaynine_high + Delaynine_low) / 2

        # print("Tenkan-Sen\n", DelayTenkan)

        if DelayTenkan <= DelayKijun and CurrentTenkan >= CurrentKijun and pricelow > CurrentTenkan:
            crossover = 1
        elif DelayTenkan >= DelayKijun and CurrentTenkan <= CurrentKijun and pricehigh < CurrentTenkan:
            crossover = -1

        else:
            crossover = 0

        ##ahead cloud colour
        ## -1 means red cloud
        ## 1 means green cloud
        ## 0 means both

        if AheadSenkouA > AheadSenkouB: AheadCloud = 1
        elif AheadSenkouA < AheadSenkouB: AheadCloud = -1
        else: AheadCloud = 0

        ##market-ema type
        ## 1 means low > 200EMA
        ## -1 means high < 200EMA
        ## 0 means otherwise

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##market-cloud type
        ## 1 means close is above current cloud, and close (lagging span) above the past cloud too
        ## -1 means close is below current cloud, and close (lagging span) below the past cloud too
        ## 0 means otherwise (absolutely no trading)

        if pricelow > max(CurrentSenkouA, CurrentSenkouB) and pricelow > max(
                PastSenkouB, PastSenkouA):
            marketCloud = 1
        elif pricehigh < min(CurrentSenkouB,
                             CurrentSenkouA) and pricehigh < min(
                                 PastSenkouA, PastSenkouB):
            marketCloud = -1
        else:
            marketCloud = 0

        if marketCloud == 1 and marketEMA > 0 and AheadCloud >= 0 and crossover > 0:
            position = 1  ##long
        elif marketCloud == -1 and marketEMA < 0 and AheadCloud <= 0 and crossover < 0:
            position = -1  ##short
        else:
            position = 0  ## no position
        amount = 50
        if position == 1:
            closeKijunDistance = priceclose - CurrentKijun
            adjustedDistance = 1.05 * closeKijunDistance
            stoploss = priceclose - adjustedDistance
            # amount = priceclose / (priceclose-stoploss)
            takeprofit = priceclose + 1.45 * (priceclose - stoploss)
            if (takeprofit - priceclose) * amount < 0.1:
                amount = 0
                position = 0
                stoploss = 0
                takeprofit = 0

        elif position == -1:
            closeKijunDistance = CurrentKijun - priceclose
            adjustedDistance = 1.05 * closeKijunDistance
            stoploss = priceclose + adjustedDistance
            # amount = priceclose / (stoploss - priceclose)
            takeprofit = priceclose - 1.45 * (stoploss - priceclose)
            if (priceclose - takeprofit) * amount < 0.1:
                amount = 0
                position = 0
                stoploss = 0
                takeprofit = 0
        else:
            amount = 0
            stoploss = 0
            takeprofit = 0

        if position * pattern > 0:
            confidence = abs(pattern)
        elif position * pattern < 0:
            confidence = abs(1 / pattern)
        elif position == 0:
            confidence = 0
        else:
            confidence = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Пример #27
0
    def bbands200(self, df, pattern, patterntype):
        df = df.dropna()

        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)

        ##b. get BBands
        bband = df.head(21)
        bband = bband.iloc[1:]
        bband = bband.iloc[::-1]
        bbandInput = bband['close'].values
        upperband, middleband, lowerband = BBANDS(bbandInput,
                                                  timeperiod=20,
                                                  nbdevup=2,
                                                  nbdevdn=2,
                                                  matype=0)

        ##c. 200EMA
        emaInput = df.head(200)
        emaInput = emaInput.iloc[::-1]
        EMAclose = emaInput['close'].values
        ema = EMA(EMAclose, timeperiod=200)

        ##d. current price action
        priceaction = df.head(1)
        pricehigh = priceaction['high'].values[0]
        pricelow = priceaction['low'].values[0]
        priceclose = priceaction['close'].values[0]

        if pricehigh > upperband[-1]: breakBand = -1
        elif pricelow < lowerband[-1]: breakBand = 1
        else: breakBand = 0

        if pricelow > ema[-1]: marketEMA = 1
        elif pricehigh < ema[-1]: marketEMA = -1
        else: marketEMA = 0

        ##OUTPUT
        if marketEMA == 1 and pattern > 0 and patterntype == -1 and breakBand == 1:
            position = 1
        elif marketEMA == -1 and pattern < 0 and patterntype == -1 and breakBand == -1:
            position = -1
        else:
            position = 0
        amount = 50
        if position == 1:
            stoploss = priceclose - 1.05 * atr
            takeprofit = priceclose + 1.45 * atr
            # amount = priceclose / (priceclose - stoploss)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0

        elif position == -1:
            stoploss = priceclose + 1.05 * atr
            takeprofit = priceclose - 1.45 * atr
            # amount = priceclose / (stoploss - priceclose)
            if (stoploss - priceclose) * amount < 0.1:
                position = 0
                amount = 0
                stoploss = 0
                takeprofit = 0

        else:
            stoploss = 0
            takeprofit = 0
            amount = 0

        if position * pattern > 0:
            confidence = abs(pattern)
        elif position * pattern < 0:
            confidence = abs(1 / pattern)
        elif position == 0:
            confidence = 0
        else:
            confidence = 1

        # ##FOR TEST
        # position = 1
        return [position, amount, priceclose, stoploss, takeprofit, confidence]
Пример #28
0
def getEMAslope(data, period=13):
    ema = EMA(data['Close'], timeperiod=period)

    ema = ema.dropna()
    iroc = ema.diff() / 1
    return iroc
Пример #29
0
def getEMA(data, period=13):
    ema = EMA(data['Close'], timeperiod=period)

    ema = ema.tail(1)
    ema = ema.iloc[0]
    return ema
Пример #30
0
    def apply_algorithm(self, market):
        print('Sell analysis...')
        url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?tickInterval=oneMin&marketName={}".format(
            market)  # change this request after api bittrex v2
        market_history = requests.get(url)
        period = max(self.params['period_sma'], self.params['period_ema'])
        data = market_history.json()['result'][-(period + 2):-1]
        historic = np.array([item['C'] for item in data
                             ])  # close price for the last period data

        while True:
            if self.params['period_sma'] is not None and self.params[
                    'period_ema'] is not None:
                # compute intersection between the two last data of historic
                sma = SMA(historic, timeperiod=self.params['period_sma'])
                ema = EMA(historic, timeperiod=self.params['period_ema'])
                # sma[-2] and ema[-2] evaluated in t = t0 = 0 (rescaled)
                # sma[-1] and ema[-1] evaluated in t = t0 + tick_time
                r = np.array([self.params['tick_time'] * 60.0, sma[-1]
                              ]) - np.array([0., sma[-2]])  # p -> p + t r
                s = np.array([self.params['tick_time'] * 60.0, ema[-1]
                              ]) - np.array([0., ema[-2]])  # q -> q + u s
                cross = np.cross(r, s)

                if cross != 0:
                    t = np.cross(
                        (np.array([0., ema[-2]]) - np.array([0., sma[-2]])),
                        s) / cross
                    u = np.cross(
                        (np.array([0., ema[-2]]) - np.array([0., sma[-2]])),
                        r) / cross

                    if u >= 0 and u <= 1 and t >= 0 and t <= 1 and r[1] > s[1]:
                        # intersection detected
                        self.send_sell_request(self.trader, market)
                        break

                time.sleep(self.params['tick_time'] * 60)
                last_price = self.get_ticker(market)['result']['Last']
                historic = np.append(historic, last_price)  # add new data
                historic = np.delete(historic,
                                     0)  # remove the oldest data (useless)

            if self.params['take_profit'] is not None and self.params[
                    'stop_loss'] is not None:
                last_price = self.get_ticker(market)['result']['Last']
                rate_growth = last_price / self.price_buy - 1.0

                if rate_growth >= self.params['take_profit']:
                    print('take profit, sold at :' + str(last_price) +
                          'profit of :' + str(rate_growth))
                    self.send_sell_request(self.trader, market)
                    break

                if last_price < self.price_tweet:
                    print('stop loss, sold at :' + str(last_price) +
                          'loss of :' + str(rate_growth))
                    self.send_sell_request(self.trader, market)
                    break

        print('Sell analysis done')
        self.set_busy(False)